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