suricata
output-lua.c
Go to the documentation of this file.
1 /* Copyright (C) 2014-2022 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Victor Julien <victor@inliniac.net>
22  *
23  */
24 
25 #include "suricata-common.h"
26 #include "output-lua.h"
27 
28 #include "util-lua-builtins.h"
29 #include "util-debug.h"
30 #include "output.h"
31 #include "app-layer-htp.h"
32 #include "app-layer-ssl.h"
33 #include "app-layer-ssh.h"
34 #include "app-layer-parser.h"
35 #include "util-time.h"
36 #include "util-lua.h"
37 #include "util-lua-common.h"
38 #include "util-lua-http.h"
39 #include "util-lua-dns.h"
40 #include "util-lua-ja3.h"
41 #include "util-lua-tls.h"
42 #include "util-lua-ssh.h"
43 #include "util-lua-hassh.h"
44 #include "util-lua-smtp.h"
45 
46 #define MODULE_NAME "LuaLog"
47 
48 /** \brief structure containing global config
49  * The OutputLuaLogInitSub which is run per script
50  * can access this to get global config info through
51  * it's parent_ctx->data ptr.
52  */
53 typedef struct LogLuaMasterCtx_ {
54  /** \brief Path to script directory. */
55  char script_dir[PATH_MAX];
56 
57  /** \brief Lua search path for Lua modules. */
58  char path[PATH_MAX];
59 
60  /** \brief Lua search path for C modules. */
61  char cpath[PATH_MAX];
63 
64 typedef struct LogLuaCtx_ {
69 
70 typedef struct LogLuaThreadCtx_ {
73 
74 static TmEcode LuaLogThreadInit(ThreadVars *t, const void *initdata, void **data);
75 static TmEcode LuaLogThreadDeinit(ThreadVars *t, void *data);
76 
77 /** \internal
78  * \brief TX logger for lua scripts
79  *
80  * A single call to this function will run one script on a single
81  * transaction.
82  *
83  * NOTE: The flow (f) also referenced by p->flow is locked.
84  */
85 static int LuaTxLogger(ThreadVars *tv, void *thread_data, const Packet *p, Flow *f, void *alstate, void *txptr, uint64_t tx_id)
86 {
87  SCEnter();
88 
89  LogLuaThreadCtx *td = (LogLuaThreadCtx *)thread_data;
90 
91  SCMutexLock(&td->lua_ctx->m);
92 
95  LuaStateSetTX(td->lua_ctx->luastate, txptr, tx_id);
97 
98  /* prepare data to pass to script */
99  lua_getglobal(td->lua_ctx->luastate, "log");
100  lua_newtable(td->lua_ctx->luastate);
101  LuaPushTableKeyValueInt(td->lua_ctx->luastate, "tx_id", (int)(tx_id));
102 
103  int retval = lua_pcall(td->lua_ctx->luastate, 1, 0, 0);
104  if (retval != 0) {
105  SCLogInfo("failed to run script: %s", lua_tostring(td->lua_ctx->luastate, -1));
106  }
107 
108  SCMutexUnlock(&td->lua_ctx->m);
109  SCReturnInt(0);
110 }
111 
112 /** \internal
113  * \brief Streaming logger for lua scripts
114  *
115  * Hooks into the Streaming Logger API. Gets called for each chunk of new
116  * streaming data.
117  */
118 static int LuaStreamingLogger(ThreadVars *tv, void *thread_data, const Flow *f,
119  const uint8_t *data, uint32_t data_len, uint64_t tx_id, uint8_t flags)
120 {
121  SCEnter();
122 
123  void *txptr = NULL;
124  LuaStreamingBuffer b = { data, data_len, flags };
125 
126  SCLogDebug("flags %02x", flags);
127 
129  if (f && f->alstate)
130  txptr = AppLayerParserGetTx(f->proto, f->alproto, f->alstate, tx_id);
131  }
132 
133  LogLuaThreadCtx *td = (LogLuaThreadCtx *)thread_data;
134 
135  SCMutexLock(&td->lua_ctx->m);
136 
139  LuaStateSetTX(td->lua_ctx->luastate, txptr, tx_id);
140  LuaStateSetFlow(td->lua_ctx->luastate, (Flow *)f);
142 
143  /* prepare data to pass to script */
144  lua_getglobal(td->lua_ctx->luastate, "log");
145  lua_newtable(td->lua_ctx->luastate);
146 
148  LuaPushTableKeyValueInt(td->lua_ctx->luastate, "tx_id", (int)(tx_id));
149 
150  int retval = lua_pcall(td->lua_ctx->luastate, 1, 0, 0);
151  if (retval != 0) {
152  SCLogInfo("failed to run script: %s", lua_tostring(td->lua_ctx->luastate, -1));
153  }
154 
155  SCMutexUnlock(&td->lua_ctx->m);
156 
158 }
159 
160 /** \internal
161  * \brief Packet Logger for lua scripts, for alerts
162  *
163  * A single call to this function will run one script for a single
164  * packet. If it is called, it means that the registered condition
165  * function has returned true.
166  *
167  * The script is called once for each alert stored in the packet.
168  *
169  * NOTE: p->flow is UNlocked
170  */
171 static int LuaPacketLoggerAlerts(ThreadVars *tv, void *thread_data, const Packet *p)
172 {
173  LogLuaThreadCtx *td = (LogLuaThreadCtx *)thread_data;
174 
175  char timebuf[64];
176  CreateTimeString(p->ts, timebuf, sizeof(timebuf));
177 
178  if (!(PacketIsIPv4(p)) && !(PacketIsIPv6(p))) {
179  /* decoder event */
180  goto not_supported;
181  }
182 
183  /* loop through alerts stored in the packet */
184  SCMutexLock(&td->lua_ctx->m);
185  uint16_t cnt;
186  for (cnt = 0; cnt < p->alerts.cnt; cnt++) {
187  const PacketAlert *pa = &p->alerts.alerts[cnt];
188  if (unlikely(pa->s == NULL)) {
189  continue;
190  }
191 
192  lua_getglobal(td->lua_ctx->luastate, "log");
193 
194  void *txptr = NULL;
195  if (p->flow && p->flow->alstate && (pa->flags & PACKET_ALERT_FLAG_TX))
196  txptr = AppLayerParserGetTx(
197  p->flow->proto, p->flow->alproto, p->flow->alstate, pa->tx_id);
198 
201  LuaStateSetTX(td->lua_ctx->luastate, txptr, pa->tx_id);
204 
205  /* prepare data to pass to script */
206  //lua_newtable(td->lua_ctx->luastate);
207 
208  int retval = lua_pcall(td->lua_ctx->luastate, 0, 0, 0);
209  if (retval != 0) {
210  SCLogInfo("failed to run script: %s", lua_tostring(td->lua_ctx->luastate, -1));
211  }
212  }
213  SCMutexUnlock(&td->lua_ctx->m);
214 not_supported:
215  SCReturnInt(0);
216 }
217 
218 static bool LuaPacketConditionAlerts(ThreadVars *tv, void *data, const Packet *p)
219 {
220  return (p->alerts.cnt > 0);
221 }
222 
223 /** \internal
224  * \brief Packet Logger for lua scripts, for packets
225  *
226  * A single call to this function will run one script for a single
227  * packet. If it is called, it means that the registered condition
228  * function has returned true.
229  *
230  * The script is called once for each packet.
231  *
232  * NOTE: p->flow is UNlocked
233  */
234 static int LuaPacketLogger(ThreadVars *tv, void *thread_data, const Packet *p)
235 {
236  LogLuaThreadCtx *td = (LogLuaThreadCtx *)thread_data;
237 
238  char timebuf[64];
239 
240  if ((!(PacketIsIPv4(p))) && (!(PacketIsIPv6(p)))) {
241  goto not_supported;
242  }
243 
244  CreateTimeString(p->ts, timebuf, sizeof(timebuf));
245 
246  /* loop through alerts stored in the packet */
247  SCMutexLock(&td->lua_ctx->m);
248  lua_getglobal(td->lua_ctx->luastate, "log");
249 
253 
254  /* prepare data to pass to script */
255  lua_newtable(td->lua_ctx->luastate);
256 
257  int retval = lua_pcall(td->lua_ctx->luastate, 1, 0, 0);
258  if (retval != 0) {
259  SCLogInfo("failed to run script: %s", lua_tostring(td->lua_ctx->luastate, -1));
260  }
261  SCMutexUnlock(&td->lua_ctx->m);
262 not_supported:
263  SCReturnInt(0);
264 }
265 
266 static bool LuaPacketCondition(ThreadVars *tv, void *data, const Packet *p)
267 {
268  return true;
269 }
270 
271 /** \internal
272  * \brief File API Logger function for Lua scripts
273  *
274  * Executes a script once for one file.
275  *
276  * NOTE p->flow is locked at this point
277  */
278 static int LuaFileLogger(ThreadVars *tv, void *thread_data, const Packet *p, const File *ff,
279  void *tx, const uint64_t tx_id, uint8_t dir)
280 {
281  SCEnter();
282  LogLuaThreadCtx *td = (LogLuaThreadCtx *)thread_data;
283 
284  if ((!(PacketIsIPv4(p))) && (!(PacketIsIPv6(p))))
285  return 0;
286 
287  BUG_ON(ff->flags & FILE_LOGGED);
288 
289  SCLogDebug("ff %p", ff);
290 
291  SCMutexLock(&td->lua_ctx->m);
292 
295  LuaStateSetTX(td->lua_ctx->luastate, tx, tx_id);
297  LuaStateSetFile(td->lua_ctx->luastate, (File *)ff);
298 
299  /* get the lua function to call */
300  lua_getglobal(td->lua_ctx->luastate, "log");
301 
302  int retval = lua_pcall(td->lua_ctx->luastate, 0, 0, 0);
303  if (retval != 0) {
304  SCLogInfo("failed to run script: %s", lua_tostring(td->lua_ctx->luastate, -1));
305  }
306  SCMutexUnlock(&td->lua_ctx->m);
307  return 0;
308 }
309 
310 /** \internal
311  * \brief Flow API Logger function for Lua scripts
312  *
313  * Executes a script once for one flow
314  *
315  * Note: flow 'f' is locked
316  */
317 static int LuaFlowLogger(ThreadVars *tv, void *thread_data, Flow *f)
318 {
319  SCEnter();
320  LogLuaThreadCtx *td = (LogLuaThreadCtx *)thread_data;
321 
322  SCLogDebug("f %p", f);
323 
324  SCMutexLock(&td->lua_ctx->m);
325 
328 
329  /* get the lua function to call */
330  lua_getglobal(td->lua_ctx->luastate, "log");
331 
332  int retval = lua_pcall(td->lua_ctx->luastate, 0, 0, 0);
333  if (retval != 0) {
334  SCLogInfo("failed to run script: %s", lua_tostring(td->lua_ctx->luastate, -1));
335  }
336  SCMutexUnlock(&td->lua_ctx->m);
337  return 0;
338 }
339 
340 
341 
342 static int LuaStatsLogger(ThreadVars *tv, void *thread_data, const StatsTable *st)
343 {
344  SCEnter();
345  LogLuaThreadCtx *td = (LogLuaThreadCtx *)thread_data;
346 
347  SCMutexLock(&td->lua_ctx->m);
348 
349  lua_State *luastate = td->lua_ctx->luastate;
350  /* get the lua function to call */
351  lua_getglobal(td->lua_ctx->luastate, "log");
352 
353  /* create lua array, which is really just a table. The key is an int (1-x),
354  * the value another table with named fields: name, tm_name, value, pvalue.
355  * { 1, { name=<name>, tmname=<tm_name>, value=<value>, pvalue=<pvalue>}}
356  * { 2, { name=<name>, tmname=<tm_name>, value=<value>, pvalue=<pvalue>}}
357  * etc
358  */
359  lua_newtable(luastate);
360  uint32_t u = 0;
361  for (; u < st->nstats; u++) {
362  lua_pushinteger(luastate, u + 1);
363 
364  lua_newtable(luastate);
365 
366  lua_pushstring(luastate, "name");
367  lua_pushstring(luastate, st->stats[u].name);
368  lua_settable(luastate, -3);
369 
370  lua_pushstring(luastate, "tmname");
371  lua_pushstring(luastate, st->stats[u].tm_name);
372  lua_settable(luastate, -3);
373 
374  lua_pushstring(luastate, "value");
375  lua_pushinteger(luastate, st->stats[u].value);
376  lua_settable(luastate, -3);
377 
378  lua_pushstring(luastate, "pvalue");
379  lua_pushinteger(luastate, st->stats[u].pvalue);
380  lua_settable(luastate, -3);
381 
382  lua_settable(luastate, -3);
383  }
384 
385  int retval = lua_pcall(td->lua_ctx->luastate, 1, 0, 0);
386  if (retval != 0) {
387  SCLogInfo("failed to run script: %s", lua_tostring(td->lua_ctx->luastate, -1));
388  }
389  SCMutexUnlock(&td->lua_ctx->m);
390  return 0;
391 
392 }
393 
394 typedef struct LogLuaScriptOptions_ {
396  int packet;
397  int alerts;
398  int file;
400  int tcp_data;
402  int flow;
403  int stats;
405 
406 /** \brief Setup or clear Lua module search paths.
407  *
408  * If search paths are provided by the configuration, set them up,
409  * otherwise clear the default search paths.
410  */
411 static void LuaSetPaths(lua_State *L, LogLuaMasterCtx *ctx)
412 {
413  lua_getglobal(L, "package");
414 
415  if (strlen(ctx->path) > 0) {
416  lua_pushstring(L, ctx->path);
417  } else {
418  lua_pushstring(L, "");
419  }
420  lua_setfield(L, -2, "path");
421 
422  if (strlen(ctx->cpath) > 0) {
423  lua_pushstring(L, ctx->cpath);
424  } else {
425  lua_pushstring(L, "");
426  }
427  lua_setfield(L, -2, "cpath");
428 
429  /* Pop package. */
430  lua_pop(L, 1);
431 }
432 
433 /** \brief load and evaluate the script
434  *
435  * This function parses the script, checks if all the required functions
436  * are defined and runs the 'init' function. The init function will inform
437  * us what the scripts needs are.
438  *
439  * \param filename filename of lua script file
440  * \param options struct to pass script requirements/options back to caller
441  * \retval errcode 0 ok, -1 error
442  */
443 static int LuaScriptInit(const char *filename, LogLuaScriptOptions *options, LogLuaMasterCtx *ctx)
444 {
445  lua_State *luastate = LuaGetState();
446  if (luastate == NULL)
447  goto error;
448  luaL_openlibs(luastate);
449  SCLuaRequirefBuiltIns(luastate);
450  LuaSetPaths(luastate, ctx);
451 
452  int status = luaL_loadfile(luastate, filename);
453  if (status) {
454  SCLogError("couldn't load file: %s", lua_tostring(luastate, -1));
455  goto error;
456  }
457 
458  /* prime the script (or something) */
459  if (lua_pcall(luastate, 0, 0, 0) != 0) {
460  SCLogError("couldn't prime file: %s", lua_tostring(luastate, -1));
461  goto error;
462  }
463 
464  lua_getglobal(luastate, "init");
465  if (lua_type(luastate, -1) != LUA_TFUNCTION) {
466  SCLogError("no init function in script");
467  goto error;
468  }
469 
470  lua_newtable(luastate); /* stack at -1 */
471  if (lua_gettop(luastate) == 0 || lua_type(luastate, 2) != LUA_TTABLE) {
472  SCLogError("no table setup");
473  goto error;
474  }
475 
476  lua_pushliteral(luastate, "script_api_ver");
477  lua_pushnumber (luastate, 1);
478  lua_settable(luastate, -3);
479 
480  if (lua_pcall(luastate, 1, 1, 0) != 0) {
481  SCLogError("couldn't run script 'init' function: %s", lua_tostring(luastate, -1));
482  goto error;
483  }
484 
485  /* process returns from script */
486  if (lua_gettop(luastate) == 0) {
487  SCLogError("init function in script should return table, nothing returned");
488  goto error;
489  }
490  if (lua_type(luastate, 1) != LUA_TTABLE) {
491  SCLogError("init function in script should return table, returned is not table");
492  goto error;
493  }
494 
495  lua_pushnil(luastate);
496  const char *k, *v;
497  while (lua_next(luastate, -2)) {
498  k = lua_tostring(luastate, -2);
499  if (k == NULL)
500  continue;
501 
502  v = lua_tostring(luastate, -1);
503  lua_pop(luastate, 1);
504  if (v == NULL)
505  continue;
506 
507  SCLogDebug("k='%s', v='%s'", k, v);
508 
509  if (strcmp(k,"protocol") == 0 && strcmp(v, "http") == 0)
510  options->alproto = ALPROTO_HTTP1;
511  else if (strcmp(k,"protocol") == 0 && strcmp(v, "dns") == 0)
512  options->alproto = ALPROTO_DNS;
513  else if (strcmp(k,"protocol") == 0 && strcmp(v, "tls") == 0)
514  options->alproto = ALPROTO_TLS;
515  else if (strcmp(k,"protocol") == 0 && strcmp(v, "ssh") == 0)
516  options->alproto = ALPROTO_SSH;
517  else if (strcmp(k,"protocol") == 0 && strcmp(v, "smtp") == 0)
518  options->alproto = ALPROTO_SMTP;
519  else if (strcmp(k, "type") == 0 && strcmp(v, "packet") == 0)
520  options->packet = 1;
521  else if (strcmp(k, "filter") == 0 && strcmp(v, "alerts") == 0)
522  options->alerts = 1;
523  else if (strcmp(k, "type") == 0 && strcmp(v, "file") == 0)
524  options->file = 1;
525  else if (strcmp(k, "type") == 0 && strcmp(v, "streaming") == 0)
526  options->streaming = 1;
527  else if (strcmp(k, "type") == 0 && strcmp(v, "flow") == 0)
528  options->flow = 1;
529  else if (strcmp(k, "filter") == 0 && strcmp(v, "tcp") == 0)
530  options->tcp_data = 1;
531  else if (strcmp(k, "type") == 0 && strcmp(v, "stats") == 0)
532  options->stats = 1;
533  else {
534  SCLogError("unknown key and/or value: k='%s', v='%s'", k, v);
535  goto error;
536  }
537  }
538 
539  if (((options->alproto != ALPROTO_UNKNOWN)) + options->packet + options->file > 1) {
540  SCLogError("invalid combination of 'needs' in the script");
541  goto error;
542  }
543 
544  lua_getglobal(luastate, "setup");
545  if (lua_type(luastate, -1) != LUA_TFUNCTION) {
546  SCLogError("no setup function in script");
547  goto error;
548  }
549 
550  lua_getglobal(luastate, "log");
551  if (lua_type(luastate, -1) != LUA_TFUNCTION) {
552  SCLogError("no log function in script");
553  goto error;
554  }
555 
556  lua_getglobal(luastate, "deinit");
557  if (lua_type(luastate, -1) != LUA_TFUNCTION) {
558  SCLogError("no deinit function in script");
559  goto error;
560  }
561 
562  LuaReturnState(luastate);
563  return 0;
564 error:
565  if (luastate)
566  LuaReturnState(luastate);
567  return -1;
568 }
569 
570 /** \brief setup a luastate for use at runtime
571  *
572  * This loads the script, primes it and then runs the 'setup' function.
573  *
574  * \retval state Returns the set up luastate on success, NULL on error
575  */
576 static lua_State *LuaScriptSetup(const char *filename, LogLuaMasterCtx *ctx)
577 {
578  lua_State *luastate = LuaGetState();
579  if (luastate == NULL) {
580  SCLogError("luaL_newstate failed");
581  goto error;
582  }
583 
584  luaL_openlibs(luastate);
585  SCLuaRequirefBuiltIns(luastate);
586  LuaSetPaths(luastate, ctx);
587 
588  int status = luaL_loadfile(luastate, filename);
589  if (status) {
590  SCLogError("couldn't load file: %s", lua_tostring(luastate, -1));
591  goto error;
592  }
593 
594  /* prime the script */
595  if (lua_pcall(luastate, 0, 0, 0) != 0) {
596  SCLogError("couldn't prime file: %s", lua_tostring(luastate, -1));
597  goto error;
598  }
599 
600  lua_getglobal(luastate, "setup");
601 
602  /* register functions common to all */
603  LuaRegisterFunctions(luastate);
604  /* unconditionally register http function. They will only work
605  * if the tx is registered in the state at runtime though. */
606  LuaRegisterHttpFunctions(luastate);
607  LuaRegisterDnsFunctions(luastate);
608  LuaRegisterJa3Functions(luastate);
609  LuaRegisterTlsFunctions(luastate);
610  LuaRegisterSshFunctions(luastate);
611  LuaRegisterHasshFunctions(luastate);
612  LuaRegisterSmtpFunctions(luastate);
613 
614  if (lua_pcall(luastate, 0, 0, 0) != 0) {
615  SCLogError("couldn't run script 'setup' function: %s", lua_tostring(luastate, -1));
616  goto error;
617  }
618 
619  SCLogDebug("lua_State %p is set up", luastate);
620  return luastate;
621 error:
622  if (luastate)
623  LuaReturnState(luastate);
624  return NULL;
625 }
626 
627 static void LogLuaSubFree(OutputCtx *oc) {
628  if (oc->data)
629  SCFree(oc->data);
630  SCFree(oc);
631 }
632 
633 /** \brief initialize output for a script instance
634  *
635  * Runs script 'setup' function.
636  */
637 static OutputInitResult OutputLuaLogInitSub(ConfNode *conf, OutputCtx *parent_ctx)
638 {
639  OutputInitResult result = { NULL, false };
640  if (conf == NULL)
641  return result;
642 
643  LogLuaCtx *lua_ctx = SCCalloc(1, sizeof(LogLuaCtx));
644  if (unlikely(lua_ctx == NULL))
645  return result;
646 
647  OutputCtx *output_ctx = SCCalloc(1, sizeof(OutputCtx));
648  if (unlikely(output_ctx == NULL)) {
649  SCFree(lua_ctx);
650  return result;
651  }
652 
653  SCMutexInit(&lua_ctx->m, NULL);
654 
655  BUG_ON(parent_ctx == NULL);
656  LogLuaMasterCtx *mc = parent_ctx->data;
657  BUG_ON(mc == NULL);
658 
659  const char *dir = mc->script_dir;
660  char path[PATH_MAX] = "";
661  int ret = snprintf(path, sizeof(path),"%s%s%s", dir, strlen(dir) ? "/" : "", conf->val);
662  if (ret < 0 || ret == sizeof(path)) {
663  SCLogError("failed to construct lua script path");
664  goto error;
665  }
666  SCLogDebug("script full path %s", path);
667 
668  SCMutexLock(&lua_ctx->m);
669  lua_ctx->luastate = LuaScriptSetup(path, mc);
670  SCMutexUnlock(&lua_ctx->m);
671  if (lua_ctx->luastate == NULL)
672  goto error;
673 
674  SCLogDebug("lua_ctx %p", lua_ctx);
675 
676  output_ctx->data = lua_ctx;
677  output_ctx->DeInit = LogLuaSubFree;
678 
679  result.ctx = output_ctx;
680  result.ok = true;
681  return result;
682 error:
683  SCMutexDestroy(&lua_ctx->m);
684  SCFree(lua_ctx);
685  SCFree(output_ctx);
686  return result;
687 }
688 
689 static void LogLuaMasterFree(OutputCtx *oc)
690 {
691  if (oc->data)
692  SCFree(oc->data);
693 
694  OutputModule *om, *tom;
695  TAILQ_FOREACH_SAFE(om, &oc->submodules, entries, tom) {
696  SCFree(om);
697  }
698  SCFree(oc);
699 }
700 
701 /** \internal
702  * \brief initialize output instance for lua module
703  *
704  * Parses nested script list, primes them to find out what they
705  * inspect, then fills the OutputCtx::submodules list with the
706  * proper Logger function for the data type the script needs.
707  */
708 static OutputInitResult OutputLuaLogInit(ConfNode *conf)
709 {
710  OutputInitResult result = { NULL, false };
711  const char *dir = ConfNodeLookupChildValue(conf, "scripts-dir");
712  if (dir == NULL)
713  dir = "";
714 
715  ConfNode *scripts = ConfNodeLookupChild(conf, "scripts");
716  if (scripts == NULL) {
717  /* No "outputs" section in the configuration. */
718  SCLogInfo("scripts not defined");
719  return result;
720  }
721 
722  /* global output ctx setup */
723  OutputCtx *output_ctx = SCCalloc(1, sizeof(OutputCtx));
724  if (unlikely(output_ctx == NULL)) {
725  return result;
726  }
727  output_ctx->DeInit = LogLuaMasterFree;
728  output_ctx->data = SCCalloc(1, sizeof(LogLuaMasterCtx));
729  if (unlikely(output_ctx->data == NULL)) {
730  SCFree(output_ctx);
731  return result;
732  }
733  LogLuaMasterCtx *master_config = output_ctx->data;
734  strlcpy(master_config->script_dir, dir, sizeof(master_config->script_dir));
735 
736  const char *lua_path = ConfNodeLookupChildValue(conf, "path");
737  if (lua_path && strlen(lua_path) > 0) {
738  strlcpy(master_config->path, lua_path, sizeof(master_config->path));
739  }
740 
741  const char *lua_cpath = ConfNodeLookupChildValue(conf, "cpath");
742  if (lua_cpath && strlen(lua_cpath) > 0) {
743  strlcpy(master_config->cpath, lua_cpath, sizeof(master_config->cpath));
744  }
745 
746  TAILQ_INIT(&output_ctx->submodules);
747 
748  /* check the enables scripts and set them up as submodules */
749  ConfNode *script;
750  TAILQ_FOREACH(script, &scripts->head, next) {
751  SCLogInfo("enabling script %s", script->val);
752  LogLuaScriptOptions opts;
753  memset(&opts, 0x00, sizeof(opts));
754 
755  char path[PATH_MAX] = "";
756  snprintf(path, sizeof(path),"%s%s%s", dir, strlen(dir) ? "/" : "", script->val);
757  SCLogDebug("script full path %s", path);
758 
759  int r = LuaScriptInit(path, &opts, master_config);
760  if (r != 0) {
761  SCLogError("couldn't initialize script");
762  goto error;
763  }
764 
765  /* create an OutputModule for this script, based
766  * on it's needs. */
767  OutputModule *om = SCCalloc(1, sizeof(*om));
768  if (om == NULL) {
769  SCLogError("calloc() failed");
770  goto error;
771  }
772 
773  om->name = MODULE_NAME;
774  om->conf_name = script->val;
775  om->InitSubFunc = OutputLuaLogInitSub;
776  om->ThreadInit = LuaLogThreadInit;
777  om->ThreadDeinit = LuaLogThreadDeinit;
778 
779  if (opts.alproto == ALPROTO_HTTP1 && opts.streaming) {
780  om->StreamingLogFunc = LuaStreamingLogger;
782  om->alproto = ALPROTO_HTTP1;
785  } else if (opts.alproto == ALPROTO_HTTP1) {
786  om->TxLogFunc = LuaTxLogger;
787  om->alproto = ALPROTO_HTTP1;
788  om->ts_log_progress = -1;
789  om->tc_log_progress = -1;
791  } else if (opts.alproto == ALPROTO_TLS) {
792  om->TxLogFunc = LuaTxLogger;
793  om->alproto = ALPROTO_TLS;
797  } else if (opts.alproto == ALPROTO_DNS) {
798  om->TxLogFunc = LuaTxLogger;
799  om->alproto = ALPROTO_DNS;
800  om->ts_log_progress = -1;
801  om->tc_log_progress = -1;
804  } else if (opts.alproto == ALPROTO_SSH) {
805  om->TxLogFunc = LuaTxLogger;
806  om->alproto = ALPROTO_SSH;
809  } else if (opts.alproto == ALPROTO_SMTP) {
810  om->TxLogFunc = LuaTxLogger;
811  om->alproto = ALPROTO_SMTP;
812  om->ts_log_progress = -1;
813  om->tc_log_progress = -1;
815  } else if (opts.packet && opts.alerts) {
816  om->PacketLogFunc = LuaPacketLoggerAlerts;
817  om->PacketConditionFunc = LuaPacketConditionAlerts;
818  } else if (opts.packet && opts.alerts == 0) {
819  om->PacketLogFunc = LuaPacketLogger;
820  om->PacketConditionFunc = LuaPacketCondition;
821  } else if (opts.file) {
822  om->FileLogFunc = LuaFileLogger;
824  } else if (opts.streaming && opts.tcp_data) {
825  om->StreamingLogFunc = LuaStreamingLogger;
827  } else if (opts.flow) {
828  om->FlowLogFunc = LuaFlowLogger;
829  } else if (opts.stats) {
830  om->StatsLogFunc = LuaStatsLogger;
831  } else {
832  SCLogError("failed to setup thread module");
833  SCFree(om);
834  goto error;
835  }
836 
837  TAILQ_INSERT_TAIL(&output_ctx->submodules, om, entries);
838  }
839 
840  result.ctx = output_ctx;
841  result.ok = true;
842  return result;
843 
844 error:
845  if (output_ctx->DeInit)
846  output_ctx->DeInit(output_ctx);
847 
848  int failure_fatal = 0;
849  if (ConfGetBool("engine.init-failure-fatal", &failure_fatal) != 1) {
850  SCLogDebug("ConfGetBool could not load the value.");
851  }
852  if (failure_fatal) {
853  FatalError("Error during setup of lua output. Details should be "
854  "described in previous error messages. Shutting down...");
855  }
856 
857  return result;
858 }
859 
860 /** \internal
861  * \brief Run the scripts 'deinit' function
862  */
863 static void OutputLuaLogDoDeinit(LogLuaCtx *lua_ctx)
864 {
865  lua_State *luastate = lua_ctx->luastate;
866 
867  lua_getglobal(luastate, "deinit");
868  if (lua_type(luastate, -1) != LUA_TFUNCTION) {
869  SCLogError("no deinit function in script");
870  return;
871  }
872  //LuaPrintStack(luastate);
873 
874  if (lua_pcall(luastate, 0, 0, 0) != 0) {
875  SCLogError("couldn't run script 'deinit' function: %s", lua_tostring(luastate, -1));
876  return;
877  }
878  LuaReturnState(luastate);
879 }
880 
881 /** \internal
882  * \brief Initialize the thread storage for lua
883  *
884  * Currently only stores a pointer to the global LogLuaCtx
885  */
886 static TmEcode LuaLogThreadInit(ThreadVars *t, const void *initdata, void **data)
887 {
888  LogLuaThreadCtx *td = SCCalloc(1, sizeof(*td));
889  if (unlikely(td == NULL))
890  return TM_ECODE_FAILED;
891 
892  if (initdata == NULL) {
893  SCLogDebug("Error getting context for LuaLog. \"initdata\" argument NULL");
894  SCFree(td);
895  return TM_ECODE_FAILED;
896  }
897 
898  LogLuaCtx *lua_ctx = ((OutputCtx *)initdata)->data;
899  SCLogDebug("lua_ctx %p", lua_ctx);
900  td->lua_ctx = lua_ctx;
901  *data = (void *)td;
902  return TM_ECODE_OK;
903 }
904 
905 /** \internal
906  * \brief Deinit the thread storage for lua
907  *
908  * Calls OutputLuaLogDoDeinit if no-one else already did.
909  */
910 static TmEcode LuaLogThreadDeinit(ThreadVars *t, void *data)
911 {
912  LogLuaThreadCtx *td = (LogLuaThreadCtx *)data;
913  if (td == NULL) {
914  return TM_ECODE_OK;
915  }
916 
917  SCMutexLock(&td->lua_ctx->m);
918  if (td->lua_ctx->deinit_once == 0) {
919  OutputLuaLogDoDeinit(td->lua_ctx);
920  td->lua_ctx->deinit_once = 1;
921  }
922  SCMutexUnlock(&td->lua_ctx->m);
923 
924  /* clear memory */
925  memset(td, 0, sizeof(*td));
926 
927  SCFree(td);
928  return TM_ECODE_OK;
929 }
930 
931 void LuaLogRegister(void) {
932  /* register as separate module */
933  OutputRegisterModule(MODULE_NAME, "lua", OutputLuaLogInit);
934 }
LuaStateSetTX
void LuaStateSetTX(lua_State *luastate, void *txptr, const uint64_t tx_id)
Definition: util-lua.c:150
LogLuaThreadCtx
struct LogLuaThreadCtx_ LogLuaThreadCtx
LuaStateSetPacket
void LuaStateSetPacket(lua_State *luastate, Packet *p)
Definition: util-lua.c:126
OutputModule_::FileLogFunc
SCFileLogger FileLogFunc
Definition: output.h:71
LogLuaMasterCtx_
structure containing global config The OutputLuaLogInitSub which is run per script can access this to...
Definition: output-lua.c:53
AppLayerHtpNeedFileInspection
void AppLayerHtpNeedFileInspection(void)
Sets a flag that informs the HTP app layer that some module in the engine needs the http request file...
Definition: app-layer-htp.c:496
LuaStateSetThreadVars
void LuaStateSetThreadVars(lua_State *luastate, ThreadVars *tv)
Definition: util-lua.c:110
util-lua-ssh.h
PacketAlert_::s
const struct Signature_ * s
Definition: decode.h:243
STREAMING_TCP_DATA
@ STREAMING_TCP_DATA
Definition: output-streaming.h:36
LogLuaScriptOptions_::file
int file
Definition: output-lua.c:398
app-layer-ssh.h
util-lua-hassh.h
LogLuaScriptOptions_::alproto
AppProto alproto
Definition: output-lua.c:395
util-lua-common.h
PACKET_ALERT_FLAG_TX
#define PACKET_ALERT_FLAG_TX
Definition: decode.h:255
TAILQ_INIT
#define TAILQ_INIT(head)
Definition: queue.h:262
LuaPushTableKeyValueInt
void LuaPushTableKeyValueInt(lua_State *luastate, const char *key, int value)
Definition: util-lua-common.c:79
ALPROTO_DNS
@ ALPROTO_DNS
Definition: app-layer-protos.h:47
LuaStreamingBuffer_
Definition: util-lua.h:34
ConfNode_::val
char * val
Definition: conf.h:34
ConfGetBool
int ConfGetBool(const char *name, int *val)
Retrieve a configuration value as a boolean.
Definition: conf.c:482
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
ALPROTO_TLS
@ ALPROTO_TLS
Definition: app-layer-protos.h:39
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:269
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
Flow_::proto
uint8_t proto
Definition: flow.h:376
util-lua.h
AppProto
uint16_t AppProto
Definition: app-layer-protos.h:85
LogLuaCtx_
Definition: output-lua.c:64
PacketAlerts_::cnt
uint16_t cnt
Definition: decode.h:267
LuaGetState
lua_State * LuaGetState(void)
Definition: util-lua.c:57
OutputModule_::name
const char * name
Definition: output.h:58
Flow_
Flow data structure.
Definition: flow.h:354
util-lua-ja3.h
ctx
struct Thresholds ctx
LuaRegisterDnsFunctions
int LuaRegisterDnsFunctions(lua_State *luastate)
register http lua extensions in a luastate
Definition: util-lua-dns.c:134
LogLuaScriptOptions_::tcp_data
int tcp_data
Definition: output-lua.c:400
OutputModule_::ts_log_progress
int ts_log_progress
Definition: output.h:79
TAILQ_FOREACH
#define TAILQ_FOREACH(var, head, field)
Definition: queue.h:252
PacketAlerts_::alerts
PacketAlert * alerts
Definition: decode.h:270
SSHTxLogCondition
bool SSHTxLogCondition(ThreadVars *tv, const Packet *p, void *state, void *tx, uint64_t tx_id)
Definition: app-layer-ssh.c:74
LuaRegisterSshFunctions
int LuaRegisterSshFunctions(lua_State *luastate)
register ssh lua extensions in a luastate
Definition: util-lua-ssh.c:199
OutputModule_::StatsLogFunc
StatsLogger StatsLogFunc
Definition: output.h:75
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
LuaStateSetFlow
void LuaStateSetFlow(lua_State *luastate, Flow *f)
set a flow pointer in the lua state
Definition: util-lua.c:176
TAILQ_INSERT_TAIL
#define TAILQ_INSERT_TAIL(head, elm, field)
Definition: queue.h:294
util-lua-builtins.h
LogLuaScriptOptions
struct LogLuaScriptOptions_ LogLuaScriptOptions
OutputModule_::InitSubFunc
OutputInitSubFunc InitSubFunc
Definition: output.h:62
ALPROTO_SSH
@ ALPROTO_SSH
Definition: app-layer-protos.h:40
StatsRecord_::pvalue
int64_t pvalue
Definition: output-stats.h:36
LogLuaThreadCtx_
Definition: output-lua.c:70
OutputModule_::PacketLogFunc
PacketLogger PacketLogFunc
Definition: output.h:67
TM_ECODE_FAILED
@ TM_ECODE_FAILED
Definition: tm-threads-common.h:81
OUTPUT_STREAMING_FLAG_TRANSACTION
#define OUTPUT_STREAMING_FLAG_TRANSACTION
Definition: output-streaming.h:33
OutputModule_::alproto
AppProto alproto
Definition: output.h:76
LogLuaMasterCtx_::path
char path[PATH_MAX]
Lua search path for Lua modules.
Definition: output-lua.c:58
Packet_::alerts
PacketAlerts alerts
Definition: decode.h:589
OutputCtx_::data
void * data
Definition: tm-modules.h:87
TM_ECODE_OK
@ TM_ECODE_OK
Definition: tm-threads-common.h:80
PacketAlert_::tx_id
uint64_t tx_id
Definition: decode.h:244
OutputCtx_
Definition: tm-modules.h:84
strlcpy
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: util-strlcpyu.c:43
lua_State
struct lua_State lua_State
Definition: suricata-common.h:515
LogLuaMasterCtx
struct LogLuaMasterCtx_ LogLuaMasterCtx
structure containing global config The OutputLuaLogInitSub which is run per script can access this to...
OutputModule_::stream_type
enum SCOutputStreamingType stream_type
Definition: output.h:77
app-layer-htp.h
OutputModule_::ThreadInit
ThreadInitFunc ThreadInit
Definition: output.h:64
LuaRegisterHttpFunctions
int LuaRegisterHttpFunctions(lua_State *luastate)
register http lua extensions in a luastate
Definition: util-lua-http.c:317
util-debug.h
LogLuaScriptOptions_
Definition: output-lua.c:394
LuaRegisterHasshFunctions
int LuaRegisterHasshFunctions(lua_State *luastate)
Register Hassh Lua extensions.
Definition: util-lua-hassh.c:199
OutputInitResult_::ctx
OutputCtx * ctx
Definition: output.h:47
OutputModule_::ThreadDeinit
ThreadDeinitFunc ThreadDeinit
Definition: output.h:65
Packet_::ts
SCTime_t ts
Definition: decode.h:524
LogLuaScriptOptions_::stats
int stats
Definition: output-lua.c:403
SCMutexUnlock
#define SCMutexUnlock(mut)
Definition: threads-debug.h:119
LuaStateSetFile
void LuaStateSetFile(lua_State *luastate, File *file)
Definition: util-lua.c:231
ALPROTO_SMTP
@ ALPROTO_SMTP
Definition: app-layer-protos.h:38
AppLayerHtpEnableRequestBodyCallback
void AppLayerHtpEnableRequestBodyCallback(void)
Sets a flag that informs the HTP app layer that some module in the engine needs the http request body...
Definition: app-layer-htp.c:469
AppLayerParserRegisterLogger
void AppLayerParserRegisterLogger(uint8_t ipproto, AppProto alproto)
Definition: app-layer-parser.c:466
OutputRegisterModule
void OutputRegisterModule(const char *, const char *, OutputInitFunc)
SCEnter
#define SCEnter(...)
Definition: util-debug.h:271
LogLuaScriptOptions_::packet
int packet
Definition: output-lua.c:396
StatsRecord_::name
const char * name
Definition: output-stats.h:32
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:58
LogLuaCtx_::luastate
lua_State * luastate
Definition: output-lua.c:66
OutputModule_::StreamingLogFunc
SCStreamingLogger StreamingLogFunc
Definition: output.h:74
LogLuaScriptOptions_::streaming
int streaming
Definition: output-lua.c:399
util-time.h
OutputInitResult_::ok
bool ok
Definition: output.h:48
app-layer-parser.h
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:309
StatsTable_
Definition: output-stats.h:39
StatsRecord_::value
int64_t value
Definition: output-stats.h:35
LogLuaCtx_::m
SCMutex m
Definition: output-lua.c:65
OutputModule_::conf_name
const char * conf_name
Definition: output.h:59
OutputModule_::FlowLogFunc
FlowLogger FlowLogFunc
Definition: output.h:73
Packet_
Definition: decode.h:476
TmEcode
TmEcode
Definition: tm-threads-common.h:79
LogLuaScriptOptions_::http_body
int http_body
Definition: output-lua.c:401
AppLayerHtpEnableResponseBodyCallback
void AppLayerHtpEnableResponseBodyCallback(void)
Sets a flag that informs the HTP app layer that some module in the engine needs the http request body...
Definition: app-layer-htp.c:482
LogLuaScriptOptions_::flow
int flow
Definition: output-lua.c:402
LuaRegisterTlsFunctions
int LuaRegisterTlsFunctions(lua_State *luastate)
register tls lua extensions in a luastate
Definition: util-lua-tls.c:338
SCLuaRequirefBuiltIns
void SCLuaRequirefBuiltIns(lua_State *L)
Register Suricata built-in modules for loading in a non-sandboxed environment.
Definition: util-lua-builtins.c:53
SCLogInfo
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:224
TAILQ_FOREACH_SAFE
#define TAILQ_FOREACH_SAFE(var, head, field, tvar)
Definition: queue.h:329
AppLayerParserGetTx
void * AppLayerParserGetTx(uint8_t ipproto, AppProto alproto, void *alstate, uint64_t tx_id)
Definition: app-layer-parser.c:1092
SCMutexInit
#define SCMutexInit(mut, mutattrs)
Definition: threads-debug.h:116
LuaRegisterJa3Functions
int LuaRegisterJa3Functions(lua_State *luastate)
Register JA3 Lua extensions.
Definition: util-lua-ja3.c:153
StatsTable_::stats
StatsRecord * stats
Definition: output-stats.h:40
util-lua-smtp.h
ConfNodeLookupChild
ConfNode * ConfNodeLookupChild(const ConfNode *node, const char *name)
Lookup a child configuration node by name.
Definition: conf.c:781
PacketAlert_::flags
uint8_t flags
Definition: decode.h:242
File_::flags
uint16_t flags
Definition: util-file.h:80
File_
Definition: util-file.h:79
LogLuaMasterCtx_::cpath
char cpath[PATH_MAX]
Lua search path for C modules.
Definition: output-lua.c:61
cnt
uint32_t cnt
Definition: tmqh-packetpool.h:7
OutputInitResult_
Definition: output.h:46
Packet_::flow
struct Flow_ * flow
Definition: decode.h:515
OutputModule_::TxLogCondition
TxLoggerCondition TxLogCondition
Definition: output.h:70
flags
uint8_t flags
Definition: decode-gre.h:0
suricata-common.h
OutputCtx_::DeInit
void(* DeInit)(struct OutputCtx_ *)
Definition: tm-modules.h:90
ALPROTO_HTTP1
@ ALPROTO_HTTP1
Definition: app-layer-protos.h:36
LuaStateSetPacketAlert
void LuaStateSetPacketAlert(lua_State *luastate, PacketAlert *pa)
Definition: util-lua.c:199
StatsRecord_::tm_name
const char * tm_name
Definition: output-stats.h:34
util-lua-dns.h
FatalError
#define FatalError(...)
Definition: util-debug.h:502
LuaLogRegister
void LuaLogRegister(void)
Definition: output-lua.c:931
tv
ThreadVars * tv
Definition: fuzz_decodepcapfile.c:32
OutputModule_::PacketConditionFunc
PacketLogCondition PacketConditionFunc
Definition: output.h:68
TLS_HANDSHAKE_DONE
@ TLS_HANDSHAKE_DONE
Definition: app-layer-ssl.h:79
FILE_LOGGED
#define FILE_LOGGED
Definition: util-file.h:53
SCLogError
#define SCLogError(...)
Macro used to log ERROR messages.
Definition: util-debug.h:261
LuaStateSetStreamingBuffer
void LuaStateSetStreamingBuffer(lua_State *luastate, LuaStreamingBuffer *b)
Definition: util-lua.c:262
SCFree
#define SCFree(p)
Definition: util-mem.h:61
ConfNode_
Definition: conf.h:32
Flow_::alstate
void * alstate
Definition: flow.h:474
OutputModule_::TxLogFunc
TxLogger TxLogFunc
Definition: output.h:69
OutputModule_::tc_log_progress
int tc_log_progress
Definition: output.h:78
util-lua-tls.h
STREAMING_HTTP_BODIES
@ STREAMING_HTTP_BODIES
Definition: output-streaming.h:37
ALPROTO_UNKNOWN
@ ALPROTO_UNKNOWN
Definition: app-layer-protos.h:29
output-lua.h
PacketAlert_
Definition: decode.h:239
LogLuaCtx_::deinit_once
int deinit_once
Definition: output-lua.c:67
util-lua-http.h
LogLuaCtx
struct LogLuaCtx_ LogLuaCtx
LuaRegisterSmtpFunctions
int LuaRegisterSmtpFunctions(lua_State *luastate)
Definition: util-lua-smtp.c:315
LogLuaScriptOptions_::alerts
int alerts
Definition: output-lua.c:397
OutputModule_
Definition: output.h:56
Flow_::alproto
AppProto alproto
application level protocol
Definition: flow.h:448
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
SCReturnInt
#define SCReturnInt(x)
Definition: util-debug.h:275
SCMutexDestroy
#define SCMutexDestroy
Definition: threads-debug.h:120
LogLuaMasterCtx_::script_dir
char script_dir[PATH_MAX]
Path to script directory.
Definition: output-lua.c:55
StatsTable_::nstats
uint32_t nstats
Definition: output-stats.h:42
LuaRegisterFunctions
int LuaRegisterFunctions(lua_State *luastate)
Definition: util-lua-common.c:784
SCMutex
#define SCMutex
Definition: threads-debug.h:114
app-layer-ssl.h
CreateTimeString
void CreateTimeString(const SCTime_t ts, char *str, size_t size)
Definition: util-time.c:272
LogLuaThreadCtx_::lua_ctx
LogLuaCtx * lua_ctx
Definition: output-lua.c:71
output.h
LuaReturnState
void LuaReturnState(lua_State *s)
Definition: util-lua.c:64
MODULE_NAME
#define MODULE_NAME
Definition: output-lua.c:46
ConfNodeLookupChildValue
const char * ConfNodeLookupChildValue(const ConfNode *node, const char *name)
Lookup the value of a child configuration node by name.
Definition: conf.c:809