1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2015 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 "zend_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(), "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(), "r", &mcryptind) == FAILURE) {           \
342        return;                                                             \
343    }                                                                                       \
344    if ((pm = (php_mcrypt *)zend_fetch_resource(Z_RES_P(mcryptind), "MCrypt", le_mcrypt)) == NULL) { \
345        RETURN_FALSE; \
346    }
347
348#define MCRYPT_GET_MODE_DIR_ARGS(DIRECTORY)                             \
349    char *dir = NULL;                                                   \
350    size_t   dir_len;                                                      \
351    char *module;                                                       \
352    size_t   module_len;                                                   \
353    if (zend_parse_parameters (ZEND_NUM_ARGS(),               \
354        "s|s", &module, &module_len, &dir, &dir_len) == FAILURE) {      \
355        return;                                                         \
356    }
357
358#define MCRYPT_OPEN_MODULE_FAILED "Module initialization failed"
359
360#define MCRYPT_ENTRY2_2_4(a,b) REGISTER_STRING_CONSTANT("MCRYPT_" #a, b, CONST_PERSISTENT)
361#define MCRYPT_ENTRY2_4(a) MCRYPT_ENTRY_NAMED(a, a)
362
363#define PHP_MCRYPT_INIT_CHECK   \
364    if (!pm->init) {    \
365        php_error_docref(NULL, E_WARNING, "Operation disallowed prior to mcrypt_generic_init().");  \
366        RETURN_FALSE;   \
367    }   \
368
369PHP_INI_BEGIN()
370    STD_PHP_INI_ENTRY("mcrypt.algorithms_dir", NULL, PHP_INI_ALL, OnUpdateString, algorithms_dir, zend_mcrypt_globals, mcrypt_globals)
371    STD_PHP_INI_ENTRY("mcrypt.modes_dir",      NULL, PHP_INI_ALL, OnUpdateString, modes_dir, zend_mcrypt_globals, mcrypt_globals)
372PHP_INI_END()
373
374static void php_mcrypt_module_dtor(zend_resource *rsrc) /* {{{ */
375{
376    php_mcrypt *pm = (php_mcrypt *) rsrc->ptr;
377    if (pm) {
378        mcrypt_generic_deinit(pm->td);
379        mcrypt_module_close(pm->td);
380        efree(pm);
381        pm = NULL;
382    }
383}
384/* }}} */
385
386static PHP_MINIT_FUNCTION(mcrypt) /* {{{ */
387{
388    le_mcrypt = zend_register_list_destructors_ex(php_mcrypt_module_dtor, NULL, "mcrypt", module_number);
389
390    /* modes for mcrypt_??? routines */
391    REGISTER_LONG_CONSTANT("MCRYPT_ENCRYPT", 0, CONST_PERSISTENT);
392    REGISTER_LONG_CONSTANT("MCRYPT_DECRYPT", 1, CONST_PERSISTENT);
393
394    /* sources for mcrypt_create_iv */
395    REGISTER_LONG_CONSTANT("MCRYPT_DEV_RANDOM", RANDOM, CONST_PERSISTENT);
396    REGISTER_LONG_CONSTANT("MCRYPT_DEV_URANDOM", URANDOM, CONST_PERSISTENT);
397    REGISTER_LONG_CONSTANT("MCRYPT_RAND", RAND, CONST_PERSISTENT);
398
399    /* ciphers */
400    MCRYPT_ENTRY2_2_4(3DES, "tripledes");
401    MCRYPT_ENTRY2_2_4(ARCFOUR_IV, "arcfour-iv");
402    MCRYPT_ENTRY2_2_4(ARCFOUR, "arcfour");
403    MCRYPT_ENTRY2_2_4(BLOWFISH, "blowfish");
404    MCRYPT_ENTRY2_2_4(BLOWFISH_COMPAT, "blowfish-compat");
405    MCRYPT_ENTRY2_2_4(CAST_128, "cast-128");
406    MCRYPT_ENTRY2_2_4(CAST_256, "cast-256");
407    MCRYPT_ENTRY2_2_4(CRYPT, "crypt");
408    MCRYPT_ENTRY2_2_4(DES, "des");
409    MCRYPT_ENTRY2_2_4(ENIGNA, "crypt");
410    MCRYPT_ENTRY2_2_4(GOST, "gost");
411    MCRYPT_ENTRY2_2_4(LOKI97, "loki97");
412    MCRYPT_ENTRY2_2_4(PANAMA, "panama");
413    MCRYPT_ENTRY2_2_4(RC2, "rc2");
414    MCRYPT_ENTRY2_2_4(RIJNDAEL_128, "rijndael-128");
415    MCRYPT_ENTRY2_2_4(RIJNDAEL_192, "rijndael-192");
416    MCRYPT_ENTRY2_2_4(RIJNDAEL_256, "rijndael-256");
417    MCRYPT_ENTRY2_2_4(SAFER64, "safer-sk64");
418    MCRYPT_ENTRY2_2_4(SAFER128, "safer-sk128");
419    MCRYPT_ENTRY2_2_4(SAFERPLUS, "saferplus");
420    MCRYPT_ENTRY2_2_4(SERPENT, "serpent");
421    MCRYPT_ENTRY2_2_4(THREEWAY, "threeway");
422    MCRYPT_ENTRY2_2_4(TRIPLEDES, "tripledes");
423    MCRYPT_ENTRY2_2_4(TWOFISH, "twofish");
424    MCRYPT_ENTRY2_2_4(WAKE, "wake");
425    MCRYPT_ENTRY2_2_4(XTEA, "xtea");
426
427    MCRYPT_ENTRY2_2_4(IDEA, "idea");
428    MCRYPT_ENTRY2_2_4(MARS, "mars");
429    MCRYPT_ENTRY2_2_4(RC6, "rc6");
430    MCRYPT_ENTRY2_2_4(SKIPJACK, "skipjack");
431/* modes */
432    MCRYPT_ENTRY2_2_4(MODE_CBC, "cbc");
433    MCRYPT_ENTRY2_2_4(MODE_CFB, "cfb");
434    MCRYPT_ENTRY2_2_4(MODE_ECB, "ecb");
435    MCRYPT_ENTRY2_2_4(MODE_NOFB, "nofb");
436    MCRYPT_ENTRY2_2_4(MODE_OFB, "ofb");
437    MCRYPT_ENTRY2_2_4(MODE_STREAM, "stream");
438    REGISTER_INI_ENTRIES();
439
440    php_stream_filter_register_factory("mcrypt.*", &php_mcrypt_filter_factory);
441    php_stream_filter_register_factory("mdecrypt.*", &php_mcrypt_filter_factory);
442
443    return SUCCESS;
444}
445/* }}} */
446
447static PHP_MSHUTDOWN_FUNCTION(mcrypt) /* {{{ */
448{
449    php_stream_filter_unregister_factory("mcrypt.*");
450    php_stream_filter_unregister_factory("mdecrypt.*");
451
452    UNREGISTER_INI_ENTRIES();
453    return SUCCESS;
454}
455/* }}} */
456
457#include "zend_smart_str.h"
458
459PHP_MINFO_FUNCTION(mcrypt) /* {{{ */
460{
461    char **modules;
462    char mcrypt_api_no[16];
463    int i, count;
464    smart_str tmp1 = {0};
465    smart_str tmp2 = {0};
466
467    modules = mcrypt_list_algorithms(MCG(algorithms_dir), &count);
468    if (count == 0) {
469        smart_str_appends(&tmp1, "none");
470    }
471    for (i = 0; i < count; i++) {
472        smart_str_appends(&tmp1, modules[i]);
473        smart_str_appendc(&tmp1, ' ');
474    }
475    smart_str_0(&tmp1);
476    mcrypt_free_p(modules, count);
477
478    modules = mcrypt_list_modes(MCG(modes_dir), &count);
479    if (count == 0) {
480        smart_str_appends(&tmp2, "none");
481    }
482    for (i = 0; i < count; i++) {
483        smart_str_appends(&tmp2, modules[i]);
484        smart_str_appendc(&tmp2, ' ');
485    }
486    smart_str_0 (&tmp2);
487    mcrypt_free_p (modules, count);
488
489    snprintf (mcrypt_api_no, 16, "%d", MCRYPT_API_VERSION);
490
491    php_info_print_table_start();
492    php_info_print_table_header(2, "mcrypt support", "enabled");
493    php_info_print_table_header(2, "mcrypt_filter support", "enabled");
494    php_info_print_table_row(2, "Version", LIBMCRYPT_VERSION);
495    php_info_print_table_row(2, "Api No", mcrypt_api_no);
496    php_info_print_table_row(2, "Supported ciphers", tmp1.s->val);
497    php_info_print_table_row(2, "Supported modes", tmp2.s->val);
498    smart_str_free(&tmp1);
499    smart_str_free(&tmp2);
500
501    php_info_print_table_end();
502
503    DISPLAY_INI_ENTRIES();
504}
505/* }}} */
506
507/* {{{ proto resource mcrypt_module_open(string cipher, string cipher_directory, string mode, string mode_directory)
508   Opens the module of the algorithm and the mode to be used */
509PHP_FUNCTION(mcrypt_module_open)
510{
511    char *cipher, *cipher_dir;
512    char *mode,   *mode_dir;
513    size_t   cipher_len, cipher_dir_len;
514    size_t   mode_len,   mode_dir_len;
515    MCRYPT td;
516    php_mcrypt *pm;
517
518    if (zend_parse_parameters (ZEND_NUM_ARGS(), "ssss",
519        &cipher, &cipher_len, &cipher_dir, &cipher_dir_len,
520        &mode,   &mode_len,   &mode_dir,   &mode_dir_len)) {
521        return;
522    }
523
524    td = mcrypt_module_open (
525        cipher,
526        cipher_dir_len > 0 ? cipher_dir : MCG(algorithms_dir),
527        mode,
528        mode_dir_len > 0 ? mode_dir : MCG(modes_dir)
529    );
530
531    if (td == MCRYPT_FAILED) {
532        php_error_docref(NULL, E_WARNING, "Could not open encryption module");
533        RETURN_FALSE;
534    } else {
535        pm = emalloc(sizeof(php_mcrypt));
536        pm->td = td;
537        pm->init = 0;
538        RETURN_RES(zend_register_resource(pm, le_mcrypt));
539    }
540}
541/* }}} */
542
543/* {{{ proto int mcrypt_generic_init(resource td, string key, string iv)
544   This function initializes all buffers for the specific module */
545PHP_FUNCTION(mcrypt_generic_init)
546{
547    char *key, *iv;
548    size_t key_len, iv_len;
549    zval *mcryptind;
550    unsigned char *key_s, *iv_s;
551    int max_key_size, key_size, iv_size;
552    php_mcrypt *pm;
553    int result = 0;
554
555    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rss", &mcryptind, &key, &key_len, &iv, &iv_len) == FAILURE) {
556        return;
557    }
558
559    if ((pm = (php_mcrypt *)zend_fetch_resource(Z_RES_P(mcryptind), "MCrypt", le_mcrypt)) == NULL) {
560        RETURN_FALSE;
561    }
562
563    max_key_size = mcrypt_enc_get_key_size(pm->td);
564    iv_size = mcrypt_enc_get_iv_size(pm->td);
565
566    if (key_len == 0) {
567        php_error_docref(NULL, E_WARNING, "Key size is 0");
568    }
569
570    key_s = emalloc(key_len);
571    memset(key_s, 0, key_len);
572
573    iv_s = emalloc(iv_size + 1);
574    memset(iv_s, 0, iv_size + 1);
575
576    if (key_len > max_key_size) {
577        php_error_docref(NULL, E_WARNING, "Key size too large; supplied length: %d, max: %d", key_len, max_key_size);
578        key_size = max_key_size;
579    } else {
580        key_size = (int)key_len;
581    }
582    memcpy(key_s, key, key_len);
583
584    if (iv_len != iv_size) {
585        php_error_docref(NULL, E_WARNING, "Iv size incorrect; supplied length: %d, needed: %d", iv_len, iv_size);
586        if (iv_len > iv_size) {
587            iv_len = iv_size;
588        }
589    }
590    memcpy(iv_s, iv, iv_len);
591
592    mcrypt_generic_deinit(pm->td);
593    result = mcrypt_generic_init(pm->td, key_s, key_size, iv_s);
594
595    /* If this function fails, close the mcrypt module to prevent crashes
596     * when further functions want to access this resource */
597    if (result < 0) {
598        zend_list_close(Z_RES_P(mcryptind));
599        switch (result) {
600            case -3:
601                php_error_docref(NULL, E_WARNING, "Key length incorrect");
602                break;
603            case -4:
604                php_error_docref(NULL, E_WARNING, "Memory allocation error");
605                break;
606            case -1:
607            default:
608                php_error_docref(NULL, E_WARNING, "Unknown error");
609                break;
610        }
611    } else {
612        pm->init = 1;
613    }
614    RETVAL_LONG(result);
615
616    efree(iv_s);
617    efree(key_s);
618}
619/* }}} */
620
621/* {{{ proto string mcrypt_generic(resource td, string data)
622   This function encrypts the plaintext */
623PHP_FUNCTION(mcrypt_generic)
624{
625    zval *mcryptind;
626    char *data;
627    size_t data_len;
628    php_mcrypt *pm;
629    char* data_s;
630    int block_size, data_size;
631
632    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &mcryptind, &data, &data_len) == FAILURE) {
633        return;
634    }
635
636    if ((pm = (php_mcrypt *)zend_fetch_resource(Z_RES_P(mcryptind), "MCrypt", le_mcrypt)) == NULL) {
637        RETURN_FALSE;
638    }
639    PHP_MCRYPT_INIT_CHECK
640
641    if (data_len == 0) {
642        php_error_docref(NULL, E_WARNING, "An empty string was passed");
643        RETURN_FALSE
644    }
645
646    /* Check blocksize */
647    if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */
648        block_size = mcrypt_enc_get_block_size(pm->td);
649        data_size = ((((int)data_len - 1) / block_size) + 1) * block_size;
650        data_s = emalloc(data_size + 1);
651        memset(data_s, 0, data_size);
652        memcpy(data_s, data, data_len);
653    } else { /* It's not a block algorithm */
654        data_size = (int)data_len;
655        data_s = emalloc(data_size + 1);
656        memset(data_s, 0, data_size);
657        memcpy(data_s, data, data_len);
658    }
659
660    mcrypt_generic(pm->td, data_s, data_size);
661    data_s[data_size] = '\0';
662
663    RETVAL_STRINGL(data_s, data_size);
664    efree(data_s);
665}
666/* }}} */
667
668/* {{{ proto string mdecrypt_generic(resource td, string data)
669   This function decrypts the plaintext */
670PHP_FUNCTION(mdecrypt_generic)
671{
672    zval *mcryptind;
673    char *data;
674    size_t data_len;
675    php_mcrypt *pm;
676    char* data_s;
677    int block_size, data_size;
678
679    if (zend_parse_parameters(ZEND_NUM_ARGS(), "rs", &mcryptind, &data, &data_len) == FAILURE) {
680        return;
681    }
682
683    if ((pm = (php_mcrypt *)zend_fetch_resource(Z_RES_P(mcryptind), "MCrypt", le_mcrypt)) == NULL) {
684        RETURN_FALSE;
685    }
686    PHP_MCRYPT_INIT_CHECK
687
688    if (data_len == 0) {
689        php_error_docref(NULL, E_WARNING, "An empty string was passed");
690        RETURN_FALSE
691    }
692
693    /* Check blocksize */
694    if (mcrypt_enc_is_block_mode(pm->td) == 1) { /* It's a block algorithm */
695        block_size = mcrypt_enc_get_block_size(pm->td);
696        data_size = ((((int)data_len - 1) / block_size) + 1) * block_size;
697        data_s = emalloc(data_size + 1);
698        memset(data_s, 0, data_size);
699        memcpy(data_s, data, data_len);
700    } else { /* It's not a block algorithm */
701        data_size = (int)data_len;
702        data_s = emalloc(data_size + 1);
703        memset(data_s, 0, data_size);
704        memcpy(data_s, data, data_len);
705    }
706
707    mdecrypt_generic(pm->td, data_s, data_size);
708
709    RETVAL_STRINGL(data_s, data_size);
710    efree(data_s);
711}
712/* }}} */
713
714/* {{{ proto array mcrypt_enc_get_supported_key_sizes(resource td)
715   This function decrypts the crypttext */
716PHP_FUNCTION(mcrypt_enc_get_supported_key_sizes)
717{
718    int i, count = 0;
719    int *key_sizes;
720
721    MCRYPT_GET_TD_ARG
722    array_init(return_value);
723
724    key_sizes = mcrypt_enc_get_supported_key_sizes(pm->td, &count);
725
726    for (i = 0; i < count; i++) {
727        add_index_long(return_value, i, key_sizes[i]);
728    }
729
730    mcrypt_free(key_sizes);
731}
732/* }}} */
733
734/* {{{ proto int mcrypt_enc_self_test(resource td)
735   This function runs the self test on the algorithm specified by the descriptor td */
736PHP_FUNCTION(mcrypt_enc_self_test)
737{
738    MCRYPT_GET_TD_ARG
739    RETURN_LONG(mcrypt_enc_self_test(pm->td));
740}
741/* }}} */
742
743/* {{{ proto bool mcrypt_module_close(resource td)
744   Free the descriptor td */
745PHP_FUNCTION(mcrypt_module_close)
746{
747    MCRYPT_GET_TD_ARG
748    zend_list_close(Z_RES_P(mcryptind));
749    RETURN_TRUE;
750}
751/* }}} */
752
753/* {{{ proto bool mcrypt_generic_deinit(resource td)
754   This function terminates encrypt specified by the descriptor td */
755PHP_FUNCTION(mcrypt_generic_deinit)
756{
757    MCRYPT_GET_TD_ARG
758
759    if (mcrypt_generic_deinit(pm->td) < 0) {
760        php_error_docref(NULL, E_WARNING, "Could not terminate encryption specifier");
761        RETURN_FALSE
762    }
763    pm->init = 0;
764    RETURN_TRUE
765}
766/* }}} */
767
768/* {{{ proto bool mcrypt_enc_is_block_algorithm_mode(resource td)
769   Returns TRUE if the mode is for use with block algorithms */
770PHP_FUNCTION(mcrypt_enc_is_block_algorithm_mode)
771{
772    MCRYPT_GET_TD_ARG
773
774    if (mcrypt_enc_is_block_algorithm_mode(pm->td) == 1) {
775        RETURN_TRUE
776    } else {
777        RETURN_FALSE
778    }
779}
780/* }}} */
781
782/* {{{ proto bool mcrypt_enc_is_block_algorithm(resource td)
783   Returns TRUE if the alrogithm is a block algorithms */
784PHP_FUNCTION(mcrypt_enc_is_block_algorithm)
785{
786    MCRYPT_GET_TD_ARG
787
788    if (mcrypt_enc_is_block_algorithm(pm->td) == 1) {
789        RETURN_TRUE
790    } else {
791        RETURN_FALSE
792    }
793}
794/* }}} */
795
796/* {{{ proto bool mcrypt_enc_is_block_mode(resource td)
797   Returns TRUE if the mode outputs blocks */
798PHP_FUNCTION(mcrypt_enc_is_block_mode)
799{
800    MCRYPT_GET_TD_ARG
801
802    if (mcrypt_enc_is_block_mode(pm->td) == 1) {
803        RETURN_TRUE
804    } else {
805        RETURN_FALSE
806    }
807}
808/* }}} */
809
810/* {{{ proto int mcrypt_enc_get_block_size(resource td)
811   Returns the block size of the cipher specified by the descriptor td */
812PHP_FUNCTION(mcrypt_enc_get_block_size)
813{
814    MCRYPT_GET_TD_ARG
815    RETURN_LONG(mcrypt_enc_get_block_size(pm->td));
816}
817/* }}} */
818
819/* {{{ proto int mcrypt_enc_get_key_size(resource td)
820   Returns the maximum supported key size in bytes of the algorithm specified by the descriptor td */
821PHP_FUNCTION(mcrypt_enc_get_key_size)
822{
823    MCRYPT_GET_TD_ARG
824    RETURN_LONG(mcrypt_enc_get_key_size(pm->td));
825}
826/* }}} */
827
828/* {{{ proto int mcrypt_enc_get_iv_size(resource td)
829   Returns the size of the IV in bytes of the algorithm specified by the descriptor td */
830PHP_FUNCTION(mcrypt_enc_get_iv_size)
831{
832    MCRYPT_GET_TD_ARG
833    RETURN_LONG(mcrypt_enc_get_iv_size(pm->td));
834}
835/* }}} */
836
837/* {{{ proto string mcrypt_enc_get_algorithms_name(resource td)
838   Returns the name of the algorithm specified by the descriptor td */
839PHP_FUNCTION(mcrypt_enc_get_algorithms_name)
840{
841    char *name;
842    MCRYPT_GET_TD_ARG
843
844    name = mcrypt_enc_get_algorithms_name(pm->td);
845    RETVAL_STRING(name);
846    mcrypt_free(name);
847}
848/* }}} */
849
850/* {{{ proto string mcrypt_enc_get_modes_name(resource td)
851   Returns the name of the mode specified by the descriptor td */
852PHP_FUNCTION(mcrypt_enc_get_modes_name)
853{
854    char *name;
855    MCRYPT_GET_TD_ARG
856
857    name = mcrypt_enc_get_modes_name(pm->td);
858    RETVAL_STRING(name);
859    mcrypt_free(name);
860}
861/* }}} */
862
863/* {{{ proto bool mcrypt_module_self_test(string algorithm [, string lib_dir])
864   Does a self test of the module "module" */
865PHP_FUNCTION(mcrypt_module_self_test)
866{
867    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir);
868
869    if (mcrypt_module_self_test(module, dir) == 0) {
870        RETURN_TRUE;
871    } else {
872        RETURN_FALSE;
873    }
874}
875/* }}} */
876
877/* {{{ proto bool mcrypt_module_is_block_algorithm_mode(string mode [, string lib_dir])
878   Returns TRUE if the mode is for use with block algorithms */
879PHP_FUNCTION(mcrypt_module_is_block_algorithm_mode)
880{
881    MCRYPT_GET_MODE_DIR_ARGS(modes_dir)
882
883    if (mcrypt_module_is_block_algorithm_mode(module, dir) == 1) {
884        RETURN_TRUE;
885    } else {
886        RETURN_FALSE;
887    }
888}
889/* }}} */
890
891/* {{{ proto bool mcrypt_module_is_block_algorithm(string algorithm [, string lib_dir])
892   Returns TRUE if the algorithm is a block algorithm */
893PHP_FUNCTION(mcrypt_module_is_block_algorithm)
894{
895    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
896
897    if (mcrypt_module_is_block_algorithm(module, dir) == 1) {
898        RETURN_TRUE;
899    } else {
900        RETURN_FALSE;
901    }
902}
903/* }}} */
904
905/* {{{ proto bool mcrypt_module_is_block_mode(string mode [, string lib_dir])
906   Returns TRUE if the mode outputs blocks of bytes */
907PHP_FUNCTION(mcrypt_module_is_block_mode)
908{
909    MCRYPT_GET_MODE_DIR_ARGS(modes_dir)
910
911    if (mcrypt_module_is_block_mode(module, dir) == 1) {
912        RETURN_TRUE;
913    } else {
914        RETURN_FALSE;
915    }
916}
917/* }}} */
918
919/* {{{ proto int mcrypt_module_get_algo_block_size(string algorithm [, string lib_dir])
920   Returns the block size of the algorithm */
921PHP_FUNCTION(mcrypt_module_get_algo_block_size)
922{
923    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
924
925    RETURN_LONG(mcrypt_module_get_algo_block_size(module, dir));
926}
927/* }}} */
928
929/* {{{ proto int mcrypt_module_get_algo_key_size(string algorithm [, string lib_dir])
930   Returns the maximum supported key size of the algorithm */
931PHP_FUNCTION(mcrypt_module_get_algo_key_size)
932{
933    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir);
934
935    RETURN_LONG(mcrypt_module_get_algo_key_size(module, dir));
936}
937/* }}} */
938
939/* {{{ proto array mcrypt_module_get_supported_key_sizes(string algorithm [, string lib_dir])
940   This function decrypts the crypttext */
941PHP_FUNCTION(mcrypt_module_get_supported_key_sizes)
942{
943    int i, count = 0;
944    int *key_sizes;
945
946    MCRYPT_GET_MODE_DIR_ARGS(algorithms_dir)
947    array_init(return_value);
948
949    key_sizes = mcrypt_module_get_algo_supported_key_sizes(module, dir, &count);
950
951    for (i = 0; i < count; i++) {
952        add_index_long(return_value, i, key_sizes[i]);
953    }
954    mcrypt_free(key_sizes);
955}
956/* }}} */
957
958/* {{{ proto array mcrypt_list_algorithms([string lib_dir])
959   List all algorithms in "module_dir" */
960PHP_FUNCTION(mcrypt_list_algorithms)
961{
962    char **modules;
963    char *lib_dir = MCG(algorithms_dir);
964    size_t   lib_dir_len;
965    int   i, count;
966
967    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s",
968        &lib_dir, &lib_dir_len) == FAILURE) {
969        return;
970    }
971
972    array_init(return_value);
973    modules = mcrypt_list_algorithms(lib_dir, &count);
974
975    if (count == 0) {
976        php_error_docref(NULL, E_WARNING, "No algorithms found in module dir");
977    }
978    for (i = 0; i < count; i++) {
979        add_index_string(return_value, i, modules[i]);
980    }
981    mcrypt_free_p(modules, count);
982}
983/* }}} */
984
985/* {{{ proto array mcrypt_list_modes([string lib_dir])
986   List all modes "module_dir" */
987PHP_FUNCTION(mcrypt_list_modes)
988{
989    char **modules;
990    char *lib_dir = MCG(modes_dir);
991    size_t   lib_dir_len;
992    int   i, count;
993
994    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|s",
995        &lib_dir, &lib_dir_len) == FAILURE) {
996        return;
997    }
998
999    array_init(return_value);
1000    modules = mcrypt_list_modes(lib_dir, &count);
1001
1002    if (count == 0) {
1003        php_error_docref(NULL, E_WARNING, "No modes found in module dir");
1004    }
1005    for (i = 0; i < count; i++) {
1006        add_index_string(return_value, i, modules[i]);
1007    }
1008    mcrypt_free_p(modules, count);
1009}
1010/* }}} */
1011
1012/* {{{ proto int mcrypt_get_key_size(string cipher, string module)
1013   Get the key size of cipher */
1014PHP_FUNCTION(mcrypt_get_key_size)
1015{
1016    char *cipher;
1017    char *module;
1018    size_t   cipher_len, module_len;
1019    char *cipher_dir_string;
1020    char *module_dir_string;
1021    MCRYPT td;
1022
1023    MCRYPT_GET_INI
1024
1025    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss",
1026        &cipher, &cipher_len, &module, &module_len) == FAILURE) {
1027        return;
1028    }
1029
1030    td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
1031    if (td != MCRYPT_FAILED) {
1032        RETVAL_LONG(mcrypt_enc_get_key_size(td));
1033        mcrypt_module_close(td);
1034    } else {
1035        php_error_docref(NULL, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1036        RETURN_FALSE;
1037    }
1038}
1039/* }}} */
1040
1041/* {{{ proto int mcrypt_get_block_size(string cipher, string module)
1042   Get the key size of cipher */
1043PHP_FUNCTION(mcrypt_get_block_size)
1044{
1045    char *cipher;
1046    char *module;
1047    size_t   cipher_len, module_len;
1048    char *cipher_dir_string;
1049    char *module_dir_string;
1050    MCRYPT td;
1051
1052    MCRYPT_GET_INI
1053
1054    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss",
1055        &cipher, &cipher_len, &module, &module_len) == FAILURE) {
1056        return;
1057    }
1058
1059    td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
1060    if (td != MCRYPT_FAILED) {
1061        RETVAL_LONG(mcrypt_enc_get_block_size(td));
1062        mcrypt_module_close(td);
1063    } else {
1064        php_error_docref(NULL, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1065        RETURN_FALSE;
1066    }
1067}
1068/* }}} */
1069
1070/* {{{ proto int mcrypt_get_iv_size(string cipher, string module)
1071   Get the IV size of cipher (Usually the same as the blocksize) */
1072PHP_FUNCTION(mcrypt_get_iv_size)
1073{
1074    char *cipher;
1075    char *module;
1076    size_t   cipher_len, module_len;
1077    char *cipher_dir_string;
1078    char *module_dir_string;
1079    MCRYPT td;
1080
1081    MCRYPT_GET_INI
1082
1083    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss",
1084        &cipher, &cipher_len, &module, &module_len) == FAILURE) {
1085        return;
1086    }
1087
1088    td = mcrypt_module_open(cipher, cipher_dir_string, module, module_dir_string);
1089    if (td != MCRYPT_FAILED) {
1090        RETVAL_LONG(mcrypt_enc_get_iv_size(td));
1091        mcrypt_module_close(td);
1092    } else {
1093        php_error_docref(NULL, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1094        RETURN_FALSE;
1095    }
1096}
1097/* }}} */
1098
1099/* {{{ proto string mcrypt_get_cipher_name(string cipher)
1100   Get the key size of cipher */
1101PHP_FUNCTION(mcrypt_get_cipher_name)
1102{
1103    char *cipher_dir_string;
1104    char *module_dir_string;
1105    char *cipher_name;
1106    char *cipher;
1107    size_t   cipher_len;
1108    MCRYPT td;
1109
1110    MCRYPT_GET_INI
1111
1112    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s",
1113        &cipher, &cipher_len) == FAILURE) {
1114        return;
1115    }
1116
1117    /* The code below is actually not very nice, but I didn't see a better
1118     * method */
1119    td = mcrypt_module_open(cipher, cipher_dir_string, "ecb", module_dir_string);
1120    if (td != MCRYPT_FAILED) {
1121        cipher_name = mcrypt_enc_get_algorithms_name(td);
1122        mcrypt_module_close(td);
1123        RETVAL_STRING(cipher_name);
1124        mcrypt_free(cipher_name);
1125    } else {
1126        td = mcrypt_module_open(cipher, cipher_dir_string, "stream", module_dir_string);
1127        if (td != MCRYPT_FAILED) {
1128            cipher_name = mcrypt_enc_get_algorithms_name(td);
1129            mcrypt_module_close(td);
1130            RETVAL_STRING(cipher_name);
1131            mcrypt_free(cipher_name);
1132        } else {
1133            php_error_docref(NULL, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1134            RETURN_FALSE;
1135        }
1136    }
1137}
1138/* }}} */
1139
1140static char *php_mcrypt_get_key_size_str(
1141        int max_key_size, const int *key_sizes, int key_size_count) /* {{{ */
1142{
1143    if (key_size_count == 0) {
1144        char *str;
1145        spprintf(&str, 0, "Only keys of size 1 to %d supported", max_key_size);
1146        return str;
1147    } else if (key_size_count == 1) {
1148        char *str;
1149        spprintf(&str, 0, "Only keys of size %d supported", key_sizes[0]);
1150        return str;
1151    } else {
1152        int i;
1153        char *result = NULL;
1154        smart_str str = {0};
1155        smart_str_appends(&str, "Only keys of sizes ");
1156
1157        for (i = 0; i < key_size_count; ++i) {
1158            if (i == key_size_count - 1) {
1159                smart_str_appends(&str, " or ");
1160            } else if (i != 0) {
1161                smart_str_appends(&str, ", ");
1162            }
1163
1164            smart_str_append_long(&str, key_sizes[i]);
1165        }
1166
1167        smart_str_appends(&str, " supported");
1168        smart_str_0(&str);
1169        result = estrndup(str.s->val, str.s->len);
1170        smart_str_free(&str);
1171
1172        return result;
1173    }
1174}
1175/* }}} */
1176
1177static zend_bool php_mcrypt_is_valid_key_size(
1178        int key_size, int max_key_size, int *key_sizes, int key_size_count) /* {{{ */
1179{
1180    int i;
1181
1182    if (key_size <= 0 || key_size > max_key_size) {
1183        return 0;
1184    }
1185
1186    if (key_size_count == 0) {
1187        /* All key sizes are valid */
1188        return 1;
1189    }
1190
1191    for (i = 0; i < key_size_count; i++) {
1192        if (key_sizes[i] == key_size) {
1193            return 1;
1194        }
1195    }
1196
1197    return 0;
1198}
1199/* }}} */
1200
1201static int php_mcrypt_ensure_valid_key_size(MCRYPT td, int key_size) /* {{{ */
1202{
1203    int key_size_count;
1204    int max_key_size = mcrypt_enc_get_key_size(td);
1205    int *key_sizes = mcrypt_enc_get_supported_key_sizes(td, &key_size_count);
1206
1207    zend_bool is_valid_key_size = php_mcrypt_is_valid_key_size(
1208        key_size, max_key_size, key_sizes, key_size_count
1209    );
1210    if (!is_valid_key_size) {
1211        char *key_size_str = php_mcrypt_get_key_size_str(
1212            max_key_size, key_sizes, key_size_count
1213        );
1214        php_error_docref(NULL, E_WARNING,
1215            "Key of size %d not supported by this algorithm. %s", key_size, key_size_str
1216        );
1217        efree(key_size_str);
1218    }
1219
1220    if (key_sizes) {
1221        mcrypt_free(key_sizes);
1222    }
1223
1224    return is_valid_key_size ? SUCCESS : FAILURE;
1225}
1226/* }}} */
1227
1228static int php_mcrypt_ensure_valid_iv(MCRYPT td, const char *iv, int iv_size) /* {{{ */
1229{
1230    if (mcrypt_enc_mode_has_iv(td) == 1) {
1231        int expected_iv_size = mcrypt_enc_get_iv_size(td);
1232
1233        if (!iv) {
1234            php_error_docref(NULL, E_WARNING,
1235                "Encryption mode requires an initialization vector of size %d", expected_iv_size
1236            );
1237            return FAILURE;
1238        }
1239
1240        if (iv_size != expected_iv_size) {
1241            php_error_docref(NULL, E_WARNING,
1242                "Received initialization vector of size %d, but size %d is required "
1243                "for this encryption mode", iv_size, expected_iv_size
1244            );
1245            return FAILURE;
1246        }
1247    }
1248
1249    return SUCCESS;
1250}
1251/* }}} */
1252
1253static void php_mcrypt_do_crypt(char* cipher, const char *key, size_t key_len, const char *data, size_t data_len, char *mode, const char *iv, size_t iv_len, size_t dencrypt, zval* return_value) /* {{{ */
1254{
1255    char *cipher_dir_string;
1256    char *module_dir_string;
1257    zend_long data_size;
1258    char *data_s;
1259    MCRYPT td;
1260
1261    MCRYPT_GET_INI
1262
1263    td = mcrypt_module_open(cipher, cipher_dir_string, mode, module_dir_string);
1264    if (td == MCRYPT_FAILED) {
1265        php_error_docref(NULL, E_WARNING, MCRYPT_OPEN_MODULE_FAILED);
1266        RETURN_FALSE;
1267    }
1268
1269    if (php_mcrypt_ensure_valid_key_size(td, (int)key_len) == FAILURE) {
1270        mcrypt_module_close(td);
1271        RETURN_FALSE;
1272    }
1273
1274    if (php_mcrypt_ensure_valid_iv(td, iv, (int)iv_len) == FAILURE) {
1275        mcrypt_module_close(td);
1276        RETURN_FALSE;
1277    }
1278
1279    /* Check blocksize */
1280    if (mcrypt_enc_is_block_mode(td) == 1) { /* It's a block algorithm */
1281        int block_size = mcrypt_enc_get_block_size(td);
1282        data_size = ((((zend_long)data_len - 1) / block_size) + 1) * block_size;
1283        data_s = emalloc(data_size + 1);
1284        memset(data_s, 0, data_size);
1285        memcpy(data_s, data, data_len);
1286    } else { /* It's not a block algorithm */
1287        data_size = data_len;
1288        data_s = emalloc(data_size + 1);
1289        memcpy(data_s, data, data_len);
1290    }
1291
1292    if (mcrypt_generic_init(td, (void *) key, (int)key_len, (void *) iv) < 0) {
1293        php_error_docref(NULL, E_RECOVERABLE_ERROR, "Mcrypt initialisation failed");
1294        mcrypt_module_close(td);
1295        RETURN_FALSE;
1296    }
1297
1298    if (dencrypt == MCRYPT_ENCRYPT) {
1299        mcrypt_generic(td, data_s, (int)data_size);
1300    } else {
1301        mdecrypt_generic(td, data_s, (int)data_size);
1302    }
1303
1304    data_s[data_size] = 0;
1305
1306    RETVAL_STRINGL(data_s, data_size);
1307    efree(data_s);
1308
1309    /* freeing vars */
1310    mcrypt_generic_end(td);
1311}
1312/* }}} */
1313
1314/* {{{ proto string mcrypt_encrypt(string cipher, string key, string data, string mode, string iv)
1315   OFB crypt/decrypt data using key key with cipher cipher starting with iv */
1316PHP_FUNCTION(mcrypt_encrypt)
1317{
1318    char *cipher, *key, *data, *mode, *iv = NULL;
1319    size_t cipher_len, key_len, data_len, mode_len, iv_len = 0;
1320
1321    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssss|s", &cipher, &cipher_len,
1322        &key, &key_len, &data, &data_len, &mode, &mode_len, &iv, &iv_len) == FAILURE) {
1323        return;
1324    }
1325
1326    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, mode, iv, iv_len, MCRYPT_ENCRYPT, return_value);
1327}
1328/* }}} */
1329
1330/* {{{ proto string mcrypt_decrypt(string cipher, string key, string data, string mode, string iv)
1331   OFB crypt/decrypt data using key key with cipher cipher starting with iv */
1332PHP_FUNCTION(mcrypt_decrypt)
1333{
1334    char *cipher, *key, *data, *mode, *iv = NULL;
1335    size_t cipher_len, key_len, data_len, mode_len, iv_len = 0;
1336
1337    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssss|s", &cipher, &cipher_len,
1338        &key, &key_len, &data, &data_len, &mode, &mode_len, &iv, &iv_len) == FAILURE) {
1339        return;
1340    }
1341
1342    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, mode, iv, iv_len, MCRYPT_DECRYPT, return_value);
1343}
1344/* }}} */
1345
1346/* {{{ proto string mcrypt_ecb(int cipher, string key, string data, int mode, string iv)
1347   ECB crypt/decrypt data using key key with cipher cipher starting with iv */
1348PHP_FUNCTION(mcrypt_ecb)
1349{
1350    zval *mode;
1351    char *cipher, *key, *data, *iv = NULL;
1352    size_t cipher_len, key_len, data_len, iv_len = 0;
1353
1354    MCRYPT_GET_CRYPT_ARGS
1355
1356    convert_to_long_ex(mode);
1357
1358    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ecb", iv, iv_len, Z_LVAL_P(mode), return_value);
1359}
1360/* }}} */
1361
1362/* {{{ proto string mcrypt_cbc(int cipher, string key, string data, int mode, string iv)
1363   CBC crypt/decrypt data using key key with cipher cipher starting with iv */
1364PHP_FUNCTION(mcrypt_cbc)
1365{
1366    zval *mode;
1367    char *cipher, *key, *data, *iv = NULL;
1368    size_t cipher_len, key_len, data_len, iv_len = 0;
1369
1370    MCRYPT_GET_CRYPT_ARGS
1371
1372    convert_to_long_ex(mode);
1373
1374    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cbc", iv, iv_len, Z_LVAL_P(mode), return_value);
1375}
1376/* }}} */
1377
1378/* {{{ proto string mcrypt_cfb(int cipher, string key, string data, int mode, string iv)
1379   CFB crypt/decrypt data using key key with cipher cipher starting with iv */
1380PHP_FUNCTION(mcrypt_cfb)
1381{
1382    zval *mode;
1383    char *cipher, *key, *data, *iv = NULL;
1384    size_t cipher_len, key_len, data_len, iv_len = 0;
1385
1386    MCRYPT_GET_CRYPT_ARGS
1387
1388    convert_to_long_ex(mode);
1389
1390    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "cfb", iv, iv_len, Z_LVAL_P(mode), return_value);
1391}
1392/* }}} */
1393
1394/* {{{ proto string mcrypt_ofb(int cipher, string key, string data, int mode, string iv)
1395   OFB crypt/decrypt data using key key with cipher cipher starting with iv */
1396PHP_FUNCTION(mcrypt_ofb)
1397{
1398    zval *mode;
1399    char *cipher, *key, *data, *iv = NULL;
1400    size_t cipher_len, key_len, data_len, iv_len = 0;
1401
1402    MCRYPT_GET_CRYPT_ARGS
1403
1404    convert_to_long_ex(mode);
1405
1406    php_mcrypt_do_crypt(cipher, key, key_len, data, data_len, "ofb", iv, iv_len, Z_LVAL_P(mode), return_value);
1407}
1408/* }}} */
1409
1410/* {{{ proto string mcrypt_create_iv(int size, int source)
1411   Create an initialization vector (IV) */
1412PHP_FUNCTION(mcrypt_create_iv)
1413{
1414    char *iv;
1415    zend_long source = URANDOM;
1416    zend_long size;
1417    int n = 0;
1418
1419    if (zend_parse_parameters(ZEND_NUM_ARGS(), "l|l", &size, &source) == FAILURE) {
1420        return;
1421    }
1422
1423    if (size <= 0 || size >= INT_MAX) {
1424        php_error_docref(NULL, E_WARNING, "Cannot create an IV with a size of less than 1 or greater than %d", INT_MAX);
1425        RETURN_FALSE;
1426    }
1427
1428    iv = ecalloc(size + 1, 1);
1429
1430    if (source == RANDOM || source == URANDOM) {
1431#if PHP_WIN32
1432        /* random/urandom equivalent on Windows */
1433        BYTE *iv_b = (BYTE *) iv;
1434        if (php_win32_get_random_bytes(iv_b, (size_t) size) == FAILURE){
1435            efree(iv);
1436            php_error_docref(NULL, E_WARNING, "Could not gather sufficient random data");
1437            RETURN_FALSE;
1438        }
1439        n = (int)size;
1440#else
1441        int    fd;
1442        size_t read_bytes = 0;
1443
1444        fd = open(source == RANDOM ? "/dev/random" : "/dev/urandom", O_RDONLY);
1445        if (fd < 0) {
1446            efree(iv);
1447            php_error_docref(NULL, E_WARNING, "Cannot open source device");
1448            RETURN_FALSE;
1449        }
1450        while (read_bytes < size) {
1451            n = read(fd, iv + read_bytes, size - read_bytes);
1452            if (n < 0) {
1453                break;
1454            }
1455            read_bytes += n;
1456        }
1457        n = read_bytes;
1458        close(fd);
1459        if (n < size) {
1460            efree(iv);
1461            php_error_docref(NULL, E_WARNING, "Could not gather sufficient random data");
1462            RETURN_FALSE;
1463        }
1464#endif
1465    } else {
1466        n = (int)size;
1467        while (size) {
1468            iv[--size] = (char) (255.0 * php_rand() / RAND_MAX);
1469        }
1470    }
1471    RETVAL_STRINGL(iv, n);
1472    efree(iv);
1473}
1474/* }}} */
1475
1476#endif
1477
1478/*
1479 * Local variables:
1480 * tab-width: 4
1481 * c-basic-offset: 4
1482 * End:
1483 * vim600: sw=4 ts=4 fdm=marker
1484 * vim<600: sw=4 ts=4
1485 */
1486