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