1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 5                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2014 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: Sascha Schumann <sascha@schumann.cx>                        |
16   |          Derick Rethans <derick@derickrethans.nl>                    |
17   +----------------------------------------------------------------------+
18 */
19/* $Id$ */
20
21#ifdef HAVE_CONFIG_H
22#include "config.h"
23#endif
24
25#include "php.h"
26
27#if HAVE_LIBMCRYPT
28
29#if PHP_WIN32
30# include "win32/winutil.h"
31#endif
32
33#include "php_mcrypt.h"
34#include "fcntl.h"
35
36#define NON_FREE
37#define MCRYPT2
38#include "mcrypt.h"
39#include "php_ini.h"
40#include "php_globals.h"
41#include "ext/standard/info.h"
42#include "ext/standard/php_rand.h"
43#include "ext/standard/php_smart_str.h"
44#include "php_mcrypt_filter.h"
45
46static int le_mcrypt;
47
48typedef struct _php_mcrypt {
49    MCRYPT td;
50    zend_bool init;
51} php_mcrypt;
52
53/* {{{ arginfo */
54ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_open, 0, 0, 4)
55    ZEND_ARG_INFO(0, cipher)
56    ZEND_ARG_INFO(0, cipher_directory)
57    ZEND_ARG_INFO(0, mode)
58    ZEND_ARG_INFO(0, mode_directory)
59ZEND_END_ARG_INFO()
60
61ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_generic_init, 0, 0, 3)
62    ZEND_ARG_INFO(0, td)
63    ZEND_ARG_INFO(0, key)
64    ZEND_ARG_INFO(0, iv)
65ZEND_END_ARG_INFO()
66
67ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_generic, 0, 0, 2)
68    ZEND_ARG_INFO(0, td)
69    ZEND_ARG_INFO(0, data)
70ZEND_END_ARG_INFO()
71
72ZEND_BEGIN_ARG_INFO_EX(arginfo_mdecrypt_generic, 0, 0, 2)
73    ZEND_ARG_INFO(0, td)
74    ZEND_ARG_INFO(0, data)
75ZEND_END_ARG_INFO()
76
77ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_supported_key_sizes, 0, 0, 1)
78    ZEND_ARG_INFO(0, td)
79ZEND_END_ARG_INFO()
80
81ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_self_test, 0, 0, 1)
82    ZEND_ARG_INFO(0, td)
83ZEND_END_ARG_INFO()
84
85ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_close, 0, 0, 1)
86    ZEND_ARG_INFO(0, td)
87ZEND_END_ARG_INFO()
88
89ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_generic_deinit, 0, 0, 1)
90    ZEND_ARG_INFO(0, td)
91ZEND_END_ARG_INFO()
92
93ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_is_block_algorithm_mode, 0, 0, 1)
94    ZEND_ARG_INFO(0, td)
95ZEND_END_ARG_INFO()
96
97ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_is_block_algorithm, 0, 0, 1)
98    ZEND_ARG_INFO(0, td)
99ZEND_END_ARG_INFO()
100
101ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_is_block_mode, 0, 0, 1)
102    ZEND_ARG_INFO(0, td)
103ZEND_END_ARG_INFO()
104
105ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_block_size, 0, 0, 1)
106    ZEND_ARG_INFO(0, td)
107ZEND_END_ARG_INFO()
108
109ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_key_size, 0, 0, 1)
110    ZEND_ARG_INFO(0, td)
111ZEND_END_ARG_INFO()
112
113ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_iv_size, 0, 0, 1)
114    ZEND_ARG_INFO(0, td)
115ZEND_END_ARG_INFO()
116
117ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_algorithms_name, 0, 0, 1)
118    ZEND_ARG_INFO(0, td)
119ZEND_END_ARG_INFO()
120
121ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_enc_get_modes_name, 0, 0, 1)
122    ZEND_ARG_INFO(0, td)
123ZEND_END_ARG_INFO()
124
125ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_self_test, 0, 0, 1)
126    ZEND_ARG_INFO(0, algorithm)
127    ZEND_ARG_INFO(0, lib_dir)
128ZEND_END_ARG_INFO()
129
130ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_is_block_algorithm_mode, 0, 0, 1)
131    ZEND_ARG_INFO(0, mode)
132    ZEND_ARG_INFO(0, lib_dir)
133ZEND_END_ARG_INFO()
134
135ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_is_block_algorithm, 0, 0, 1)
136    ZEND_ARG_INFO(0, algorithm)
137    ZEND_ARG_INFO(0, lib_dir)
138ZEND_END_ARG_INFO()
139
140ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_is_block_mode, 0, 0, 1)
141    ZEND_ARG_INFO(0, mode)
142    ZEND_ARG_INFO(0, lib_dir)
143ZEND_END_ARG_INFO()
144
145ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_get_algo_block_size, 0, 0, 1)
146    ZEND_ARG_INFO(0, algorithm)
147    ZEND_ARG_INFO(0, lib_dir)
148ZEND_END_ARG_INFO()
149
150ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_get_algo_key_size, 0, 0, 1)
151    ZEND_ARG_INFO(0, algorithm)
152    ZEND_ARG_INFO(0, lib_dir)
153ZEND_END_ARG_INFO()
154
155ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_module_get_supported_key_sizes, 0, 0, 1)
156    ZEND_ARG_INFO(0, algorithm)
157    ZEND_ARG_INFO(0, lib_dir)
158ZEND_END_ARG_INFO()
159
160ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_list_algorithms, 0, 0, 0)
161    ZEND_ARG_INFO(0, lib_dir)
162ZEND_END_ARG_INFO()
163
164ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_list_modes, 0, 0, 0)
165    ZEND_ARG_INFO(0, lib_dir)
166ZEND_END_ARG_INFO()
167
168ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_get_key_size, 0, 0, 2)
169    ZEND_ARG_INFO(0, cipher)
170    ZEND_ARG_INFO(0, module)
171ZEND_END_ARG_INFO()
172
173ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_get_block_size, 0, 0, 2)
174    ZEND_ARG_INFO(0, cipher)
175    ZEND_ARG_INFO(0, module)
176ZEND_END_ARG_INFO()
177
178ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_get_iv_size, 0, 0, 2)
179    ZEND_ARG_INFO(0, cipher)
180    ZEND_ARG_INFO(0, module)
181ZEND_END_ARG_INFO()
182
183ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_get_cipher_name, 0, 0, 1)
184    ZEND_ARG_INFO(0, cipher)
185ZEND_END_ARG_INFO()
186
187ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_encrypt, 0, 0, 5)
188    ZEND_ARG_INFO(0, cipher)
189    ZEND_ARG_INFO(0, key)
190    ZEND_ARG_INFO(0, data)
191    ZEND_ARG_INFO(0, mode)
192    ZEND_ARG_INFO(0, iv)
193ZEND_END_ARG_INFO()
194
195ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_decrypt, 0, 0, 5)
196    ZEND_ARG_INFO(0, cipher)
197    ZEND_ARG_INFO(0, key)
198    ZEND_ARG_INFO(0, data)
199    ZEND_ARG_INFO(0, mode)
200    ZEND_ARG_INFO(0, iv)
201ZEND_END_ARG_INFO()
202
203ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_ecb, 0, 0, 5)
204    ZEND_ARG_INFO(0, cipher)
205    ZEND_ARG_INFO(0, key)
206    ZEND_ARG_INFO(0, data)
207    ZEND_ARG_INFO(0, mode)
208    ZEND_ARG_INFO(0, iv)
209ZEND_END_ARG_INFO()
210
211ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_cbc, 0, 0, 5)
212    ZEND_ARG_INFO(0, cipher)
213    ZEND_ARG_INFO(0, key)
214    ZEND_ARG_INFO(0, data)
215    ZEND_ARG_INFO(0, mode)
216    ZEND_ARG_INFO(0, iv)
217ZEND_END_ARG_INFO()
218
219ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_cfb, 0, 0, 5)
220    ZEND_ARG_INFO(0, cipher)
221    ZEND_ARG_INFO(0, key)
222    ZEND_ARG_INFO(0, data)
223    ZEND_ARG_INFO(0, mode)
224    ZEND_ARG_INFO(0, iv)
225ZEND_END_ARG_INFO()
226
227ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_ofb, 0, 0, 5)
228    ZEND_ARG_INFO(0, cipher)
229    ZEND_ARG_INFO(0, key)
230    ZEND_ARG_INFO(0, data)
231    ZEND_ARG_INFO(0, mode)
232    ZEND_ARG_INFO(0, iv)
233ZEND_END_ARG_INFO()
234
235ZEND_BEGIN_ARG_INFO_EX(arginfo_mcrypt_create_iv, 0, 0, 1)
236    ZEND_ARG_INFO(0, size)
237    ZEND_ARG_INFO(0, source)
238ZEND_END_ARG_INFO()
239/* }}} */
240
241const zend_function_entry mcrypt_functions[] = { /* {{{ */
242    PHP_DEP_FE(mcrypt_ecb,              arginfo_mcrypt_ecb)
243    PHP_DEP_FE(mcrypt_cbc,              arginfo_mcrypt_cbc)
244    PHP_DEP_FE(mcrypt_cfb,              arginfo_mcrypt_cfb)
245    PHP_DEP_FE(mcrypt_ofb,              arginfo_mcrypt_ofb)
246    PHP_FE(mcrypt_get_key_size,     arginfo_mcrypt_get_key_size)
247    PHP_FE(mcrypt_get_block_size,   arginfo_mcrypt_get_block_size)
248    PHP_FE(mcrypt_get_cipher_name,  arginfo_mcrypt_get_cipher_name)
249    PHP_FE(mcrypt_create_iv,        arginfo_mcrypt_create_iv)
250
251    PHP_FE(mcrypt_list_algorithms,  arginfo_mcrypt_list_algorithms)
252    PHP_FE(mcrypt_list_modes,       arginfo_mcrypt_list_modes)
253    PHP_FE(mcrypt_get_iv_size,      arginfo_mcrypt_get_iv_size)
254    PHP_FE(mcrypt_encrypt,          arginfo_mcrypt_encrypt)
255    PHP_FE(mcrypt_decrypt,          arginfo_mcrypt_decrypt)
256
257    PHP_FE(mcrypt_module_open,      arginfo_mcrypt_module_open)
258    PHP_FE(mcrypt_generic_init,     arginfo_mcrypt_generic_init)
259    PHP_FE(mcrypt_generic,          arginfo_mcrypt_generic)
260    PHP_FE(mdecrypt_generic,        arginfo_mdecrypt_generic)
261    PHP_DEP_FALIAS(mcrypt_generic_end, mcrypt_generic_deinit, arginfo_mcrypt_generic_deinit)
262    PHP_FE(mcrypt_generic_deinit,   arginfo_mcrypt_generic_deinit)
263
264    PHP_FE(mcrypt_enc_self_test,    arginfo_mcrypt_enc_self_test)
265    PHP_FE(mcrypt_enc_is_block_algorithm_mode, arginfo_mcrypt_enc_is_block_algorithm_mode)
266    PHP_FE(mcrypt_enc_is_block_algorithm,   arginfo_mcrypt_enc_is_block_algorithm)
267    PHP_FE(mcrypt_enc_is_block_mode,        arginfo_mcrypt_enc_is_block_mode)
268    PHP_FE(mcrypt_enc_get_block_size,       arginfo_mcrypt_enc_get_block_size)
269    PHP_FE(mcrypt_enc_get_key_size,         arginfo_mcrypt_enc_get_key_size)
270    PHP_FE(mcrypt_enc_get_supported_key_sizes, arginfo_mcrypt_enc_get_supported_key_sizes)
271    PHP_FE(mcrypt_enc_get_iv_size,          arginfo_mcrypt_enc_get_iv_size)
272    PHP_FE(mcrypt_enc_get_algorithms_name,  arginfo_mcrypt_enc_get_algorithms_name)
273    PHP_FE(mcrypt_enc_get_modes_name,       arginfo_mcrypt_enc_get_modes_name)
274    PHP_FE(mcrypt_module_self_test,         arginfo_mcrypt_module_self_test)
275
276    PHP_FE(mcrypt_module_is_block_algorithm_mode,   arginfo_mcrypt_module_is_block_algorithm_mode)
277    PHP_FE(mcrypt_module_is_block_algorithm,        arginfo_mcrypt_module_is_block_algorithm)
278    PHP_FE(mcrypt_module_is_block_mode,             arginfo_mcrypt_module_is_block_mode)
279    PHP_FE(mcrypt_module_get_algo_block_size,       arginfo_mcrypt_module_get_algo_block_size)
280    PHP_FE(mcrypt_module_get_algo_key_size,         arginfo_mcrypt_module_get_algo_key_size)
281    PHP_FE(mcrypt_module_get_supported_key_sizes,   arginfo_mcrypt_module_get_supported_key_sizes)
282
283    PHP_FE(mcrypt_module_close,                     arginfo_mcrypt_module_close)
284    PHP_FE_END
285};
286/* }}} */
287
288static PHP_MINFO_FUNCTION(mcrypt);
289static PHP_MINIT_FUNCTION(mcrypt);
290static PHP_MSHUTDOWN_FUNCTION(mcrypt);
291
292ZEND_DECLARE_MODULE_GLOBALS(mcrypt)
293
294zend_module_entry mcrypt_module_entry = {
295    STANDARD_MODULE_HEADER,
296    "mcrypt",
297    mcrypt_functions,
298    PHP_MINIT(mcrypt), PHP_MSHUTDOWN(mcrypt),
299    NULL, NULL,
300    PHP_MINFO(mcrypt),
301    NO_VERSION_YET,
302    PHP_MODULE_GLOBALS(mcrypt),
303    NULL,
304    NULL,
305    NULL,
306    STANDARD_MODULE_PROPERTIES_EX
307};
308
309#ifdef COMPILE_DL_MCRYPT
310ZEND_GET_MODULE(mcrypt)
311#endif
312
313#define MCRYPT_ENCRYPT 0
314#define MCRYPT_DECRYPT 1
315
316typedef enum {
317    RANDOM = 0,
318    URANDOM,
319    RAND
320} iv_source;
321
322#define MCRYPT_GET_INI                                          \
323    cipher_dir_string = MCG(algorithms_dir);                    \
324    module_dir_string = MCG(modes_dir);
325
326/*
327 * #warning is not ANSI C
328 * #warning Invalidate resource if the param count is wrong, or other problems
329 * #warning occurred during functions.
330 */
331
332#define MCRYPT_GET_CRYPT_ARGS                                       \
333    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sssz|s",  \
334        &cipher, &cipher_len, &key, &key_len, &data, &data_len, &mode, &iv, &iv_len) == FAILURE) {  \
335        return;     \
336    }
337
338#define MCRYPT_GET_TD_ARG                                       \
339    zval *mcryptind;                                            \
340    php_mcrypt *pm;                                                 \
341    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &mcryptind) == FAILURE) {         \
342        return;                                                             \
343    }                                                                                       \
344    ZEND_FETCH_RESOURCE (pm, php_mcrypt *, mcryptind, -1, "MCrypt", le_mcrypt);
345
346#define MCRYPT_GET_MODE_DIR_ARGS(DIRECTORY)                             \
347    char *dir = NULL;                                                   \
348    size_t   dir_len;                                                      \
349    char *module;                                                       \
350    size_t   module_len;                                                   \
351    if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC,               \
352        "s|s", &module, &module_len, &dir, &dir_len) == FAILURE) {      \
353        return;                                                         \
354    }
355
356#define MCRYPT_OPEN_MODULE_FAILED "Module initialization failed"
357
358#define MCRYPT_ENTRY2_2_4(a,b) REGISTER_STRING_CONSTANT("MCRYPT_" #a, b, CONST_PERSISTENT)
359#define MCRYPT_ENTRY2_4(a) MCRYPT_ENTRY_NAMED(a, a)
360
361#define PHP_MCRYPT_INIT_CHECK   \
362    if (!pm->init) {    \
363        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Operation disallowed prior to mcrypt_generic_init().");    \
364        RETURN_FALSE;   \
365    }   \
366
367PHP_INI_BEGIN()
368    STD_PHP_INI_ENTRY("mcrypt.algorithms_dir", NULL, PHP_INI_ALL, OnUpdateString, algorithms_dir, zend_mcrypt_globals, mcrypt_globals)
369    STD_PHP_INI_ENTRY("mcrypt.modes_dir",      NULL, PHP_INI_ALL, OnUpdateString, modes_dir, zend_mcrypt_globals, mcrypt_globals)
370PHP_INI_END()
371
372static void php_mcrypt_module_dtor(zend_resource *rsrc TSRMLS_DC) /* {{{ */
373{
374    php_mcrypt *pm = (php_mcrypt *) rsrc->ptr;
375    if (pm) {
376        mcrypt_generic_deinit(pm->td);
377        mcrypt_module_close(pm->td);
378        efree(pm);
379        pm = NULL;
380    }
381}
382/* }}} */
383
384static PHP_MINIT_FUNCTION(mcrypt) /* {{{ */
385{
386    le_mcrypt = zend_register_list_destructors_ex(php_mcrypt_module_dtor, NULL, "mcrypt", module_number);
387
388    /* modes for mcrypt_??? routines */
389    REGISTER_LONG_CONSTANT("MCRYPT_ENCRYPT", 0, CONST_PERSISTENT);
390    REGISTER_LONG_CONSTANT("MCRYPT_DECRYPT", 1, CONST_PERSISTENT);
391
392    /* sources for mcrypt_create_iv */
393    REGISTER_LONG_CONSTANT("MCRYPT_DEV_RANDOM", RANDOM, CONST_PERSISTENT);
394    REGISTER_LONG_CONSTANT("MCRYPT_DEV_URANDOM", URANDOM, CONST_PERSISTENT);
395    REGISTER_LONG_CONSTANT("MCRYPT_RAND", RAND, CONST_PERSISTENT);
396
397    /* ciphers */
398    MCRYPT_ENTRY2_2_4(3DES, "tripledes");
399    MCRYPT_ENTRY2_2_4(ARCFOUR_IV, "arcfour-iv");
400    MCRYPT_ENTRY2_2_4(ARCFOUR, "arcfour");
401    MCRYPT_ENTRY2_2_4(BLOWFISH, "blowfish");
402    MCRYPT_ENTRY2_2_4(BLOWFISH_COMPAT, "blowfish-compat");
403    MCRYPT_ENTRY2_2_4(CAST_128, "cast-128");
404    MCRYPT_ENTRY2_2_4(CAST_256, "cast-256");
405    MCRYPT_ENTRY2_2_4(CRYPT, "crypt");
406    MCRYPT_ENTRY2_2_4(DES, "des");
407    MCRYPT_ENTRY2_2_4(ENIGNA, "crypt");
408    MCRYPT_ENTRY2_2_4(GOST, "gost");
409    MCRYPT_ENTRY2_2_4(LOKI97, "loki97");
410    MCRYPT_ENTRY2_2_4(PANAMA, "panama");
411    MCRYPT_ENTRY2_2_4(RC2, "rc2");
412    MCRYPT_ENTRY2_2_4(RIJNDAEL_128, "rijndael-128");
413    MCRYPT_ENTRY2_2_4(RIJNDAEL_192, "rijndael-192");
414    MCRYPT_ENTRY2_2_4(RIJNDAEL_256, "rijndael-256");
415    MCRYPT_ENTRY2_2_4(SAFER64, "safer-sk64");
416    MCRYPT_ENTRY2_2_4(SAFER128, "safer-sk128");
417    MCRYPT_ENTRY2_2_4(SAFERPLUS, "saferplus");
418    MCRYPT_ENTRY2_2_4(SERPENT, "serpent");
419    MCRYPT_ENTRY2_2_4(THREEWAY, "threeway");
420    MCRYPT_ENTRY2_2_4(TRIPLEDES, "tripledes");
421    MCRYPT_ENTRY2_2_4(TWOFISH, "twofish");
422    MCRYPT_ENTRY2_2_4(WAKE, "wake");
423    MCRYPT_ENTRY2_2_4(XTEA, "xtea");
424
425    MCRYPT_ENTRY2_2_4(IDEA, "idea");
426    MCRYPT_ENTRY2_2_4(MARS, "mars");
427    MCRYPT_ENTRY2_2_4(RC6, "rc6");
428    MCRYPT_ENTRY2_2_4(SKIPJACK, "skipjack");
429/* modes */
430    MCRYPT_ENTRY2_2_4(MODE_CBC, "cbc");
431    MCRYPT_ENTRY2_2_4(MODE_CFB, "cfb");
432    MCRYPT_ENTRY2_2_4(MODE_ECB, "ecb");
433    MCRYPT_ENTRY2_2_4(MODE_NOFB, "nofb");
434    MCRYPT_ENTRY2_2_4(MODE_OFB, "ofb");
435    MCRYPT_ENTRY2_2_4(MODE_STREAM, "stream");
436    REGISTER_INI_ENTRIES();
437
438    php_stream_filter_register_factory("mcrypt.*", &php_mcrypt_filter_factory TSRMLS_CC);
439    php_stream_filter_register_factory("mdecrypt.*", &php_mcrypt_filter_factory TSRMLS_CC);
440
441    return SUCCESS;
442}
443/* }}} */
444
445static PHP_MSHUTDOWN_FUNCTION(mcrypt) /* {{{ */
446{
447    php_stream_filter_unregister_factory("mcrypt.*" TSRMLS_CC);
448    php_stream_filter_unregister_factory("mdecrypt.*" TSRMLS_CC);
449
450    UNREGISTER_INI_ENTRIES();
451    return SUCCESS;
452}
453/* }}} */
454
455#include "ext/standard/php_smart_str.h"
456
457PHP_MINFO_FUNCTION(mcrypt) /* {{{ */
458{
459    char **modules;
460    char mcrypt_api_no[16];
461    int i, count;
462    smart_str tmp1 = {0};
463    smart_str tmp2 = {0};
464
465    modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count);
466    if (count == 0) {
467        smart_str_appends(&tmp1, "none");
468    }
469    for (i = 0; i < count; i++) {
470        smart_str_appends(&tmp1, modules[i]);
471        smart_str_appendc(&tmp1, ' ');
472    }
473    smart_str_0(&tmp1);
474    mcrypt_free_p(modules, count);
475
476    modules = mcrypt_list_modes(MCG(modes_dir), &count);
477    if (count == 0) {
478        smart_str_appends(&tmp2, "none");
479    }
480    for (i = 0; i < count; i++) {
481        smart_str_appends(&tmp2, modules[i]);
482        smart_str_appendc(&tmp2, ' ');
483    }
484    smart_str_0 (&tmp2);
485    mcrypt_free_p (modules, count);
486
487    snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION);
488
489    php_info_print_table_start();
490    php_info_print_table_header(2, "mcrypt support", "enabled");
491    php_info_print_table_header(2, "mcrypt_filter support", "enabled");
492    php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION);
493    php_info_print_table_row(2, "Api No", mcrypt_api_no);
494    php_info_print_table_row(2, "Supported ciphers", tmp1.s->val);
495    php_info_print_table_row(2, "Supported modes", tmp2.s->val);
496    smart_str_free(&tmp1);
497    smart_str_free(&tmp2);
498
499    php_info_print_table_end();
500
501    DISPLAY_INI_ENTRIES();
502}
503/* }}} */
504
505/* {{{ proto resource mcrypt_module_open(string cipher, string cipher_directory, string mode, string mode_directory)
506   Opens the module of the algorithm and the mode to be used */
507PHP_FUNCTION(mcrypt_module_open)
508{
509    char *cipher, *cipher_dir;
510    char *mode,   *mode_dir;
511    size_t   cipher_len, cipher_dir_len;
512    size_t   mode_len,   mode_dir_len;
513    MCRYPT td;
514    php_mcrypt *pm;
515
516    if (zend_parse_parameters (ZEND_NUM_ARGS() TSRMLS_CC, "ssss",
517        &cipher, &cipher_len, &cipher_dir, &cipher_dir_len,
518        &mode,   &mode_len,   &mode_dir,   &mode_dir_len)) {
519        return;
520    }
521
522    td = mcrypt_module_open (
523        cipher,
524        cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir),
525        mode,
526        mode_dir_len > 0 ? mode_dir : MCG(modes_dir)
527    );
528
529    if (td == MCRYPT_FAILED) {
530        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not open encryption module");
531        RETURN_FALSE;
532    } else {
533        pm = emalloc(sizeof(php_mcrypt));
534        pm->td = td;
535        pm->init = 0;
536        ZEND_REGISTER_RESOURCE(return_value, pm, le_mcrypt);
537    }
538}
539/* }}} */
540
541/* {{{ proto int mcrypt_generic_init(resource td, string key, string iv)
542   This function initializes all buffers for the specific module */
543PHP_FUNCTION(mcrypt_generic_init)
544{
545    char *key, *iv;
546    size_t key_len, iv_len;
547    zval *mcryptind;
548    unsigned char *key_s, *iv_s;
549    int max_key_size, key_size, iv_size;
550    php_mcrypt *pm;
551    int result = 0;
552
553    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) {
554        return;
555    }
556
557    ZEND_FETCH_RESOURCE(pm, php_mcrypt *, mcryptind, -1, "MCrypt", le_mcrypt);
558
559    max_key_size = mcrypt_enc_get_key_size(pm->td);
560    iv_size = mcrypt_enc_get_iv_size(pm->td);
561
562    if (key_len == 0) {
563        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size is 0");
564    }
565
566    key_s = emalloc(key_len);
567    memset(key_s, 0, key_len);
568
569    iv_s = emalloc(iv_size + 1);
570    memset(iv_s, 0, iv_size + 1);
571
572    if (key_len > max_key_size) {
573        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size);
574        key_size = max_key_size;
575    } else {
576        key_size = key_len;
577    }
578    memcpy(key_s, key, key_len);
579
580    if (iv_len != iv_size) {
581        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size);
582    }
583    memcpy(iv_s, iv, iv_size);
584
585    mcrypt_generic_deinit(pm->td);
586    result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s);
587
588    /* If this function fails, close the mcrypt module to prevent crashes
589     * when further functions want to access this resource */
590    if (result < 0) {
591        zend_list_close(Z_RES_P(mcryptind));
592        switch (result) {
593            case -3:
594                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Key length incorrect");
595                break;
596            case -4:
597                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Memory allocation error");
598                break;
599            case -1:
600            default:
601                php_error_docref(NULL TSRMLS_CC, E_WARNING, "Unknown error");
602                break;
603        }
604    }
605    pm->init = 1;
606    RETVAL_LONG(result);
607
608    efree(iv_s);
609    efree(key_s);
610}
611/* }}} */
612
613/* {{{ proto string mcrypt_generic(resource td, string data)
614   This function encrypts the plaintext */
615PHP_FUNCTION(mcrypt_generic)
616{
617    zval *mcryptind;
618    char *data;
619    size_t data_len;
620    php_mcrypt *pm;
621    char* data_s;
622    int block_size, data_size;
623
624    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) {
625        return;
626    }
627
628    ZEND_FETCH_RESOURCE(pm, php_mcrypt *, mcryptind, -1, "MCrypt", le_mcrypt);
629    PHP_MCRYPT_INIT_CHECK
630
631    if (data_len == 0) {
632        php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed");
633        RETURN_FALSE
634    }
635
636    /* Check blocksize */
637    if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */
638        block_size = mcrypt_enc_get_block_size(pm->td);
639        data_size = (((data_len - 1) / block_size) + 1) * block_size;
640        data_s = emalloc(data_size + 1);
641        memset(data_s, 0, data_size);
642        memcpy(data_s, data, data_len);
643    } else { /* It's not a block algorithm */
644        data_size = data_len;
645        data_s = emalloc(data_size + 1);
646        memset(data_s, 0, data_size);
647        memcpy(data_s, data, data_len);
648    }
649
650    mcrypt_generic(pm->td, data_s, data_size);
651    data_s[data_size] = '\0';
652
653    RETVAL_STRINGL(data_s, data_size);
654    efree(data_s);
655}
656/* }}} */
657
658/* {{{ proto string mdecrypt_generic(resource td, string data)
659   This function decrypts the plaintext */
660PHP_FUNCTION(mdecrypt_generic)
661{
662    zval *mcryptind;
663    char *data;
664    size_t data_len;
665    php_mcrypt *pm;
666    char* data_s;
667    int block_size, data_size;
668
669    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs", &mcryptind, &data, &data_len) == FAILURE) {
670        return;
671    }
672
673    ZEND_FETCH_RESOURCE(pm, php_mcrypt * , mcryptind, -1, "MCrypt", le_mcrypt);
674    PHP_MCRYPT_INIT_CHECK
675
676    if (data_len == 0) {
677        php_error_docref(NULL TSRMLS_CC, E_WARNING, "An empty string was passed");
678        RETURN_FALSE
679    }
680
681    /* Check blocksize */
682    if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */
683        block_size = mcrypt_enc_get_block_size(pm->td);
684        data_size = (((data_len - 1) / block_size) + 1) * block_size;
685        data_s = emalloc(data_size + 1);
686        memset(data_s, 0, data_size);
687        memcpy(data_s, data, data_len);
688    } else { /* It's not a block algorithm */
689        data_size = data_len;
690        data_s = emalloc(data_size + 1);
691        memset(data_s, 0, data_size);
692        memcpy(data_s, data, data_len);
693    }
694
695    mdecrypt_generic(pm->td, data_s, data_size);
696
697    RETVAL_STRINGL(data_s, data_size);
698    efree(data_s);
699}
700/* }}} */
701
702/* {{{ proto array mcrypt_enc_get_supported_key_sizes(resource td)
703   This function decrypts the crypttext */
704PHP_FUNCTION(mcrypt_enc_get_supported_key_sizes)
705{
706    int i, count = 0;
707    int *key_sizes;
708
709    MCRYPT_GET_TD_ARG
710    array_init(return_value);
711
712    key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count);
713
714    for (i = 0; i < count; i++) {
715        add_index_long(return_value, i, key_sizes[i]);
716    }
717
718    mcrypt_free(key_sizes);
719}
720/* }}} */
721
722/* {{{ proto int mcrypt_enc_self_test(resource td)
723   This function runs the self test on the algorithm specified by the descriptor td */
724PHP_FUNCTION(mcrypt_enc_self_test)
725{
726    MCRYPT_GET_TD_ARG
727    RETURN_LONG(mcrypt_enc_self_test(pm->td));
728}
729/* }}} */
730
731/* {{{ proto bool mcrypt_module_close(resource td)
732   Free the descriptor td */
733PHP_FUNCTION(mcrypt_module_close)
734{
735    MCRYPT_GET_TD_ARG
736    zend_list_close(Z_RES_P(mcryptind));
737    RETURN_TRUE;
738}
739/* }}} */
740
741/* {{{ proto bool mcrypt_generic_deinit(resource td)
742   This function terminates encrypt specified by the descriptor td */
743PHP_FUNCTION(mcrypt_generic_deinit)
744{
745    MCRYPT_GET_TD_ARG
746
747    if (mcrypt_generic_deinit(pm->td) < 0) {
748        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not terminate encryption specifier");
749        RETURN_FALSE
750    }
751    pm->init = 0;
752    RETURN_TRUE
753}
754/* }}} */
755
756/* {{{ proto bool mcrypt_enc_is_block_algorithm_mode(resource td)
757   Returns TRUE if the mode is for use with block algorithms */
758PHP_FUNCTION(mcrypt_enc_is_block_algorithm_mode)
759{
760    MCRYPT_GET_TD_ARG
761
762    if (mcrypt_enc_is_block_algorithm_mode(pm->td) == 1) {
763        RETURN_TRUE
764    } else {
765        RETURN_FALSE
766    }
767}
768/* }}} */
769
770/* {{{ proto bool mcrypt_enc_is_block_algorithm(resource td)
771   Returns TRUE if the alrogithm is a block algorithms */
772PHP_FUNCTION(mcrypt_enc_is_block_algorithm)
773{
774    MCRYPT_GET_TD_ARG
775
776    if (mcrypt_enc_is_block_algorithm(pm->td) == 1) {
777        RETURN_TRUE
778    } else {
779        RETURN_FALSE
780    }
781}
782/* }}} */
783
784/* {{{ proto bool mcrypt_enc_is_block_mode(resource td)
785   Returns TRUE if the mode outputs blocks */
786PHP_FUNCTION(mcrypt_enc_is_block_mode)
787{
788    MCRYPT_GET_TD_ARG
789
790    if (mcrypt_enc_is_block_mode(pm->td) == 1) {
791        RETURN_TRUE
792    } else {
793        RETURN_FALSE
794    }
795}
796/* }}} */
797
798/* {{{ proto int mcrypt_enc_get_block_size(resource td)
799   Returns the block size of the cipher specified by the descriptor td */
800PHP_FUNCTION(mcrypt_enc_get_block_size)
801{
802    MCRYPT_GET_TD_ARG
803    RETURN_LONG(mcrypt_enc_get_block_size(pm->td));
804}
805/* }}} */
806
807/* {{{ proto int mcrypt_enc_get_key_size(resource td)
808   Returns the maximum supported key size in bytes of the algorithm specified by the descriptor td */
809PHP_FUNCTION(mcrypt_enc_get_key_size)
810{
811    MCRYPT_GET_TD_ARG
812    RETURN_LONG(mcrypt_enc_get_key_size(pm->td));
813}
814/* }}} */
815
816/* {{{ proto int mcrypt_enc_get_iv_size(resource td)
817   Returns the size of the IV in bytes of the algorithm specified by the descriptor td */
818PHP_FUNCTION(mcrypt_enc_get_iv_size)
819{
820    MCRYPT_GET_TD_ARG
821    RETURN_LONG(mcrypt_enc_get_iv_size(pm->td));
822}
823/* }}} */
824
825/* {{{ proto string mcrypt_enc_get_algorithms_name(resource td)
826   Returns the name of the algorithm specified by the descriptor td */
827PHP_FUNCTION(mcrypt_enc_get_algorithms_name)
828{
829    char *name;
830    MCRYPT_GET_TD_ARG
831
832    name = mcrypt_enc_get_algorithms_name(pm->td);
833    RETVAL_STRING(name);
834    mcrypt_free(name);
835}
836/* }}} */
837
838/* {{{ proto string mcrypt_enc_get_modes_name(resource td)
839   Returns the name of the mode specified by the descriptor td */
840PHP_FUNCTION(mcrypt_enc_get_modes_name)
841{
842    char *name;
843    MCRYPT_GET_TD_ARG
844
845    name = mcrypt_enc_get_modes_name(pm->td);
846    RETVAL_STRING(name);
847    mcrypt_free(name);
848}
849/* }}} */
850
851/* {{{ proto bool mcrypt_module_self_test(string algorithm [, string lib_dir])
852   Does a self test of the module "module" */
853PHP_FUNCTION(mcrypt_module_self_test)
854{
855    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir);
856
857    if (mcrypt_module_self_test(module, dir) == 0) {
858        RETURN_TRUE;
859    } else {
860        RETURN_FALSE;
861    }
862}
863/* }}} */
864
865/* {{{ proto bool mcrypt_module_is_block_algorithm_mode(string mode [, string lib_dir])
866   Returns TRUE if the mode is for use with block algorithms */
867PHP_FUNCTION(mcrypt_module_is_block_algorithm_mode)
868{
869    MCRYPT_GET_MODE_DIR_ARGS(modes_dir)
870
871    if (mcrypt_module_is_block_algorithm_mode(module, dir) == 1) {
872        RETURN_TRUE;
873    } else {
874        RETURN_FALSE;
875    }
876}
877/* }}} */
878
879/* {{{ proto bool mcrypt_module_is_block_algorithm(string algorithm [, string lib_dir])
880   Returns TRUE if the algorithm is a block algorithm */
881PHP_FUNCTION(mcrypt_module_is_block_algorithm)
882{
883    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
884
885    if (mcrypt_module_is_block_algorithm(module, dir) == 1) {
886        RETURN_TRUE;
887    } else {
888        RETURN_FALSE;
889    }
890}
891/* }}} */
892
893/* {{{ proto bool mcrypt_module_is_block_mode(string mode [, string lib_dir])
894   Returns TRUE if the mode outputs blocks of bytes */
895PHP_FUNCTION(mcrypt_module_is_block_mode)
896{
897    MCRYPT_GET_MODE_DIR_ARGS(modes_dir)
898
899    if (mcrypt_module_is_block_mode(module, dir) == 1) {
900        RETURN_TRUE;
901    } else {
902        RETURN_FALSE;
903    }
904}
905/* }}} */
906
907/* {{{ proto int mcrypt_module_get_algo_block_size(string algorithm [, string lib_dir])
908   Returns the block size of the algorithm */
909PHP_FUNCTION(mcrypt_module_get_algo_block_size)
910{
911    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
912
913    RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir));
914}
915/* }}} */
916
917/* {{{ proto int mcrypt_module_get_algo_key_size(string algorithm [, string lib_dir])
918   Returns the maximum supported key size of the algorithm */
919PHP_FUNCTION(mcrypt_module_get_algo_key_size)
920{
921    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir);
922
923    RETURN_LONG(mcrypt_module_get_algo_key_size(module, dir));
924}
925/* }}} */
926
927/* {{{ proto array mcrypt_module_get_supported_key_sizes(string algorithm [, string lib_dir])
928   This function decrypts the crypttext */
929PHP_FUNCTION(mcrypt_module_get_supported_key_sizes)
930{
931    int i, count = 0;
932    int *key_sizes;
933
934    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
935    array_init(return_value);
936
937    key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count);
938
939    for (i = 0; i < count; i++) {
940        add_index_long(return_value, i, key_sizes[i]);
941    }
942    mcrypt_free(key_sizes);
943}
944/* }}} */
945
946/* {{{ proto array mcrypt_list_algorithms([string lib_dir])
947   List all algorithms in "module_dir" */
948PHP_FUNCTION(mcrypt_list_algorithms)
949{
950    char **modules;
951    char *lib_dir = MCG(algorithms_dir);
952    size_t   lib_dir_len;
953    int   i, count;
954
955    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s",
956        &lib_dir, &lib_dir_len) == FAILURE) {
957        return;
958    }
959
960    array_init(return_value);
961    modules = mcrypt_list_algorithms(lib_dir, &count);
962
963    if (count == 0) {
964        php_error_docref(NULL TSRMLS_CC, E_WARNING, "No algorithms found in module dir");
965    }
966    for (i = 0; i < count; i++) {
967        add_index_string(return_value, i, modules[i]);
968    }
969    mcrypt_free_p(modules, count);
970}
971/* }}} */
972
973/* {{{ proto array mcrypt_list_modes([string lib_dir])
974   List all modes "module_dir" */
975PHP_FUNCTION(mcrypt_list_modes)
976{
977    char **modules;
978    char *lib_dir = MCG(modes_dir);
979    size_t   lib_dir_len;
980    int   i, count;
981
982    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|s",
983        &lib_dir, &lib_dir_len) == FAILURE) {
984        return;
985    }
986
987    array_init(return_value);
988    modules = mcrypt_list_modes(lib_dir, &count);
989
990    if (count == 0) {
991        php_error_docref(NULL TSRMLS_CC, E_WARNING, "No modes found in module dir");
992    }
993    for (i = 0; i < count; i++) {
994        add_index_string(return_value, i, modules[i]);
995    }
996    mcrypt_free_p(modules, count);
997}
998/* }}} */
999
1000/* {{{ proto int mcrypt_get_key_size(string cipher, string module)
1001   Get the key size of cipher */
1002PHP_FUNCTION(mcrypt_get_key_size)
1003{
1004    char *cipher;
1005    char *module;
1006    size_t   cipher_len, module_len;
1007    char *cipher_dir_string;
1008    char *module_dir_string;
1009    MCRYPT td;
1010
1011    MCRYPT_GET_INI
1012
1013    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
1014        &cipher, &cipher_len, &module, &module_len) == FAILURE) {
1015        return;
1016    }
1017
1018    td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
1019    if (td != MCRYPT_FAILED) {
1020        RETVAL_LONG(mcrypt_enc_get_key_size(td));
1021        mcrypt_module_close(td);
1022    } else {
1023        php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1024        RETURN_FALSE;
1025    }
1026}
1027/* }}} */
1028
1029/* {{{ proto int mcrypt_get_block_size(string cipher, string module)
1030   Get the key size of cipher */
1031PHP_FUNCTION(mcrypt_get_block_size)
1032{
1033    char *cipher;
1034    char *module;
1035    size_t   cipher_len, module_len;
1036    char *cipher_dir_string;
1037    char *module_dir_string;
1038    MCRYPT td;
1039
1040    MCRYPT_GET_INI
1041
1042    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
1043        &cipher, &cipher_len, &module, &module_len) == FAILURE) {
1044        return;
1045    }
1046
1047    td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
1048    if (td != MCRYPT_FAILED) {
1049        RETVAL_LONG(mcrypt_enc_get_block_size(td));
1050        mcrypt_module_close(td);
1051    } else {
1052        php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1053        RETURN_FALSE;
1054    }
1055}
1056/* }}} */
1057
1058/* {{{ proto int mcrypt_get_iv_size(string cipher, string module)
1059   Get the IV size of cipher (Usually the same as the blocksize) */
1060PHP_FUNCTION(mcrypt_get_iv_size)
1061{
1062    char *cipher;
1063    char *module;
1064    size_t   cipher_len, module_len;
1065    char *cipher_dir_string;
1066    char *module_dir_string;
1067    MCRYPT td;
1068
1069    MCRYPT_GET_INI
1070
1071    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss",
1072        &cipher, &cipher_len, &module, &module_len) == FAILURE) {
1073        return;
1074    }
1075
1076    td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
1077    if (td != MCRYPT_FAILED) {
1078        RETVAL_LONG(mcrypt_enc_get_iv_size(td));
1079        mcrypt_module_close(td);
1080    } else {
1081        php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1082        RETURN_FALSE;
1083    }
1084}
1085/* }}} */
1086
1087/* {{{ proto string mcrypt_get_cipher_name(string cipher)
1088   Get the key size of cipher */
1089PHP_FUNCTION(mcrypt_get_cipher_name)
1090{
1091    char *cipher_dir_string;
1092    char *module_dir_string;
1093    char *cipher_name;
1094    char *cipher;
1095    size_t   cipher_len;
1096    MCRYPT td;
1097
1098    MCRYPT_GET_INI
1099
1100    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s",
1101        &cipher, &cipher_len) == FAILURE) {
1102        return;
1103    }
1104
1105    /* The code below is actually not very nice, but I didn't see a better
1106     * method */
1107    td = mcrypt_module_open(cipher, cipher_dir_string, "ecb", module_dir_string);
1108    if (td != MCRYPT_FAILED) {
1109        cipher_name = mcrypt_enc_get_algorithms_name(td);
1110        mcrypt_module_close(td);
1111        RETVAL_STRING(cipher_name);
1112        mcrypt_free(cipher_name);
1113    } else {
1114        td = mcrypt_module_open(cipher, cipher_dir_string, "stream", module_dir_string);
1115        if (td != MCRYPT_FAILED) {
1116            cipher_name = mcrypt_enc_get_algorithms_name(td);
1117            mcrypt_module_close(td);
1118            RETVAL_STRING(cipher_name);
1119            mcrypt_free(cipher_name);
1120        } else {
1121            php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1122            RETURN_FALSE;
1123        }
1124    }
1125}
1126/* }}} */
1127
1128static char *php_mcrypt_get_key_size_str(
1129        int max_key_size, const int *key_sizes, int key_size_count) /* {{{ */
1130{
1131    if (key_size_count == 0) {
1132        char *str;
1133        spprintf(&str, 0, "Only keys of size 1 to %d supported", max_key_size);
1134        return str;
1135    } else if (key_size_count == 1) {
1136        char *str;
1137        spprintf(&str, 0, "Only keys of size %d supported", key_sizes[0]);
1138        return str;
1139    } else {
1140        int i;
1141        char *result = NULL;
1142        smart_str str = {0};
1143        smart_str_appends(&str, "Only keys of sizes ");
1144
1145        for (i = 0; i < key_size_count; ++i) {
1146            if (i == key_size_count - 1) {
1147                smart_str_appends(&str, " or ");
1148            } else if (i != 0) {
1149                smart_str_appends(&str, ", ");
1150            }
1151
1152            smart_str_append_long(&str, key_sizes[i]);
1153        }
1154
1155        smart_str_appends(&str, " supported");
1156        smart_str_0(&str);
1157        result = estrndup(str.s->val, str.s->len);
1158        smart_str_free(&str);
1159
1160        return result;
1161    }
1162}
1163/* }}} */
1164
1165static zend_bool php_mcrypt_is_valid_key_size(
1166        int key_size, int max_key_size, int *key_sizes, int key_size_count) /* {{{ */
1167{
1168    int i;
1169
1170    if (key_size <= 0 || key_size > max_key_size) {
1171        return 0;
1172    }
1173
1174    if (key_size_count == 0) {
1175        /* All key sizes are valid */
1176        return 1;
1177    }
1178
1179    for (i = 0; i < key_size_count; i++) {
1180        if (key_sizes[i] == key_size) {
1181            return 1;
1182        }
1183    }
1184
1185    return 0;
1186}
1187/* }}} */
1188
1189static int php_mcrypt_ensure_valid_key_size(MCRYPT td, int key_size TSRMLS_DC) /* {{{ */
1190{
1191    int key_size_count;
1192    int max_key_size = mcrypt_enc_get_key_size(td);
1193    int *key_sizes = mcrypt_enc_get_supported_key_sizes(td, &key_size_count);
1194
1195    zend_bool is_valid_key_size = php_mcrypt_is_valid_key_size(
1196        key_size, max_key_size, key_sizes, key_size_count
1197    );
1198    if (!is_valid_key_size) {
1199        char *key_size_str = php_mcrypt_get_key_size_str(
1200            max_key_size, key_sizes, key_size_count
1201        );
1202        php_error_docref(NULL TSRMLS_CC, E_WARNING,
1203            "Key of size %d not supported by this algorithm. %s", key_size, key_size_str
1204        );
1205        efree(key_size_str);
1206    }
1207
1208    if (key_sizes) {
1209        mcrypt_free(key_sizes);
1210    }
1211
1212    return is_valid_key_size ? SUCCESS : FAILURE;
1213}
1214/* }}} */
1215
1216static int php_mcrypt_ensure_valid_iv(MCRYPT td, const char *iv, int iv_size TSRMLS_DC) /* {{{ */
1217{
1218    if (mcrypt_enc_mode_has_iv(td) == 1) {
1219        int expected_iv_size = mcrypt_enc_get_iv_size(td);
1220
1221        if (!iv) {
1222            php_error_docref(NULL TSRMLS_CC, E_WARNING,
1223                "Encryption mode requires an initialization vector of size %d", expected_iv_size
1224            );
1225            return FAILURE;
1226        }
1227
1228        if (iv_size != expected_iv_size) {
1229            php_error_docref(NULL TSRMLS_CC, E_WARNING,
1230                "Received initialization vector of size %d, but size %d is required "
1231                "for this encryption mode", iv_size, expected_iv_size
1232            );
1233            return FAILURE;
1234        }
1235    }
1236
1237    return SUCCESS;
1238}
1239/* }}} */
1240
1241static void php_mcrypt_do_crypt(char* cipher, const char *key, int key_len, const char *data, int data_len, char *mode, const char *iv, size_t iv_len, size_t dencrypt, zval* return_value TSRMLS_DC) /* {{{ */
1242{
1243    char *cipher_dir_string;
1244    char *module_dir_string;
1245    zend_long data_size;
1246    char *data_s;
1247    MCRYPT td;
1248
1249    MCRYPT_GET_INI
1250
1251    td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string);
1252    if (td == MCRYPT_FAILED) {
1253        php_error_docref(NULL TSRMLS_CC, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1254        RETURN_FALSE;
1255    }
1256
1257    if (php_mcrypt_ensure_valid_key_size(td, key_len TSRMLS_CC) == FAILURE) {
1258        mcrypt_module_close(td);
1259        RETURN_FALSE;
1260    }
1261
1262    if (php_mcrypt_ensure_valid_iv(td, iv, iv_len TSRMLS_CC) == FAILURE) {
1263        mcrypt_module_close(td);
1264        RETURN_FALSE;
1265    }
1266
1267    /* Check blocksize */
1268    if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */
1269        int block_size = mcrypt_enc_get_block_size(td);
1270        data_size = (((data_len - 1) / block_size) + 1) * block_size;
1271        data_s = emalloc(data_size + 1);
1272        memset(data_s, 0, data_size);
1273        memcpy(data_s, data, data_len);
1274    } else { /* It's not a block algorithm */
1275        data_size = data_len;
1276        data_s = emalloc(data_size + 1);
1277        memcpy(data_s, data, data_len);
1278    }
1279
1280    if (mcrypt_generic_init(td, (void *) key, key_len, (void *) iv) < 0) {
1281        php_error_docref(NULL TSRMLS_CC, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed");
1282        mcrypt_module_close(td);
1283        RETURN_FALSE;
1284    }
1285
1286    if (dencrypt == MCRYPT_ENCRYPT) {
1287        mcrypt_generic(td, data_s, data_size);
1288    } else {
1289        mdecrypt_generic(td, data_s, data_size);
1290    }
1291
1292    data_s[data_size] = 0;
1293
1294    RETVAL_STRINGL(data_s, data_size);
1295    efree(data_s);
1296
1297    /* freeing vars */
1298    mcrypt_generic_end(td);
1299}
1300/* }}} */
1301
1302/* {{{ proto string mcrypt_encrypt(string cipher, string key, string data, string mode, string iv)
1303   OFB crypt/decrypt data using key key with cipher cipher starting with iv */
1304PHP_FUNCTION(mcrypt_encrypt)
1305{
1306    char *cipher, *key, *data, *mode, *iv = NULL;
1307    size_t cipher_len, key_len, data_len, mode_len, iv_len = 0;
1308
1309    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssss|s", &cipher, &cipher_len,
1310        &key, &key_len, &data, &data_len, &mode, &mode_len, &iv, &iv_len) == FAILURE) {
1311        return;
1312    }
1313
1314    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, mode, iv, iv_len, MCRYPT_ENCRYPT, return_value TSRMLS_CC);
1315}
1316/* }}} */
1317
1318/* {{{ proto string mcrypt_decrypt(string cipher, string key, string data, string mode, string iv)
1319   OFB crypt/decrypt data using key key with cipher cipher starting with iv */
1320PHP_FUNCTION(mcrypt_decrypt)
1321{
1322    char *cipher, *key, *data, *mode, *iv = NULL;
1323    size_t cipher_len, key_len, data_len, mode_len, iv_len = 0;
1324
1325    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssss|s", &cipher, &cipher_len,
1326        &key, &key_len, &data, &data_len, &mode, &mode_len, &iv, &iv_len) == FAILURE) {
1327        return;
1328    }
1329
1330    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, mode, iv, iv_len, MCRYPT_DECRYPT, return_value TSRMLS_CC);
1331}
1332/* }}} */
1333
1334/* {{{ proto string mcrypt_ecb(int cipher, string key, string data, int mode, string iv)
1335   ECB crypt/decrypt data using key key with cipher cipher starting with iv */
1336PHP_FUNCTION(mcrypt_ecb)
1337{
1338    zval *mode;
1339    char *cipher, *key, *data, *iv = NULL;
1340    size_t cipher_len, key_len, data_len, iv_len = 0;
1341
1342    MCRYPT_GET_CRYPT_ARGS
1343
1344    convert_to_long_ex(mode);
1345
1346    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ecb", iv, iv_len, Z_LVAL_P(mode), return_value TSRMLS_CC);
1347}
1348/* }}} */
1349
1350/* {{{ proto string mcrypt_cbc(int cipher, string key, string data, int mode, string iv)
1351   CBC crypt/decrypt data using key key with cipher cipher starting with iv */
1352PHP_FUNCTION(mcrypt_cbc)
1353{
1354    zval *mode;
1355    char *cipher, *key, *data, *iv = NULL;
1356    size_t cipher_len, key_len, data_len, iv_len = 0;
1357
1358    MCRYPT_GET_CRYPT_ARGS
1359
1360    convert_to_long_ex(mode);
1361
1362    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cbc", iv, iv_len, Z_LVAL_P(mode), return_value TSRMLS_CC);
1363}
1364/* }}} */
1365
1366/* {{{ proto string mcrypt_cfb(int cipher, string key, string data, int mode, string iv)
1367   CFB crypt/decrypt data using key key with cipher cipher starting with iv */
1368PHP_FUNCTION(mcrypt_cfb)
1369{
1370    zval *mode;
1371    char *cipher, *key, *data, *iv = NULL;
1372    size_t cipher_len, key_len, data_len, iv_len = 0;
1373
1374    MCRYPT_GET_CRYPT_ARGS
1375
1376    convert_to_long_ex(mode);
1377
1378    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, Z_LVAL_P(mode), return_value TSRMLS_CC);
1379}
1380/* }}} */
1381
1382/* {{{ proto string mcrypt_ofb(int cipher, string key, string data, int mode, string iv)
1383   OFB crypt/decrypt data using key key with cipher cipher starting with iv */
1384PHP_FUNCTION(mcrypt_ofb)
1385{
1386    zval *mode;
1387    char *cipher, *key, *data, *iv = NULL;
1388    size_t cipher_len, key_len, data_len, iv_len = 0;
1389
1390    MCRYPT_GET_CRYPT_ARGS
1391
1392    convert_to_long_ex(mode);
1393
1394    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, Z_LVAL_P(mode), return_value TSRMLS_CC);
1395}
1396/* }}} */
1397
1398/* {{{ proto string mcrypt_create_iv(int size, int source)
1399   Create an initialization vector (IV) */
1400PHP_FUNCTION(mcrypt_create_iv)
1401{
1402    char *iv;
1403    zend_long source = URANDOM;
1404    zend_long size;
1405    int n = 0;
1406
1407    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l|l", &size, &source) == FAILURE) {
1408        return;
1409    }
1410
1411    if (size <= 0 || size >= INT_MAX) {
1412        php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot create an IV with a size of less than 1 or greater than %d", INT_MAX);
1413        RETURN_FALSE;
1414    }
1415
1416    iv = ecalloc(size + 1, 1);
1417
1418    if (source == RANDOM || source == URANDOM) {
1419#if PHP_WIN32
1420        /* random/urandom equivalent on Windows */
1421        BYTE *iv_b = (BYTE *) iv;
1422        if (php_win32_get_random_bytes(iv_b, (size_t) size) == FAILURE){
1423            efree(iv);
1424            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
1425            RETURN_FALSE;
1426        }
1427        n = size;
1428#else
1429        int    fd;
1430        size_t read_bytes = 0;
1431
1432        fd = open(source == RANDOM ? "/dev/random" : "/dev/urandom", O_RDONLY);
1433        if (fd < 0) {
1434            efree(iv);
1435            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot open source device");
1436            RETURN_FALSE;
1437        }
1438        while (read_bytes < size) {
1439            n = read(fd, iv + read_bytes, size - read_bytes);
1440            if (n < 0) {
1441                break;
1442            }
1443            read_bytes += n;
1444        }
1445        n = read_bytes;
1446        close(fd);
1447        if (n < size) {
1448            efree(iv);
1449            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Could not gather sufficient random data");
1450            RETURN_FALSE;
1451        }
1452#endif
1453    } else {
1454        n = size;
1455        while (size) {
1456            iv[--size] = (char) (255.0 * php_rand(TSRMLS_C) / RAND_MAX);
1457        }
1458    }
1459    RETVAL_STRINGL(iv, n);
1460    efree(iv);
1461}
1462/* }}} */
1463
1464#endif
1465
1466/*
1467 * Local variables:
1468 * tab-width: 4
1469 * c-basic-offset: 4
1470 * End:
1471 * vim600: sw=4 ts=4 fdm=marker
1472 * vim<600: sw=4 ts=4
1473 */
1474