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