Imported Upstream version 2.5.11
[libapache-mod-security.git] / apache2 / msc_lua.c
1 /*
2  * ModSecurity for Apache 2.x, http://www.modsecurity.org/
3  * Copyright (c) 2004-2009 Breach Security, Inc. (http://www.breach.com/)
4  *
5  * This product is released under the terms of the General Public Licence,
6  * version 2 (GPLv2). Please refer to the file LICENSE (included with this
7  * distribution) which contains the complete text of the licence.
8  *
9  * There are special exceptions to the terms and conditions of the GPL
10  * as it is applied to this software. View the full text of the exception in
11  * file MODSECURITY_LICENSING_EXCEPTION in the directory of this software
12  * distribution.
13  *
14  * If any of the files related to licensing are missing or if you have any
15  * other questions related to licensing please contact Breach Security, Inc.
16  * directly using the email address support@breach.com.
17  *
18  */
19 #if defined(WITH_LUA)
20
21 #include "msc_lua.h"
22
23 #include "apr_strings.h"
24
25 typedef struct {
26     apr_array_header_t *parts;
27     apr_pool_t *pool;
28 } msc_lua_dumpw_t;
29
30 typedef struct {
31     msc_script *script;
32     int index;
33 } msc_lua_dumpr_t;
34
35 /**
36  *
37  */
38 static const char* dump_reader(lua_State* L, void* user_data, size_t* size) {
39     msc_lua_dumpr_t *dumpr = (msc_lua_dumpr_t *)user_data;
40     msc_script_part *part;
41
42     /* Do we have more chunks to return? */
43     if (dumpr->index == dumpr->script->parts->nelts) {
44         return NULL;
45     }
46
47     /* Get one chunk. */
48     part = ((msc_script_part **)dumpr->script->parts->elts)[dumpr->index];
49     *size = part->len;
50
51     dumpr->index++;
52
53     return part->data;
54 }
55
56 /**
57  *
58  */
59 static int dump_writer(lua_State *L, const void* data, size_t len, void* user_data) {
60     msc_lua_dumpw_t *dump = (msc_lua_dumpw_t *)user_data;
61     msc_script_part *part;
62     void *part_data;
63
64     /* Allocate new part, copy the data into it. */
65     part_data = apr_palloc(dump->pool, len);
66     memcpy(part_data, data, len);
67     part = apr_palloc(dump->pool, sizeof(msc_script_part));
68     part->data = part_data;
69     part->len = len;
70
71     /* Then add it to the list of parsts. */
72     *(const msc_script_part **)apr_array_push(dump->parts) = part;
73
74     return 0;
75 }
76
77 /**
78  *
79  */
80 static int lua_restore(lua_State *L, msc_script *script) {
81     msc_lua_dumpr_t dumpr;
82
83     dumpr.script = script;
84     dumpr.index = 0;
85
86     return lua_load(L, dump_reader, &dumpr, script->name);
87 }
88
89 /**
90  *
91  */
92 char *lua_compile(msc_script **script, const char *filename, apr_pool_t *pool) {
93     lua_State *L = NULL;
94     msc_lua_dumpw_t dump;
95
96     /* Initialise state. */
97     L = lua_open();
98     luaL_openlibs(L);
99
100     /* Find script. */
101     if (luaL_loadfile(L, filename)) {
102         return apr_psprintf(pool, "ModSecurity: Failed to compile script %s: %s",
103             filename, lua_tostring(L, -1));
104     }
105
106     /* Dump the script into binary form. */
107     dump.pool = pool;
108     dump.parts = apr_array_make(pool, 128, sizeof(msc_script_part *));
109
110     lua_dump(L, dump_writer, &dump);
111
112     (*script) = apr_pcalloc(pool, sizeof(msc_script));
113     (*script)->name = filename;
114     (*script)->parts = dump.parts;
115
116     /* Destroy state. */
117     lua_close(L);
118
119     return NULL;
120 }
121
122 /**
123  *
124  */
125 static int l_log(lua_State *L) {
126     modsec_rec *msr = NULL;
127     const char *text;
128     int level;
129
130     /* Retrieve parameters. */
131     level = luaL_checknumber(L, 1);
132     text = luaL_checkstring(L, 2);
133
134     /* Retrieve msr. */
135     lua_getglobal(L, "__msr");
136     msr = (modsec_rec *)lua_topointer(L, -1);
137
138     /* Log message. */
139     if (msr != NULL) {
140         msr_log(msr, level, "%s", text);
141     }
142
143     return 0;
144 }
145
146 /**
147  *
148  */
149 static apr_array_header_t *resolve_tfns(lua_State *L, int idx, modsec_rec *msr, apr_pool_t *mp) {
150     apr_array_header_t *tfn_arr = NULL;
151     msre_tfn_metadata *tfn = NULL;
152     char *name = NULL;
153
154     tfn_arr = apr_array_make(mp, 25, sizeof(msre_tfn_metadata *));
155     if (tfn_arr == NULL) return NULL;
156
157     /* ENH: Why is this userdata and not none/nil when parameter not given? */
158     if (lua_isuserdata(L, idx) || lua_isnoneornil(L, idx)) { /* No second parameter */
159         return tfn_arr;
160     } else if (lua_istable(L, idx)) { /* Is the second parameter an array? */
161         int i, n = lua_objlen(L, idx);
162
163         for(i = 1; i <= n; i++) {
164             lua_rawgeti(L, idx, i);
165             name = (char *)luaL_checkstring(L, -1);
166
167             /* A "none" means start over */
168             if (strcmp("none", name) == 0) {
169                 tfn_arr->nelts = 0;
170                 continue;
171             }
172
173             tfn = msre_engine_tfn_resolve(msr->modsecurity->msre, name);
174             if (tfn == NULL) {
175                 msr_log(msr, 1, "SecRuleScript: Invalid transformation function: %s", name);
176             } else {
177                 *(msre_tfn_metadata **)apr_array_push(tfn_arr) = tfn;
178             }
179         }
180     } else if (lua_isstring(L, idx)) { /* The second parameter may be a simple string? */
181         name = (char *)luaL_checkstring(L, idx);
182
183         /* A "none" means start over */
184         if (strcmp("none", name) == 0) {
185             tfn_arr->nelts = 0;
186         }
187         else {
188             tfn = msre_engine_tfn_resolve(msr->modsecurity->msre, name);
189             if (tfn == NULL) {
190                 msr_log(msr, 1, "SecRuleScript: Invalid transformation function: %s", name);
191             } else {
192                 *(msre_tfn_metadata **)apr_array_push(tfn_arr) = tfn;
193             }
194         }
195     } else {
196         msr_log(msr, 1, "SecRuleScript: Transformation parameter must be a transformation name or array of transformation names, but found \"%s\" (type %d).", lua_typename(L, idx), lua_type(L, idx));
197         return NULL;
198     }
199
200     return tfn_arr;
201 }
202
203 /**
204  *
205  */
206 static int l_getvar(lua_State *L) {
207     char *varname = NULL, *param = NULL;
208     modsec_rec *msr = NULL;
209     msre_rule *rule = NULL;
210     char *my_error_msg = NULL;
211     char *p1 = NULL;
212     apr_array_header_t *tfn_arr = NULL;
213     msre_var *vx = NULL;
214     msre_var *var;
215
216     /* Retrieve parameters. */
217     p1 = (char *)luaL_checkstring(L, 1);
218
219     /* Retrieve msr. */
220     lua_getglobal(L, "__msr");
221     msr = (modsec_rec *)lua_topointer(L, -1);
222
223     /* Retrieve rule. */
224     lua_getglobal(L, "__rule");
225     rule = (msre_rule *)lua_topointer(L, -1);
226
227     /* Extract the variable name and its parameter from the script. */
228     varname = apr_pstrdup(msr->msc_rule_mptmp, p1);
229     param = strchr(varname, '.');
230     if (param != NULL) {
231         *param = '\0';
232         param++;
233     }
234
235     /* Resolve variable. */
236     var = msre_create_var_ex(msr->msc_rule_mptmp, msr->modsecurity->msre,
237         varname, param, msr, &my_error_msg);
238
239     if (var == NULL) {
240         msr_log(msr, 1, "%s", my_error_msg);
241
242         lua_pushnil(L);
243
244         return 0;
245     }
246
247     /* Resolve transformation functions. */
248     tfn_arr = resolve_tfns(L, 2, msr, msr->msc_rule_mptmp);
249
250     /* Generate variable. */
251     vx = generate_single_var(msr, var, tfn_arr, rule, msr->msc_rule_mptmp);
252     if (vx == NULL) {
253         lua_pushnil(L);
254
255         return 0;
256     }
257
258     /* Return variable value. */
259     lua_pushlstring(L, vx->value, vx->value_len);
260
261     return 1;
262 }
263
264 /**
265  *
266  */
267 static int l_getvars(lua_State *L) {
268     const apr_array_header_t *tarr;
269     const apr_table_entry_t *telts;
270     apr_table_t *vartable = NULL;
271     apr_array_header_t *tfn_arr = NULL;
272     char *varname = NULL, *param = NULL;
273     modsec_rec *msr = NULL;
274     msre_rule *rule = NULL;
275     msre_var *vartemplate = NULL;
276     char *my_error_msg = NULL;
277     char *p1 = NULL;
278     int i;
279
280     /* Retrieve parameters. */
281     p1 = (char *)luaL_checkstring(L, 1);
282
283     /* Retrieve msr. */
284     lua_getglobal(L, "__msr");
285     msr = (modsec_rec *)lua_topointer(L, -1);
286
287     /* Retrieve rule. */
288     lua_getglobal(L, "__rule");
289     rule = (msre_rule *)lua_topointer(L, -1);
290
291     /* Extract the variable name and its parameter from the script. */
292     varname = apr_pstrdup(msr->msc_rule_mptmp, p1);
293     param = strchr(varname, '.');
294     if (param != NULL) {
295         *param = '\0';
296         param++;
297     }
298
299     /* Resolve transformation functions. */
300     tfn_arr = resolve_tfns(L, 2, msr, msr->msc_rule_mptmp);
301
302     lua_newtable(L);
303
304     /* Resolve variable. */
305     vartemplate = msre_create_var_ex(msr->msc_rule_mptmp, msr->modsecurity->msre,
306         varname, param, msr, &my_error_msg);
307
308     if (vartemplate == NULL) {
309         msr_log(msr, 1, "%s", my_error_msg);
310
311         /* Returning empty table. */
312         return 1;
313     }
314
315     vartable = generate_multi_var(msr, vartemplate, tfn_arr, rule, msr->msc_rule_mptmp);
316
317     tarr = apr_table_elts(vartable);
318     telts = (const apr_table_entry_t*)tarr->elts;
319     for (i = 0; i < tarr->nelts; i++) {
320         msre_var *var = (msre_var *)telts[i].val;
321
322         lua_pushnumber(L, i + 1); /* Index is not zero-based. */
323
324         lua_newtable(L); /* Per-parameter table. */
325
326         lua_pushstring(L, "name");
327         lua_pushlstring(L, var->name, strlen(var->name));
328         lua_settable(L, -3);
329
330         lua_pushstring(L, "value");
331         lua_pushlstring(L, var->value, var->value_len);
332         lua_settable(L, -3);
333
334         lua_settable(L, -3); /* Push one parameter into the results table. */
335     }
336
337     return 1;
338 }
339
340 static const struct luaL_Reg mylib[] = {
341     { "log", l_log },
342     { "getvar", l_getvar },
343     { "getvars", l_getvars },
344     { NULL, NULL }
345 };
346
347 /**
348  *
349  */
350 int lua_execute(msc_script *script, char *param, modsec_rec *msr, msre_rule *rule, char **error_msg) {
351     apr_time_t time_before;
352     lua_State *L = NULL;
353     int rc;
354
355     if (error_msg == NULL) return -1;
356     *error_msg = NULL;
357
358     if (msr->txcfg->debuglog_level >= 8) {
359         msr_log(msr, 8, "Lua: Executing script: %s", script->name);
360     }
361
362     time_before = apr_time_now();
363
364     /* Create new state. */
365     L = lua_open();
366
367     luaL_openlibs(L);
368
369     /* Associate msr with the state. */
370     lua_pushlightuserdata(L, (void *)msr);
371     lua_setglobal(L, "__msr");
372
373     /* Associate rule with the state. */
374     if (rule != NULL) {
375         lua_pushlightuserdata(L, (void *)rule);
376         lua_setglobal(L, "__rule");
377     }
378
379     /* Register functions. */
380     luaL_register(L, "m", mylib);
381
382     rc = lua_restore(L, script);
383     if (rc) {
384         *error_msg = apr_psprintf(msr->mp, "Lua: Failed to restore script with %i.", rc);
385         return -1;
386     }
387
388     /* Execute the chunk so that the functions are defined. */
389     lua_pcall(L, 0, 0, 0);
390
391     /* Execute main() */
392     lua_getglobal(L, "main");
393
394     /* Put the parameter on the stack. */
395     if (param != NULL) {
396         lua_pushlstring(L, param, strlen(param));
397     }
398
399     if (lua_pcall(L, ((param != NULL) ? 1 : 0), 1, 0)) {
400         *error_msg = apr_psprintf(msr->mp, "Lua: Script execution failed: %s", lua_tostring(L, -1));
401         return -1;
402     }
403
404     /* Get the response from the script. */
405     *error_msg = (char *)lua_tostring(L, -1);
406     if (*error_msg != NULL) {
407         *error_msg = apr_pstrdup(msr->mp, *error_msg);
408     }
409
410     /* Destroy state. */
411     lua_pop(L, 1);
412     lua_close(L);
413
414     /* Returns status code to caller. */
415     if (msr->txcfg->debuglog_level >= 8) {
416         msr_log(msr, 8, "Lua: Script completed in %" APR_TIME_T_FMT " usec, returning: %s.",
417             (apr_time_now() - time_before), *error_msg);
418     }
419
420     return ((*error_msg != NULL) ? RULE_MATCH : RULE_NO_MATCH);
421 }
422
423 #endif /* WITH_LUA */