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

/ext/openssl/openssl.c

http://github.com/infusion/PHP
C | 4921 lines | 3809 code | 704 blank | 408 comment | 1025 complexity | def9cf9a3ae9c4308d994129835e2aaa MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.1, BSD-3-Clause
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2011 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 3.01 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available through the world-wide-web at the following url: |
  10. | http://www.php.net/license/3_01.txt |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | license@php.net so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Authors: Stig Venaas <venaas@php.net> |
  16. | Wez Furlong <wez@thebrainroom.com> |
  17. | Sascha Kettler <kettler@gmx.net> |
  18. | Pierre-Alain Joye <pierre@php.net> |
  19. | Marc Delling <delling@silpion.de> (PKCS12 functions) |
  20. +----------------------------------------------------------------------+
  21. */
  22. /* $Id: openssl.c 308534 2011-02-21 12:47:38Z pajoye $ */
  23. #ifdef HAVE_CONFIG_H
  24. #include "config.h"
  25. #endif
  26. #include "php.h"
  27. #include "php_openssl.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. /* OpenSSL includes */
  35. #include <openssl/evp.h>
  36. #include <openssl/x509.h>
  37. #include <openssl/x509v3.h>
  38. #include <openssl/crypto.h>
  39. #include <openssl/pem.h>
  40. #include <openssl/err.h>
  41. #include <openssl/conf.h>
  42. #include <openssl/rand.h>
  43. #include <openssl/ssl.h>
  44. #include <openssl/pkcs12.h>
  45. /* Common */
  46. #include <time.h>
  47. #ifdef NETWARE
  48. #define timezone _timezone /* timezone is called _timezone in LibC */
  49. #endif
  50. #define DEFAULT_KEY_LENGTH 512
  51. #define MIN_KEY_LENGTH 384
  52. #define OPENSSL_ALGO_SHA1 1
  53. #define OPENSSL_ALGO_MD5 2
  54. #define OPENSSL_ALGO_MD4 3
  55. #ifdef HAVE_OPENSSL_MD2_H
  56. #define OPENSSL_ALGO_MD2 4
  57. #endif
  58. #define OPENSSL_ALGO_DSS1 5
  59. #define DEBUG_SMIME 0
  60. /* FIXME: Use the openssl constants instead of
  61. * enum. It is now impossible to match real values
  62. * against php constants. Also sorry to break the
  63. * enum principles here, BC...
  64. */
  65. enum php_openssl_key_type {
  66. OPENSSL_KEYTYPE_RSA,
  67. OPENSSL_KEYTYPE_DSA,
  68. OPENSSL_KEYTYPE_DH,
  69. OPENSSL_KEYTYPE_DEFAULT = OPENSSL_KEYTYPE_RSA,
  70. #ifdef EVP_PKEY_EC
  71. OPENSSL_KEYTYPE_EC = OPENSSL_KEYTYPE_DH +1
  72. #endif
  73. };
  74. enum php_openssl_cipher_type {
  75. PHP_OPENSSL_CIPHER_RC2_40,
  76. PHP_OPENSSL_CIPHER_RC2_128,
  77. PHP_OPENSSL_CIPHER_RC2_64,
  78. PHP_OPENSSL_CIPHER_DES,
  79. PHP_OPENSSL_CIPHER_3DES,
  80. PHP_OPENSSL_CIPHER_DEFAULT = PHP_OPENSSL_CIPHER_RC2_40
  81. };
  82. PHP_FUNCTION(openssl_get_md_methods);
  83. PHP_FUNCTION(openssl_get_cipher_methods);
  84. PHP_FUNCTION(openssl_digest);
  85. PHP_FUNCTION(openssl_encrypt);
  86. PHP_FUNCTION(openssl_decrypt);
  87. PHP_FUNCTION(openssl_cipher_iv_length);
  88. PHP_FUNCTION(openssl_dh_compute_key);
  89. PHP_FUNCTION(openssl_random_pseudo_bytes);
  90. /* {{{ arginfo */
  91. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_x509_export_to_file, 0, 0, 2)
  92. ZEND_ARG_INFO(0, x509)
  93. ZEND_ARG_INFO(0, outfilename)
  94. ZEND_ARG_INFO(0, notext)
  95. ZEND_END_ARG_INFO()
  96. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_x509_export, 0, 0, 2)
  97. ZEND_ARG_INFO(0, x509)
  98. ZEND_ARG_INFO(1, out)
  99. ZEND_ARG_INFO(0, notext)
  100. ZEND_END_ARG_INFO()
  101. ZEND_BEGIN_ARG_INFO(arginfo_openssl_x509_check_private_key, 0)
  102. ZEND_ARG_INFO(0, cert)
  103. ZEND_ARG_INFO(0, key)
  104. ZEND_END_ARG_INFO()
  105. ZEND_BEGIN_ARG_INFO(arginfo_openssl_x509_parse, 0)
  106. ZEND_ARG_INFO(0, x509)
  107. ZEND_ARG_INFO(0, shortname)
  108. ZEND_END_ARG_INFO()
  109. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_x509_checkpurpose, 0, 0, 3)
  110. ZEND_ARG_INFO(0, x509cert)
  111. ZEND_ARG_INFO(0, purpose)
  112. ZEND_ARG_INFO(0, cainfo) /* array */
  113. ZEND_ARG_INFO(0, untrustedfile)
  114. ZEND_END_ARG_INFO()
  115. ZEND_BEGIN_ARG_INFO(arginfo_openssl_x509_read, 0)
  116. ZEND_ARG_INFO(0, cert)
  117. ZEND_END_ARG_INFO()
  118. ZEND_BEGIN_ARG_INFO(arginfo_openssl_x509_free, 0)
  119. ZEND_ARG_INFO(0, x509)
  120. ZEND_END_ARG_INFO()
  121. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs12_export_to_file, 0, 0, 4)
  122. ZEND_ARG_INFO(0, x509)
  123. ZEND_ARG_INFO(0, filename)
  124. ZEND_ARG_INFO(0, priv_key)
  125. ZEND_ARG_INFO(0, pass)
  126. ZEND_ARG_INFO(0, args) /* array */
  127. ZEND_END_ARG_INFO()
  128. ZEND_BEGIN_ARG_INFO(arginfo_openssl_pkcs12_export, 0)
  129. ZEND_ARG_INFO(0, x509)
  130. ZEND_ARG_INFO(1, out)
  131. ZEND_ARG_INFO(0, priv_key)
  132. ZEND_ARG_INFO(0, pass)
  133. ZEND_ARG_INFO(0, args) /* array */
  134. ZEND_END_ARG_INFO()
  135. ZEND_BEGIN_ARG_INFO(arginfo_openssl_pkcs12_read, 0)
  136. ZEND_ARG_INFO(0, PKCS12)
  137. ZEND_ARG_INFO(1, certs) /* array */
  138. ZEND_ARG_INFO(0, pass)
  139. ZEND_END_ARG_INFO()
  140. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_export_to_file, 0, 0, 2)
  141. ZEND_ARG_INFO(0, csr)
  142. ZEND_ARG_INFO(0, outfilename)
  143. ZEND_ARG_INFO(0, notext)
  144. ZEND_END_ARG_INFO()
  145. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_export, 0, 0, 2)
  146. ZEND_ARG_INFO(0, csr)
  147. ZEND_ARG_INFO(1, out)
  148. ZEND_ARG_INFO(0, notext)
  149. ZEND_END_ARG_INFO()
  150. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_sign, 0, 0, 4)
  151. ZEND_ARG_INFO(0, csr)
  152. ZEND_ARG_INFO(0, x509)
  153. ZEND_ARG_INFO(0, priv_key)
  154. ZEND_ARG_INFO(0, days)
  155. ZEND_ARG_INFO(0, config_args) /* array */
  156. ZEND_ARG_INFO(0, serial)
  157. ZEND_END_ARG_INFO()
  158. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_csr_new, 0, 0, 2)
  159. ZEND_ARG_INFO(0, dn) /* array */
  160. ZEND_ARG_INFO(1, privkey)
  161. ZEND_ARG_INFO(0, configargs)
  162. ZEND_ARG_INFO(0, extraattribs)
  163. ZEND_END_ARG_INFO()
  164. ZEND_BEGIN_ARG_INFO(arginfo_openssl_csr_get_subject, 0)
  165. ZEND_ARG_INFO(0, csr)
  166. ZEND_END_ARG_INFO()
  167. ZEND_BEGIN_ARG_INFO(arginfo_openssl_csr_get_public_key, 0)
  168. ZEND_ARG_INFO(0, csr)
  169. ZEND_END_ARG_INFO()
  170. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkey_new, 0, 0, 0)
  171. ZEND_ARG_INFO(0, configargs) /* array */
  172. ZEND_END_ARG_INFO()
  173. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkey_export_to_file, 0, 0, 2)
  174. ZEND_ARG_INFO(0, key)
  175. ZEND_ARG_INFO(0, outfilename)
  176. ZEND_ARG_INFO(0, passphrase)
  177. ZEND_ARG_INFO(0, config_args) /* array */
  178. ZEND_END_ARG_INFO()
  179. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkey_export, 0, 0, 2)
  180. ZEND_ARG_INFO(0, key)
  181. ZEND_ARG_INFO(1, out)
  182. ZEND_ARG_INFO(0, passphrase)
  183. ZEND_ARG_INFO(0, config_args) /* array */
  184. ZEND_END_ARG_INFO()
  185. ZEND_BEGIN_ARG_INFO(arginfo_openssl_pkey_get_public, 0)
  186. ZEND_ARG_INFO(0, cert)
  187. ZEND_END_ARG_INFO()
  188. ZEND_BEGIN_ARG_INFO(arginfo_openssl_pkey_free, 0)
  189. ZEND_ARG_INFO(0, key)
  190. ZEND_END_ARG_INFO()
  191. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkey_get_private, 0, 0, 1)
  192. ZEND_ARG_INFO(0, key)
  193. ZEND_ARG_INFO(0, passphrase)
  194. ZEND_END_ARG_INFO()
  195. ZEND_BEGIN_ARG_INFO(arginfo_openssl_pkey_get_details, 0)
  196. ZEND_ARG_INFO(0, key)
  197. ZEND_END_ARG_INFO()
  198. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs7_verify, 0, 0, 2)
  199. ZEND_ARG_INFO(0, filename)
  200. ZEND_ARG_INFO(0, flags)
  201. ZEND_ARG_INFO(0, signerscerts)
  202. ZEND_ARG_INFO(0, cainfo) /* array */
  203. ZEND_ARG_INFO(0, extracerts)
  204. ZEND_ARG_INFO(0, content)
  205. ZEND_END_ARG_INFO()
  206. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs7_encrypt, 0, 0, 4)
  207. ZEND_ARG_INFO(0, infile)
  208. ZEND_ARG_INFO(0, outfile)
  209. ZEND_ARG_INFO(0, recipcerts)
  210. ZEND_ARG_INFO(0, headers) /* array */
  211. ZEND_ARG_INFO(0, flags)
  212. ZEND_ARG_INFO(0, cipher)
  213. ZEND_END_ARG_INFO()
  214. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs7_sign, 0, 0, 5)
  215. ZEND_ARG_INFO(0, infile)
  216. ZEND_ARG_INFO(0, outfile)
  217. ZEND_ARG_INFO(0, signcert)
  218. ZEND_ARG_INFO(0, signkey)
  219. ZEND_ARG_INFO(0, headers) /* array */
  220. ZEND_ARG_INFO(0, flags)
  221. ZEND_ARG_INFO(0, extracertsfilename)
  222. ZEND_END_ARG_INFO()
  223. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_pkcs7_decrypt, 0, 0, 3)
  224. ZEND_ARG_INFO(0, infilename)
  225. ZEND_ARG_INFO(0, outfilename)
  226. ZEND_ARG_INFO(0, recipcert)
  227. ZEND_ARG_INFO(0, recipkey)
  228. ZEND_END_ARG_INFO()
  229. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_private_encrypt, 0, 0, 3)
  230. ZEND_ARG_INFO(0, data)
  231. ZEND_ARG_INFO(1, crypted)
  232. ZEND_ARG_INFO(0, key)
  233. ZEND_ARG_INFO(0, padding)
  234. ZEND_END_ARG_INFO()
  235. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_private_decrypt, 0, 0, 3)
  236. ZEND_ARG_INFO(0, data)
  237. ZEND_ARG_INFO(1, crypted)
  238. ZEND_ARG_INFO(0, key)
  239. ZEND_ARG_INFO(0, padding)
  240. ZEND_END_ARG_INFO()
  241. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_public_encrypt, 0, 0, 3)
  242. ZEND_ARG_INFO(0, data)
  243. ZEND_ARG_INFO(1, crypted)
  244. ZEND_ARG_INFO(0, key)
  245. ZEND_ARG_INFO(0, padding)
  246. ZEND_END_ARG_INFO()
  247. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_public_decrypt, 0, 0, 3)
  248. ZEND_ARG_INFO(0, data)
  249. ZEND_ARG_INFO(1, crypted)
  250. ZEND_ARG_INFO(0, key)
  251. ZEND_ARG_INFO(0, padding)
  252. ZEND_END_ARG_INFO()
  253. ZEND_BEGIN_ARG_INFO(arginfo_openssl_error_string, 0)
  254. ZEND_END_ARG_INFO()
  255. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_sign, 0, 0, 3)
  256. ZEND_ARG_INFO(0, data)
  257. ZEND_ARG_INFO(1, signature)
  258. ZEND_ARG_INFO(0, key)
  259. ZEND_ARG_INFO(0, method)
  260. ZEND_END_ARG_INFO()
  261. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_verify, 0, 0, 3)
  262. ZEND_ARG_INFO(0, data)
  263. ZEND_ARG_INFO(0, signature)
  264. ZEND_ARG_INFO(0, key)
  265. ZEND_ARG_INFO(0, method)
  266. ZEND_END_ARG_INFO()
  267. ZEND_BEGIN_ARG_INFO(arginfo_openssl_seal, 0)
  268. ZEND_ARG_INFO(0, data)
  269. ZEND_ARG_INFO(1, sealdata)
  270. ZEND_ARG_INFO(1, ekeys) /* arary */
  271. ZEND_ARG_INFO(0, pubkeys) /* array */
  272. ZEND_END_ARG_INFO()
  273. ZEND_BEGIN_ARG_INFO(arginfo_openssl_open, 0)
  274. ZEND_ARG_INFO(0, data)
  275. ZEND_ARG_INFO(1, opendata)
  276. ZEND_ARG_INFO(0, ekey)
  277. ZEND_ARG_INFO(0, privkey)
  278. ZEND_END_ARG_INFO()
  279. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_get_md_methods, 0, 0, 0)
  280. ZEND_ARG_INFO(0, aliases)
  281. ZEND_END_ARG_INFO()
  282. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_get_cipher_methods, 0, 0, 0)
  283. ZEND_ARG_INFO(0, aliases)
  284. ZEND_END_ARG_INFO()
  285. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_digest, 0, 0, 2)
  286. ZEND_ARG_INFO(0, data)
  287. ZEND_ARG_INFO(0, method)
  288. ZEND_ARG_INFO(0, raw_output)
  289. ZEND_END_ARG_INFO()
  290. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_encrypt, 0, 0, 3)
  291. ZEND_ARG_INFO(0, data)
  292. ZEND_ARG_INFO(0, method)
  293. ZEND_ARG_INFO(0, password)
  294. ZEND_ARG_INFO(0, raw_output)
  295. ZEND_ARG_INFO(0, iv)
  296. ZEND_END_ARG_INFO()
  297. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_decrypt, 0, 0, 3)
  298. ZEND_ARG_INFO(0, data)
  299. ZEND_ARG_INFO(0, method)
  300. ZEND_ARG_INFO(0, password)
  301. ZEND_ARG_INFO(0, raw_input)
  302. ZEND_ARG_INFO(0, iv)
  303. ZEND_END_ARG_INFO()
  304. ZEND_BEGIN_ARG_INFO(arginfo_openssl_cipher_iv_length, 0)
  305. ZEND_ARG_INFO(0, method)
  306. ZEND_END_ARG_INFO()
  307. ZEND_BEGIN_ARG_INFO(arginfo_openssl_dh_compute_key, 0)
  308. ZEND_ARG_INFO(0, pub_key)
  309. ZEND_ARG_INFO(0, dh_key)
  310. ZEND_END_ARG_INFO()
  311. ZEND_BEGIN_ARG_INFO_EX(arginfo_openssl_random_pseudo_bytes, 0, 0, 1)
  312. ZEND_ARG_INFO(0, length)
  313. ZEND_ARG_INFO(1, result_is_strong)
  314. ZEND_END_ARG_INFO()
  315. /* }}} */
  316. /* {{{ openssl_functions[]
  317. */
  318. const zend_function_entry openssl_functions[] = {
  319. /* public/private key functions */
  320. PHP_FE(openssl_pkey_free, arginfo_openssl_pkey_free)
  321. PHP_FE(openssl_pkey_new, arginfo_openssl_pkey_new)
  322. PHP_FE(openssl_pkey_export, arginfo_openssl_pkey_export)
  323. PHP_FE(openssl_pkey_export_to_file, arginfo_openssl_pkey_export_to_file)
  324. PHP_FE(openssl_pkey_get_private, arginfo_openssl_pkey_get_private)
  325. PHP_FE(openssl_pkey_get_public, arginfo_openssl_pkey_get_public)
  326. PHP_FE(openssl_pkey_get_details, arginfo_openssl_pkey_get_details)
  327. PHP_FALIAS(openssl_free_key, openssl_pkey_free, arginfo_openssl_pkey_free)
  328. PHP_FALIAS(openssl_get_privatekey, openssl_pkey_get_private, arginfo_openssl_pkey_get_private)
  329. PHP_FALIAS(openssl_get_publickey, openssl_pkey_get_public, arginfo_openssl_pkey_get_public)
  330. /* x.509 cert funcs */
  331. PHP_FE(openssl_x509_read, arginfo_openssl_x509_read)
  332. PHP_FE(openssl_x509_free, arginfo_openssl_x509_free)
  333. PHP_FE(openssl_x509_parse, arginfo_openssl_x509_parse)
  334. PHP_FE(openssl_x509_checkpurpose, arginfo_openssl_x509_checkpurpose)
  335. PHP_FE(openssl_x509_check_private_key, arginfo_openssl_x509_check_private_key)
  336. PHP_FE(openssl_x509_export, arginfo_openssl_x509_export)
  337. PHP_FE(openssl_x509_export_to_file, arginfo_openssl_x509_export_to_file)
  338. /* PKCS12 funcs */
  339. PHP_FE(openssl_pkcs12_export, arginfo_openssl_pkcs12_export)
  340. PHP_FE(openssl_pkcs12_export_to_file, arginfo_openssl_pkcs12_export_to_file)
  341. PHP_FE(openssl_pkcs12_read, arginfo_openssl_pkcs12_read)
  342. /* CSR funcs */
  343. PHP_FE(openssl_csr_new, arginfo_openssl_csr_new)
  344. PHP_FE(openssl_csr_export, arginfo_openssl_csr_export)
  345. PHP_FE(openssl_csr_export_to_file, arginfo_openssl_csr_export_to_file)
  346. PHP_FE(openssl_csr_sign, arginfo_openssl_csr_sign)
  347. PHP_FE(openssl_csr_get_subject, arginfo_openssl_csr_get_subject)
  348. PHP_FE(openssl_csr_get_public_key, arginfo_openssl_csr_get_public_key)
  349. PHP_FE(openssl_digest, arginfo_openssl_digest)
  350. PHP_FE(openssl_encrypt, arginfo_openssl_encrypt)
  351. PHP_FE(openssl_decrypt, arginfo_openssl_decrypt)
  352. PHP_FE(openssl_cipher_iv_length, arginfo_openssl_cipher_iv_length)
  353. PHP_FE(openssl_sign, arginfo_openssl_sign)
  354. PHP_FE(openssl_verify, arginfo_openssl_verify)
  355. PHP_FE(openssl_seal, arginfo_openssl_seal)
  356. PHP_FE(openssl_open, arginfo_openssl_open)
  357. /* for S/MIME handling */
  358. PHP_FE(openssl_pkcs7_verify, arginfo_openssl_pkcs7_verify)
  359. PHP_FE(openssl_pkcs7_decrypt, arginfo_openssl_pkcs7_decrypt)
  360. PHP_FE(openssl_pkcs7_sign, arginfo_openssl_pkcs7_sign)
  361. PHP_FE(openssl_pkcs7_encrypt, arginfo_openssl_pkcs7_encrypt)
  362. PHP_FE(openssl_private_encrypt, arginfo_openssl_private_encrypt)
  363. PHP_FE(openssl_private_decrypt, arginfo_openssl_private_decrypt)
  364. PHP_FE(openssl_public_encrypt, arginfo_openssl_public_encrypt)
  365. PHP_FE(openssl_public_decrypt, arginfo_openssl_public_decrypt)
  366. PHP_FE(openssl_get_md_methods, arginfo_openssl_get_md_methods)
  367. PHP_FE(openssl_get_cipher_methods, arginfo_openssl_get_cipher_methods)
  368. PHP_FE(openssl_dh_compute_key, arginfo_openssl_dh_compute_key)
  369. PHP_FE(openssl_random_pseudo_bytes, arginfo_openssl_random_pseudo_bytes)
  370. PHP_FE(openssl_error_string, arginfo_openssl_error_string)
  371. {NULL, NULL, NULL}
  372. };
  373. /* }}} */
  374. /* {{{ openssl_module_entry
  375. */
  376. zend_module_entry openssl_module_entry = {
  377. STANDARD_MODULE_HEADER,
  378. "openssl",
  379. openssl_functions,
  380. PHP_MINIT(openssl),
  381. PHP_MSHUTDOWN(openssl),
  382. NULL,
  383. NULL,
  384. PHP_MINFO(openssl),
  385. NO_VERSION_YET,
  386. STANDARD_MODULE_PROPERTIES
  387. };
  388. /* }}} */
  389. #ifdef COMPILE_DL_OPENSSL
  390. ZEND_GET_MODULE(openssl)
  391. #endif
  392. static int le_key;
  393. static int le_x509;
  394. static int le_csr;
  395. static int ssl_stream_data_index;
  396. int php_openssl_get_x509_list_id(void) /* {{{ */
  397. {
  398. return le_x509;
  399. }
  400. /* }}} */
  401. /* {{{ resource destructors */
  402. static void php_pkey_free(zend_rsrc_list_entry *rsrc TSRMLS_DC)
  403. {
  404. EVP_PKEY *pkey = (EVP_PKEY *)rsrc->ptr;
  405. assert(pkey != NULL);
  406. EVP_PKEY_free(pkey);
  407. }
  408. static void php_x509_free(zend_rsrc_list_entry *rsrc TSRMLS_DC)
  409. {
  410. X509 *x509 = (X509 *)rsrc->ptr;
  411. X509_free(x509);
  412. }
  413. static void php_csr_free(zend_rsrc_list_entry *rsrc TSRMLS_DC)
  414. {
  415. X509_REQ * csr = (X509_REQ*)rsrc->ptr;
  416. X509_REQ_free(csr);
  417. }
  418. /* }}} */
  419. /* {{{ openssl safe_mode & open_basedir checks */
  420. inline static int php_openssl_safe_mode_chk(char *filename TSRMLS_DC)
  421. {
  422. if (php_check_open_basedir(filename TSRMLS_CC)) {
  423. return -1;
  424. }
  425. return 0;
  426. }
  427. /* }}} */
  428. /* openssl -> PHP "bridging" */
  429. /* true global; readonly after module startup */
  430. static char default_ssl_conf_filename[MAXPATHLEN];
  431. struct php_x509_request { /* {{{ */
  432. #if OPENSSL_VERSION_NUMBER >= 0x10000002L
  433. LHASH_OF(CONF_VALUE) * global_config; /* Global SSL config */
  434. LHASH_OF(CONF_VALUE) * req_config; /* SSL config for this request */
  435. #else
  436. LHASH * global_config; /* Global SSL config */
  437. LHASH * req_config; /* SSL config for this request */
  438. #endif
  439. const EVP_MD * md_alg;
  440. const EVP_MD * digest;
  441. char * section_name,
  442. * config_filename,
  443. * digest_name,
  444. * extensions_section,
  445. * request_extensions_section;
  446. int priv_key_bits;
  447. int priv_key_type;
  448. int priv_key_encrypt;
  449. EVP_PKEY * priv_key;
  450. };
  451. /* }}} */
  452. static X509 * php_openssl_x509_from_zval(zval ** val, int makeresource, long * resourceval TSRMLS_DC);
  453. static EVP_PKEY * php_openssl_evp_from_zval(zval ** val, int public_key, char * passphrase, int makeresource, long * resourceval TSRMLS_DC);
  454. static int php_openssl_is_private_key(EVP_PKEY* pkey TSRMLS_DC);
  455. static X509_STORE * setup_verify(zval * calist TSRMLS_DC);
  456. static STACK_OF(X509) * load_all_certs_from_file(char *certfile);
  457. static X509_REQ * php_openssl_csr_from_zval(zval ** val, int makeresource, long * resourceval TSRMLS_DC);
  458. static EVP_PKEY * php_openssl_generate_private_key(struct php_x509_request * req TSRMLS_DC);
  459. static void add_assoc_name_entry(zval * val, char * key, X509_NAME * name, int shortname TSRMLS_DC) /* {{{ */
  460. {
  461. zval *subitem, *subentries;
  462. int i, j = -1, last = -1, obj_cnt = 0;
  463. char *sname;
  464. int nid;
  465. X509_NAME_ENTRY * ne;
  466. ASN1_STRING * str = NULL;
  467. ASN1_OBJECT * obj;
  468. if (key != NULL) {
  469. MAKE_STD_ZVAL(subitem);
  470. array_init(subitem);
  471. } else {
  472. subitem = val;
  473. }
  474. for (i = 0; i < X509_NAME_entry_count(name); i++) {
  475. unsigned char *to_add;
  476. int to_add_len;
  477. ne = X509_NAME_get_entry(name, i);
  478. obj = X509_NAME_ENTRY_get_object(ne);
  479. nid = OBJ_obj2nid(obj);
  480. obj_cnt = 0;
  481. if (shortname) {
  482. sname = (char *) OBJ_nid2sn(nid);
  483. } else {
  484. sname = (char *) OBJ_nid2ln(nid);
  485. }
  486. MAKE_STD_ZVAL(subentries);
  487. array_init(subentries);
  488. last = -1;
  489. for (;;) {
  490. j = X509_NAME_get_index_by_OBJ(name, obj, last);
  491. if (j < 0) {
  492. if (last != -1) break;
  493. } else {
  494. obj_cnt++;
  495. ne = X509_NAME_get_entry(name, j);
  496. str = X509_NAME_ENTRY_get_data(ne);
  497. if (ASN1_STRING_type(str) != V_ASN1_UTF8STRING) {
  498. to_add_len = ASN1_STRING_to_UTF8(&to_add, str);
  499. if (to_add_len != -1) {
  500. add_next_index_stringl(subentries, (char *)to_add, to_add_len, 1);
  501. }
  502. } else {
  503. to_add = ASN1_STRING_data(str);
  504. to_add_len = ASN1_STRING_length(str);
  505. add_next_index_stringl(subentries, (char *)to_add, to_add_len, 1);
  506. }
  507. }
  508. last = j;
  509. }
  510. i = last;
  511. if (obj_cnt > 1) {
  512. add_assoc_zval_ex(subitem, sname, strlen(sname) + 1, subentries);
  513. } else {
  514. zval_dtor(subentries);
  515. FREE_ZVAL(subentries);
  516. if (obj_cnt && str && to_add_len > -1) {
  517. add_assoc_stringl(subitem, sname, (char *)to_add, to_add_len, 1);
  518. }
  519. }
  520. }
  521. if (key != NULL) {
  522. zend_hash_update(HASH_OF(val), key, strlen(key) + 1, (void *)&subitem, sizeof(subitem), NULL);
  523. }
  524. }
  525. /* }}} */
  526. static void add_assoc_asn1_string(zval * val, char * key, ASN1_STRING * str) /* {{{ */
  527. {
  528. add_assoc_stringl(val, key, (char *)str->data, str->length, 1);
  529. }
  530. /* }}} */
  531. static time_t asn1_time_to_time_t(ASN1_UTCTIME * timestr TSRMLS_DC) /* {{{ */
  532. {
  533. /*
  534. This is how the time string is formatted:
  535. snprintf(p, sizeof(p), "%02d%02d%02d%02d%02d%02dZ",ts->tm_year%100,
  536. ts->tm_mon+1,ts->tm_mday,ts->tm_hour,ts->tm_min,ts->tm_sec);
  537. */
  538. time_t ret;
  539. struct tm thetime;
  540. char * strbuf;
  541. char * thestr;
  542. long gmadjust = 0;
  543. if (timestr->length < 13) {
  544. php_error_docref(NULL TSRMLS_CC, E_WARNING, "extension author too lazy to parse %s correctly", timestr->data);
  545. return (time_t)-1;
  546. }
  547. strbuf = estrdup((char *)timestr->data);
  548. memset(&thetime, 0, sizeof(thetime));
  549. /* we work backwards so that we can use atoi more easily */
  550. thestr = strbuf + timestr->length - 3;
  551. thetime.tm_sec = atoi(thestr);
  552. *thestr = '\0';
  553. thestr -= 2;
  554. thetime.tm_min = atoi(thestr);
  555. *thestr = '\0';
  556. thestr -= 2;
  557. thetime.tm_hour = atoi(thestr);
  558. *thestr = '\0';
  559. thestr -= 2;
  560. thetime.tm_mday = atoi(thestr);
  561. *thestr = '\0';
  562. thestr -= 2;
  563. thetime.tm_mon = atoi(thestr)-1;
  564. *thestr = '\0';
  565. thestr -= 2;
  566. thetime.tm_year = atoi(thestr);
  567. if (thetime.tm_year < 68) {
  568. thetime.tm_year += 100;
  569. }
  570. thetime.tm_isdst = -1;
  571. ret = mktime(&thetime);
  572. #if HAVE_TM_GMTOFF
  573. gmadjust = thetime.tm_gmtoff;
  574. #else
  575. /*
  576. ** If correcting for daylight savings time, we set the adjustment to
  577. ** the value of timezone - 3600 seconds. Otherwise, we need to overcorrect and
  578. ** set the adjustment to the main timezone + 3600 seconds.
  579. */
  580. gmadjust = -(thetime.tm_isdst ? (long)timezone - 3600 : (long)timezone + 3600);
  581. #endif
  582. ret += gmadjust;
  583. efree(strbuf);
  584. return ret;
  585. }
  586. /* }}} */
  587. #if OPENSSL_VERSION_NUMBER >= 0x10000002L
  588. static inline int php_openssl_config_check_syntax(const char * section_label, const char * config_filename, const char * section, LHASH_OF(CONF_VALUE) * config TSRMLS_DC) /* {{{ */
  589. #else
  590. static inline int php_openssl_config_check_syntax(const char * section_label, const char * config_filename, const char * section, LHASH * config TSRMLS_DC)
  591. #endif
  592. {
  593. X509V3_CTX ctx;
  594. X509V3_set_ctx_test(&ctx);
  595. X509V3_set_conf_lhash(&ctx, config);
  596. if (!X509V3_EXT_add_conf(config, &ctx, (char *)section, NULL)) {
  597. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error loading %s section %s of %s",
  598. section_label,
  599. section,
  600. config_filename);
  601. return FAILURE;
  602. }
  603. return SUCCESS;
  604. }
  605. /* }}} */
  606. static int add_oid_section(struct php_x509_request * req TSRMLS_DC) /* {{{ */
  607. {
  608. char * str;
  609. STACK_OF(CONF_VALUE) * sktmp;
  610. CONF_VALUE * cnf;
  611. int i;
  612. str = CONF_get_string(req->req_config, NULL, "oid_section");
  613. if (str == NULL) {
  614. return SUCCESS;
  615. }
  616. sktmp = CONF_get_section(req->req_config, str);
  617. if (sktmp == NULL) {
  618. php_error_docref(NULL TSRMLS_CC, E_WARNING, "problem loading oid section %s", str);
  619. return FAILURE;
  620. }
  621. for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) {
  622. cnf = sk_CONF_VALUE_value(sktmp, i);
  623. if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) {
  624. php_error_docref(NULL TSRMLS_CC, E_WARNING, "problem creating object %s=%s", cnf->name, cnf->value);
  625. return FAILURE;
  626. }
  627. }
  628. return SUCCESS;
  629. }
  630. /* }}} */
  631. #define PHP_SSL_REQ_INIT(req) memset(req, 0, sizeof(*req))
  632. #define PHP_SSL_REQ_DISPOSE(req) php_openssl_dispose_config(req TSRMLS_CC)
  633. #define PHP_SSL_REQ_PARSE(req, zval) php_openssl_parse_config(req, zval TSRMLS_CC)
  634. #define PHP_SSL_CONFIG_SYNTAX_CHECK(var) if (req->var && php_openssl_config_check_syntax(#var, \
  635. req->config_filename, req->var, req->req_config TSRMLS_CC) == FAILURE) return FAILURE
  636. #define SET_OPTIONAL_STRING_ARG(key, varname, defval) \
  637. if (optional_args && zend_hash_find(Z_ARRVAL_P(optional_args), key, sizeof(key), (void**)&item) == SUCCESS) \
  638. varname = Z_STRVAL_PP(item); \
  639. else \
  640. varname = defval
  641. #define SET_OPTIONAL_LONG_ARG(key, varname, defval) \
  642. if (optional_args && zend_hash_find(Z_ARRVAL_P(optional_args), key, sizeof(key), (void**)&item) == SUCCESS) \
  643. varname = Z_LVAL_PP(item); \
  644. else \
  645. varname = defval
  646. static int php_openssl_parse_config(struct php_x509_request * req, zval * optional_args TSRMLS_DC) /* {{{ */
  647. {
  648. char * str;
  649. zval ** item;
  650. SET_OPTIONAL_STRING_ARG("config", req->config_filename, default_ssl_conf_filename);
  651. SET_OPTIONAL_STRING_ARG("config_section_name", req->section_name, "req");
  652. req->global_config = CONF_load(NULL, default_ssl_conf_filename, NULL);
  653. req->req_config = CONF_load(NULL, req->config_filename, NULL);
  654. if (req->req_config == NULL) {
  655. return FAILURE;
  656. }
  657. /* read in the oids */
  658. str = CONF_get_string(req->req_config, NULL, "oid_file");
  659. if (str && !php_openssl_safe_mode_chk(str TSRMLS_CC)) {
  660. BIO *oid_bio = BIO_new_file(str, "r");
  661. if (oid_bio) {
  662. OBJ_create_objects(oid_bio);
  663. BIO_free(oid_bio);
  664. }
  665. }
  666. if (add_oid_section(req TSRMLS_CC) == FAILURE) {
  667. return FAILURE;
  668. }
  669. SET_OPTIONAL_STRING_ARG("digest_alg", req->digest_name,
  670. CONF_get_string(req->req_config, req->section_name, "default_md"));
  671. SET_OPTIONAL_STRING_ARG("x509_extensions", req->extensions_section,
  672. CONF_get_string(req->req_config, req->section_name, "x509_extensions"));
  673. SET_OPTIONAL_STRING_ARG("req_extensions", req->request_extensions_section,
  674. CONF_get_string(req->req_config, req->section_name, "req_extensions"));
  675. SET_OPTIONAL_LONG_ARG("private_key_bits", req->priv_key_bits,
  676. CONF_get_number(req->req_config, req->section_name, "default_bits"));
  677. SET_OPTIONAL_LONG_ARG("private_key_type", req->priv_key_type, OPENSSL_KEYTYPE_DEFAULT);
  678. if (optional_args && zend_hash_find(Z_ARRVAL_P(optional_args), "encrypt_key", sizeof("encrypt_key"), (void**)&item) == SUCCESS) {
  679. req->priv_key_encrypt = Z_BVAL_PP(item);
  680. } else {
  681. str = CONF_get_string(req->req_config, req->section_name, "encrypt_rsa_key");
  682. if (str == NULL) {
  683. str = CONF_get_string(req->req_config, req->section_name, "encrypt_key");
  684. }
  685. if (str && strcmp(str, "no") == 0) {
  686. req->priv_key_encrypt = 0;
  687. } else {
  688. req->priv_key_encrypt = 1;
  689. }
  690. }
  691. /* digest alg */
  692. if (req->digest_name == NULL) {
  693. req->digest_name = CONF_get_string(req->req_config, req->section_name, "default_md");
  694. }
  695. if (req->digest_name) {
  696. req->digest = req->md_alg = EVP_get_digestbyname(req->digest_name);
  697. }
  698. if (req->md_alg == NULL) {
  699. req->md_alg = req->digest = EVP_md5();
  700. }
  701. PHP_SSL_CONFIG_SYNTAX_CHECK(extensions_section);
  702. /* set the string mask */
  703. str = CONF_get_string(req->req_config, req->section_name, "string_mask");
  704. if (str && !ASN1_STRING_set_default_mask_asc(str)) {
  705. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Invalid global string mask setting %s", str);
  706. return FAILURE;
  707. }
  708. PHP_SSL_CONFIG_SYNTAX_CHECK(request_extensions_section);
  709. return SUCCESS;
  710. }
  711. /* }}} */
  712. static void php_openssl_dispose_config(struct php_x509_request * req TSRMLS_DC) /* {{{ */
  713. {
  714. if (req->priv_key) {
  715. EVP_PKEY_free(req->priv_key);
  716. req->priv_key = NULL;
  717. }
  718. if (req->global_config) {
  719. CONF_free(req->global_config);
  720. req->global_config = NULL;
  721. }
  722. if (req->req_config) {
  723. CONF_free(req->req_config);
  724. req->req_config = NULL;
  725. }
  726. }
  727. /* }}} */
  728. static int php_openssl_load_rand_file(const char * file, int *egdsocket, int *seeded) /* {{{ */
  729. {
  730. char buffer[MAXPATHLEN];
  731. TSRMLS_FETCH();
  732. *egdsocket = 0;
  733. *seeded = 0;
  734. if (file == NULL) {
  735. file = RAND_file_name(buffer, sizeof(buffer));
  736. } else if (RAND_egd(file) > 0) {
  737. /* if the given filename is an EGD socket, don't
  738. * write anything back to it */
  739. *egdsocket = 1;
  740. return SUCCESS;
  741. }
  742. if (file == NULL || !RAND_load_file(file, -1)) {
  743. if (RAND_status() == 0) {
  744. php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to load random state; not enough random data!");
  745. return FAILURE;
  746. }
  747. return FAILURE;
  748. }
  749. *seeded = 1;
  750. return SUCCESS;
  751. }
  752. /* }}} */
  753. static int php_openssl_write_rand_file(const char * file, int egdsocket, int seeded) /* {{{ */
  754. {
  755. char buffer[MAXPATHLEN];
  756. TSRMLS_FETCH();
  757. if (egdsocket || !seeded) {
  758. /* if we did not manage to read the seed file, we should not write
  759. * a low-entropy seed file back */
  760. return FAILURE;
  761. }
  762. if (file == NULL) {
  763. file = RAND_file_name(buffer, sizeof(buffer));
  764. }
  765. if (file == NULL || !RAND_write_file(file)) {
  766. php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to write random state");
  767. return FAILURE;
  768. }
  769. return SUCCESS;
  770. }
  771. /* }}} */
  772. static EVP_MD * php_openssl_get_evp_md_from_algo(long algo) { /* {{{ */
  773. EVP_MD *mdtype;
  774. switch (algo) {
  775. case OPENSSL_ALGO_SHA1:
  776. mdtype = (EVP_MD *) EVP_sha1();
  777. break;
  778. case OPENSSL_ALGO_MD5:
  779. mdtype = (EVP_MD *) EVP_md5();
  780. break;
  781. case OPENSSL_ALGO_MD4:
  782. mdtype = (EVP_MD *) EVP_md4();
  783. break;
  784. #ifdef HAVE_OPENSSL_MD2_H
  785. case OPENSSL_ALGO_MD2:
  786. mdtype = (EVP_MD *) EVP_md2();
  787. break;
  788. #endif
  789. case OPENSSL_ALGO_DSS1:
  790. mdtype = (EVP_MD *) EVP_dss1();
  791. break;
  792. default:
  793. return NULL;
  794. break;
  795. }
  796. return mdtype;
  797. }
  798. /* }}} */
  799. static const EVP_CIPHER * php_openssl_get_evp_cipher_from_algo(long algo) { /* {{{ */
  800. switch (algo) {
  801. #ifndef OPENSSL_NO_RC2
  802. case PHP_OPENSSL_CIPHER_RC2_40:
  803. return EVP_rc2_40_cbc();
  804. break;
  805. case PHP_OPENSSL_CIPHER_RC2_64:
  806. return EVP_rc2_64_cbc();
  807. break;
  808. case PHP_OPENSSL_CIPHER_RC2_128:
  809. return EVP_rc2_cbc();
  810. break;
  811. #endif
  812. #ifndef OPENSSL_NO_DES
  813. case PHP_OPENSSL_CIPHER_DES:
  814. return EVP_des_cbc();
  815. break;
  816. case PHP_OPENSSL_CIPHER_3DES:
  817. return EVP_des_ede3_cbc();
  818. break;
  819. #endif
  820. default:
  821. return NULL;
  822. break;
  823. }
  824. }
  825. /* }}} */
  826. /* {{{ PHP_MINIT_FUNCTION
  827. */
  828. PHP_MINIT_FUNCTION(openssl)
  829. {
  830. char * config_filename;
  831. le_key = zend_register_list_destructors_ex(php_pkey_free, NULL, "OpenSSL key", module_number);
  832. le_x509 = zend_register_list_destructors_ex(php_x509_free, NULL, "OpenSSL X.509", module_number);
  833. le_csr = zend_register_list_destructors_ex(php_csr_free, NULL, "OpenSSL X.509 CSR", module_number);
  834. SSL_library_init();
  835. OpenSSL_add_all_ciphers();
  836. OpenSSL_add_all_digests();
  837. OpenSSL_add_all_algorithms();
  838. ERR_load_ERR_strings();
  839. ERR_load_crypto_strings();
  840. ERR_load_EVP_strings();
  841. /* register a resource id number with openSSL so that we can map SSL -> stream structures in
  842. * openSSL callbacks */
  843. ssl_stream_data_index = SSL_get_ex_new_index(0, "PHP stream index", NULL, NULL, NULL);
  844. REGISTER_STRING_CONSTANT("OPENSSL_VERSION_TEXT", OPENSSL_VERSION_TEXT, CONST_CS|CONST_PERSISTENT);
  845. REGISTER_LONG_CONSTANT("OPENSSL_VERSION_NUMBER", OPENSSL_VERSION_NUMBER, CONST_CS|CONST_PERSISTENT);
  846. /* purposes for cert purpose checking */
  847. REGISTER_LONG_CONSTANT("X509_PURPOSE_SSL_CLIENT", X509_PURPOSE_SSL_CLIENT, CONST_CS|CONST_PERSISTENT);
  848. REGISTER_LONG_CONSTANT("X509_PURPOSE_SSL_SERVER", X509_PURPOSE_SSL_SERVER, CONST_CS|CONST_PERSISTENT);
  849. REGISTER_LONG_CONSTANT("X509_PURPOSE_NS_SSL_SERVER", X509_PURPOSE_NS_SSL_SERVER, CONST_CS|CONST_PERSISTENT);
  850. REGISTER_LONG_CONSTANT("X509_PURPOSE_SMIME_SIGN", X509_PURPOSE_SMIME_SIGN, CONST_CS|CONST_PERSISTENT);
  851. REGISTER_LONG_CONSTANT("X509_PURPOSE_SMIME_ENCRYPT", X509_PURPOSE_SMIME_ENCRYPT, CONST_CS|CONST_PERSISTENT);
  852. REGISTER_LONG_CONSTANT("X509_PURPOSE_CRL_SIGN", X509_PURPOSE_CRL_SIGN, CONST_CS|CONST_PERSISTENT);
  853. #ifdef X509_PURPOSE_ANY
  854. REGISTER_LONG_CONSTANT("X509_PURPOSE_ANY", X509_PURPOSE_ANY, CONST_CS|CONST_PERSISTENT);
  855. #endif
  856. /* signature algorithm constants */
  857. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_SHA1", OPENSSL_ALGO_SHA1, CONST_CS|CONST_PERSISTENT);
  858. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_MD5", OPENSSL_ALGO_MD5, CONST_CS|CONST_PERSISTENT);
  859. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_MD4", OPENSSL_ALGO_MD4, CONST_CS|CONST_PERSISTENT);
  860. #ifdef HAVE_OPENSSL_MD2_H
  861. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_MD2", OPENSSL_ALGO_MD2, CONST_CS|CONST_PERSISTENT);
  862. #endif
  863. REGISTER_LONG_CONSTANT("OPENSSL_ALGO_DSS1", OPENSSL_ALGO_DSS1, CONST_CS|CONST_PERSISTENT);
  864. /* flags for S/MIME */
  865. REGISTER_LONG_CONSTANT("PKCS7_DETACHED", PKCS7_DETACHED, CONST_CS|CONST_PERSISTENT);
  866. REGISTER_LONG_CONSTANT("PKCS7_TEXT", PKCS7_TEXT, CONST_CS|CONST_PERSISTENT);
  867. REGISTER_LONG_CONSTANT("PKCS7_NOINTERN", PKCS7_NOINTERN, CONST_CS|CONST_PERSISTENT);
  868. REGISTER_LONG_CONSTANT("PKCS7_NOVERIFY", PKCS7_NOVERIFY, CONST_CS|CONST_PERSISTENT);
  869. REGISTER_LONG_CONSTANT("PKCS7_NOCHAIN", PKCS7_NOCHAIN, CONST_CS|CONST_PERSISTENT);
  870. REGISTER_LONG_CONSTANT("PKCS7_NOCERTS", PKCS7_NOCERTS, CONST_CS|CONST_PERSISTENT);
  871. REGISTER_LONG_CONSTANT("PKCS7_NOATTR", PKCS7_NOATTR, CONST_CS|CONST_PERSISTENT);
  872. REGISTER_LONG_CONSTANT("PKCS7_BINARY", PKCS7_BINARY, CONST_CS|CONST_PERSISTENT);
  873. REGISTER_LONG_CONSTANT("PKCS7_NOSIGS", PKCS7_NOSIGS, CONST_CS|CONST_PERSISTENT);
  874. REGISTER_LONG_CONSTANT("OPENSSL_PKCS1_PADDING", RSA_PKCS1_PADDING, CONST_CS|CONST_PERSISTENT);
  875. REGISTER_LONG_CONSTANT("OPENSSL_SSLV23_PADDING", RSA_SSLV23_PADDING, CONST_CS|CONST_PERSISTENT);
  876. REGISTER_LONG_CONSTANT("OPENSSL_NO_PADDING", RSA_NO_PADDING, CONST_CS|CONST_PERSISTENT);
  877. REGISTER_LONG_CONSTANT("OPENSSL_PKCS1_OAEP_PADDING", RSA_PKCS1_OAEP_PADDING, CONST_CS|CONST_PERSISTENT);
  878. /* Ciphers */
  879. #ifndef OPENSSL_NO_RC2
  880. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_RC2_40", PHP_OPENSSL_CIPHER_RC2_40, CONST_CS|CONST_PERSISTENT);
  881. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_RC2_128", PHP_OPENSSL_CIPHER_RC2_128, CONST_CS|CONST_PERSISTENT);
  882. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_RC2_64", PHP_OPENSSL_CIPHER_RC2_64, CONST_CS|CONST_PERSISTENT);
  883. #endif
  884. #ifndef OPENSSL_NO_DES
  885. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_DES", PHP_OPENSSL_CIPHER_DES, CONST_CS|CONST_PERSISTENT);
  886. REGISTER_LONG_CONSTANT("OPENSSL_CIPHER_3DES", PHP_OPENSSL_CIPHER_3DES, CONST_CS|CONST_PERSISTENT);
  887. #endif
  888. /* Values for key types */
  889. REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_RSA", OPENSSL_KEYTYPE_RSA, CONST_CS|CONST_PERSISTENT);
  890. #ifndef NO_DSA
  891. REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_DSA", OPENSSL_KEYTYPE_DSA, CONST_CS|CONST_PERSISTENT);
  892. #endif
  893. REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_DH", OPENSSL_KEYTYPE_DH, CONST_CS|CONST_PERSISTENT);
  894. #ifdef EVP_PKEY_EC
  895. REGISTER_LONG_CONSTANT("OPENSSL_KEYTYPE_EC", OPENSSL_KEYTYPE_EC, CONST_CS|CONST_PERSISTENT);
  896. #endif
  897. #if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
  898. /* SNI support included in OpenSSL >= 0.9.8j */
  899. REGISTER_LONG_CONSTANT("OPENSSL_TLSEXT_SERVER_NAME", 1, CONST_CS|CONST_PERSISTENT);
  900. #endif
  901. /* Determine default SSL configuration file */
  902. config_filename = getenv("OPENSSL_CONF");
  903. if (config_filename == NULL) {
  904. config_filename = getenv("SSLEAY_CONF");
  905. }
  906. /* default to 'openssl.cnf' if no environment variable is set */
  907. if (config_filename == NULL) {
  908. snprintf(default_ssl_conf_filename, sizeof(default_ssl_conf_filename), "%s/%s",
  909. X509_get_default_cert_area(),
  910. "openssl.cnf");
  911. } else {
  912. strlcpy(default_ssl_conf_filename, config_filename, sizeof(default_ssl_conf_filename));
  913. }
  914. php_stream_xport_register("ssl", php_openssl_ssl_socket_factory TSRMLS_CC);
  915. php_stream_xport_register("sslv3", php_openssl_ssl_socket_factory TSRMLS_CC);
  916. php_stream_xport_register("sslv2", php_openssl_ssl_socket_factory TSRMLS_CC);
  917. php_stream_xport_register("tls", php_openssl_ssl_socket_factory TSRMLS_CC);
  918. /* override the default tcp socket provider */
  919. php_stream_xport_register("tcp", php_openssl_ssl_socket_factory TSRMLS_CC);
  920. php_register_url_stream_wrapper("https", &php_stream_http_wrapper TSRMLS_CC);
  921. php_register_url_stream_wrapper("ftps", &php_stream_ftp_wrapper TSRMLS_CC);
  922. return SUCCESS;
  923. }
  924. /* }}} */
  925. /* {{{ PHP_MINFO_FUNCTION
  926. */
  927. PHP_MINFO_FUNCTION(openssl)
  928. {
  929. php_info_print_table_start();
  930. php_info_print_table_row(2, "OpenSSL support", "enabled");
  931. php_info_print_table_row(2, "OpenSSL Library Version", SSLeay_version(SSLEAY_VERSION));
  932. php_info_print_table_row(2, "OpenSSL Header Version", OPENSSL_VERSION_TEXT);
  933. php_info_print_table_end();
  934. }
  935. /* }}} */
  936. /* {{{ PHP_MSHUTDOWN_FUNCTION
  937. */
  938. PHP_MSHUTDOWN_FUNCTION(openssl)
  939. {
  940. EVP_cleanup();
  941. php_unregister_url_stream_wrapper("https" TSRMLS_CC);
  942. php_unregister_url_stream_wrapper("ftps" TSRMLS_CC);
  943. php_stream_xport_unregister("ssl" TSRMLS_CC);
  944. php_stream_xport_unregister("sslv2" TSRMLS_CC);
  945. php_stream_xport_unregister("sslv3" TSRMLS_CC);
  946. php_stream_xport_unregister("tls" TSRMLS_CC);
  947. /* reinstate the default tcp handler */
  948. php_stream_xport_register("tcp", php_stream_generic_socket_factory TSRMLS_CC);
  949. return SUCCESS;
  950. }
  951. /* }}} */
  952. /* {{{ x509 cert functions */
  953. /* {{{ php_openssl_x509_from_zval
  954. Given a zval, coerce it into an X509 object.
  955. The zval can be:
  956. . X509 resource created using openssl_read_x509()
  957. . if it starts with file:// then it will be interpreted as the path to that cert
  958. . it will be interpreted as the cert data
  959. If you supply makeresource, the result will be registered as an x509 resource and
  960. it's value returned in makeresource.
  961. */
  962. static X509 * php_openssl_x509_from_zval(zval ** val, int makeresource, long * resourceval TSRMLS_DC)
  963. {
  964. X509 *cert = NULL;
  965. if (resourceval) {
  966. *resourceval = -1;
  967. }
  968. if (Z_TYPE_PP(val) == IS_RESOURCE) {
  969. /* is it an x509 resource ? */
  970. void * what;
  971. int type;
  972. what = zend_fetch_resource(val TSRMLS_CC, -1, "OpenSSL X.509", &type, 1, le_x509);
  973. if (!what) {
  974. return NULL;
  975. }
  976. /* this is so callers can decide if they should free the X509 */
  977. if (resourceval) {
  978. *resourceval = Z_LVAL_PP(val);
  979. }
  980. if (type == le_x509) {
  981. return (X509*)what;
  982. }
  983. /* other types could be used here - eg: file pointers and read in the data from them */
  984. return NULL;
  985. }
  986. if (!(Z_TYPE_PP(val) == IS_STRING || Z_TYPE_PP(val) == IS_OBJECT)) {
  987. return NULL;
  988. }
  989. /* force it to be a string and check if it refers to a file */
  990. convert_to_string_ex(val);
  991. if (Z_STRLEN_PP(val) > 7 && memcmp(Z_STRVAL_PP(val), "file://", sizeof("file://") - 1) == 0) {
  992. /* read cert from the named file */
  993. BIO *in;
  994. if (php_openssl_safe_mode_chk(Z_STRVAL_PP(val) + (sizeof("file://") - 1) TSRMLS_CC)) {
  995. return NULL;
  996. }
  997. in = BIO_new_file(Z_STRVAL_PP(val) + (sizeof("file://") - 1), "r");
  998. if (in == NULL) {
  999. return NULL;
  1000. }
  1001. cert = PEM_read_bio_X509(in, NULL, NULL, NULL);
  1002. BIO_free(in);
  1003. } else {
  1004. BIO *in;
  1005. in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val));
  1006. if (in == NULL) {
  1007. return NULL;
  1008. }
  1009. #ifdef TYPEDEF_D2I_OF
  1010. cert = (X509 *) PEM_ASN1_read_bio((d2i_of_void *)d2i_X509, PEM_STRING_X509, in, NULL, NULL, NULL);
  1011. #else
  1012. cert = (X509 *) PEM_ASN1_read_bio((char *(*)())d2i_X509, PEM_STRING_X509, in, NULL, NULL, NULL);
  1013. #endif
  1014. BIO_free(in);
  1015. }
  1016. if (cert && makeresource && resourceval) {
  1017. *resourceval = zend_list_insert(cert, le_x509);
  1018. }
  1019. return cert;
  1020. }
  1021. /* }}} */
  1022. /* {{{ proto bool openssl_x509_export_to_file(mixed x509, string outfilename [, bool notext = true])
  1023. Exports a CERT to file or a var */
  1024. PHP_FUNCTION(openssl_x509_export_to_file)
  1025. {
  1026. X509 * cert;
  1027. zval ** zcert;
  1028. zend_bool notext = 1;
  1029. BIO * bio_out;
  1030. long certresource;
  1031. char * filename;
  1032. int filename_len;
  1033. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zs|b", &zcert, &filename, &filename_len, &notext) == FAILURE) {
  1034. return;
  1035. }
  1036. RETVAL_FALSE;
  1037. cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC);
  1038. if (cert == NULL) {
  1039. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get cert from parameter 1");
  1040. return;
  1041. }
  1042. if (php_openssl_safe_mode_chk(filename TSRMLS_CC)) {
  1043. return;
  1044. }
  1045. bio_out = BIO_new_file(filename, "w");
  1046. if (bio_out) {
  1047. if (!notext) {
  1048. X509_print(bio_out, cert);
  1049. }
  1050. PEM_write_bio_X509(bio_out, cert);
  1051. RETVAL_TRUE;
  1052. } else {
  1053. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error opening file %s", filename);
  1054. }
  1055. if (certresource == -1 && cert) {
  1056. X509_free(cert);
  1057. }
  1058. BIO_free(bio_out);
  1059. }
  1060. /* }}} */
  1061. /* {{{ proto bool openssl_x509_export(mixed x509, string &out [, bool notext = true])
  1062. Exports a CERT to file or a var */
  1063. PHP_FUNCTION(openssl_x509_export)
  1064. {
  1065. X509 * cert;
  1066. zval ** zcert, *zout;
  1067. zend_bool notext = 1;
  1068. BIO * bio_out;
  1069. long certresource;
  1070. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zz|b", &zcert, &zout, &notext) == FAILURE) {
  1071. return;
  1072. }
  1073. RETVAL_FALSE;
  1074. cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC);
  1075. if (cert == NULL) {
  1076. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get cert from parameter 1");
  1077. return;
  1078. }
  1079. bio_out = BIO_new(BIO_s_mem());
  1080. if (!notext) {
  1081. X509_print(bio_out, cert);
  1082. }
  1083. if (PEM_write_bio_X509(bio_out, cert)) {
  1084. BUF_MEM *bio_buf;
  1085. zval_dtor(zout);
  1086. BIO_get_mem_ptr(bio_out, &bio_buf);
  1087. ZVAL_STRINGL(zout, bio_buf->data, bio_buf->length, 1);
  1088. RETVAL_TRUE;
  1089. }
  1090. if (certresource == -1 && cert) {
  1091. X509_free(cert);
  1092. }
  1093. BIO_free(bio_out);
  1094. }
  1095. /* }}} */
  1096. /* {{{ proto bool openssl_x509_check_private_key(mixed cert, mixed key)
  1097. Checks if a private key corresponds to a CERT */
  1098. PHP_FUNCTION(openssl_x509_check_private_key)
  1099. {
  1100. zval ** zcert, **zkey;
  1101. X509 * cert = NULL;
  1102. EVP_PKEY * key = NULL;
  1103. long certresource = -1, keyresource = -1;
  1104. RETVAL_FALSE;
  1105. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ZZ", &zcert, &zkey) == FAILURE) {
  1106. return;
  1107. }
  1108. cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC);
  1109. if (cert == NULL) {
  1110. RETURN_FALSE;
  1111. }
  1112. key = php_openssl_evp_from_zval(zkey, 0, "", 1, &keyresource TSRMLS_CC);
  1113. if (key) {
  1114. RETVAL_BOOL(X509_check_private_key(cert, key));
  1115. }
  1116. if (keyresource == -1 && key) {
  1117. EVP_PKEY_free(key);
  1118. }
  1119. if (certresource == -1 && cert) {
  1120. X509_free(cert);
  1121. }
  1122. }
  1123. /* }}} */
  1124. /* {{{ proto array openssl_x509_parse(mixed x509 [, bool shortnames=true])
  1125. Returns an array of the fields/values of the CERT */
  1126. PHP_FUNCTION(openssl_x509_parse)
  1127. {
  1128. zval ** zcert;
  1129. X509 * cert = NULL;
  1130. long certresource = -1;
  1131. int i;
  1132. zend_bool useshortnames = 1;
  1133. char * tmpstr;
  1134. zval * subitem;
  1135. X509_EXTENSION *extension;
  1136. char *extname;
  1137. BIO *bio_out;
  1138. BUF_MEM *bio_buf;
  1139. char buf[256];
  1140. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|b", &zcert, &useshortnames) == FAILURE) {
  1141. return;
  1142. }
  1143. cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC);
  1144. if (cert == NULL) {
  1145. RETURN_FALSE;
  1146. }
  1147. array_init(return_value);
  1148. if (cert->name) {
  1149. add_assoc_string(return_value, "name", cert->name, 1);
  1150. }
  1151. /* add_assoc_bool(return_value, "valid", cert->valid); */
  1152. add_assoc_name_entry(return_value, "subject", X509_get_subject_name(cert), useshortnames TSRMLS_CC);
  1153. /* hash as used in CA directories to lookup cert by subject name */
  1154. {
  1155. char buf[32];
  1156. snprintf(buf, sizeof(buf), "%08lx", X509_subject_name_hash(cert));
  1157. add_assoc_string(return_value, "hash", buf, 1);
  1158. }
  1159. add_assoc_name_entry(return_value, "issuer", X509_get_issuer_name(cert), useshortnames TSRMLS_CC);
  1160. add_assoc_long(return_value, "version", X509_get_version(cert));
  1161. add_assoc_string(return_value, "serialNumber", i2s_ASN1_INTEGER(NULL, X509_get_serialNumber(cert)), 1);
  1162. add_assoc_asn1_string(return_value, "validFrom", X509_get_notBefore(cert));
  1163. add_assoc_asn1_string(return_value, "validTo", X509_get_notAfter(cert));
  1164. add_assoc_long(return_value, "validFrom_time_t", asn1_time_to_time_t(X509_get_notBefore(cert) TSRMLS_CC));
  1165. add_assoc_long(return_value, "validTo_time_t", asn1_time_to_time_t(X509_get_notAfter(cert) TSRMLS_CC));
  1166. tmpstr = (char *)X509_alias_get0(cert, NULL);
  1167. if (tmpstr) {
  1168. add_assoc_string(return_value, "alias", tmpstr, 1);
  1169. }
  1170. /*
  1171. add_assoc_long(return_value, "signaturetypeLONG", X509_get_signature_type(cert));
  1172. add_assoc_string(return_value, "signaturetype", OBJ_nid2sn(X509_get_signature_type(cert)), 1);
  1173. add_assoc_string(return_value, "signaturetypeLN", OBJ_nid2ln(X509_get_signature_type(cert)), 1);
  1174. */
  1175. MAKE_STD_ZVAL(subitem);
  1176. array_init(subitem);
  1177. /* NOTE: the purposes are added as integer keys - the keys match up to the X509_PURPOSE_SSL_XXX defines
  1178. in x509v3.h */
  1179. for (i = 0; i < X509_PURPOSE_get_count(); i++) {
  1180. int id, purpset;
  1181. char * pname;
  1182. X509_PURPOSE * purp;
  1183. zval * subsub;
  1184. MAKE_STD_ZVAL(subsub);
  1185. array_init(subsub);
  1186. purp = X509_PURPOSE_get0(i);
  1187. id = X509_PURPOSE_get_id(purp);
  1188. purpset = X509_check_purpose(cert, id, 0);
  1189. add_index_bool(subsub, 0, purpset);
  1190. purpset = X509_check_purpose(cert, id, 1);
  1191. add_index_bool(subsub, 1, purpset);
  1192. pname = useshortnames ? X509_PURPOSE_get0_sname(purp) : X509_PURPOSE_get0_name(purp);
  1193. add_index_string(subsub, 2, pname, 1);
  1194. /* NOTE: if purpset > 1 then it's a warning - we should mention it ? */
  1195. add_index_zval(subitem, id, subsub);
  1196. }
  1197. add_assoc_zval(return_value, "purposes", subitem);
  1198. MAKE_STD_ZVAL(subitem);
  1199. array_init(subitem);
  1200. for (i = 0; i < X509_get_ext_count(cert); i++) {
  1201. extension = X509_get_ext(cert, i);
  1202. if (OBJ_obj2nid(X509_EXTENSION_get_object(extension)) != NID_undef) {
  1203. extname = (char *)OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(extension)));
  1204. } else {
  1205. OBJ_obj2txt(buf, sizeof(buf)-1, X509_EXTENSION_get_object(extension), 1);
  1206. extname = buf;
  1207. }
  1208. bio_out = BIO_new(BIO_s_mem());
  1209. if (X509V3_EXT_print(bio_out, extension, 0, 0)) {
  1210. BIO_get_mem_ptr(bio_out, &bio_buf);
  1211. add_assoc_stringl(subitem, extname, bio_buf->data, bio_buf->length, 1);
  1212. } else {
  1213. add_assoc_asn1_string(subitem, extname, X509_EXTENSION_get_data(extension));
  1214. }
  1215. BIO_free(bio_out);
  1216. }
  1217. add_assoc_zval(return_value, "extensions", subitem);
  1218. if (certresource == -1 && cert) {
  1219. X509_free(cert);
  1220. }
  1221. }
  1222. /* }}} */
  1223. /* {{{ load_all_certs_from_file */
  1224. static STACK_OF(X509) * load_all_certs_from_file(char *certfile)
  1225. {
  1226. STACK_OF(X509_INFO) *sk=NULL;
  1227. STACK_OF(X509) *stack=NULL, *ret=NULL;
  1228. BIO *in=NULL;
  1229. X509_INFO *xi;
  1230. TSRMLS_FETCH();
  1231. if(!(stack = sk_X509_new_null())) {
  1232. php_error_docref(NULL TSRMLS_CC, E_ERROR, "memory allocation failure");
  1233. goto end;
  1234. }
  1235. if (php_openssl_safe_mode_chk(certfile TSRMLS_CC)) {
  1236. sk_X509_free(stack);
  1237. goto end;
  1238. }
  1239. if(!(in=BIO_new_file(certfile, "r"))) {
  1240. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error opening the file, %s", certfile);
  1241. sk_X509_free(stack);
  1242. goto end;
  1243. }
  1244. /* This loads from a file, a stack of x509/crl/pkey sets */
  1245. if(!(sk=PEM_X509_INFO_read_bio(in, NULL, NULL, NULL))) {
  1246. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error reading the file, %s", certfile);
  1247. sk_X509_free(stack);
  1248. goto end;
  1249. }
  1250. /* scan over it and pull out the certs */
  1251. while (sk_X509_INFO_num(sk)) {
  1252. xi=sk_X509_INFO_shift(sk);
  1253. if (xi->x509 != NULL) {
  1254. sk_X509_push(stack,xi->x509);
  1255. xi->x509=NULL;
  1256. }
  1257. X509_INFO_free(xi);
  1258. }
  1259. if(!sk_X509_num(stack)) {
  1260. php_error_docref(NULL TSRMLS_CC, E_WARNING, "no certificates in file, %s", certfile);
  1261. sk_X509_free(stack);
  1262. goto end;
  1263. }
  1264. ret=stack;
  1265. end:
  1266. BIO_free(in);
  1267. sk_X509_INFO_free(sk);
  1268. return ret;
  1269. }
  1270. /* }}} */
  1271. /* {{{ check_cert */
  1272. static int check_cert(X509_STORE *ctx, X509 *x, STACK_OF(X509) *untrustedchain, int purpose)
  1273. {
  1274. int ret=0;
  1275. X509_STORE_CTX *csc;
  1276. TSRMLS_FETCH();
  1277. csc = X509_STORE_CTX_new();
  1278. if (csc == NULL) {
  1279. php_error_docref(NULL TSRMLS_CC, E_ERROR, "memory allocation failure");
  1280. return 0;
  1281. }
  1282. X509_STORE_CTX_init(csc, ctx, x, untrustedchain);
  1283. if(purpose >= 0) {
  1284. X509_STORE_CTX_set_purpose(csc, purpose);
  1285. }
  1286. ret = X509_verify_cert(csc);
  1287. X509_STORE_CTX_free(csc);
  1288. return ret;
  1289. }
  1290. /* }}} */
  1291. /* {{{ proto int openssl_x509_checkpurpose(mixed x509cert, int purpose, array cainfo [, string untrustedfile])
  1292. Checks the CERT to see if it can be used for the purpose in purpose. cainfo holds information about trusted CAs */
  1293. PHP_FUNCTION(openssl_x509_checkpurpose)
  1294. {
  1295. zval ** zcert, * zcainfo = NULL;
  1296. X509_STORE * cainfo = NULL;
  1297. X509 * cert = NULL;
  1298. long certresource = -1;
  1299. STACK_OF(X509) * untrustedchain = NULL;
  1300. long purpose;
  1301. char * untrusted = NULL;
  1302. int untrusted_len = 0, ret;
  1303. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zl|a!s", &zcert, &purpose, &zcainfo, &untrusted, &untrusted_len) == FAILURE) {
  1304. return;
  1305. }
  1306. RETVAL_LONG(-1);
  1307. if (untrusted) {
  1308. untrustedchain = load_all_certs_from_file(untrusted);
  1309. if (untrustedchain == NULL) {
  1310. goto clean_exit;
  1311. }
  1312. }
  1313. cainfo = setup_verify(zcainfo TSRMLS_CC);
  1314. if (cainfo == NULL) {
  1315. goto clean_exit;
  1316. }
  1317. cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC);
  1318. if (cert == NULL) {
  1319. goto clean_exit;
  1320. }
  1321. ret = check_cert(cainfo, cert, untrustedchain, purpose);
  1322. if (ret != 0 && ret != 1) {
  1323. RETVAL_LONG(ret);
  1324. } else {
  1325. RETVAL_BOOL(ret);
  1326. }
  1327. clean_exit:
  1328. if (certresource == 1 && cert) {
  1329. X509_free(cert);
  1330. }
  1331. if (cainfo) {
  1332. X509_STORE_free(cainfo);
  1333. }
  1334. if (untrustedchain) {
  1335. sk_X509_pop_free(untrustedchain, X509_free);
  1336. }
  1337. }
  1338. /* }}} */
  1339. /* {{{ setup_verify
  1340. * calist is an array containing file and directory names. create a
  1341. * certificate store and add those certs to it for use in verification.
  1342. */
  1343. static X509_STORE * setup_verify(zval * calist TSRMLS_DC)
  1344. {
  1345. X509_STORE *store;
  1346. X509_LOOKUP * dir_lookup, * file_lookup;
  1347. HashPosition pos;
  1348. int ndirs = 0, nfiles = 0;
  1349. store = X509_STORE_new();
  1350. if (store == NULL) {
  1351. return NULL;
  1352. }
  1353. if (calist && (Z_TYPE_P(calist) == IS_ARRAY)) {
  1354. zend_hash_internal_pointer_reset_ex(HASH_OF(calist), &pos);
  1355. for (;; zend_hash_move_forward_ex(HASH_OF(calist), &pos)) {
  1356. zval ** item;
  1357. struct stat sb;
  1358. if (zend_hash_get_current_data_ex(HASH_OF(calist), (void**)&item, &pos) == FAILURE) {
  1359. break;
  1360. }
  1361. convert_to_string_ex(item);
  1362. if (VCWD_STAT(Z_STRVAL_PP(item), &sb) == -1) {
  1363. php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to stat %s", Z_STRVAL_PP(item));
  1364. continue;
  1365. }
  1366. if ((sb.st_mode & S_IFREG) == S_IFREG) {
  1367. file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  1368. if (file_lookup == NULL || !X509_LOOKUP_load_file(file_lookup, Z_STRVAL_PP(item), X509_FILETYPE_PEM)) {
  1369. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error loading file %s", Z_STRVAL_PP(item));
  1370. } else {
  1371. nfiles++;
  1372. }
  1373. file_lookup = NULL;
  1374. } else {
  1375. dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
  1376. if (dir_lookup == NULL || !X509_LOOKUP_add_dir(dir_lookup, Z_STRVAL_PP(item), X509_FILETYPE_PEM)) {
  1377. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error loading directory %s", Z_STRVAL_PP(item));
  1378. } else {
  1379. ndirs++;
  1380. }
  1381. dir_lookup = NULL;
  1382. }
  1383. }
  1384. }
  1385. if (nfiles == 0) {
  1386. file_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file());
  1387. if (file_lookup) {
  1388. X509_LOOKUP_load_file(file_lookup, NULL, X509_FILETYPE_DEFAULT);
  1389. }
  1390. }
  1391. if (ndirs == 0) {
  1392. dir_lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir());
  1393. if (dir_lookup) {
  1394. X509_LOOKUP_add_dir(dir_lookup, NULL, X509_FILETYPE_DEFAULT);
  1395. }
  1396. }
  1397. return store;
  1398. }
  1399. /* }}} */
  1400. /* {{{ proto resource openssl_x509_read(mixed cert)
  1401. Reads X.509 certificates */
  1402. PHP_FUNCTION(openssl_x509_read)
  1403. {
  1404. zval **cert;
  1405. X509 *x509;
  1406. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &cert) == FAILURE) {
  1407. return;
  1408. }
  1409. Z_TYPE_P(return_value) = IS_RESOURCE;
  1410. x509 = php_openssl_x509_from_zval(cert, 1, &Z_LVAL_P(return_value) TSRMLS_CC);
  1411. if (x509 == NULL) {
  1412. php_error_docref(NULL TSRMLS_CC, E_WARNING, "supplied parameter cannot be coerced into an X509 certificate!");
  1413. RETURN_FALSE;
  1414. }
  1415. }
  1416. /* }}} */
  1417. /* {{{ proto void openssl_x509_free(resource x509)
  1418. Frees X.509 certificates */
  1419. PHP_FUNCTION(openssl_x509_free)
  1420. {
  1421. zval *x509;
  1422. X509 *cert;
  1423. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &x509) == FAILURE) {
  1424. return;
  1425. }
  1426. ZEND_FETCH_RESOURCE(cert, X509 *, &x509, -1, "OpenSSL X.509", le_x509);
  1427. zend_list_delete(Z_LVAL_P(x509));
  1428. }
  1429. /* }}} */
  1430. /* }}} */
  1431. /* Pop all X509 from Stack and free them, free the stack afterwards */
  1432. static void php_sk_X509_free(STACK_OF(X509) * sk) /* {{{ */
  1433. {
  1434. for (;;) {
  1435. X509* x = sk_X509_pop(sk);
  1436. if (!x) break;
  1437. X509_free(x);
  1438. }
  1439. sk_X509_free(sk);
  1440. }
  1441. /* }}} */
  1442. static STACK_OF(X509) * php_array_to_X509_sk(zval ** zcerts TSRMLS_DC) /* {{{ */
  1443. {
  1444. HashPosition hpos;
  1445. zval ** zcertval;
  1446. STACK_OF(X509) * sk = NULL;
  1447. X509 * cert;
  1448. long certresource;
  1449. sk = sk_X509_new_null();
  1450. /* get certs */
  1451. if (Z_TYPE_PP(zcerts) == IS_ARRAY) {
  1452. zend_hash_internal_pointer_reset_ex(HASH_OF(*zcerts), &hpos);
  1453. while(zend_hash_get_current_data_ex(HASH_OF(*zcerts), (void**)&zcertval, &hpos) == SUCCESS) {
  1454. cert = php_openssl_x509_from_zval(zcertval, 0, &certresource TSRMLS_CC);
  1455. if (cert == NULL) {
  1456. goto clean_exit;
  1457. }
  1458. if (certresource != -1) {
  1459. cert = X509_dup(cert);
  1460. if (cert == NULL) {
  1461. goto clean_exit;
  1462. }
  1463. }
  1464. sk_X509_push(sk, cert);
  1465. zend_hash_move_forward_ex(HASH_OF(*zcerts), &hpos);
  1466. }
  1467. } else {
  1468. /* a single certificate */
  1469. cert = php_openssl_x509_from_zval(zcerts, 0, &certresource TSRMLS_CC);
  1470. if (cert == NULL) {
  1471. goto clean_exit;
  1472. }
  1473. if (certresource != -1) {
  1474. cert = X509_dup(cert);
  1475. if (cert == NULL) {
  1476. goto clean_exit;
  1477. }
  1478. }
  1479. sk_X509_push(sk, cert);
  1480. }
  1481. clean_exit:
  1482. return sk;
  1483. }
  1484. /* }}} */
  1485. /* {{{ proto bool openssl_pkcs12_export_to_file(mixed x509, string filename, mixed priv_key, string pass[, array args])
  1486. Creates and exports a PKCS to file */
  1487. PHP_FUNCTION(openssl_pkcs12_export_to_file)
  1488. {
  1489. X509 * cert = NULL;
  1490. BIO * bio_out = NULL;
  1491. PKCS12 * p12 = NULL;
  1492. char * filename;
  1493. char * friendly_name = NULL;
  1494. int filename_len;
  1495. char * pass;
  1496. int pass_len;
  1497. zval **zcert = NULL, *zpkey = NULL, *args = NULL;
  1498. EVP_PKEY *priv_key = NULL;
  1499. long certresource, keyresource;
  1500. zval ** item;
  1501. STACK_OF(X509) *ca = NULL;
  1502. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zszs|a", &zcert, &filename, &filename_len, &zpkey, &pass, &pass_len, &args) == FAILURE)
  1503. return;
  1504. RETVAL_FALSE;
  1505. if (strlen(filename) != filename_len) {
  1506. return;
  1507. }
  1508. cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC);
  1509. if (cert == NULL) {
  1510. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get cert from parameter 1");
  1511. return;
  1512. }
  1513. priv_key = php_openssl_evp_from_zval(&zpkey, 0, "", 1, &keyresource TSRMLS_CC);
  1514. if (priv_key == NULL) {
  1515. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get private key from parameter 3");
  1516. goto cleanup;
  1517. }
  1518. if (cert && !X509_check_private_key(cert, priv_key)) {
  1519. php_error_docref(NULL TSRMLS_CC, E_WARNING, "private key does not correspond to cert");
  1520. goto cleanup;
  1521. }
  1522. if (php_openssl_safe_mode_chk(filename TSRMLS_CC)) {
  1523. goto cleanup;
  1524. }
  1525. /* parse extra config from args array, promote this to an extra function */
  1526. if (args && zend_hash_find(Z_ARRVAL_P(args), "friendly_name", sizeof("friendly_name"), (void**)&item) == SUCCESS)
  1527. friendly_name = Z_STRVAL_PP(item);
  1528. /* certpbe (default RC2-40)
  1529. keypbe (default 3DES)
  1530. friendly_caname
  1531. */
  1532. if (args && zend_hash_find(Z_ARRVAL_P(args), "extracerts", sizeof("extracerts"), (void**)&item) == SUCCESS)
  1533. ca = php_array_to_X509_sk(item TSRMLS_CC);
  1534. /* end parse extra config */
  1535. /*PKCS12 *PKCS12_create(char *pass, char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca,
  1536. int nid_key, int nid_cert, int iter, int mac_iter, int keytype);*/
  1537. p12 = PKCS12_create(pass, friendly_name, priv_key, cert, ca, 0, 0, 0, 0, 0);
  1538. bio_out = BIO_new_file(filename, "w");
  1539. if (bio_out) {
  1540. i2d_PKCS12_bio(bio_out, p12);
  1541. RETVAL_TRUE;
  1542. } else {
  1543. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error opening file %s", filename);
  1544. }
  1545. BIO_free(bio_out);
  1546. PKCS12_free(p12);
  1547. php_sk_X509_free(ca);
  1548. cleanup:
  1549. if (keyresource == -1 && priv_key) {
  1550. EVP_PKEY_free(priv_key);
  1551. }
  1552. if (certresource == -1 && cert) {
  1553. X509_free(cert);
  1554. }
  1555. }
  1556. /* }}} */
  1557. /* {{{ proto bool openssl_pkcs12_export(mixed x509, string &out, mixed priv_key, string pass[, array args])
  1558. Creates and exports a PKCS12 to a var */
  1559. PHP_FUNCTION(openssl_pkcs12_export)
  1560. {
  1561. X509 * cert = NULL;
  1562. BIO * bio_out;
  1563. PKCS12 * p12 = NULL;
  1564. zval * zcert = NULL, *zout = NULL, *zpkey, *args = NULL;
  1565. EVP_PKEY *priv_key = NULL;
  1566. long certresource, keyresource;
  1567. char * pass;
  1568. int pass_len;
  1569. char * friendly_name = NULL;
  1570. zval ** item;
  1571. STACK_OF(X509) *ca = NULL;
  1572. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "zzzs|a", &zcert, &zout, &zpkey, &pass, &pass_len, &args) == FAILURE)
  1573. return;
  1574. RETVAL_FALSE;
  1575. cert = php_openssl_x509_from_zval(&zcert, 0, &certresource TSRMLS_CC);
  1576. if (cert == NULL) {
  1577. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get cert from parameter 1");
  1578. return;
  1579. }
  1580. priv_key = php_openssl_evp_from_zval(&zpkey, 0, "", 1, &keyresource TSRMLS_CC);
  1581. if (priv_key == NULL) {
  1582. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get private key from parameter 3");
  1583. goto cleanup;
  1584. }
  1585. if (cert && !X509_check_private_key(cert, priv_key)) {
  1586. php_error_docref(NULL TSRMLS_CC, E_WARNING, "private key does not correspond to cert");
  1587. goto cleanup;
  1588. }
  1589. /* parse extra config from args array, promote this to an extra function */
  1590. if (args && zend_hash_find(Z_ARRVAL_P(args), "friendly_name", sizeof("friendly_name"), (void**)&item) == SUCCESS)
  1591. friendly_name = Z_STRVAL_PP(item);
  1592. if (args && zend_hash_find(Z_ARRVAL_P(args), "extracerts", sizeof("extracerts"), (void**)&item) == SUCCESS)
  1593. ca = php_array_to_X509_sk(item TSRMLS_CC);
  1594. /* end parse extra config */
  1595. p12 = PKCS12_create(pass, friendly_name, priv_key, cert, ca, 0, 0, 0, 0, 0);
  1596. bio_out = BIO_new(BIO_s_mem());
  1597. if (i2d_PKCS12_bio(bio_out, p12)) {
  1598. BUF_MEM *bio_buf;
  1599. zval_dtor(zout);
  1600. BIO_get_mem_ptr(bio_out, &bio_buf);
  1601. ZVAL_STRINGL(zout, bio_buf->data, bio_buf->length, 1);
  1602. RETVAL_TRUE;
  1603. }
  1604. BIO_free(bio_out);
  1605. PKCS12_free(p12);
  1606. php_sk_X509_free(ca);
  1607. cleanup:
  1608. if (keyresource == -1 && priv_key) {
  1609. EVP_PKEY_free(priv_key);
  1610. }
  1611. if (certresource == -1 && cert) {
  1612. X509_free(cert);
  1613. }
  1614. }
  1615. /* }}} */
  1616. /* {{{ proto bool openssl_pkcs12_read(string PKCS12, array &certs, string pass)
  1617. Parses a PKCS12 to an array */
  1618. PHP_FUNCTION(openssl_pkcs12_read)
  1619. {
  1620. zval *zout = NULL, *zextracerts, *zcert, *zpkey;
  1621. char *pass, *zp12;
  1622. int pass_len, zp12_len;
  1623. PKCS12 * p12 = NULL;
  1624. EVP_PKEY * pkey = NULL;
  1625. X509 * cert = NULL;
  1626. STACK_OF(X509) * ca = NULL;
  1627. BIO * bio_in = NULL;
  1628. int i;
  1629. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szs", &zp12, &zp12_len, &zout, &pass, &pass_len) == FAILURE)
  1630. return;
  1631. RETVAL_FALSE;
  1632. bio_in = BIO_new(BIO_s_mem());
  1633. if(!BIO_write(bio_in, zp12, zp12_len))
  1634. goto cleanup;
  1635. if(d2i_PKCS12_bio(bio_in, &p12)) {
  1636. if(PKCS12_parse(p12, pass, &pkey, &cert, &ca)) {
  1637. BIO * bio_out;
  1638. zval_dtor(zout);
  1639. array_init(zout);
  1640. bio_out = BIO_new(BIO_s_mem());
  1641. if (PEM_write_bio_X509(bio_out, cert)) {
  1642. BUF_MEM *bio_buf;
  1643. BIO_get_mem_ptr(bio_out, &bio_buf);
  1644. MAKE_STD_ZVAL(zcert);
  1645. ZVAL_STRINGL(zcert, bio_buf->data, bio_buf->length, 1);
  1646. add_assoc_zval(zout, "cert", zcert);
  1647. }
  1648. BIO_free(bio_out);
  1649. bio_out = BIO_new(BIO_s_mem());
  1650. if (PEM_write_bio_PrivateKey(bio_out, pkey, NULL, NULL, 0, 0, NULL)) {
  1651. BUF_MEM *bio_buf;
  1652. BIO_get_mem_ptr(bio_out, &bio_buf);
  1653. MAKE_STD_ZVAL(zpkey);
  1654. ZVAL_STRINGL(zpkey, bio_buf->data, bio_buf->length, 1);
  1655. add_assoc_zval(zout, "pkey", zpkey);
  1656. }
  1657. BIO_free(bio_out);
  1658. MAKE_STD_ZVAL(zextracerts);
  1659. array_init(zextracerts);
  1660. for (i=0;;i++) {
  1661. zval * zextracert;
  1662. X509* aCA = sk_X509_pop(ca);
  1663. if (!aCA) break;
  1664. bio_out = BIO_new(BIO_s_mem());
  1665. if (PEM_write_bio_X509(bio_out, aCA)) {
  1666. BUF_MEM *bio_buf;
  1667. BIO_get_mem_ptr(bio_out, &bio_buf);
  1668. MAKE_STD_ZVAL(zextracert);
  1669. ZVAL_STRINGL(zextracert, bio_buf->data, bio_buf->length, 1);
  1670. add_index_zval(zextracerts, i, zextracert);
  1671. }
  1672. BIO_free(bio_out);
  1673. X509_free(aCA);
  1674. }
  1675. if(ca) {
  1676. sk_X509_free(ca);
  1677. add_assoc_zval(zout, "extracerts", zextracerts);
  1678. } else {
  1679. zval_dtor(zextracerts);
  1680. }
  1681. RETVAL_TRUE;
  1682. PKCS12_free(p12);
  1683. }
  1684. }
  1685. cleanup:
  1686. if (bio_in) {
  1687. BIO_free(bio_in);
  1688. }
  1689. if (pkey) {
  1690. EVP_PKEY_free(pkey);
  1691. }
  1692. if (cert) {
  1693. X509_free(cert);
  1694. }
  1695. }
  1696. /* }}} */
  1697. /* {{{ x509 CSR functions */
  1698. /* {{{ php_openssl_make_REQ */
  1699. static int php_openssl_make_REQ(struct php_x509_request * req, X509_REQ * csr, zval * dn, zval * attribs TSRMLS_DC)
  1700. {
  1701. STACK_OF(CONF_VALUE) * dn_sk, *attr_sk = NULL;
  1702. char * str, *dn_sect, *attr_sect;
  1703. dn_sect = CONF_get_string(req->req_config, req->section_name, "distinguished_name");
  1704. if (dn_sect == NULL) {
  1705. return FAILURE;
  1706. }
  1707. dn_sk = CONF_get_section(req->req_config, dn_sect);
  1708. if (dn_sk == NULL) {
  1709. return FAILURE;
  1710. }
  1711. attr_sect = CONF_get_string(req->req_config, req->section_name, "attributes");
  1712. if (attr_sect == NULL) {
  1713. attr_sk = NULL;
  1714. } else {
  1715. attr_sk = CONF_get_section(req->req_config, attr_sect);
  1716. if (attr_sk == NULL) {
  1717. return FAILURE;
  1718. }
  1719. }
  1720. /* setup the version number: version 1 */
  1721. if (X509_REQ_set_version(csr, 0L)) {
  1722. int i, nid;
  1723. char * type;
  1724. CONF_VALUE * v;
  1725. X509_NAME * subj;
  1726. HashPosition hpos;
  1727. zval ** item;
  1728. subj = X509_REQ_get_subject_name(csr);
  1729. /* apply values from the dn hash */
  1730. zend_hash_internal_pointer_reset_ex(HASH_OF(dn), &hpos);
  1731. while(zend_hash_get_current_data_ex(HASH_OF(dn), (void**)&item, &hpos) == SUCCESS) {
  1732. char * strindex = NULL;
  1733. uint strindexlen = 0;
  1734. ulong intindex;
  1735. zend_hash_get_current_key_ex(HASH_OF(dn), &strindex, &strindexlen, &intindex, 0, &hpos);
  1736. convert_to_string_ex(item);
  1737. if (strindex) {
  1738. int nid;
  1739. nid = OBJ_txt2nid(strindex);
  1740. if (nid != NID_undef) {
  1741. if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_ASC,
  1742. (unsigned char*)Z_STRVAL_PP(item), -1, -1, 0))
  1743. {
  1744. php_error_docref(NULL TSRMLS_CC, E_WARNING, "dn: add_entry_by_NID %d -> %s (failed)", nid, Z_STRVAL_PP(item));
  1745. return FAILURE;
  1746. }
  1747. } else {
  1748. php_error_docref(NULL TSRMLS_CC, E_WARNING, "dn: %s is not a recognized name", strindex);
  1749. }
  1750. }
  1751. zend_hash_move_forward_ex(HASH_OF(dn), &hpos);
  1752. }
  1753. /* Finally apply defaults from config file */
  1754. for(i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
  1755. int len;
  1756. char buffer[200 + 1]; /*200 + \0 !*/
  1757. v = sk_CONF_VALUE_value(dn_sk, i);
  1758. type = v->name;
  1759. len = strlen(type);
  1760. if (len < sizeof("_default")) {
  1761. continue;
  1762. }
  1763. len -= sizeof("_default") - 1;
  1764. if (strcmp("_default", type + len) != 0) {
  1765. continue;
  1766. }
  1767. if (len > 200) {
  1768. len = 200;
  1769. }
  1770. memcpy(buffer, type, len);
  1771. buffer[len] = '\0';
  1772. type = buffer;
  1773. /* Skip past any leading X. X: X, etc to allow for multiple
  1774. * instances */
  1775. for (str = type; *str; str++) {
  1776. if (*str == ':' || *str == ',' || *str == '.') {
  1777. str++;
  1778. if (*str) {
  1779. type = str;
  1780. }
  1781. break;
  1782. }
  1783. }
  1784. /* if it is already set, skip this */
  1785. nid = OBJ_txt2nid(type);
  1786. if (X509_NAME_get_index_by_NID(subj, nid, -1) >= 0) {
  1787. continue;
  1788. }
  1789. if (!X509_NAME_add_entry_by_txt(subj, type, MBSTRING_ASC, (unsigned char*)v->value, -1, -1, 0)) {
  1790. php_error_docref(NULL TSRMLS_CC, E_WARNING, "add_entry_by_txt %s -> %s (failed)", type, v->value);
  1791. return FAILURE;
  1792. }
  1793. if (!X509_NAME_entry_count(subj)) {
  1794. php_error_docref(NULL TSRMLS_CC, E_WARNING, "no objects specified in config file");
  1795. return FAILURE;
  1796. }
  1797. }
  1798. if (attribs) {
  1799. zend_hash_internal_pointer_reset_ex(HASH_OF(attribs), &hpos);
  1800. while(zend_hash_get_current_data_ex(HASH_OF(attribs), (void**)&item, &hpos) == SUCCESS) {
  1801. char *strindex = NULL;
  1802. uint strindexlen;
  1803. ulong intindex;
  1804. zend_hash_get_current_key_ex(HASH_OF(attribs), &strindex, &strindexlen, &intindex, 0, &hpos);
  1805. convert_to_string_ex(item);
  1806. if (strindex) {
  1807. int nid;
  1808. nid = OBJ_txt2nid(strindex);
  1809. if (nid != NID_undef) {
  1810. if (!X509_NAME_add_entry_by_NID(subj, nid, MBSTRING_ASC, (unsigned char*)Z_STRVAL_PP(item), -1, -1, 0)) {
  1811. php_error_docref(NULL TSRMLS_CC, E_WARNING, "attribs: add_entry_by_NID %d -> %s (failed)", nid, Z_STRVAL_PP(item));
  1812. return FAILURE;
  1813. }
  1814. } else {
  1815. php_error_docref(NULL TSRMLS_CC, E_WARNING, "dn: %s is not a recognized name", strindex);
  1816. }
  1817. }
  1818. zend_hash_move_forward_ex(HASH_OF(attribs), &hpos);
  1819. }
  1820. for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) {
  1821. v = sk_CONF_VALUE_value(attr_sk, i);
  1822. /* if it is already set, skip this */
  1823. nid = OBJ_txt2nid(v->name);
  1824. if (X509_REQ_get_attr_by_NID(csr, nid, -1) >= 0) {
  1825. continue;
  1826. }
  1827. if (!X509_REQ_add1_attr_by_txt(csr, v->name, MBSTRING_ASC, (unsigned char*)v->value, -1)) {
  1828. php_error_docref(NULL TSRMLS_CC, E_WARNING, "add1_attr_by_txt %s -> %s (failed)", v->name, v->value);
  1829. return FAILURE;
  1830. }
  1831. }
  1832. }
  1833. }
  1834. X509_REQ_set_pubkey(csr, req->priv_key);
  1835. return SUCCESS;
  1836. }
  1837. /* }}} */
  1838. /* {{{ php_openssl_csr_from_zval */
  1839. static X509_REQ * php_openssl_csr_from_zval(zval ** val, int makeresource, long * resourceval TSRMLS_DC)
  1840. {
  1841. X509_REQ * csr = NULL;
  1842. char * filename = NULL;
  1843. BIO * in;
  1844. if (resourceval) {
  1845. *resourceval = -1;
  1846. }
  1847. if (Z_TYPE_PP(val) == IS_RESOURCE) {
  1848. void * what;
  1849. int type;
  1850. what = zend_fetch_resource(val TSRMLS_CC, -1, "OpenSSL X.509 CSR", &type, 1, le_csr);
  1851. if (what) {
  1852. if (resourceval) {
  1853. *resourceval = Z_LVAL_PP(val);
  1854. }
  1855. return (X509_REQ*)what;
  1856. }
  1857. return NULL;
  1858. } else if (Z_TYPE_PP(val) != IS_STRING) {
  1859. return NULL;
  1860. }
  1861. if (Z_STRLEN_PP(val) > 7 && memcmp(Z_STRVAL_PP(val), "file://", sizeof("file://") - 1) == 0) {
  1862. filename = Z_STRVAL_PP(val) + (sizeof("file://") - 1);
  1863. }
  1864. if (filename) {
  1865. if (php_openssl_safe_mode_chk(filename TSRMLS_CC)) {
  1866. return NULL;
  1867. }
  1868. in = BIO_new_file(filename, "r");
  1869. } else {
  1870. in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val));
  1871. }
  1872. csr = PEM_read_bio_X509_REQ(in, NULL,NULL,NULL);
  1873. BIO_free(in);
  1874. return csr;
  1875. }
  1876. /* }}} */
  1877. /* {{{ proto bool openssl_csr_export_to_file(resource csr, string outfilename [, bool notext=true])
  1878. Exports a CSR to file */
  1879. PHP_FUNCTION(openssl_csr_export_to_file)
  1880. {
  1881. X509_REQ * csr;
  1882. zval * zcsr = NULL;
  1883. zend_bool notext = 1;
  1884. char * filename = NULL; int filename_len;
  1885. BIO * bio_out;
  1886. long csr_resource;
  1887. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|b", &zcsr, &filename, &filename_len, &notext) == FAILURE) {
  1888. return;
  1889. }
  1890. RETVAL_FALSE;
  1891. if (strlen(filename) != filename_len) {
  1892. return;
  1893. }
  1894. csr = php_openssl_csr_from_zval(&zcsr, 0, &csr_resource TSRMLS_CC);
  1895. if (csr == NULL) {
  1896. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get CSR from parameter 1");
  1897. return;
  1898. }
  1899. if (php_openssl_safe_mode_chk(filename TSRMLS_CC)) {
  1900. return;
  1901. }
  1902. bio_out = BIO_new_file(filename, "w");
  1903. if (bio_out) {
  1904. if (!notext) {
  1905. X509_REQ_print(bio_out, csr);
  1906. }
  1907. PEM_write_bio_X509_REQ(bio_out, csr);
  1908. RETVAL_TRUE;
  1909. } else {
  1910. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error opening file %s", filename);
  1911. }
  1912. if (csr_resource == -1 && csr) {
  1913. X509_REQ_free(csr);
  1914. }
  1915. BIO_free(bio_out);
  1916. }
  1917. /* }}} */
  1918. /* {{{ proto bool openssl_csr_export(resource csr, string &out [, bool notext=true])
  1919. Exports a CSR to file or a var */
  1920. PHP_FUNCTION(openssl_csr_export)
  1921. {
  1922. X509_REQ * csr;
  1923. zval * zcsr = NULL, *zout=NULL;
  1924. zend_bool notext = 1;
  1925. BIO * bio_out;
  1926. long csr_resource;
  1927. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rz|b", &zcsr, &zout, &notext) == FAILURE) {
  1928. return;
  1929. }
  1930. RETVAL_FALSE;
  1931. csr = php_openssl_csr_from_zval(&zcsr, 0, &csr_resource TSRMLS_CC);
  1932. if (csr == NULL) {
  1933. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get CSR from parameter 1");
  1934. return;
  1935. }
  1936. /* export to a var */
  1937. bio_out = BIO_new(BIO_s_mem());
  1938. if (!notext) {
  1939. X509_REQ_print(bio_out, csr);
  1940. }
  1941. if (PEM_write_bio_X509_REQ(bio_out, csr)) {
  1942. BUF_MEM *bio_buf;
  1943. BIO_get_mem_ptr(bio_out, &bio_buf);
  1944. zval_dtor(zout);
  1945. ZVAL_STRINGL(zout, bio_buf->data, bio_buf->length, 1);
  1946. RETVAL_TRUE;
  1947. }
  1948. if (csr_resource == -1 && csr) {
  1949. X509_REQ_free(csr);
  1950. }
  1951. BIO_free(bio_out);
  1952. }
  1953. /* }}} */
  1954. /* {{{ proto resource openssl_csr_sign(mixed csr, mixed x509, mixed priv_key, long days [, array config_args [, long serial]])
  1955. Signs a cert with another CERT */
  1956. PHP_FUNCTION(openssl_csr_sign)
  1957. {
  1958. zval ** zcert = NULL, **zcsr, **zpkey, *args = NULL;
  1959. long num_days;
  1960. long serial = 0L;
  1961. X509 * cert = NULL, *new_cert = NULL;
  1962. X509_REQ * csr;
  1963. EVP_PKEY * key = NULL, *priv_key = NULL;
  1964. long csr_resource, certresource = 0, keyresource = -1;
  1965. int i;
  1966. struct php_x509_request req;
  1967. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ZZ!Zl|a!l", &zcsr, &zcert, &zpkey, &num_days, &args, &serial) == FAILURE)
  1968. return;
  1969. RETVAL_FALSE;
  1970. PHP_SSL_REQ_INIT(&req);
  1971. csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource TSRMLS_CC);
  1972. if (csr == NULL) {
  1973. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get CSR from parameter 1");
  1974. return;
  1975. }
  1976. if (zcert) {
  1977. cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC);
  1978. if (cert == NULL) {
  1979. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get cert from parameter 2");
  1980. goto cleanup;
  1981. }
  1982. }
  1983. priv_key = php_openssl_evp_from_zval(zpkey, 0, "", 1, &keyresource TSRMLS_CC);
  1984. if (priv_key == NULL) {
  1985. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get private key from parameter 3");
  1986. goto cleanup;
  1987. }
  1988. if (cert && !X509_check_private_key(cert, priv_key)) {
  1989. php_error_docref(NULL TSRMLS_CC, E_WARNING, "private key does not correspond to signing cert");
  1990. goto cleanup;
  1991. }
  1992. if (PHP_SSL_REQ_PARSE(&req, args) == FAILURE) {
  1993. goto cleanup;
  1994. }
  1995. /* Check that the request matches the signature */
  1996. key = X509_REQ_get_pubkey(csr);
  1997. if (key == NULL) {
  1998. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error unpacking public key");
  1999. goto cleanup;
  2000. }
  2001. i = X509_REQ_verify(csr, key);
  2002. if (i < 0) {
  2003. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Signature verification problems");
  2004. goto cleanup;
  2005. }
  2006. else if (i == 0) {
  2007. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Signature did not match the certificate request");
  2008. goto cleanup;
  2009. }
  2010. /* Now we can get on with it */
  2011. new_cert = X509_new();
  2012. if (new_cert == NULL) {
  2013. php_error_docref(NULL TSRMLS_CC, E_WARNING, "No memory");
  2014. goto cleanup;
  2015. }
  2016. /* Version 3 cert */
  2017. if (!X509_set_version(new_cert, 2))
  2018. goto cleanup;
  2019. ASN1_INTEGER_set(X509_get_serialNumber(new_cert), serial);
  2020. X509_set_subject_name(new_cert, X509_REQ_get_subject_name(csr));
  2021. if (cert == NULL) {
  2022. cert = new_cert;
  2023. }
  2024. if (!X509_set_issuer_name(new_cert, X509_get_subject_name(cert))) {
  2025. goto cleanup;
  2026. }
  2027. X509_gmtime_adj(X509_get_notBefore(new_cert), 0);
  2028. X509_gmtime_adj(X509_get_notAfter(new_cert), (long)60*60*24*num_days);
  2029. i = X509_set_pubkey(new_cert, key);
  2030. if (!i) {
  2031. goto cleanup;
  2032. }
  2033. if (req.extensions_section) {
  2034. X509V3_CTX ctx;
  2035. X509V3_set_ctx(&ctx, cert, new_cert, csr, NULL, 0);
  2036. X509V3_set_conf_lhash(&ctx, req.req_config);
  2037. if (!X509V3_EXT_add_conf(req.req_config, &ctx, req.extensions_section, new_cert)) {
  2038. goto cleanup;
  2039. }
  2040. }
  2041. /* Now sign it */
  2042. if (!X509_sign(new_cert, priv_key, req.digest)) {
  2043. php_error_docref(NULL TSRMLS_CC, E_WARNING, "failed to sign it");
  2044. goto cleanup;
  2045. }
  2046. /* Succeeded; lets return the cert */
  2047. RETVAL_RESOURCE(zend_list_insert(new_cert, le_x509));
  2048. new_cert = NULL;
  2049. cleanup:
  2050. if (cert == new_cert) {
  2051. cert = NULL;
  2052. }
  2053. PHP_SSL_REQ_DISPOSE(&req);
  2054. if (keyresource == -1 && priv_key) {
  2055. EVP_PKEY_free(priv_key);
  2056. }
  2057. if (key) {
  2058. EVP_PKEY_free(key);
  2059. }
  2060. if (csr_resource == -1 && csr) {
  2061. X509_REQ_free(csr);
  2062. }
  2063. if (certresource == -1 && cert) {
  2064. X509_free(cert);
  2065. }
  2066. if (new_cert) {
  2067. X509_free(new_cert);
  2068. }
  2069. }
  2070. /* }}} */
  2071. /* {{{ proto bool openssl_csr_new(array dn, resource &privkey [, array configargs [, array extraattribs]])
  2072. Generates a privkey and CSR */
  2073. PHP_FUNCTION(openssl_csr_new)
  2074. {
  2075. struct php_x509_request req;
  2076. zval * args = NULL, * dn, *attribs = NULL;
  2077. zval * out_pkey;
  2078. X509_REQ * csr = NULL;
  2079. int we_made_the_key = 1;
  2080. long key_resource;
  2081. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "az|a!a!", &dn, &out_pkey, &args, &attribs) == FAILURE) {
  2082. return;
  2083. }
  2084. RETVAL_FALSE;
  2085. PHP_SSL_REQ_INIT(&req);
  2086. if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) {
  2087. /* Generate or use a private key */
  2088. if (Z_TYPE_P(out_pkey) != IS_NULL) {
  2089. req.priv_key = php_openssl_evp_from_zval(&out_pkey, 0, NULL, 0, &key_resource TSRMLS_CC);
  2090. if (req.priv_key != NULL) {
  2091. we_made_the_key = 0;
  2092. }
  2093. }
  2094. if (req.priv_key == NULL) {
  2095. php_openssl_generate_private_key(&req TSRMLS_CC);
  2096. }
  2097. if (req.priv_key == NULL) {
  2098. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to generate a private key");
  2099. } else {
  2100. csr = X509_REQ_new();
  2101. if (csr) {
  2102. if (php_openssl_make_REQ(&req, csr, dn, attribs TSRMLS_CC) == SUCCESS) {
  2103. X509V3_CTX ext_ctx;
  2104. X509V3_set_ctx(&ext_ctx, NULL, NULL, csr, NULL, 0);
  2105. X509V3_set_conf_lhash(&ext_ctx, req.req_config);
  2106. /* Add extensions */
  2107. if (req.request_extensions_section && !X509V3_EXT_REQ_add_conf(req.req_config,
  2108. &ext_ctx, req.request_extensions_section, csr))
  2109. {
  2110. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error loading extension section %s", req.request_extensions_section);
  2111. } else {
  2112. RETVAL_TRUE;
  2113. if (X509_REQ_sign(csr, req.priv_key, req.digest)) {
  2114. RETVAL_RESOURCE(zend_list_insert(csr, le_csr));
  2115. csr = NULL;
  2116. } else {
  2117. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Error signing request");
  2118. }
  2119. if (we_made_the_key) {
  2120. /* and a resource for the private key */
  2121. zval_dtor(out_pkey);
  2122. ZVAL_RESOURCE(out_pkey, zend_list_insert(req.priv_key, le_key));
  2123. req.priv_key = NULL; /* make sure the cleanup code doesn't zap it! */
  2124. } else if (key_resource != -1) {
  2125. req.priv_key = NULL; /* make sure the cleanup code doesn't zap it! */
  2126. }
  2127. }
  2128. }
  2129. else {
  2130. if (!we_made_the_key) {
  2131. /* if we have not made the key we are not supposed to zap it by calling dispose! */
  2132. req.priv_key = NULL;
  2133. }
  2134. }
  2135. }
  2136. }
  2137. }
  2138. if (csr) {
  2139. X509_REQ_free(csr);
  2140. }
  2141. PHP_SSL_REQ_DISPOSE(&req);
  2142. }
  2143. /* }}} */
  2144. /* {{{ proto mixed openssl_csr_get_subject(mixed csr)
  2145. Returns the subject of a CERT or FALSE on error */
  2146. PHP_FUNCTION(openssl_csr_get_subject)
  2147. {
  2148. zval ** zcsr;
  2149. zend_bool use_shortnames = 1;
  2150. long csr_resource;
  2151. X509_NAME * subject;
  2152. X509_REQ * csr;
  2153. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|b", &zcsr, &use_shortnames) == FAILURE) {
  2154. return;
  2155. }
  2156. csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource TSRMLS_CC);
  2157. if (csr == NULL) {
  2158. RETURN_FALSE;
  2159. }
  2160. subject = X509_REQ_get_subject_name(csr);
  2161. array_init(return_value);
  2162. add_assoc_name_entry(return_value, NULL, subject, use_shortnames TSRMLS_CC);
  2163. return;
  2164. }
  2165. /* }}} */
  2166. /* {{{ proto mixed openssl_csr_get_public_key(mixed csr)
  2167. Returns the subject of a CERT or FALSE on error */
  2168. PHP_FUNCTION(openssl_csr_get_public_key)
  2169. {
  2170. zval ** zcsr;
  2171. zend_bool use_shortnames = 1;
  2172. long csr_resource;
  2173. X509_REQ * csr;
  2174. EVP_PKEY *tpubkey;
  2175. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|b", &zcsr, &use_shortnames) == FAILURE) {
  2176. return;
  2177. }
  2178. csr = php_openssl_csr_from_zval(zcsr, 0, &csr_resource TSRMLS_CC);
  2179. if (csr == NULL) {
  2180. RETURN_FALSE;
  2181. }
  2182. tpubkey=X509_REQ_get_pubkey(csr);
  2183. RETVAL_RESOURCE(zend_list_insert(tpubkey, le_key));
  2184. return;
  2185. }
  2186. /* }}} */
  2187. /* }}} */
  2188. /* {{{ EVP Public/Private key functions */
  2189. /* {{{ php_openssl_evp_from_zval
  2190. Given a zval, coerce it into a EVP_PKEY object.
  2191. It can be:
  2192. 1. private key resource from openssl_get_privatekey()
  2193. 2. X509 resource -> public key will be extracted from it
  2194. 3. if it starts with file:// interpreted as path to key file
  2195. 4. interpreted as the data from the cert/key file and interpreted in same way as openssl_get_privatekey()
  2196. 5. an array(0 => [items 2..4], 1 => passphrase)
  2197. 6. if val is a string (possibly starting with file:///) and it is not an X509 certificate, then interpret as public key
  2198. NOTE: If you are requesting a private key but have not specified a passphrase, you should use an
  2199. empty string rather than NULL for the passphrase - NULL causes a passphrase prompt to be emitted in
  2200. the Apache error log!
  2201. */
  2202. static EVP_PKEY * php_openssl_evp_from_zval(zval ** val, int public_key, char * passphrase, int makeresource, long * resourceval TSRMLS_DC)
  2203. {
  2204. EVP_PKEY * key = NULL;
  2205. X509 * cert = NULL;
  2206. int free_cert = 0;
  2207. long cert_res = -1;
  2208. char * filename = NULL;
  2209. zval tmp;
  2210. Z_TYPE(tmp) = IS_NULL;
  2211. #define TMP_CLEAN \
  2212. if (Z_TYPE(tmp) == IS_STRING) {\
  2213. zval_dtor(&tmp); \
  2214. } \
  2215. return NULL;
  2216. if (resourceval) {
  2217. *resourceval = -1;
  2218. }
  2219. if (Z_TYPE_PP(val) == IS_ARRAY) {
  2220. zval ** zphrase;
  2221. /* get passphrase */
  2222. if (zend_hash_index_find(HASH_OF(*val), 1, (void **)&zphrase) == FAILURE) {
  2223. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key array must be of the form array(0 => key, 1 => phrase)");
  2224. return NULL;
  2225. }
  2226. if (Z_TYPE_PP(zphrase) == IS_STRING) {
  2227. passphrase = Z_STRVAL_PP(zphrase);
  2228. } else {
  2229. tmp = **zphrase;
  2230. zval_copy_ctor(&tmp);
  2231. convert_to_string(&tmp);
  2232. passphrase = Z_STRVAL(tmp);
  2233. }
  2234. /* now set val to be the key param and continue */
  2235. if (zend_hash_index_find(HASH_OF(*val), 0, (void **)&val) == FAILURE) {
  2236. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key array must be of the form array(0 => key, 1 => phrase)");
  2237. TMP_CLEAN;
  2238. }
  2239. }
  2240. if (Z_TYPE_PP(val) == IS_RESOURCE) {
  2241. void * what;
  2242. int type;
  2243. what = zend_fetch_resource(val TSRMLS_CC, -1, "OpenSSL X.509/key", &type, 2, le_x509, le_key);
  2244. if (!what) {
  2245. TMP_CLEAN;
  2246. }
  2247. if (resourceval) {
  2248. *resourceval = Z_LVAL_PP(val);
  2249. }
  2250. if (type == le_x509) {
  2251. /* extract key from cert, depending on public_key param */
  2252. cert = (X509*)what;
  2253. free_cert = 0;
  2254. } else if (type == le_key) {
  2255. int is_priv;
  2256. is_priv = php_openssl_is_private_key((EVP_PKEY*)what TSRMLS_CC);
  2257. /* check whether it is actually a private key if requested */
  2258. if (!public_key && !is_priv) {
  2259. php_error_docref(NULL TSRMLS_CC, E_WARNING, "supplied key param is a public key");
  2260. TMP_CLEAN;
  2261. }
  2262. if (public_key && is_priv) {
  2263. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Don't know how to get public key from this private key");
  2264. TMP_CLEAN;
  2265. } else {
  2266. if (Z_TYPE(tmp) == IS_STRING) {
  2267. zval_dtor(&tmp);
  2268. }
  2269. /* got the key - return it */
  2270. return (EVP_PKEY*)what;
  2271. }
  2272. } else {
  2273. /* other types could be used here - eg: file pointers and read in the data from them */
  2274. TMP_CLEAN;
  2275. }
  2276. } else {
  2277. /* force it to be a string and check if it refers to a file */
  2278. /* passing non string values leaks, object uses toString, it returns NULL
  2279. * See bug38255.phpt
  2280. */
  2281. if (!(Z_TYPE_PP(val) == IS_STRING || Z_TYPE_PP(val) == IS_OBJECT)) {
  2282. TMP_CLEAN;
  2283. }
  2284. convert_to_string_ex(val);
  2285. if (Z_STRLEN_PP(val) > 7 && memcmp(Z_STRVAL_PP(val), "file://", sizeof("file://") - 1) == 0) {
  2286. filename = Z_STRVAL_PP(val) + (sizeof("file://") - 1);
  2287. }
  2288. /* it's an X509 file/cert of some kind, and we need to extract the data from that */
  2289. if (public_key) {
  2290. cert = php_openssl_x509_from_zval(val, 0, &cert_res TSRMLS_CC);
  2291. free_cert = (cert_res == -1);
  2292. /* actual extraction done later */
  2293. if (!cert) {
  2294. /* not a X509 certificate, try to retrieve public key */
  2295. BIO* in;
  2296. if (filename) {
  2297. in = BIO_new_file(filename, "r");
  2298. } else {
  2299. in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val));
  2300. }
  2301. if (in == NULL) {
  2302. TMP_CLEAN;
  2303. }
  2304. key = PEM_read_bio_PUBKEY(in, NULL,NULL, NULL);
  2305. BIO_free(in);
  2306. }
  2307. } else {
  2308. /* we want the private key */
  2309. BIO *in;
  2310. if (filename) {
  2311. if (php_openssl_safe_mode_chk(filename TSRMLS_CC)) {
  2312. TMP_CLEAN;
  2313. }
  2314. in = BIO_new_file(filename, "r");
  2315. } else {
  2316. in = BIO_new_mem_buf(Z_STRVAL_PP(val), Z_STRLEN_PP(val));
  2317. }
  2318. if (in == NULL) {
  2319. TMP_CLEAN;
  2320. }
  2321. key = PEM_read_bio_PrivateKey(in, NULL,NULL, passphrase);
  2322. BIO_free(in);
  2323. }
  2324. }
  2325. if (public_key && cert && key == NULL) {
  2326. /* extract public key from X509 cert */
  2327. key = (EVP_PKEY *) X509_get_pubkey(cert);
  2328. }
  2329. if (free_cert && cert) {
  2330. X509_free(cert);
  2331. }
  2332. if (key && makeresource && resourceval) {
  2333. *resourceval = ZEND_REGISTER_RESOURCE(NULL, key, le_key);
  2334. }
  2335. if (Z_TYPE(tmp) == IS_STRING) {
  2336. zval_dtor(&tmp);
  2337. }
  2338. return key;
  2339. }
  2340. /* }}} */
  2341. /* {{{ php_openssl_generate_private_key */
  2342. static EVP_PKEY * php_openssl_generate_private_key(struct php_x509_request * req TSRMLS_DC)
  2343. {
  2344. char * randfile = NULL;
  2345. int egdsocket, seeded;
  2346. EVP_PKEY * return_val = NULL;
  2347. if (req->priv_key_bits < MIN_KEY_LENGTH) {
  2348. php_error_docref(NULL TSRMLS_CC, E_WARNING, "private key length is too short; it needs to be at least %d bits, not %d",
  2349. MIN_KEY_LENGTH, req->priv_key_bits);
  2350. return NULL;
  2351. }
  2352. randfile = CONF_get_string(req->req_config, req->section_name, "RANDFILE");
  2353. php_openssl_load_rand_file(randfile, &egdsocket, &seeded);
  2354. if ((req->priv_key = EVP_PKEY_new()) != NULL) {
  2355. switch(req->priv_key_type) {
  2356. case OPENSSL_KEYTYPE_RSA:
  2357. if (EVP_PKEY_assign_RSA(req->priv_key, RSA_generate_key(req->priv_key_bits, 0x10001, NULL, NULL))) {
  2358. return_val = req->priv_key;
  2359. }
  2360. break;
  2361. #if !defined(NO_DSA) && defined(HAVE_DSA_DEFAULT_METHOD)
  2362. case OPENSSL_KEYTYPE_DSA:
  2363. {
  2364. DSA *dsapar = DSA_generate_parameters(req->priv_key_bits, NULL, 0, NULL, NULL, NULL, NULL);
  2365. if (dsapar) {
  2366. DSA_set_method(dsapar, DSA_get_default_method());
  2367. if (DSA_generate_key(dsapar)) {
  2368. if (EVP_PKEY_assign_DSA(req->priv_key, dsapar)) {
  2369. return_val = req->priv_key;
  2370. }
  2371. } else {
  2372. DSA_free(dsapar);
  2373. }
  2374. }
  2375. }
  2376. break;
  2377. #endif
  2378. #if !defined(NO_DH)
  2379. case OPENSSL_KEYTYPE_DH:
  2380. {
  2381. DH *dhpar = DH_generate_parameters(req->priv_key_bits, 2, NULL, NULL);
  2382. int codes = 0;
  2383. if (dhpar) {
  2384. DH_set_method(dhpar, DH_get_default_method());
  2385. if (DH_check(dhpar, &codes) && codes == 0 && DH_generate_key(dhpar)) {
  2386. if (EVP_PKEY_assign_DH(req->priv_key, dhpar)) {
  2387. return_val = req->priv_key;
  2388. }
  2389. } else {
  2390. DH_free(dhpar);
  2391. }
  2392. }
  2393. }
  2394. break;
  2395. #endif
  2396. default:
  2397. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unsupported private key type");
  2398. }
  2399. }
  2400. php_openssl_write_rand_file(randfile, egdsocket, seeded);
  2401. if (return_val == NULL) {
  2402. EVP_PKEY_free(req->priv_key);
  2403. req->priv_key = NULL;
  2404. return NULL;
  2405. }
  2406. return return_val;
  2407. }
  2408. /* }}} */
  2409. /* {{{ php_openssl_is_private_key
  2410. Check whether the supplied key is a private key by checking if the secret prime factors are set */
  2411. static int php_openssl_is_private_key(EVP_PKEY* pkey TSRMLS_DC)
  2412. {
  2413. assert(pkey != NULL);
  2414. switch (pkey->type) {
  2415. #ifndef NO_RSA
  2416. case EVP_PKEY_RSA:
  2417. case EVP_PKEY_RSA2:
  2418. assert(pkey->pkey.rsa != NULL);
  2419. if (pkey->pkey.rsa != NULL && (NULL == pkey->pkey.rsa->p || NULL == pkey->pkey.rsa->q)) {
  2420. return 0;
  2421. }
  2422. break;
  2423. #endif
  2424. #ifndef NO_DSA
  2425. case EVP_PKEY_DSA:
  2426. case EVP_PKEY_DSA1:
  2427. case EVP_PKEY_DSA2:
  2428. case EVP_PKEY_DSA3:
  2429. case EVP_PKEY_DSA4:
  2430. assert(pkey->pkey.dsa != NULL);
  2431. if (NULL == pkey->pkey.dsa->p || NULL == pkey->pkey.dsa->q || NULL == pkey->pkey.dsa->priv_key){
  2432. return 0;
  2433. }
  2434. break;
  2435. #endif
  2436. #ifndef NO_DH
  2437. case EVP_PKEY_DH:
  2438. assert(pkey->pkey.dh != NULL);
  2439. if (NULL == pkey->pkey.dh->p || NULL == pkey->pkey.dh->priv_key) {
  2440. return 0;
  2441. }
  2442. break;
  2443. #endif
  2444. default:
  2445. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key type not supported in this PHP build!");
  2446. break;
  2447. }
  2448. return 1;
  2449. }
  2450. /* }}} */
  2451. #define OPENSSL_PKEY_GET_BN(_type, _name) do { \
  2452. if (pkey->pkey._type->_name != NULL) { \
  2453. int len = BN_num_bytes(pkey->pkey._type->_name); \
  2454. char *str = emalloc(len + 1); \
  2455. BN_bn2bin(pkey->pkey._type->_name, (unsigned char*)str); \
  2456. str[len] = 0; \
  2457. add_assoc_stringl(_type, #_name, str, len, 0); \
  2458. } \
  2459. } while (0)
  2460. #define OPENSSL_PKEY_SET_BN(_ht, _type, _name) do { \
  2461. zval **bn; \
  2462. if (zend_hash_find(_ht, #_name, sizeof(#_name), (void**)&bn) == SUCCESS && \
  2463. Z_TYPE_PP(bn) == IS_STRING) { \
  2464. _type->_name = BN_bin2bn( \
  2465. (unsigned char*)Z_STRVAL_PP(bn), \
  2466. Z_STRLEN_PP(bn), NULL); \
  2467. } \
  2468. } while (0);
  2469. /* {{{ proto resource openssl_pkey_new([array configargs])
  2470. Generates a new private key */
  2471. PHP_FUNCTION(openssl_pkey_new)
  2472. {
  2473. struct php_x509_request req;
  2474. zval * args = NULL;
  2475. zval **data;
  2476. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|a!", &args) == FAILURE) {
  2477. return;
  2478. }
  2479. RETVAL_FALSE;
  2480. if (args && Z_TYPE_P(args) == IS_ARRAY) {
  2481. EVP_PKEY *pkey;
  2482. if (zend_hash_find(Z_ARRVAL_P(args), "rsa", sizeof("rsa"), (void**)&data) == SUCCESS &&
  2483. Z_TYPE_PP(data) == IS_ARRAY) {
  2484. pkey = EVP_PKEY_new();
  2485. if (pkey) {
  2486. RSA *rsa = RSA_new();
  2487. if (rsa) {
  2488. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, n);
  2489. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, e);
  2490. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, d);
  2491. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, p);
  2492. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, q);
  2493. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, dmp1);
  2494. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, dmq1);
  2495. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), rsa, iqmp);
  2496. if (rsa->n && rsa->d) {
  2497. if (EVP_PKEY_assign_RSA(pkey, rsa)) {
  2498. RETURN_RESOURCE(zend_list_insert(pkey, le_key));
  2499. }
  2500. }
  2501. RSA_free(rsa);
  2502. }
  2503. EVP_PKEY_free(pkey);
  2504. }
  2505. RETURN_FALSE;
  2506. } else if (zend_hash_find(Z_ARRVAL_P(args), "dsa", sizeof("dsa"), (void**)&data) == SUCCESS &&
  2507. Z_TYPE_PP(data) == IS_ARRAY) {
  2508. pkey = EVP_PKEY_new();
  2509. if (pkey) {
  2510. DSA *dsa = DSA_new();
  2511. if (dsa) {
  2512. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, p);
  2513. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, q);
  2514. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, g);
  2515. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, priv_key);
  2516. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dsa, pub_key);
  2517. if (dsa->p && dsa->q && dsa->g) {
  2518. if (!dsa->priv_key && !dsa->pub_key) {
  2519. DSA_generate_key(dsa);
  2520. }
  2521. if (EVP_PKEY_assign_DSA(pkey, dsa)) {
  2522. RETURN_RESOURCE(zend_list_insert(pkey, le_key));
  2523. }
  2524. }
  2525. DSA_free(dsa);
  2526. }
  2527. EVP_PKEY_free(pkey);
  2528. }
  2529. RETURN_FALSE;
  2530. } else if (zend_hash_find(Z_ARRVAL_P(args), "dh", sizeof("dh"), (void**)&data) == SUCCESS &&
  2531. Z_TYPE_PP(data) == IS_ARRAY) {
  2532. pkey = EVP_PKEY_new();
  2533. if (pkey) {
  2534. DH *dh = DH_new();
  2535. if (dh) {
  2536. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dh, p);
  2537. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dh, g);
  2538. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dh, priv_key);
  2539. OPENSSL_PKEY_SET_BN(Z_ARRVAL_PP(data), dh, pub_key);
  2540. if (dh->p && dh->g) {
  2541. if (!dh->pub_key) {
  2542. DH_generate_key(dh);
  2543. }
  2544. if (EVP_PKEY_assign_DH(pkey, dh)) {
  2545. RETURN_RESOURCE(zend_list_insert(pkey, le_key));
  2546. }
  2547. }
  2548. DH_free(dh);
  2549. }
  2550. EVP_PKEY_free(pkey);
  2551. }
  2552. RETURN_FALSE;
  2553. }
  2554. }
  2555. PHP_SSL_REQ_INIT(&req);
  2556. if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS)
  2557. {
  2558. if (php_openssl_generate_private_key(&req TSRMLS_CC)) {
  2559. /* pass back a key resource */
  2560. RETVAL_RESOURCE(zend_list_insert(req.priv_key, le_key));
  2561. /* make sure the cleanup code doesn't zap it! */
  2562. req.priv_key = NULL;
  2563. }
  2564. }
  2565. PHP_SSL_REQ_DISPOSE(&req);
  2566. }
  2567. /* }}} */
  2568. /* {{{ proto bool openssl_pkey_export_to_file(mixed key, string outfilename [, string passphrase, array config_args)
  2569. Gets an exportable representation of a key into a file */
  2570. PHP_FUNCTION(openssl_pkey_export_to_file)
  2571. {
  2572. struct php_x509_request req;
  2573. zval ** zpkey, * args = NULL;
  2574. char * passphrase = NULL; int passphrase_len = 0;
  2575. char * filename = NULL; int filename_len = 0;
  2576. long key_resource = -1;
  2577. EVP_PKEY * key;
  2578. BIO * bio_out = NULL;
  2579. const EVP_CIPHER * cipher;
  2580. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zs|s!a!", &zpkey, &filename, &filename_len, &passphrase, &passphrase_len, &args) == FAILURE) {
  2581. return;
  2582. }
  2583. RETVAL_FALSE;
  2584. if (strlen(filename) != filename_len) {
  2585. return;
  2586. }
  2587. key = php_openssl_evp_from_zval(zpkey, 0, passphrase, 0, &key_resource TSRMLS_CC);
  2588. if (key == NULL) {
  2589. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get key from parameter 1");
  2590. RETURN_FALSE;
  2591. }
  2592. if (php_openssl_safe_mode_chk(filename TSRMLS_CC)) {
  2593. RETURN_FALSE;
  2594. }
  2595. PHP_SSL_REQ_INIT(&req);
  2596. if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) {
  2597. bio_out = BIO_new_file(filename, "w");
  2598. if (passphrase && req.priv_key_encrypt) {
  2599. cipher = (EVP_CIPHER *) EVP_des_ede3_cbc();
  2600. } else {
  2601. cipher = NULL;
  2602. }
  2603. if (PEM_write_bio_PrivateKey(bio_out, key, cipher, (unsigned char *)passphrase, passphrase_len, NULL, NULL)) {
  2604. /* Success!
  2605. * If returning the output as a string, do so now */
  2606. RETVAL_TRUE;
  2607. }
  2608. }
  2609. PHP_SSL_REQ_DISPOSE(&req);
  2610. if (key_resource == -1 && key) {
  2611. EVP_PKEY_free(key);
  2612. }
  2613. if (bio_out) {
  2614. BIO_free(bio_out);
  2615. }
  2616. }
  2617. /* }}} */
  2618. /* {{{ proto bool openssl_pkey_export(mixed key, &mixed out [, string passphrase [, array config_args]])
  2619. Gets an exportable representation of a key into a string or file */
  2620. PHP_FUNCTION(openssl_pkey_export)
  2621. {
  2622. struct php_x509_request req;
  2623. zval ** zpkey, * args = NULL, *out;
  2624. char * passphrase = NULL; int passphrase_len = 0;
  2625. long key_resource = -1;
  2626. EVP_PKEY * key;
  2627. BIO * bio_out = NULL;
  2628. const EVP_CIPHER * cipher;
  2629. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zz|s!a!", &zpkey, &out, &passphrase, &passphrase_len, &args) == FAILURE) {
  2630. return;
  2631. }
  2632. RETVAL_FALSE;
  2633. key = php_openssl_evp_from_zval(zpkey, 0, passphrase, 0, &key_resource TSRMLS_CC);
  2634. if (key == NULL) {
  2635. php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot get key from parameter 1");
  2636. RETURN_FALSE;
  2637. }
  2638. PHP_SSL_REQ_INIT(&req);
  2639. if (PHP_SSL_REQ_PARSE(&req, args) == SUCCESS) {
  2640. bio_out = BIO_new(BIO_s_mem());
  2641. if (passphrase && req.priv_key_encrypt) {
  2642. cipher = (EVP_CIPHER *) EVP_des_ede3_cbc();
  2643. } else {
  2644. cipher = NULL;
  2645. }
  2646. if (PEM_write_bio_PrivateKey(bio_out, key, cipher, (unsigned char *)passphrase, passphrase_len, NULL, NULL)) {
  2647. /* Success!
  2648. * If returning the output as a string, do so now */
  2649. char * bio_mem_ptr;
  2650. long bio_mem_len;
  2651. RETVAL_TRUE;
  2652. bio_mem_len = BIO_get_mem_data(bio_out, &bio_mem_ptr);
  2653. zval_dtor(out);
  2654. ZVAL_STRINGL(out, bio_mem_ptr, bio_mem_len, 1);
  2655. }
  2656. }
  2657. PHP_SSL_REQ_DISPOSE(&req);
  2658. if (key_resource == -1 && key) {
  2659. EVP_PKEY_free(key);
  2660. }
  2661. if (bio_out) {
  2662. BIO_free(bio_out);
  2663. }
  2664. }
  2665. /* }}} */
  2666. /* {{{ proto int openssl_pkey_get_public(mixed cert)
  2667. Gets public key from X.509 certificate */
  2668. PHP_FUNCTION(openssl_pkey_get_public)
  2669. {
  2670. zval **cert;
  2671. EVP_PKEY *pkey;
  2672. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z", &cert) == FAILURE) {
  2673. return;
  2674. }
  2675. Z_TYPE_P(return_value) = IS_RESOURCE;
  2676. pkey = php_openssl_evp_from_zval(cert, 1, NULL, 1, &Z_LVAL_P(return_value) TSRMLS_CC);
  2677. if (pkey == NULL) {
  2678. RETURN_FALSE;
  2679. }
  2680. }
  2681. /* }}} */
  2682. /* {{{ proto void openssl_pkey_free(int key)
  2683. Frees a key */
  2684. PHP_FUNCTION(openssl_pkey_free)
  2685. {
  2686. zval *key;
  2687. EVP_PKEY *pkey;
  2688. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &key) == FAILURE) {
  2689. return;
  2690. }
  2691. ZEND_FETCH_RESOURCE(pkey, EVP_PKEY *, &key, -1, "OpenSSL key", le_key);
  2692. zend_list_delete(Z_LVAL_P(key));
  2693. }
  2694. /* }}} */
  2695. /* {{{ proto int openssl_pkey_get_private(string key [, string passphrase])
  2696. Gets private keys */
  2697. PHP_FUNCTION(openssl_pkey_get_private)
  2698. {
  2699. zval **cert;
  2700. EVP_PKEY *pkey;
  2701. char * passphrase = "";
  2702. int passphrase_len = sizeof("")-1;
  2703. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Z|s", &cert, &passphrase, &passphrase_len) == FAILURE) {
  2704. return;
  2705. }
  2706. Z_TYPE_P(return_value) = IS_RESOURCE;
  2707. pkey = php_openssl_evp_from_zval(cert, 0, passphrase, 1, &Z_LVAL_P(return_value) TSRMLS_CC);
  2708. if (pkey == NULL) {
  2709. RETURN_FALSE;
  2710. }
  2711. }
  2712. /* }}} */
  2713. /* {{{ proto resource openssl_pkey_get_details(resource key)
  2714. returns an array with the key details (bits, pkey, type)*/
  2715. PHP_FUNCTION(openssl_pkey_get_details)
  2716. {
  2717. zval *key;
  2718. EVP_PKEY *pkey;
  2719. BIO *out;
  2720. unsigned int pbio_len;
  2721. char *pbio;
  2722. long ktype;
  2723. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &key) == FAILURE) {
  2724. return;
  2725. }
  2726. ZEND_FETCH_RESOURCE(pkey, EVP_PKEY *, &key, -1, "OpenSSL key", le_key);
  2727. if (!pkey) {
  2728. RETURN_FALSE;
  2729. }
  2730. out = BIO_new(BIO_s_mem());
  2731. PEM_write_bio_PUBKEY(out, pkey);
  2732. pbio_len = BIO_get_mem_data(out, &pbio);
  2733. array_init(return_value);
  2734. add_assoc_long(return_value, "bits", EVP_PKEY_bits(pkey));
  2735. add_assoc_stringl(return_value, "key", pbio, pbio_len, 1);
  2736. /*TODO: Use the real values once the openssl constants are used
  2737. * See the enum at the top of this file
  2738. */
  2739. switch (EVP_PKEY_type(pkey->type)) {
  2740. case EVP_PKEY_RSA:
  2741. case EVP_PKEY_RSA2:
  2742. ktype = OPENSSL_KEYTYPE_RSA;
  2743. if (pkey->pkey.rsa != NULL) {
  2744. zval *rsa;
  2745. ALLOC_INIT_ZVAL(rsa);
  2746. array_init(rsa);
  2747. OPENSSL_PKEY_GET_BN(rsa, n);
  2748. OPENSSL_PKEY_GET_BN(rsa, e);
  2749. OPENSSL_PKEY_GET_BN(rsa, d);
  2750. OPENSSL_PKEY_GET_BN(rsa, p);
  2751. OPENSSL_PKEY_GET_BN(rsa, q);
  2752. OPENSSL_PKEY_GET_BN(rsa, dmp1);
  2753. OPENSSL_PKEY_GET_BN(rsa, dmq1);
  2754. OPENSSL_PKEY_GET_BN(rsa, iqmp);
  2755. add_assoc_zval(return_value, "rsa", rsa);
  2756. }
  2757. break;
  2758. case EVP_PKEY_DSA:
  2759. case EVP_PKEY_DSA2:
  2760. case EVP_PKEY_DSA3:
  2761. case EVP_PKEY_DSA4:
  2762. ktype = OPENSSL_KEYTYPE_DSA;
  2763. if (pkey->pkey.dsa != NULL) {
  2764. zval *dsa;
  2765. ALLOC_INIT_ZVAL(dsa);
  2766. array_init(dsa);
  2767. OPENSSL_PKEY_GET_BN(dsa, p);
  2768. OPENSSL_PKEY_GET_BN(dsa, q);
  2769. OPENSSL_PKEY_GET_BN(dsa, g);
  2770. OPENSSL_PKEY_GET_BN(dsa, priv_key);
  2771. OPENSSL_PKEY_GET_BN(dsa, pub_key);
  2772. add_assoc_zval(return_value, "dsa", dsa);
  2773. }
  2774. break;
  2775. case EVP_PKEY_DH:
  2776. ktype = OPENSSL_KEYTYPE_DH;
  2777. if (pkey->pkey.dh != NULL) {
  2778. zval *dh;
  2779. ALLOC_INIT_ZVAL(dh);
  2780. array_init(dh);
  2781. OPENSSL_PKEY_GET_BN(dh, p);
  2782. OPENSSL_PKEY_GET_BN(dh, g);
  2783. OPENSSL_PKEY_GET_BN(dh, priv_key);
  2784. OPENSSL_PKEY_GET_BN(dh, pub_key);
  2785. add_assoc_zval(return_value, "dh", dh);
  2786. }
  2787. break;
  2788. #ifdef EVP_PKEY_EC
  2789. case EVP_PKEY_EC:
  2790. ktype = OPENSSL_KEYTYPE_EC;
  2791. break;
  2792. #endif
  2793. default:
  2794. ktype = -1;
  2795. break;
  2796. }
  2797. add_assoc_long(return_value, "type", ktype);
  2798. BIO_free(out);
  2799. }
  2800. /* }}} */
  2801. /* }}} */
  2802. /* {{{ PKCS7 S/MIME functions */
  2803. /* {{{ proto bool openssl_pkcs7_verify(string filename, long flags [, string signerscerts [, array cainfo [, string extracerts [, string content]]]])
  2804. Verifys that the data block is intact, the signer is who they say they are, and returns the CERTs of the signers */
  2805. PHP_FUNCTION(openssl_pkcs7_verify)
  2806. {
  2807. X509_STORE * store = NULL;
  2808. zval * cainfo = NULL;
  2809. STACK_OF(X509) *signers= NULL;
  2810. STACK_OF(X509) *others = NULL;
  2811. PKCS7 * p7 = NULL;
  2812. BIO * in = NULL, * datain = NULL, * dataout = NULL;
  2813. long flags = 0;
  2814. char * filename; int filename_len;
  2815. char * extracerts = NULL; int extracerts_len = 0;
  2816. char * signersfilename = NULL; int signersfilename_len = 0;
  2817. char * datafilename = NULL; int datafilename_len = 0;
  2818. RETVAL_LONG(-1);
  2819. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl|sass", &filename, &filename_len,
  2820. &flags, &signersfilename, &signersfilename_len, &cainfo,
  2821. &extracerts, &extracerts_len, &datafilename, &datafilename_len) == FAILURE) {
  2822. return;
  2823. }
  2824. if (extracerts) {
  2825. others = load_all_certs_from_file(extracerts);
  2826. if (others == NULL) {
  2827. goto clean_exit;
  2828. }
  2829. }
  2830. flags = flags & ~PKCS7_DETACHED;
  2831. store = setup_verify(cainfo TSRMLS_CC);
  2832. if (!store) {
  2833. goto clean_exit;
  2834. }
  2835. if (php_openssl_safe_mode_chk(filename TSRMLS_CC)) {
  2836. goto clean_exit;
  2837. }
  2838. in = BIO_new_file(filename, (flags & PKCS7_BINARY) ? "rb" : "r");
  2839. if (in == NULL) {
  2840. goto clean_exit;
  2841. }
  2842. p7 = SMIME_read_PKCS7(in, &datain);
  2843. if (p7 == NULL) {
  2844. #if DEBUG_SMIME
  2845. zend_printf("SMIME_read_PKCS7 failed\n");
  2846. #endif
  2847. goto clean_exit;
  2848. }
  2849. if (datafilename) {
  2850. if (php_openssl_safe_mode_chk(datafilename TSRMLS_CC)) {
  2851. goto clean_exit;
  2852. }
  2853. dataout = BIO_new_file(datafilename, "w");
  2854. if (dataout == NULL) {
  2855. goto clean_exit;
  2856. }
  2857. }
  2858. #if DEBUG_SMIME
  2859. zend_printf("Calling PKCS7 verify\n");
  2860. #endif
  2861. if (PKCS7_verify(p7, others, store, datain, dataout, flags)) {
  2862. RETVAL_TRUE;
  2863. if (signersfilename) {
  2864. BIO *certout;
  2865. if (php_openssl_safe_mode_chk(signersfilename TSRMLS_CC)) {
  2866. goto clean_exit;
  2867. }
  2868. certout = BIO_new_file(signersfilename, "w");
  2869. if (certout) {
  2870. int i;
  2871. signers = PKCS7_get0_signers(p7, NULL, flags);
  2872. for(i = 0; i < sk_X509_num(signers); i++) {
  2873. PEM_write_bio_X509(certout, sk_X509_value(signers, i));
  2874. }
  2875. BIO_free(certout);
  2876. sk_X509_free(signers);
  2877. } else {
  2878. php_error_docref(NULL TSRMLS_CC, E_WARNING, "signature OK, but cannot open %s for writing", signersfilename);
  2879. RETVAL_LONG(-1);
  2880. }
  2881. }
  2882. goto clean_exit;
  2883. } else {
  2884. RETVAL_FALSE;
  2885. }
  2886. clean_exit:
  2887. X509_STORE_free(store);
  2888. BIO_free(datain);
  2889. BIO_free(in);
  2890. BIO_free(dataout);
  2891. PKCS7_free(p7);
  2892. sk_X509_free(others);
  2893. }
  2894. /* }}} */
  2895. /* {{{ proto bool openssl_pkcs7_encrypt(string infile, string outfile, mixed recipcerts, array headers [, long flags [, long cipher]])
  2896. Encrypts the message in the file named infile with the certificates in recipcerts and output the result to the file named outfile */
  2897. PHP_FUNCTION(openssl_pkcs7_encrypt)
  2898. {
  2899. zval ** zrecipcerts, * zheaders = NULL;
  2900. STACK_OF(X509) * recipcerts = NULL;
  2901. BIO * infile = NULL, * outfile = NULL;
  2902. long flags = 0;
  2903. PKCS7 * p7 = NULL;
  2904. HashPosition hpos;
  2905. zval ** zcertval;
  2906. X509 * cert;
  2907. const EVP_CIPHER *cipher = NULL;
  2908. long cipherid = PHP_OPENSSL_CIPHER_DEFAULT;
  2909. uint strindexlen;
  2910. ulong intindex;
  2911. char * strindex;
  2912. char * infilename = NULL; int infilename_len;
  2913. char * outfilename = NULL; int outfilename_len;
  2914. RETVAL_FALSE;
  2915. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssZa!|ll", &infilename, &infilename_len,
  2916. &outfilename, &outfilename_len, &zrecipcerts, &zheaders, &flags, &cipherid) == FAILURE)
  2917. return;
  2918. if (strlen(infilename) != infilename_len) {
  2919. return;
  2920. }
  2921. if (strlen(outfilename) != outfilename_len) {
  2922. return;
  2923. }
  2924. if (php_openssl_safe_mode_chk(infilename TSRMLS_CC) || php_openssl_safe_mode_chk(outfilename TSRMLS_CC)) {
  2925. return;
  2926. }
  2927. infile = BIO_new_file(infilename, "r");
  2928. if (infile == NULL) {
  2929. goto clean_exit;
  2930. }
  2931. outfile = BIO_new_file(outfilename, "w");
  2932. if (outfile == NULL) {
  2933. goto clean_exit;
  2934. }
  2935. recipcerts = sk_X509_new_null();
  2936. /* get certs */
  2937. if (Z_TYPE_PP(zrecipcerts) == IS_ARRAY) {
  2938. zend_hash_internal_pointer_reset_ex(HASH_OF(*zrecipcerts), &hpos);
  2939. while(zend_hash_get_current_data_ex(HASH_OF(*zrecipcerts), (void**)&zcertval, &hpos) == SUCCESS) {
  2940. long certresource;
  2941. cert = php_openssl_x509_from_zval(zcertval, 0, &certresource TSRMLS_CC);
  2942. if (cert == NULL) {
  2943. goto clean_exit;
  2944. }
  2945. if (certresource != -1) {
  2946. /* we shouldn't free this particular cert, as it is a resource.
  2947. make a copy and push that on the stack instead */
  2948. cert = X509_dup(cert);
  2949. if (cert == NULL) {
  2950. goto clean_exit;
  2951. }
  2952. }
  2953. sk_X509_push(recipcerts, cert);
  2954. zend_hash_move_forward_ex(HASH_OF(*zrecipcerts), &hpos);
  2955. }
  2956. } else {
  2957. /* a single certificate */
  2958. long certresource;
  2959. cert = php_openssl_x509_from_zval(zrecipcerts, 0, &certresource TSRMLS_CC);
  2960. if (cert == NULL) {
  2961. goto clean_exit;
  2962. }
  2963. if (certresource != -1) {
  2964. /* we shouldn't free this particular cert, as it is a resource.
  2965. make a copy and push that on the stack instead */
  2966. cert = X509_dup(cert);
  2967. if (cert == NULL) {
  2968. goto clean_exit;
  2969. }
  2970. }
  2971. sk_X509_push(recipcerts, cert);
  2972. }
  2973. /* sanity check the cipher */
  2974. cipher = php_openssl_get_evp_cipher_from_algo(cipherid);
  2975. if (cipher == NULL) {
  2976. /* shouldn't happen */
  2977. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to get cipher");
  2978. goto clean_exit;
  2979. }
  2980. p7 = PKCS7_encrypt(recipcerts, infile, (EVP_CIPHER*)cipher, flags);
  2981. if (p7 == NULL) {
  2982. goto clean_exit;
  2983. }
  2984. /* tack on extra headers */
  2985. if (zheaders) {
  2986. zend_hash_internal_pointer_reset_ex(HASH_OF(zheaders), &hpos);
  2987. while(zend_hash_get_current_data_ex(HASH_OF(zheaders), (void**)&zcertval, &hpos) == SUCCESS) {
  2988. strindex = NULL;
  2989. zend_hash_get_current_key_ex(HASH_OF(zheaders), &strindex, &strindexlen, &intindex, 0, &hpos);
  2990. convert_to_string_ex(zcertval);
  2991. if (strindex) {
  2992. BIO_printf(outfile, "%s: %s\n", strindex, Z_STRVAL_PP(zcertval));
  2993. } else {
  2994. BIO_printf(outfile, "%s\n", Z_STRVAL_PP(zcertval));
  2995. }
  2996. zend_hash_move_forward_ex(HASH_OF(zheaders), &hpos);
  2997. }
  2998. }
  2999. (void)BIO_reset(infile);
  3000. /* write the encrypted data */
  3001. SMIME_write_PKCS7(outfile, p7, infile, flags);
  3002. RETVAL_TRUE;
  3003. clean_exit:
  3004. PKCS7_free(p7);
  3005. BIO_free(infile);
  3006. BIO_free(outfile);
  3007. if (recipcerts) {
  3008. sk_X509_pop_free(recipcerts, X509_free);
  3009. }
  3010. }
  3011. /* }}} */
  3012. /* {{{ proto bool openssl_pkcs7_sign(string infile, string outfile, mixed signcert, mixed signkey, array headers [, long flags [, string extracertsfilename]])
  3013. 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 */
  3014. PHP_FUNCTION(openssl_pkcs7_sign)
  3015. {
  3016. zval ** zcert, ** zprivkey, * zheaders;
  3017. zval ** hval;
  3018. X509 * cert = NULL;
  3019. EVP_PKEY * privkey = NULL;
  3020. long flags = PKCS7_DETACHED;
  3021. PKCS7 * p7 = NULL;
  3022. BIO * infile = NULL, * outfile = NULL;
  3023. STACK_OF(X509) *others = NULL;
  3024. long certresource = -1, keyresource = -1;
  3025. ulong intindex;
  3026. uint strindexlen;
  3027. HashPosition hpos;
  3028. char * strindex;
  3029. char * infilename; int infilename_len;
  3030. char * outfilename; int outfilename_len;
  3031. char * extracertsfilename = NULL; int extracertsfilename_len;
  3032. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssZZa!|ls",
  3033. &infilename, &infilename_len, &outfilename, &outfilename_len,
  3034. &zcert, &zprivkey, &zheaders, &flags, &extracertsfilename,
  3035. &extracertsfilename_len) == FAILURE) {
  3036. return;
  3037. }
  3038. RETVAL_FALSE;
  3039. if (strlen(infilename) != infilename_len) {
  3040. return;
  3041. }
  3042. if (strlen(outfilename) != outfilename_len) {
  3043. return;
  3044. }
  3045. if (extracertsfilename) {
  3046. others = load_all_certs_from_file(extracertsfilename);
  3047. if (others == NULL) {
  3048. goto clean_exit;
  3049. }
  3050. }
  3051. privkey = php_openssl_evp_from_zval(zprivkey, 0, "", 0, &keyresource TSRMLS_CC);
  3052. if (privkey == NULL) {
  3053. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error getting private key");
  3054. goto clean_exit;
  3055. }
  3056. cert = php_openssl_x509_from_zval(zcert, 0, &certresource TSRMLS_CC);
  3057. if (cert == NULL) {
  3058. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error getting cert");
  3059. goto clean_exit;
  3060. }
  3061. if (php_openssl_safe_mode_chk(infilename TSRMLS_CC) || php_openssl_safe_mode_chk(outfilename TSRMLS_CC)) {
  3062. goto clean_exit;
  3063. }
  3064. infile = BIO_new_file(infilename, "r");
  3065. if (infile == NULL) {
  3066. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error opening input file %s!", infilename);
  3067. goto clean_exit;
  3068. }
  3069. outfile = BIO_new_file(outfilename, "w");
  3070. if (outfile == NULL) {
  3071. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error opening output file %s!", outfilename);
  3072. goto clean_exit;
  3073. }
  3074. p7 = PKCS7_sign(cert, privkey, others, infile, flags);
  3075. if (p7 == NULL) {
  3076. php_error_docref(NULL TSRMLS_CC, E_WARNING, "error creating PKCS7 structure!");
  3077. goto clean_exit;
  3078. }
  3079. (void)BIO_reset(infile);
  3080. /* tack on extra headers */
  3081. if (zheaders) {
  3082. zend_hash_internal_pointer_reset_ex(HASH_OF(zheaders), &hpos);
  3083. while(zend_hash_get_current_data_ex(HASH_OF(zheaders), (void**)&hval, &hpos) == SUCCESS) {
  3084. strindex = NULL;
  3085. zend_hash_get_current_key_ex(HASH_OF(zheaders), &strindex, &strindexlen, &intindex, 0, &hpos);
  3086. convert_to_string_ex(hval);
  3087. if (strindex) {
  3088. BIO_printf(outfile, "%s: %s\n", strindex, Z_STRVAL_PP(hval));
  3089. } else {
  3090. BIO_printf(outfile, "%s\n", Z_STRVAL_PP(hval));
  3091. }
  3092. zend_hash_move_forward_ex(HASH_OF(zheaders), &hpos);
  3093. }
  3094. }
  3095. /* write the signed data */
  3096. SMIME_write_PKCS7(outfile, p7, infile, flags);
  3097. RETVAL_TRUE;
  3098. clean_exit:
  3099. PKCS7_free(p7);
  3100. BIO_free(infile);
  3101. BIO_free(outfile);
  3102. if (others) {
  3103. sk_X509_pop_free(others, X509_free);
  3104. }
  3105. if (privkey && keyresource == -1) {
  3106. EVP_PKEY_free(privkey);
  3107. }
  3108. if (cert && certresource == -1) {
  3109. X509_free(cert);
  3110. }
  3111. }
  3112. /* }}} */
  3113. /* {{{ proto bool openssl_pkcs7_decrypt(string infilename, string outfilename, mixed recipcert [, mixed recipkey])
  3114. 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 */
  3115. PHP_FUNCTION(openssl_pkcs7_decrypt)
  3116. {
  3117. zval ** recipcert, ** recipkey = NULL;
  3118. X509 * cert = NULL;
  3119. EVP_PKEY * key = NULL;
  3120. long certresval, keyresval;
  3121. BIO * in = NULL, * out = NULL, * datain = NULL;
  3122. PKCS7 * p7 = NULL;
  3123. char * infilename; int infilename_len;
  3124. char * outfilename; int outfilename_len;
  3125. RETVAL_FALSE;
  3126. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssZ|Z", &infilename, &infilename_len,
  3127. &outfilename, &outfilename_len, &recipcert, &recipkey) == FAILURE) {
  3128. return;
  3129. }
  3130. if (strlen(infilename) != infilename_len) {
  3131. return;
  3132. }
  3133. if (strlen(outfilename) != outfilename_len) {
  3134. return;
  3135. }
  3136. cert = php_openssl_x509_from_zval(recipcert, 0, &certresval TSRMLS_CC);
  3137. if (cert == NULL) {
  3138. php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to coerce parameter 3 to x509 cert");
  3139. goto clean_exit;
  3140. }
  3141. key = php_openssl_evp_from_zval(recipkey ? recipkey : recipcert, 0, "", 0, &keyresval TSRMLS_CC);
  3142. if (key == NULL) {
  3143. php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to get private key");
  3144. goto clean_exit;
  3145. }
  3146. if (php_openssl_safe_mode_chk(infilename TSRMLS_CC) || php_openssl_safe_mode_chk(outfilename TSRMLS_CC)) {
  3147. goto clean_exit;
  3148. }
  3149. in = BIO_new_file(infilename, "r");
  3150. if (in == NULL) {
  3151. goto clean_exit;
  3152. }
  3153. out = BIO_new_file(outfilename, "w");
  3154. if (out == NULL) {
  3155. goto clean_exit;
  3156. }
  3157. p7 = SMIME_read_PKCS7(in, &datain);
  3158. if (p7 == NULL) {
  3159. goto clean_exit;
  3160. }
  3161. if (PKCS7_decrypt(p7, key, cert, out, PKCS7_DETACHED)) {
  3162. RETVAL_TRUE;
  3163. }
  3164. clean_exit:
  3165. PKCS7_free(p7);
  3166. BIO_free(datain);
  3167. BIO_free(in);
  3168. BIO_free(out);
  3169. if (cert && certresval == -1) {
  3170. X509_free(cert);
  3171. }
  3172. if (key && keyresval == -1) {
  3173. EVP_PKEY_free(key);
  3174. }
  3175. }
  3176. /* }}} */
  3177. /* }}} */
  3178. /* {{{ proto bool openssl_private_encrypt(string data, string &crypted, mixed key [, int padding])
  3179. Encrypts data with private key */
  3180. PHP_FUNCTION(openssl_private_encrypt)
  3181. {
  3182. zval **key, *crypted;
  3183. EVP_PKEY *pkey;
  3184. int cryptedlen;
  3185. unsigned char *cryptedbuf = NULL;
  3186. int successful = 0;
  3187. long keyresource = -1;
  3188. char * data;
  3189. int data_len;
  3190. long padding = RSA_PKCS1_PADDING;
  3191. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szZ|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) {
  3192. return;
  3193. }
  3194. RETVAL_FALSE;
  3195. pkey = php_openssl_evp_from_zval(key, 0, "", 0, &keyresource TSRMLS_CC);
  3196. if (pkey == NULL) {
  3197. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key param is not a valid private key");
  3198. RETURN_FALSE;
  3199. }
  3200. cryptedlen = EVP_PKEY_size(pkey);
  3201. cryptedbuf = emalloc(cryptedlen + 1);
  3202. switch (pkey->type) {
  3203. case EVP_PKEY_RSA:
  3204. case EVP_PKEY_RSA2:
  3205. successful = (RSA_private_encrypt(data_len,
  3206. (unsigned char *)data,
  3207. cryptedbuf,
  3208. pkey->pkey.rsa,
  3209. padding) == cryptedlen);
  3210. break;
  3211. default:
  3212. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key type not supported in this PHP build!");
  3213. }
  3214. if (successful) {
  3215. zval_dtor(crypted);
  3216. cryptedbuf[cryptedlen] = '\0';
  3217. ZVAL_STRINGL(crypted, (char *)cryptedbuf, cryptedlen, 0);
  3218. cryptedbuf = NULL;
  3219. RETVAL_TRUE;
  3220. }
  3221. if (cryptedbuf) {
  3222. efree(cryptedbuf);
  3223. }
  3224. if (keyresource == -1) {
  3225. EVP_PKEY_free(pkey);
  3226. }
  3227. }
  3228. /* }}} */
  3229. /* {{{ proto bool openssl_private_decrypt(string data, string &decrypted, mixed key [, int padding])
  3230. Decrypts data with private key */
  3231. PHP_FUNCTION(openssl_private_decrypt)
  3232. {
  3233. zval **key, *crypted;
  3234. EVP_PKEY *pkey;
  3235. int cryptedlen;
  3236. unsigned char *cryptedbuf = NULL;
  3237. unsigned char *crypttemp;
  3238. int successful = 0;
  3239. long padding = RSA_PKCS1_PADDING;
  3240. long keyresource = -1;
  3241. char * data;
  3242. int data_len;
  3243. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szZ|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) {
  3244. return;
  3245. }
  3246. RETVAL_FALSE;
  3247. pkey = php_openssl_evp_from_zval(key, 0, "", 0, &keyresource TSRMLS_CC);
  3248. if (pkey == NULL) {
  3249. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key parameter is not a valid private key");
  3250. RETURN_FALSE;
  3251. }
  3252. cryptedlen = EVP_PKEY_size(pkey);
  3253. crypttemp = emalloc(cryptedlen + 1);
  3254. switch (pkey->type) {
  3255. case EVP_PKEY_RSA:
  3256. case EVP_PKEY_RSA2:
  3257. cryptedlen = RSA_private_decrypt(data_len,
  3258. (unsigned char *)data,
  3259. crypttemp,
  3260. pkey->pkey.rsa,
  3261. padding);
  3262. if (cryptedlen != -1) {
  3263. cryptedbuf = emalloc(cryptedlen + 1);
  3264. memcpy(cryptedbuf, crypttemp, cryptedlen);
  3265. successful = 1;
  3266. }
  3267. break;
  3268. default:
  3269. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key type not supported in this PHP build!");
  3270. }
  3271. efree(crypttemp);
  3272. if (successful) {
  3273. zval_dtor(crypted);
  3274. cryptedbuf[cryptedlen] = '\0';
  3275. ZVAL_STRINGL(crypted, (char *)cryptedbuf, cryptedlen, 0);
  3276. cryptedbuf = NULL;
  3277. RETVAL_TRUE;
  3278. }
  3279. if (keyresource == -1) {
  3280. EVP_PKEY_free(pkey);
  3281. }
  3282. if (cryptedbuf) {
  3283. efree(cryptedbuf);
  3284. }
  3285. }
  3286. /* }}} */
  3287. /* {{{ proto bool openssl_public_encrypt(string data, string &crypted, mixed key [, int padding])
  3288. Encrypts data with public key */
  3289. PHP_FUNCTION(openssl_public_encrypt)
  3290. {
  3291. zval **key, *crypted;
  3292. EVP_PKEY *pkey;
  3293. int cryptedlen;
  3294. unsigned char *cryptedbuf;
  3295. int successful = 0;
  3296. long keyresource = -1;
  3297. long padding = RSA_PKCS1_PADDING;
  3298. char * data;
  3299. int data_len;
  3300. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szZ|l", &data, &data_len, &crypted, &key, &padding) == FAILURE)
  3301. return;
  3302. RETVAL_FALSE;
  3303. pkey = php_openssl_evp_from_zval(key, 1, NULL, 0, &keyresource TSRMLS_CC);
  3304. if (pkey == NULL) {
  3305. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key parameter is not a valid public key");
  3306. RETURN_FALSE;
  3307. }
  3308. cryptedlen = EVP_PKEY_size(pkey);
  3309. cryptedbuf = emalloc(cryptedlen + 1);
  3310. switch (pkey->type) {
  3311. case EVP_PKEY_RSA:
  3312. case EVP_PKEY_RSA2:
  3313. successful = (RSA_public_encrypt(data_len,
  3314. (unsigned char *)data,
  3315. cryptedbuf,
  3316. pkey->pkey.rsa,
  3317. padding) == cryptedlen);
  3318. break;
  3319. default:
  3320. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key type not supported in this PHP build!");
  3321. }
  3322. if (successful) {
  3323. zval_dtor(crypted);
  3324. cryptedbuf[cryptedlen] = '\0';
  3325. ZVAL_STRINGL(crypted, (char *)cryptedbuf, cryptedlen, 0);
  3326. cryptedbuf = NULL;
  3327. RETVAL_TRUE;
  3328. }
  3329. if (keyresource == -1) {
  3330. EVP_PKEY_free(pkey);
  3331. }
  3332. if (cryptedbuf) {
  3333. efree(cryptedbuf);
  3334. }
  3335. }
  3336. /* }}} */
  3337. /* {{{ proto bool openssl_public_decrypt(string data, string &crypted, resource key [, int padding])
  3338. Decrypts data with public key */
  3339. PHP_FUNCTION(openssl_public_decrypt)
  3340. {
  3341. zval **key, *crypted;
  3342. EVP_PKEY *pkey;
  3343. int cryptedlen;
  3344. unsigned char *cryptedbuf = NULL;
  3345. unsigned char *crypttemp;
  3346. int successful = 0;
  3347. long keyresource = -1;
  3348. long padding = RSA_PKCS1_PADDING;
  3349. char * data;
  3350. int data_len;
  3351. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szZ|l", &data, &data_len, &crypted, &key, &padding) == FAILURE) {
  3352. return;
  3353. }
  3354. RETVAL_FALSE;
  3355. pkey = php_openssl_evp_from_zval(key, 1, NULL, 0, &keyresource TSRMLS_CC);
  3356. if (pkey == NULL) {
  3357. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key parameter is not a valid public key");
  3358. RETURN_FALSE;
  3359. }
  3360. cryptedlen = EVP_PKEY_size(pkey);
  3361. crypttemp = emalloc(cryptedlen + 1);
  3362. switch (pkey->type) {
  3363. case EVP_PKEY_RSA:
  3364. case EVP_PKEY_RSA2:
  3365. cryptedlen = RSA_public_decrypt(data_len,
  3366. (unsigned char *)data,
  3367. crypttemp,
  3368. pkey->pkey.rsa,
  3369. padding);
  3370. if (cryptedlen != -1) {
  3371. cryptedbuf = emalloc(cryptedlen + 1);
  3372. memcpy(cryptedbuf, crypttemp, cryptedlen);
  3373. successful = 1;
  3374. }
  3375. break;
  3376. default:
  3377. php_error_docref(NULL TSRMLS_CC, E_WARNING, "key type not supported in this PHP build!");
  3378. }
  3379. efree(crypttemp);
  3380. if (successful) {
  3381. zval_dtor(crypted);
  3382. cryptedbuf[cryptedlen] = '\0';
  3383. ZVAL_STRINGL(crypted, (char *)cryptedbuf, cryptedlen, 0);
  3384. cryptedbuf = NULL;
  3385. RETVAL_TRUE;
  3386. }
  3387. if (cryptedbuf) {
  3388. efree(cryptedbuf);
  3389. }
  3390. if (keyresource == -1) {
  3391. EVP_PKEY_free(pkey);
  3392. }
  3393. }
  3394. /* }}} */
  3395. /* {{{ proto mixed openssl_error_string(void)
  3396. Returns a description of the last error, and alters the index of the error messages. Returns false when the are no more messages */
  3397. PHP_FUNCTION(openssl_error_string)
  3398. {
  3399. char buf[512];
  3400. unsigned long val;
  3401. if (zend_parse_parameters_none() == FAILURE) {
  3402. return;
  3403. }
  3404. val = ERR_get_error();
  3405. if (val) {
  3406. RETURN_STRING(ERR_error_string(val, buf), 1);
  3407. } else {
  3408. RETURN_FALSE;
  3409. }
  3410. }
  3411. /* }}} */
  3412. /* {{{ proto bool openssl_sign(string data, &string signature, mixed key[, mixed method])
  3413. Signs data */
  3414. PHP_FUNCTION(openssl_sign)
  3415. {
  3416. zval **key, *signature;
  3417. EVP_PKEY *pkey;
  3418. int siglen;
  3419. unsigned char *sigbuf;
  3420. long keyresource = -1;
  3421. char * data;
  3422. int data_len;
  3423. EVP_MD_CTX md_ctx;
  3424. zval *method = NULL;
  3425. long signature_algo = OPENSSL_ALGO_SHA1;
  3426. const EVP_MD *mdtype;
  3427. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szZ|z", &data, &data_len, &signature, &key, &method) == FAILURE) {
  3428. return;
  3429. }
  3430. pkey = php_openssl_evp_from_zval(key, 0, "", 0, &keyresource TSRMLS_CC);
  3431. if (pkey == NULL) {
  3432. php_error_docref(NULL TSRMLS_CC, E_WARNING, "supplied key param cannot be coerced into a private key");
  3433. RETURN_FALSE;
  3434. }
  3435. if (method == NULL || Z_TYPE_P(method) == IS_LONG) {
  3436. if (method != NULL) {
  3437. signature_algo = Z_LVAL_P(method);
  3438. }
  3439. mdtype = php_openssl_get_evp_md_from_algo(signature_algo);
  3440. } else if (Z_TYPE_P(method) == IS_STRING) {
  3441. mdtype = EVP_get_digestbyname(Z_STRVAL_P(method));
  3442. } else {
  3443. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
  3444. RETURN_FALSE;
  3445. }
  3446. if (!mdtype) {
  3447. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
  3448. RETURN_FALSE;
  3449. }
  3450. siglen = EVP_PKEY_size(pkey);
  3451. sigbuf = emalloc(siglen + 1);
  3452. EVP_SignInit(&md_ctx, mdtype);
  3453. EVP_SignUpdate(&md_ctx, data, data_len);
  3454. if (EVP_SignFinal (&md_ctx, sigbuf,(unsigned int *)&siglen, pkey)) {
  3455. zval_dtor(signature);
  3456. sigbuf[siglen] = '\0';
  3457. ZVAL_STRINGL(signature, (char *)sigbuf, siglen, 0);
  3458. RETVAL_TRUE;
  3459. } else {
  3460. efree(sigbuf);
  3461. RETVAL_FALSE;
  3462. }
  3463. EVP_MD_CTX_cleanup(&md_ctx);
  3464. if (keyresource == -1) {
  3465. EVP_PKEY_free(pkey);
  3466. }
  3467. }
  3468. /* }}} */
  3469. /* {{{ proto int openssl_verify(string data, string signature, mixed key[, mixed method])
  3470. Verifys data */
  3471. PHP_FUNCTION(openssl_verify)
  3472. {
  3473. zval **key;
  3474. EVP_PKEY *pkey;
  3475. int err;
  3476. EVP_MD_CTX md_ctx;
  3477. const EVP_MD *mdtype;
  3478. long keyresource = -1;
  3479. char * data; int data_len;
  3480. char * signature; int signature_len;
  3481. zval *method = NULL;
  3482. long signature_algo = OPENSSL_ALGO_SHA1;
  3483. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssZ|z", &data, &data_len, &signature, &signature_len, &key, &method) == FAILURE) {
  3484. return;
  3485. }
  3486. if (method == NULL || Z_TYPE_P(method) == IS_LONG) {
  3487. if (method != NULL) {
  3488. signature_algo = Z_LVAL_P(method);
  3489. }
  3490. mdtype = php_openssl_get_evp_md_from_algo(signature_algo);
  3491. } else if (Z_TYPE_P(method) == IS_STRING) {
  3492. mdtype = EVP_get_digestbyname(Z_STRVAL_P(method));
  3493. } else {
  3494. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
  3495. RETURN_FALSE;
  3496. }
  3497. if (!mdtype) {
  3498. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
  3499. RETURN_FALSE;
  3500. }
  3501. pkey = php_openssl_evp_from_zval(key, 1, NULL, 0, &keyresource TSRMLS_CC);
  3502. if (pkey == NULL) {
  3503. php_error_docref(NULL TSRMLS_CC, E_WARNING, "supplied key param cannot be coerced into a public key");
  3504. RETURN_FALSE;
  3505. }
  3506. EVP_VerifyInit (&md_ctx, mdtype);
  3507. EVP_VerifyUpdate (&md_ctx, data, data_len);
  3508. err = EVP_VerifyFinal (&md_ctx, (unsigned char *)signature, signature_len, pkey);
  3509. EVP_MD_CTX_cleanup(&md_ctx);
  3510. if (keyresource == -1) {
  3511. EVP_PKEY_free(pkey);
  3512. }
  3513. RETURN_LONG(err);
  3514. }
  3515. /* }}} */
  3516. /* {{{ proto int openssl_seal(string data, &string sealdata, &array ekeys, array pubkeys)
  3517. Seals data */
  3518. PHP_FUNCTION(openssl_seal)
  3519. {
  3520. zval *pubkeys, **pubkey, *sealdata, *ekeys;
  3521. HashTable *pubkeysht;
  3522. HashPosition pos;
  3523. EVP_PKEY **pkeys;
  3524. long * key_resources; /* so we know what to cleanup */
  3525. int i, len1, len2, *eksl, nkeys;
  3526. unsigned char *buf = NULL, **eks;
  3527. char * data; int data_len;
  3528. char *method =NULL;
  3529. int method_len = 0;
  3530. const EVP_CIPHER *cipher;
  3531. EVP_CIPHER_CTX ctx;
  3532. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szza/|s", &data, &data_len, &sealdata, &ekeys, &pubkeys, &method, &method_len) == FAILURE) {
  3533. return;
  3534. }
  3535. pubkeysht = HASH_OF(pubkeys);
  3536. nkeys = pubkeysht ? zend_hash_num_elements(pubkeysht) : 0;
  3537. if (!nkeys) {
  3538. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Fourth argument to openssl_seal() must be a non-empty array");
  3539. RETURN_FALSE;
  3540. }
  3541. if (method) {
  3542. cipher = EVP_get_cipherbyname(method);
  3543. if (!cipher) {
  3544. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
  3545. RETURN_FALSE;
  3546. }
  3547. } else {
  3548. cipher = EVP_rc4();
  3549. }
  3550. pkeys = safe_emalloc(nkeys, sizeof(*pkeys), 0);
  3551. eksl = safe_emalloc(nkeys, sizeof(*eksl), 0);
  3552. eks = safe_emalloc(nkeys, sizeof(*eks), 0);
  3553. memset(eks, 0, sizeof(*eks) * nkeys);
  3554. key_resources = safe_emalloc(nkeys, sizeof(long), 0);
  3555. memset(key_resources, 0, sizeof(*key_resources) * nkeys);
  3556. /* get the public keys we are using to seal this data */
  3557. zend_hash_internal_pointer_reset_ex(pubkeysht, &pos);
  3558. i = 0;
  3559. while (zend_hash_get_current_data_ex(pubkeysht, (void **) &pubkey,
  3560. &pos) == SUCCESS) {
  3561. pkeys[i] = php_openssl_evp_from_zval(pubkey, 1, NULL, 0, &key_resources[i] TSRMLS_CC);
  3562. if (pkeys[i] == NULL) {
  3563. php_error_docref(NULL TSRMLS_CC, E_WARNING, "not a public key (%dth member of pubkeys)", i+1);
  3564. RETVAL_FALSE;
  3565. goto clean_exit;
  3566. }
  3567. eks[i] = emalloc(EVP_PKEY_size(pkeys[i]) + 1);
  3568. zend_hash_move_forward_ex(pubkeysht, &pos);
  3569. i++;
  3570. }
  3571. if (!EVP_EncryptInit(&ctx,cipher,NULL,NULL)) {
  3572. RETVAL_FALSE;
  3573. goto clean_exit;
  3574. }
  3575. #if 0
  3576. /* Need this if allow ciphers that require initialization vector */
  3577. ivlen = EVP_CIPHER_CTX_iv_length(&ctx);
  3578. iv = ivlen ? emalloc(ivlen + 1) : NULL;
  3579. #endif
  3580. /* allocate one byte extra to make room for \0 */
  3581. buf = emalloc(data_len + EVP_CIPHER_CTX_block_size(&ctx));
  3582. if (!EVP_SealInit(&ctx, cipher, eks, eksl, NULL, pkeys, nkeys) || !EVP_SealUpdate(&ctx, buf, &len1, (unsigned char *)data, data_len)) {
  3583. RETVAL_FALSE;
  3584. efree(buf);
  3585. goto clean_exit;
  3586. }
  3587. EVP_SealFinal(&ctx, buf + len1, &len2);
  3588. if (len1 + len2 > 0) {
  3589. zval_dtor(sealdata);
  3590. buf[len1 + len2] = '\0';
  3591. buf = erealloc(buf, len1 + len2 + 1);
  3592. ZVAL_STRINGL(sealdata, (char *)buf, len1 + len2, 0);
  3593. zval_dtor(ekeys);
  3594. array_init(ekeys);
  3595. for (i=0; i<nkeys; i++) {
  3596. eks[i][eksl[i]] = '\0';
  3597. add_next_index_stringl(ekeys, erealloc(eks[i], eksl[i] + 1), eksl[i], 0);
  3598. eks[i] = NULL;
  3599. }
  3600. #if 0
  3601. /* If allow ciphers that need IV, we need this */
  3602. zval_dtor(*ivec);
  3603. if (ivlen) {
  3604. iv[ivlen] = '\0';
  3605. ZVAL_STRINGL(*ivec, erealloc(iv, ivlen + 1), ivlen, 0);
  3606. } else {
  3607. ZVAL_EMPTY_STRING(*ivec);
  3608. }
  3609. #endif
  3610. } else {
  3611. efree(buf);
  3612. }
  3613. RETVAL_LONG(len1 + len2);
  3614. clean_exit:
  3615. for (i=0; i<nkeys; i++) {
  3616. if (key_resources[i] == -1) {
  3617. EVP_PKEY_free(pkeys[i]);
  3618. }
  3619. if (eks[i]) {
  3620. efree(eks[i]);
  3621. }
  3622. }
  3623. efree(eks);
  3624. efree(eksl);
  3625. efree(pkeys);
  3626. efree(key_resources);
  3627. }
  3628. /* }}} */
  3629. /* {{{ proto bool openssl_open(string data, &string opendata, string ekey, mixed privkey)
  3630. Opens data */
  3631. PHP_FUNCTION(openssl_open)
  3632. {
  3633. zval **privkey, *opendata;
  3634. EVP_PKEY *pkey;
  3635. int len1, len2;
  3636. unsigned char *buf;
  3637. long keyresource = -1;
  3638. EVP_CIPHER_CTX ctx;
  3639. char * data; int data_len;
  3640. char * ekey; int ekey_len;
  3641. char *method =NULL;
  3642. int method_len = 0;
  3643. const EVP_CIPHER *cipher;
  3644. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szsZ|s", &data, &data_len, &opendata, &ekey, &ekey_len, &privkey, &method, &method_len) == FAILURE) {
  3645. return;
  3646. }
  3647. pkey = php_openssl_evp_from_zval(privkey, 0, "", 0, &keyresource TSRMLS_CC);
  3648. if (pkey == NULL) {
  3649. php_error_docref(NULL TSRMLS_CC, E_WARNING, "unable to coerce parameter 4 into a private key");
  3650. RETURN_FALSE;
  3651. }
  3652. if (method) {
  3653. cipher = EVP_get_cipherbyname(method);
  3654. if (!cipher) {
  3655. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm.");
  3656. RETURN_FALSE;
  3657. }
  3658. } else {
  3659. cipher = EVP_rc4();
  3660. }
  3661. buf = emalloc(data_len + 1);
  3662. if (EVP_OpenInit(&ctx, cipher, (unsigned char *)ekey, ekey_len, NULL, pkey) && EVP_OpenUpdate(&ctx, buf, &len1, (unsigned char *)data, data_len)) {
  3663. if (!EVP_OpenFinal(&ctx, buf + len1, &len2) || (len1 + len2 == 0)) {
  3664. efree(buf);
  3665. if (keyresource == -1) {
  3666. EVP_PKEY_free(pkey);
  3667. }
  3668. RETURN_FALSE;
  3669. }
  3670. } else {
  3671. efree(buf);
  3672. if (keyresource == -1) {
  3673. EVP_PKEY_free(pkey);
  3674. }
  3675. RETURN_FALSE;
  3676. }
  3677. if (keyresource == -1) {
  3678. EVP_PKEY_free(pkey);
  3679. }
  3680. zval_dtor(opendata);
  3681. buf[len1 + len2] = '\0';
  3682. ZVAL_STRINGL(opendata, erealloc(buf, len1 + len2 + 1), len1 + len2, 0);
  3683. RETURN_TRUE;
  3684. }
  3685. /* }}} */
  3686. /* SSL verification functions */
  3687. #define GET_VER_OPT(name) (stream->context && SUCCESS == php_stream_context_get_option(stream->context, "ssl", name, &val))
  3688. #define GET_VER_OPT_STRING(name, str) if (GET_VER_OPT(name)) { convert_to_string_ex(val); str = Z_STRVAL_PP(val); }
  3689. static int verify_callback(int preverify_ok, X509_STORE_CTX *ctx) /* {{{ */
  3690. {
  3691. php_stream *stream;
  3692. SSL *ssl;
  3693. X509 *err_cert;
  3694. int err, depth, ret;
  3695. zval **val;
  3696. ret = preverify_ok;
  3697. /* determine the status for the current cert */
  3698. err_cert = X509_STORE_CTX_get_current_cert(ctx);
  3699. err = X509_STORE_CTX_get_error(ctx);
  3700. depth = X509_STORE_CTX_get_error_depth(ctx);
  3701. /* conjure the stream & context to use */
  3702. ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
  3703. stream = (php_stream*)SSL_get_ex_data(ssl, ssl_stream_data_index);
  3704. /* if allow_self_signed is set, make sure that verification succeeds */
  3705. if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT && GET_VER_OPT("allow_self_signed") && zval_is_true(*val)) {
  3706. ret = 1;
  3707. }
  3708. /* check the depth */
  3709. if (GET_VER_OPT("verify_depth")) {
  3710. convert_to_long_ex(val);
  3711. if (depth > Z_LVAL_PP(val)) {
  3712. ret = 0;
  3713. X509_STORE_CTX_set_error(ctx, X509_V_ERR_CERT_CHAIN_TOO_LONG);
  3714. }
  3715. }
  3716. return ret;
  3717. }
  3718. /* }}} */
  3719. int php_openssl_apply_verification_policy(SSL *ssl, X509 *peer, php_stream *stream TSRMLS_DC) /* {{{ */
  3720. {
  3721. zval **val = NULL;
  3722. char *cnmatch = NULL;
  3723. X509_NAME *name;
  3724. char buf[1024];
  3725. int err;
  3726. /* verification is turned off */
  3727. if (!(GET_VER_OPT("verify_peer") && zval_is_true(*val))) {
  3728. return SUCCESS;
  3729. }
  3730. if (peer == NULL) {
  3731. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not get peer certificate");
  3732. return FAILURE;
  3733. }
  3734. err = SSL_get_verify_result(ssl);
  3735. switch (err) {
  3736. case X509_V_OK:
  3737. /* fine */
  3738. break;
  3739. case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
  3740. if (GET_VER_OPT("allow_self_signed") && zval_is_true(*val)) {
  3741. /* allowed */
  3742. break;
  3743. }
  3744. /* not allowed, so fall through */
  3745. default:
  3746. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not verify peer: code:%d %s", err, X509_verify_cert_error_string(err));
  3747. return FAILURE;
  3748. }
  3749. /* if the cert passed the usual checks, apply our own local policies now */
  3750. name = X509_get_subject_name(peer);
  3751. /* Does the common name match ? (used primarily for https://) */
  3752. GET_VER_OPT_STRING("CN_match", cnmatch);
  3753. if (cnmatch) {
  3754. int match = 0;
  3755. int name_len = X509_NAME_get_text_by_NID(name, NID_commonName, buf, sizeof(buf));
  3756. if (name_len == -1) {
  3757. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to locate peer certificate CN");
  3758. return FAILURE;
  3759. } else if (name_len != strlen(buf)) {
  3760. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Peer certificate CN=`%.*s' is malformed", name_len, buf);
  3761. return FAILURE;
  3762. }
  3763. match = strcmp(cnmatch, buf) == 0;
  3764. if (!match && strlen(buf) > 3 && buf[0] == '*' && buf[1] == '.') {
  3765. /* Try wildcard */
  3766. if (strchr(buf+2, '.')) {
  3767. char *tmp = strstr(cnmatch, buf+1);
  3768. match = tmp && strcmp(tmp, buf+2) && tmp == strchr(cnmatch, '.');
  3769. }
  3770. }
  3771. if (!match) {
  3772. /* didn't match */
  3773. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Peer certificate CN=`%.*s' did not match expected CN=`%s'", name_len, buf, cnmatch);
  3774. return FAILURE;
  3775. }
  3776. }
  3777. return SUCCESS;
  3778. }
  3779. /* }}} */
  3780. static int passwd_callback(char *buf, int num, int verify, void *data) /* {{{ */
  3781. {
  3782. php_stream *stream = (php_stream *)data;
  3783. zval **val = NULL;
  3784. char *passphrase = NULL;
  3785. /* TODO: could expand this to make a callback into PHP user-space */
  3786. GET_VER_OPT_STRING("passphrase", passphrase);
  3787. if (passphrase) {
  3788. if (Z_STRLEN_PP(val) < num - 1) {
  3789. memcpy(buf, Z_STRVAL_PP(val), Z_STRLEN_PP(val)+1);
  3790. return Z_STRLEN_PP(val);
  3791. }
  3792. }
  3793. return 0;
  3794. }
  3795. /* }}} */
  3796. SSL *php_SSL_new_from_context(SSL_CTX *ctx, php_stream *stream TSRMLS_DC) /* {{{ */
  3797. {
  3798. zval **val = NULL;
  3799. char *cafile = NULL;
  3800. char *capath = NULL;
  3801. char *certfile = NULL;
  3802. char *cipherlist = NULL;
  3803. int ok = 1;
  3804. ERR_clear_error();
  3805. /* look at context options in the stream and set appropriate verification flags */
  3806. if (GET_VER_OPT("verify_peer") && zval_is_true(*val)) {
  3807. /* turn on verification callback */
  3808. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, verify_callback);
  3809. /* CA stuff */
  3810. GET_VER_OPT_STRING("cafile", cafile);
  3811. GET_VER_OPT_STRING("capath", capath);
  3812. if (cafile || capath) {
  3813. if (!SSL_CTX_load_verify_locations(ctx, cafile, capath)) {
  3814. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to set verify locations `%s' `%s'", cafile, capath);
  3815. return NULL;
  3816. }
  3817. }
  3818. if (GET_VER_OPT("verify_depth")) {
  3819. convert_to_long_ex(val);
  3820. SSL_CTX_set_verify_depth(ctx, Z_LVAL_PP(val));
  3821. }
  3822. } else {
  3823. SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
  3824. }
  3825. /* callback for the passphrase (for localcert) */
  3826. if (GET_VER_OPT("passphrase")) {
  3827. SSL_CTX_set_default_passwd_cb_userdata(ctx, stream);
  3828. SSL_CTX_set_default_passwd_cb(ctx, passwd_callback);
  3829. }
  3830. GET_VER_OPT_STRING("ciphers", cipherlist);
  3831. if (!cipherlist) {
  3832. cipherlist = "DEFAULT";
  3833. }
  3834. if (SSL_CTX_set_cipher_list(ctx, cipherlist) != 1) {
  3835. return NULL;
  3836. }
  3837. GET_VER_OPT_STRING("local_cert", certfile);
  3838. if (certfile) {
  3839. X509 *cert = NULL;
  3840. EVP_PKEY *key = NULL;
  3841. SSL *tmpssl;
  3842. char resolved_path_buff[MAXPATHLEN];
  3843. const char * private_key = NULL;
  3844. if (VCWD_REALPATH(certfile, resolved_path_buff)) {
  3845. /* a certificate to use for authentication */
  3846. if (SSL_CTX_use_certificate_chain_file(ctx, resolved_path_buff) != 1) {
  3847. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to set local cert chain file `%s'; Check that your cafile/capath settings include details of your certificate and its issuer", certfile);
  3848. return NULL;
  3849. }
  3850. GET_VER_OPT_STRING("local_pk", private_key);
  3851. if (private_key) {
  3852. char resolved_path_buff_pk[MAXPATHLEN];
  3853. if (VCWD_REALPATH(private_key, resolved_path_buff_pk)) {
  3854. if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff_pk, SSL_FILETYPE_PEM) != 1) {
  3855. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to set private key file `%s'", resolved_path_buff_pk);
  3856. return NULL;
  3857. }
  3858. }
  3859. } else {
  3860. if (SSL_CTX_use_PrivateKey_file(ctx, resolved_path_buff, SSL_FILETYPE_PEM) != 1) {
  3861. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unable to set private key file `%s'", resolved_path_buff);
  3862. return NULL;
  3863. }
  3864. }
  3865. tmpssl = SSL_new(ctx);
  3866. cert = SSL_get_certificate(tmpssl);
  3867. if (cert) {
  3868. key = X509_get_pubkey(cert);
  3869. EVP_PKEY_copy_parameters(key, SSL_get_privatekey(tmpssl));
  3870. EVP_PKEY_free(key);
  3871. }
  3872. SSL_free(tmpssl);
  3873. if (!SSL_CTX_check_private_key(ctx)) {
  3874. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Private key does not match certificate!");
  3875. }
  3876. }
  3877. }
  3878. if (ok) {
  3879. SSL *ssl = SSL_new(ctx);
  3880. if (ssl) {
  3881. /* map SSL => stream */
  3882. SSL_set_ex_data(ssl, ssl_stream_data_index, stream);
  3883. }
  3884. return ssl;
  3885. }
  3886. return NULL;
  3887. }
  3888. /* }}} */
  3889. static void openssl_add_method_or_alias(const OBJ_NAME *name, void *arg) /* {{{ */
  3890. {
  3891. add_next_index_string((zval*)arg, (char*)name->name, 1);
  3892. }
  3893. /* }}} */
  3894. static void openssl_add_method(const OBJ_NAME *name, void *arg) /* {{{ */
  3895. {
  3896. if (name->alias == 0) {
  3897. add_next_index_string((zval*)arg, (char*)name->name, 1);
  3898. }
  3899. }
  3900. /* }}} */
  3901. /* {{{ proto array openssl_get_md_methods([bool aliases = false])
  3902. Return array of available digest methods */
  3903. PHP_FUNCTION(openssl_get_md_methods)
  3904. {
  3905. zend_bool aliases = 0;
  3906. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &aliases) == FAILURE) {
  3907. return;
  3908. }
  3909. array_init(return_value);
  3910. OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH,
  3911. aliases ? openssl_add_method_or_alias: openssl_add_method,
  3912. return_value);
  3913. }
  3914. /* }}} */
  3915. /* {{{ proto array openssl_get_cipher_methods([bool aliases = false])
  3916. Return array of available cipher methods */
  3917. PHP_FUNCTION(openssl_get_cipher_methods)
  3918. {
  3919. zend_bool aliases = 0;
  3920. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &aliases) == FAILURE) {
  3921. return;
  3922. }
  3923. array_init(return_value);
  3924. OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
  3925. aliases ? openssl_add_method_or_alias: openssl_add_method,
  3926. return_value);
  3927. }
  3928. /* }}} */
  3929. /* {{{ proto string openssl_digest(string data, string method [, bool raw_output=false])
  3930. Computes digest hash value for given data using given method, returns raw or binhex encoded string */
  3931. PHP_FUNCTION(openssl_digest)
  3932. {
  3933. zend_bool raw_output = 0;
  3934. char *data, *method;
  3935. int data_len, method_len;
  3936. const EVP_MD *mdtype;
  3937. EVP_MD_CTX md_ctx;
  3938. int siglen;
  3939. unsigned char *sigbuf;
  3940. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss|b", &data, &data_len, &method, &method_len, &raw_output) == FAILURE) {
  3941. return;
  3942. }
  3943. mdtype = EVP_get_digestbyname(method);
  3944. if (!mdtype) {
  3945. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown signature algorithm");
  3946. RETURN_FALSE;
  3947. }
  3948. siglen = EVP_MD_size(mdtype);
  3949. sigbuf = emalloc(siglen + 1);
  3950. EVP_DigestInit(&md_ctx, mdtype);
  3951. EVP_DigestUpdate(&md_ctx, (unsigned char *)data, data_len);
  3952. if (EVP_DigestFinal (&md_ctx, (unsigned char *)sigbuf, (unsigned int *)&siglen)) {
  3953. if (raw_output) {
  3954. sigbuf[siglen] = '\0';
  3955. RETVAL_STRINGL((char *)sigbuf, siglen, 0);
  3956. } else {
  3957. int digest_str_len = siglen * 2;
  3958. char *digest_str = emalloc(digest_str_len + 1);
  3959. make_digest_ex(digest_str, sigbuf, siglen);
  3960. efree(sigbuf);
  3961. RETVAL_STRINGL(digest_str, digest_str_len, 0);
  3962. }
  3963. } else {
  3964. efree(sigbuf);
  3965. RETVAL_FALSE;
  3966. }
  3967. }
  3968. /* }}} */
  3969. static zend_bool php_openssl_validate_iv(char **piv, int *piv_len, int iv_required_len TSRMLS_DC)
  3970. {
  3971. char *iv_new;
  3972. /* Best case scenario, user behaved */
  3973. if (*piv_len == iv_required_len) {
  3974. return 0;
  3975. }
  3976. iv_new = ecalloc(1, iv_required_len + 1);
  3977. if (*piv_len <= 0) {
  3978. /* BC behavior */
  3979. *piv_len = iv_required_len;
  3980. *piv = iv_new;
  3981. return 1;
  3982. }
  3983. if (*piv_len < iv_required_len) {
  3984. php_error_docref(NULL TSRMLS_CC, E_WARNING, "IV passed is only %d bytes long, cipher expects an IV of precisely %d bytes, padding with \\0", *piv_len, iv_required_len);
  3985. memcpy(iv_new, *piv, *piv_len);
  3986. *piv_len = iv_required_len;
  3987. *piv = iv_new;
  3988. return 1;
  3989. }
  3990. php_error_docref(NULL TSRMLS_CC, E_WARNING, "IV passed is %d bytes long which is longer than the %d expected by selected cipher, truncating", *piv_len, iv_required_len);
  3991. memcpy(iv_new, *piv, iv_required_len);
  3992. *piv_len = iv_required_len;
  3993. *piv = iv_new;
  3994. return 1;
  3995. }
  3996. /* {{{ proto string openssl_encrypt(string data, string method, string password [, bool raw_output=false [, string $iv='']])
  3997. Encrypts given data with given method and key, returns raw or base64 encoded string */
  3998. PHP_FUNCTION(openssl_encrypt)
  3999. {
  4000. zend_bool raw_output = 0;
  4001. char *data, *method, *password, *iv = "";
  4002. int data_len, method_len, password_len, iv_len = 0, max_iv_len;
  4003. const EVP_CIPHER *cipher_type;
  4004. EVP_CIPHER_CTX cipher_ctx;
  4005. int i, outlen, keylen;
  4006. unsigned char *outbuf, *key;
  4007. zend_bool free_iv;
  4008. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_output, &iv, &iv_len) == FAILURE) {
  4009. return;
  4010. }
  4011. cipher_type = EVP_get_cipherbyname(method);
  4012. if (!cipher_type) {
  4013. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
  4014. RETURN_FALSE;
  4015. }
  4016. keylen = EVP_CIPHER_key_length(cipher_type);
  4017. if (keylen > password_len) {
  4018. key = emalloc(keylen);
  4019. memset(key, 0, keylen);
  4020. memcpy(key, password, password_len);
  4021. } else {
  4022. key = (unsigned char*)password;
  4023. }
  4024. max_iv_len = EVP_CIPHER_iv_length(cipher_type);
  4025. if (iv_len <= 0 && max_iv_len > 0) {
  4026. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Using an empty Initialization Vector (iv) is potentially insecure and not recommended");
  4027. }
  4028. free_iv = php_openssl_validate_iv(&iv, &iv_len, max_iv_len TSRMLS_CC);
  4029. outlen = data_len + EVP_CIPHER_block_size(cipher_type);
  4030. outbuf = emalloc(outlen + 1);
  4031. EVP_EncryptInit(&cipher_ctx, cipher_type, key, (unsigned char *)iv);
  4032. EVP_EncryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);
  4033. outlen = i;
  4034. if (EVP_EncryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {
  4035. outlen += i;
  4036. if (raw_output) {
  4037. outbuf[outlen] = '\0';
  4038. RETVAL_STRINGL((char *)outbuf, outlen, 0);
  4039. } else {
  4040. int base64_str_len;
  4041. char *base64_str;
  4042. base64_str = (char*)php_base64_encode(outbuf, outlen, &base64_str_len);
  4043. efree(outbuf);
  4044. RETVAL_STRINGL(base64_str, base64_str_len, 0);
  4045. }
  4046. } else {
  4047. efree(outbuf);
  4048. RETVAL_FALSE;
  4049. }
  4050. if (key != (unsigned char*)password) {
  4051. efree(key);
  4052. }
  4053. if (free_iv) {
  4054. efree(iv);
  4055. }
  4056. EVP_CIPHER_CTX_cleanup(&cipher_ctx);
  4057. }
  4058. /* }}} */
  4059. /* {{{ proto string openssl_decrypt(string data, string method, string password [, bool raw_input=false [, string $iv = '']])
  4060. Takes raw or base64 encoded string and dectupt it using given method and key */
  4061. PHP_FUNCTION(openssl_decrypt)
  4062. {
  4063. zend_bool raw_input = 0;
  4064. char *data, *method, *password, *iv = "";
  4065. int data_len, method_len, password_len, iv_len = 0;
  4066. const EVP_CIPHER *cipher_type;
  4067. EVP_CIPHER_CTX cipher_ctx;
  4068. int i, outlen, keylen;
  4069. unsigned char *outbuf, *key;
  4070. int base64_str_len;
  4071. char *base64_str = NULL;
  4072. zend_bool free_iv;
  4073. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss|bs", &data, &data_len, &method, &method_len, &password, &password_len, &raw_input, &iv, &iv_len) == FAILURE) {
  4074. return;
  4075. }
  4076. if (!method_len) {
  4077. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
  4078. RETURN_FALSE;
  4079. }
  4080. cipher_type = EVP_get_cipherbyname(method);
  4081. if (!cipher_type) {
  4082. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
  4083. RETURN_FALSE;
  4084. }
  4085. if (!raw_input) {
  4086. base64_str = (char*)php_base64_decode((unsigned char*)data, data_len, &base64_str_len);
  4087. data_len = base64_str_len;
  4088. data = base64_str;
  4089. }
  4090. keylen = EVP_CIPHER_key_length(cipher_type);
  4091. if (keylen > password_len) {
  4092. key = emalloc(keylen);
  4093. memset(key, 0, keylen);
  4094. memcpy(key, password, password_len);
  4095. } else {
  4096. key = (unsigned char*)password;
  4097. }
  4098. free_iv = php_openssl_validate_iv(&iv, &iv_len, EVP_CIPHER_iv_length(cipher_type) TSRMLS_CC);
  4099. outlen = data_len + EVP_CIPHER_block_size(cipher_type);
  4100. outbuf = emalloc(outlen + 1);
  4101. EVP_DecryptInit(&cipher_ctx, cipher_type, key, (unsigned char *)iv);
  4102. EVP_DecryptUpdate(&cipher_ctx, outbuf, &i, (unsigned char *)data, data_len);
  4103. outlen = i;
  4104. if (EVP_DecryptFinal(&cipher_ctx, (unsigned char *)outbuf + i, &i)) {
  4105. outlen += i;
  4106. outbuf[outlen] = '\0';
  4107. RETVAL_STRINGL((char *)outbuf, outlen, 0);
  4108. } else {
  4109. efree(outbuf);
  4110. RETVAL_FALSE;
  4111. }
  4112. if (key != (unsigned char*)password) {
  4113. efree(key);
  4114. }
  4115. if (free_iv) {
  4116. efree(iv);
  4117. }
  4118. if (base64_str) {
  4119. efree(base64_str);
  4120. }
  4121. EVP_CIPHER_CTX_cleanup(&cipher_ctx);
  4122. }
  4123. /* }}} */
  4124. /* {{{ proto int openssl_cipher_iv_length(string $method) */
  4125. PHP_FUNCTION(openssl_cipher_iv_length)
  4126. {
  4127. char *method;
  4128. int method_len;
  4129. const EVP_CIPHER *cipher_type;
  4130. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &method, &method_len) == FAILURE) {
  4131. return;
  4132. }
  4133. if (!method_len) {
  4134. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
  4135. RETURN_FALSE;
  4136. }
  4137. cipher_type = EVP_get_cipherbyname(method);
  4138. if (!cipher_type) {
  4139. php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown cipher algorithm");
  4140. RETURN_FALSE;
  4141. }
  4142. RETURN_LONG(EVP_CIPHER_iv_length(cipher_type));
  4143. }
  4144. /* }}} */
  4145. /* {{{ proto string openssl_dh_compute_key(string pub_key, resource dh_key)
  4146. Computes shared sicret for public value of remote DH key and local DH key */
  4147. PHP_FUNCTION(openssl_dh_compute_key)
  4148. {
  4149. zval *key;
  4150. char *pub_str;
  4151. int pub_len;
  4152. EVP_PKEY *pkey;
  4153. BIGNUM *pub;
  4154. char *data;
  4155. int len;
  4156. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sr", &pub_str, &pub_len, &key) == FAILURE) {
  4157. return;
  4158. }
  4159. ZEND_FETCH_RESOURCE(pkey, EVP_PKEY *, &key, -1, "OpenSSL key", le_key);
  4160. if (!pkey || EVP_PKEY_type(pkey->type) != EVP_PKEY_DH || !pkey->pkey.dh) {
  4161. RETURN_FALSE;
  4162. }
  4163. pub = BN_bin2bn((unsigned char*)pub_str, pub_len, NULL);
  4164. data = emalloc(DH_size(pkey->pkey.dh) + 1);
  4165. len = DH_compute_key((unsigned char*)data, pub, pkey->pkey.dh);
  4166. if (len >= 0) {
  4167. data[len] = 0;
  4168. RETVAL_STRINGL(data, len, 0);
  4169. } else {
  4170. efree(data);
  4171. RETVAL_FALSE;
  4172. }
  4173. BN_free(pub);
  4174. }
  4175. /* }}} */
  4176. /* {{{ proto string openssl_random_pseudo_bytes(integer length [, &bool returned_strong_result])
  4177. Returns a string of the length specified filled with random pseudo bytes */
  4178. PHP_FUNCTION(openssl_random_pseudo_bytes)
  4179. {
  4180. long buffer_length;
  4181. unsigned char *buffer = NULL;
  4182. zval *zstrong_result_returned = NULL;
  4183. int strong_result = 0;
  4184. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|z", &buffer_length, &zstrong_result_returned) == FAILURE) {
  4185. return;
  4186. }
  4187. if (buffer_length <= 0) {
  4188. RETURN_FALSE;
  4189. }
  4190. if (zstrong_result_returned) {
  4191. zval_dtor(zstrong_result_returned);
  4192. ZVAL_BOOL(zstrong_result_returned, 0);
  4193. }
  4194. buffer = emalloc(buffer_length + 1);
  4195. #ifdef WINDOWS
  4196. RAND_screen();
  4197. #endif
  4198. if ((strong_result = RAND_pseudo_bytes(buffer, buffer_length)) < 0) {
  4199. efree(buffer);
  4200. RETURN_FALSE;
  4201. }
  4202. buffer[buffer_length] = 0;
  4203. RETVAL_STRINGL((char *)buffer, buffer_length, 0);
  4204. if (zstrong_result_returned) {
  4205. ZVAL_BOOL(zstrong_result_returned, strong_result);
  4206. }
  4207. }
  4208. /* }}} */
  4209. /*
  4210. * Local variables:
  4211. * tab-width: 8
  4212. * c-basic-offset: 8
  4213. * End:
  4214. * vim600: sw=4 ts=4 fdm=marker
  4215. * vim<600: sw=4 ts=4
  4216. */