1 #include "nmap.h"
2 #include "nbase.h"
3 #include "nmap_error.h"
4 #include "portlist.h"
5 #include "nsock.h"
6 #include "NmapOps.h"
7 #include "timing.h"
8 #include "Target.h"
9 #include "nmap_tty.h"
10 #include "xml.h"
11 
12 #include "nse_main.h"
13 #include "nse_utility.h"
14 #include "nse_fs.h"
15 #include "nse_nsock.h"
16 #include "nse_nmaplib.h"
17 #include "nse_pcrelib.h"
18 #include "nse_openssl.h"
19 #include "nse_debug.h"
20 #include "nse_lpeg.h"
21 #include "nse_libssh2.h"
22 #include "nse_zlib.h"
23 
24 #include <math.h>
25 
26 #define NSE_MAIN "NSE_MAIN" /* the main function */
27 
28 /* Script Scan phases */
29 #define NSE_PRE_SCAN  "NSE_PRE_SCAN"
30 #define NSE_SCAN      "NSE_SCAN"
31 #define NSE_POST_SCAN "NSE_POST_SCAN"
32 
33 /* These are indices into the registry, for data shared with nse_main.lua. The
34    definitions here must match those in nse_main.lua. */
35 #define NSE_YIELD "NSE_YIELD"
36 #define NSE_BASE "NSE_BASE"
37 #define NSE_WAITING_TO_RUNNING "NSE_WAITING_TO_RUNNING"
38 #define NSE_DESTRUCTOR "NSE_DESTRUCTOR"
39 #define NSE_SELECTED_BY_NAME "NSE_SELECTED_BY_NAME"
40 #define NSE_CURRENT_HOSTS "NSE_CURRENT_HOSTS"
41 
42 #define NSE_FORMAT_TABLE "NSE_FORMAT_TABLE"
43 #define NSE_FORMAT_XML "NSE_FORMAT_XML"
44 #define NSE_PARALLELISM "NSE_PARALLELISM"
45 
46 #ifndef MAXPATHLEN
47 #  define MAXPATHLEN 2048
48 #endif
49 
50 extern NmapOps o;
51 
52 /* global object to store Pre-Scan and Post-Scan script results */
53 static ScriptResults script_scan_results;
54 
timedOut(lua_State * L)55 static int timedOut (lua_State *L)
56 {
57   Target *target = nseU_gettarget(L, 1);
58   lua_pushboolean(L, target->timedOut(NULL));
59   return 1;
60 }
61 
startTimeOutClock(lua_State * L)62 static int startTimeOutClock (lua_State *L)
63 {
64   Target *target = nseU_gettarget(L, 1);
65   if (!target->timeOutClockRunning())
66     target->startTimeOutClock(NULL);
67   return 0;
68 }
69 
stopTimeOutClock(lua_State * L)70 static int stopTimeOutClock (lua_State *L)
71 {
72   Target *target = nseU_gettarget(L, 1);
73   if (target->timeOutClockRunning())
74     target->stopTimeOutClock(NULL);
75   return 0;
76 }
77 
next_port(lua_State * L)78 static int next_port (lua_State *L)
79 {
80   lua_settop(L, 2);
81   lua_pushvalue(L, lua_upvalueindex(1));
82   lua_pushvalue(L, 2);
83   if (lua_next(L, -2) == 0)
84     return 0;
85   else {
86     lua_pop(L, 1); /* pop boolean value */
87     return 1;
88   }
89 }
90 
ports(lua_State * L)91 static int ports (lua_State *L)
92 {
93   static const int states[] = {
94     PORT_OPEN,
95     PORT_OPENFILTERED,
96     PORT_UNFILTERED,
97     PORT_HIGHEST_STATE /* last one marks end */
98   };
99   Target *target = nseU_gettarget(L, 1);
100   PortList *plist = &(target->ports);
101   Port *current = NULL;
102   Port port;
103   lua_newtable(L);
104   for (int i = 0; states[i] != PORT_HIGHEST_STATE; i++)
105     while ((current = plist->nextPort(current, &port, TCPANDUDPANDSCTP,
106             states[i])) != NULL)
107     {
108       lua_createtable(L, 0, NSE_NUM_PORTINFO_FIELDS);
109       set_portinfo(L, target, current);
110       lua_pushboolean(L, 1);
111       lua_rawset(L, -3);
112     }
113   lua_pushcclosure(L, next_port, 1);
114   lua_pushnil(L);
115   lua_pushnil(L);
116   return 3;
117 }
118 
script_set_output(lua_State * L)119 static int script_set_output (lua_State *L)
120 {
121   ScriptResult sr;
122   sr.set_id(luaL_checkstring(L, 1));
123   sr.set_output_tab(L, 2);
124   if (!lua_isnil(L, 3)) {
125     lua_len(L, 3);
126     sr.set_output_str(luaL_checkstring(L, 3), luaL_checkinteger(L,-1));
127   }
128   script_scan_results.push_back(sr);
129   return 0;
130 }
131 
host_set_output(lua_State * L)132 static int host_set_output (lua_State *L)
133 {
134   ScriptResult sr;
135   Target *target = nseU_gettarget(L, 1);
136   sr.set_id(luaL_checkstring(L, 2));
137   sr.set_output_tab(L, 3);
138   if (!lua_isnil(L, 4)) {
139     lua_len(L, 4);
140     sr.set_output_str(luaL_checkstring(L, 4), luaL_checkinteger(L,-1));
141   }
142   target->scriptResults.push_back(sr);
143   return 0;
144 }
145 
port_set_output(lua_State * L)146 static int port_set_output (lua_State *L)
147 {
148   Port *p;
149   Port port;
150   ScriptResult sr;
151   Target *target = nseU_gettarget(L, 1);
152   p = nseU_getport(L, target, &port, 2);
153   sr.set_id(luaL_checkstring(L, 3));
154   sr.set_output_tab(L, 4);
155   if (!lua_isnil(L, 5)) {
156     lua_len(L, 5);
157     sr.set_output_str(luaL_checkstring(L, 5), luaL_checkinteger(L,-1));
158   }
159   target->ports.addScriptResult(p->portno, p->proto, sr);
160   target->ports.numscriptresults++;
161   return 0;
162 }
163 
key_was_pressed(lua_State * L)164 static int key_was_pressed (lua_State *L)
165 {
166   lua_pushboolean(L, keyWasPressed());
167   return 1;
168 }
169 
scp(lua_State * L)170 static int scp (lua_State *L)
171 {
172   static const char * const ops[] = {"printStats", "printStatsIfNecessary",
173     "mayBePrinted", "endTask", NULL};
174   ScanProgressMeter *progress =
175     (ScanProgressMeter *) lua_touserdata(L, lua_upvalueindex(1));
176   switch (luaL_checkoption(L, 1, NULL, ops))
177   {
178     case 0: /* printStats */
179       progress->printStats((double) luaL_checknumber(L, 2), NULL);
180       break;
181     case 1:
182       progress->printStatsIfNecessary((double) luaL_checknumber(L, 2), NULL);
183       break;
184     case 2: /*mayBePrinted */
185       lua_pushboolean(L, progress->mayBePrinted(NULL));
186       return 1;
187     case 3: /* endTask */
188       progress->endTask(NULL, NULL);
189       delete progress;
190       break;
191   }
192   return 0;
193 }
194 
scan_progress_meter(lua_State * L)195 static int scan_progress_meter (lua_State *L)
196 {
197   lua_pushlightuserdata(L, new ScanProgressMeter(luaL_checkstring(L, 1)));
198   lua_pushcclosure(L, scp, 1);
199   return 1;
200 }
201 
202 /* This is like nmap.log_write, but doesn't append "NSE:" to the beginning of
203    messages. It is only used internally by nse_main.lua and is not available to
204    scripts. */
l_log_write(lua_State * L)205 static int l_log_write(lua_State *L)
206 {
207   static const char *const ops[] = {"stdout", "stderr", NULL};
208   static const int logs[] = {LOG_STDOUT, LOG_STDERR};
209   int log = logs[luaL_checkoption(L, 1, NULL, ops)];
210   log_write(log, "%s", luaL_checkstring(L, 2));
211   return 0;
212 }
213 
l_xml_start_tag(lua_State * L)214 static int l_xml_start_tag(lua_State *L)
215 {
216   const char *name;
217 
218   name = luaL_checkstring(L, 1);
219   xml_open_start_tag(name);
220 
221   if (lua_isnoneornil(L, 2)) {
222     lua_newtable(L);
223     lua_replace(L, 2);
224   }
225 
226   for (lua_pushnil(L); lua_next(L, 2); lua_pop(L, 1))
227     xml_attribute(luaL_checkstring(L, -2), "%s", luaL_checkstring(L, -1));
228 
229   xml_close_start_tag();
230 
231   return 0;
232 }
233 
l_xml_end_tag(lua_State * L)234 static int l_xml_end_tag(lua_State *L)
235 {
236   xml_end_tag();
237 
238   return 0;
239 }
240 
l_xml_write_escaped(lua_State * L)241 static int l_xml_write_escaped(lua_State *L)
242 {
243   const char *text;
244 
245   text = luaL_checkstring(L, 1);
246   xml_write_escaped("%s", text);
247 
248   return 0;
249 }
250 
l_xml_newline(lua_State * L)251 static int l_xml_newline(lua_State *L)
252 {
253   xml_newline();
254 
255   return 0;
256 }
257 
l_protect_xml(lua_State * L)258 static int l_protect_xml(lua_State *L)
259 {
260   const char *text;
261   size_t len;
262   std::string output;
263 
264   text = luaL_checklstring(L, 1, &len);
265   output = protect_xml(std::string(text, len));
266   lua_pushlstring(L, output.c_str(), output.size());
267 
268   return 1;
269 }
270 
nse_fetch(lua_State * L,int (* fetch)(char *,size_t,const char *))271 static int nse_fetch (lua_State *L, int (*fetch)(char *, size_t, const char *))
272 {
273   char path[MAXPATHLEN];
274   const char *input = luaL_checkstring(L, 1);
275   switch (fetch(path, sizeof(path), input))
276   {
277     case 0: // no such path
278       lua_pushnil(L);
279       lua_pushfstring(L, "no path to file/directory: %s", lua_tostring(L, 1));
280       break;
281     case 1: // file returned
282       lua_pushliteral(L, "file");
283       lua_pushstring(L, path);
284       break;
285     case 2: // directory returned
286       if (input[strlen(input) - 1] == '/') {
287         lua_pushliteral(L, "directory");
288       }
289       else {
290         lua_pushliteral(L, "bare_directory");
291       }
292       lua_pushstring(L, path);
293       break;
294     default:
295       return luaL_error(L, "nse_fetch returned bad code");
296   }
297   return 2;
298 }
299 
filename_is_absolute(const char * file)300 static bool filename_is_absolute(const char *file) {
301   if (file[0] == '/')
302     return true;
303 #ifdef WIN32
304   if ((file[0] != '\0' && file[1] == ':') || file[0] == '\\')
305     return true;
306 #endif
307   return false;
308 }
309 
310 /* This is a modification of nmap_fetchfile that first looks for an
311  * absolute file name.
312  */
nse_fetchfile_absolute(char * path,size_t path_len,const char * file)313 static int nse_fetchfile_absolute(char *path, size_t path_len, const char *file) {
314   if (filename_is_absolute(file)) {
315     if (o.debugging > 1)
316       log_write(LOG_STDOUT, "%s: Trying absolute path %s\n", SCRIPT_ENGINE, file);
317     Strncpy(path, file, path_len);
318     return file_is_readable(file);
319   }
320 
321   return nmap_fetchfile(path, path_len, file);
322 }
323 
324 /* This is a modification of nmap_fetchfile specialized to look for files
325  * in the scripts subdirectory. If the path is absolute, it is always tried
326  * verbatim. Otherwise, the file is looked for under scripts/, and then finally
327  * in the current directory.
328  */
nse_fetchscript(char * path,size_t path_len,const char * file)329 static int nse_fetchscript(char *path, size_t path_len, const char *file) {
330   std::string scripts_path = std::string(SCRIPT_ENGINE_LUA_DIR) + std::string(file);
331   int type;
332 
333   if (filename_is_absolute(file)) {
334     if (o.debugging > 1)
335       log_write(LOG_STDOUT, "%s: Trying absolute path %s\n", SCRIPT_ENGINE, file);
336     Strncpy(path, file, path_len);
337     return file_is_readable(file);
338   }
339 
340   // lets look in <path>/scripts
341   type = nmap_fetchfile(path, path_len, scripts_path.c_str());
342 
343   if (type == 0) {
344     // current directory
345     Strncpy(path, file, path_len);
346     return file_is_readable(file);
347   }
348 
349   return type;
350 }
351 
fetchscript(lua_State * L)352 static int fetchscript (lua_State *L)
353 {
354   return nse_fetch(L, nse_fetchscript);
355 }
356 
fetchfile_absolute(lua_State * L)357 static int fetchfile_absolute (lua_State *L)
358 {
359   return nse_fetch(L, nse_fetchfile_absolute);
360 }
361 
open_cnse(lua_State * L)362 static void open_cnse (lua_State *L)
363 {
364   static const luaL_Reg nse[] = {
365     {"fetchfile_absolute", fetchfile_absolute},
366     {"fetchscript", fetchscript},
367     {"key_was_pressed", key_was_pressed},
368     {"scan_progress_meter", scan_progress_meter},
369     {"timedOut", timedOut},
370     {"startTimeOutClock", startTimeOutClock},
371     {"stopTimeOutClock", stopTimeOutClock},
372     {"ports", ports},
373     {"script_set_output", script_set_output},
374     {"host_set_output", host_set_output},
375     {"port_set_output", port_set_output},
376     {"log_write", l_log_write},
377     {"xml_start_tag", l_xml_start_tag},
378     {"xml_end_tag", l_xml_end_tag},
379     {"xml_write_escaped", l_xml_write_escaped},
380     {"xml_newline", l_xml_newline},
381     {"protect_xml", l_protect_xml},
382     {NULL, NULL}
383   };
384 
385   luaL_newlib(L, nse);
386   /* Add some other fields */
387   nseU_setbfield(L, -1, "default", o.script);
388   nseU_setbfield(L, -1, "scriptversion", o.scriptversion);
389   nseU_setbfield(L, -1, "scriptupdatedb", o.scriptupdatedb);
390   nseU_setbfield(L, -1, "scripthelp", o.scripthelp);
391   nseU_setsfield(L, -1, "script_dbpath", SCRIPT_ENGINE_DATABASE);
392   nseU_setsfield(L, -1, "scriptargs", o.scriptargs);
393   nseU_setsfield(L, -1, "scriptargsfile", o.scriptargsfile);
394   nseU_setsfield(L, -1, "NMAP_URL", NMAP_URL);
395   nseU_setnfield(L, -1, "script_timeout", o.scripttimeout);
396 
397 }
398 
399 /* Global persistent Lua state used by the engine. */
400 static lua_State *L_NSE = NULL;
401 
clear(void)402 void ScriptResult::clear (void)
403 {
404   if (o.debugging > 3)
405     log_write(LOG_STDOUT, "ScriptResult::clear %d id %s\n", output_ref, get_id());
406   luaL_unref(L_NSE, LUA_REGISTRYINDEX, output_ref);
407   output_ref = LUA_NOREF;
408 }
409 
set_output_tab(lua_State * L,int pos)410 void ScriptResult::set_output_tab (lua_State *L, int pos)
411 {
412   clear();
413   lua_pushvalue(L, pos);
414   output_ref = luaL_ref(L_NSE, LUA_REGISTRYINDEX);
415   if (o.debugging > 3)
416     log_write(LOG_STDOUT, "ScriptResult::set_output_tab %d id %s\n", output_ref, get_id());
417 }
418 
set_output_str(const char * out)419 void ScriptResult::set_output_str (const char *out)
420 {
421   output_str = std::string(out);
422 }
423 
set_output_str(const char * out,size_t len)424 void ScriptResult::set_output_str (const char *out, size_t len)
425 {
426   output_str = std::string(out, len);
427 }
428 
format_obj(lua_State * L,int pos)429 static std::string format_obj(lua_State *L, int pos)
430 {
431   std::string output;
432 
433   pos = lua_absindex(L, pos);
434 
435   /* Look up the FORMAT_TABLE function from nse_main.lua and call it. */
436   lua_getfield(L, LUA_REGISTRYINDEX, NSE_FORMAT_TABLE);
437   if (lua_isnil(L, -1)) {
438     log_write(LOG_STDOUT, "%s: Cannot find function _R[\"%s\"] that should be in nse_main.lua\n",
439       SCRIPT_ENGINE, NSE_FORMAT_TABLE);
440     lua_pop(L, 1);
441     return output;
442   }
443 
444   lua_pushvalue(L, pos);
445   if (lua_pcall(L, 1, 1, 0) != 0) {
446     if (o.debugging)
447       log_write(LOG_STDOUT, "%s: Error in FORMAT_TABLE: %s\n", SCRIPT_ENGINE, lua_tostring(L, -1));
448     lua_pop(L, 1);
449     return output;
450   }
451 
452   lua_len(L, -1);
453   output = std::string(lua_tostring(L, -2), luaL_checkinteger(L, -1));
454   lua_pop(L, 1);
455 
456   return output;
457 }
458 
get_output_str(void) const459 std::string ScriptResult::get_output_str (void) const
460 {
461   std::string output;
462 
463   /* Explicit string output? */
464   if (!output_str.empty())
465     return output_str;
466 
467   /* Auto-formatted table output? */
468   lua_rawgeti(L_NSE, LUA_REGISTRYINDEX, output_ref);
469   if (!lua_isnil(L_NSE, -1))
470     output = format_obj(L_NSE, -1);
471 
472   lua_pop(L_NSE, 1);
473 
474   return output;
475 }
476 
set_id(const char * ident)477 void ScriptResult::set_id (const char *ident)
478 {
479   id = std::string(ident);
480 }
481 
get_id(void) const482 const char *ScriptResult::get_id (void) const
483 {
484   return id.c_str();
485 }
486 
get_script_scan_results_obj(void)487 ScriptResults *get_script_scan_results_obj (void)
488 {
489   return &script_scan_results;
490 }
491 
format_xml(lua_State * L,int pos)492 static void format_xml(lua_State *L, int pos)
493 {
494   pos = lua_absindex(L, pos);
495 
496   /* Look up the FORMAT_XML function from nse_main.lua and call it. */
497   lua_getfield(L, LUA_REGISTRYINDEX, NSE_FORMAT_XML);
498   if (lua_isnil(L, -1)) {
499     log_write(LOG_STDOUT, "%s: Cannot find function _R[\"%s\"] that should be in nse_main.lua\n",
500       SCRIPT_ENGINE, NSE_FORMAT_XML);
501     lua_pop(L, 1);
502     return;
503   }
504 
505   lua_pushvalue(L, pos);
506   if (lua_pcall(L, 1, 1, 0) != 0) {
507     if (o.debugging)
508       log_write(LOG_STDOUT, "%s: Error in FORMAT_XML: %s\n", SCRIPT_ENGINE, lua_tostring(L, -1));
509     lua_pop(L, 1);
510     return;
511   }
512 }
513 
write_xml() const514 void ScriptResult::write_xml() const
515 {
516   std::string output_str;
517 
518   xml_open_start_tag("script");
519   xml_attribute("id", "%s", get_id());
520 
521   output_str = get_output_str();
522   if (!output_str.empty())
523     xml_attribute("output", "%s", protect_xml(output_str).c_str());
524 
525   /* Any table output? */
526   lua_rawgeti(L_NSE, LUA_REGISTRYINDEX, output_ref);
527   if (!lua_isnil(L_NSE, -1)) {
528     xml_close_start_tag();
529     format_xml(L_NSE, -1);
530     xml_end_tag();
531   } else {
532     xml_close_empty_tag();
533   }
534 
535   lua_pop(L_NSE, 1);
536 }
537 
538 /* int panic (lua_State *L)
539  *
540  * Panic function set via lua_atpanic().
541  */
panic(lua_State * L)542 static int panic (lua_State *L)
543 {
544   const char *err = lua_tostring(L, 1);
545   fatal("Unprotected error in Lua:\n%s\n", err);
546   return 0;
547 }
548 
set_nmap_libraries(lua_State * L)549 static void set_nmap_libraries (lua_State *L)
550 {
551   static const luaL_Reg libs[] = {
552     {NSE_PCRELIBNAME, luaopen_pcrelib},
553     {NSE_NMAPLIBNAME, luaopen_nmap},
554     {LFSLIBNAME, luaopen_lfs},
555     {LPEGLIBNAME, luaopen_lpeg},
556 #ifdef HAVE_LIBSSH2
557     {LIBSSH2LIBNAME, luaopen_libssh2},
558 #endif
559 #ifdef HAVE_OPENSSL
560     {OPENSSLLIBNAME, luaopen_openssl},
561 #endif
562 #ifdef HAVE_LIBZ
563     {NSE_ZLIBNAME, luaopen_zlib},
564 #endif
565     {NULL, NULL}
566   };
567 
568   for (int i = 0; libs[i].name; i++) {
569     luaL_requiref(L, libs[i].name, libs[i].func, 1);
570     lua_pop(L, 1);
571   }
572 }
573 
init_main(lua_State * L)574 static int init_main (lua_State *L)
575 {
576   char path[MAXPATHLEN];
577   std::vector<std::string> *rules = (std::vector<std::string> *)
578       lua_touserdata(L, 1);
579 
580   /* Load some basic libraries */
581   luaL_openlibs(L);
582   set_nmap_libraries(L);
583 
584   lua_newtable(L);
585   lua_setfield(L, LUA_REGISTRYINDEX, NSE_CURRENT_HOSTS);
586 
587   if (nmap_fetchfile(path, sizeof(path), "nse_main.lua") != 1)
588     luaL_error(L, "could not locate nse_main.lua");
589   if (luaL_loadfile(L, path) != 0)
590     luaL_error(L, "could not load nse_main.lua: %s", lua_tostring(L, -1));
591 
592   /* The first argument to the NSE Main Lua code is the private nse
593    * library table which exposes certain necessary C functions to
594    * the Lua engine.
595    */
596   open_cnse(L); /* first argument */
597 
598   /* The second argument is the script rules, including the
599    * files/directories/categories passed as the userdata to this function.
600    */
601   lua_createtable(L, rules->size(), 0); /* second argument */
602   for (std::vector<std::string>::iterator si = rules->begin(); si != rules->end(); si++)
603     nseU_appendfstr(L, -1, "%s", si->c_str());
604 
605   lua_call(L, 2, 1); /* returns the NSE main function */
606 
607   lua_setfield(L, LUA_REGISTRYINDEX, NSE_MAIN);
608 
609   lua_pushinteger(L, o.min_parallelism);
610   lua_setfield(L, LUA_REGISTRYINDEX, NSE_PARALLELISM);
611 
612   return 0;
613 }
614 
run_main(lua_State * L)615 static int run_main (lua_State *L)
616 {
617   std::vector<Target *> *targets = (std::vector<Target*> *)
618       lua_touserdata(L, 1);
619 
620   /* New host group */
621   lua_newtable(L);
622   lua_setfield(L, LUA_REGISTRYINDEX, NSE_CURRENT_HOSTS);
623 
624   lua_getfield(L, LUA_REGISTRYINDEX, NSE_MAIN);
625   assert(lua_isfunction(L, -1));
626 
627   /* The first argument to the NSE main function is the list of targets.  This
628    * has all the target names, 1-N, in a list.
629    */
630   lua_createtable(L, targets->size(), 0);
631   int targets_table = lua_gettop(L);
632   lua_getfield(L, LUA_REGISTRYINDEX, NSE_CURRENT_HOSTS);
633   int current_hosts = lua_gettop(L);
634   for (std::vector<Target *>::iterator ti = targets->begin(); ti != targets->end(); ti++)
635   {
636     Target *target = (Target *) *ti;
637     if (target->timedOut(NULL)) {
638       continue;
639     }
640     const char *TargetName = target->TargetName();
641     const char *targetipstr = target->targetipstr();
642     lua_newtable(L);
643     set_hostinfo(L, target);
644     lua_rawseti(L, targets_table, lua_rawlen(L, targets_table) + 1);
645     /* Index this Target in NSE_CURRENT_HOSTS under targetname and IP so we can
646      * retrieve it later */
647     if (TargetName != NULL && strcmp(TargetName, "") != 0) {
648       lua_pushstring(L, TargetName);
649       lua_pushlightuserdata(L, target);
650       lua_rawset(L, current_hosts); /* add to NSE_CURRENT_HOSTS */
651     }
652     lua_pushstring(L, targetipstr);
653     lua_pushlightuserdata(L, target);
654     lua_rawset(L, current_hosts); /* add to NSE_CURRENT_HOSTS */
655   }
656   lua_settop(L, targets_table);
657 
658   /* Push script scan phase type. Second argument to NSE main function */
659   switch (o.current_scantype)
660   {
661     case SCRIPT_PRE_SCAN:
662       lua_pushliteral(L, NSE_PRE_SCAN);
663       break;
664     case SCRIPT_SCAN:
665       lua_pushliteral(L, NSE_SCAN);
666       break;
667     case SCRIPT_POST_SCAN:
668       lua_pushliteral(L, NSE_POST_SCAN);
669       break;
670     default:
671       fatal("%s: failed to set the script scan phase.\n", SCRIPT_ENGINE);
672   }
673 
674   lua_call(L, 2, 0);
675 
676   return 0;
677 }
678 
679 /* int nse_yield (lua_State *L, int ctx, lua_CFunction k)  [-?, +?, e]
680  *
681  * This function will yield the running thread back to NSE, even across script
682  * auxiliary coroutines. All NSE initiated yields must use this function. The
683  * correct and only way to call is as a tail call:
684  *   return nse_yield(L, 0, NULL);
685  */
nse_yield(lua_State * L,lua_KContext ctx,lua_KFunction k)686 int nse_yield (lua_State *L, lua_KContext ctx, lua_KFunction k)
687 {
688   lua_getfield(L, LUA_REGISTRYINDEX, NSE_YIELD);
689   lua_pushthread(L);
690   lua_call(L, 1, 1); /* returns NSE_YIELD_VALUE */
691   return lua_yieldk(L, 1, ctx, k); /* yield with NSE_YIELD_VALUE */
692 }
693 
694 /* void nse_restore (lua_State *L, int number)             [-, -, e]
695  *
696  * Restore the thread 'L' back into the running NSE queue. 'number' is the
697  * number of values on the stack to be passed when the thread is resumed. This
698  * function may cause a panic due to extraordinary and unavoidable
699  * circumstances.
700  */
nse_restore(lua_State * L,int number)701 void nse_restore (lua_State *L, int number)
702 {
703   luaL_checkstack(L, 5, "nse_restore: stack overflow");
704   lua_pushthread(L);
705   lua_getfield(L, LUA_REGISTRYINDEX, NSE_WAITING_TO_RUNNING);
706   lua_insert(L, -(number+2)); /* move WAITING_TO_RUNNING down below the args */
707   lua_insert(L, -(number+1)); /* move thread above WAITING_TO_RUNNING */
708   /* Call WAITING_TO_RUNNING (defined in nse_main.lua) on the thread and any
709      other arguments. */
710   if (lua_pcall(L, number+1, 0, 0) != 0)
711     fatal("%s: WAITING_TO_RUNNING error!\n%s", __func__, lua_tostring(L, -1));
712 }
713 
714 /* void nse_destructor (lua_State *L, char what)           [-(1|2), +0, e]
715  *
716  * This function adds (what = 'a') or removes (what = 'r') a destructor from
717  * the Thread owning the running Lua thread (L). A destructor is called when
718  * the thread finishes for any reason (including error). A unique key is used
719  * to associate with the destructor so it is removable later.
720  *
721  * what == 'r', destructor key on stack
722  * what == 'a', destructor key and destructor function on stack
723  */
nse_destructor(lua_State * L,char what)724 void nse_destructor (lua_State *L, char what)
725 {
726   assert(what == 'a' || what == 'r');
727   lua_getfield(L, LUA_REGISTRYINDEX, NSE_DESTRUCTOR);
728   lua_pushstring(L, what == 'a' ? "add" : "remove");
729   lua_pushthread(L);
730   if (what == 'a')
731   {
732     lua_pushvalue(L, -5); /* destructor key */
733     lua_pushvalue(L, -5); /* destructor */
734   }
735   else
736   {
737     lua_pushvalue(L, -4); /* destructor key */
738     lua_pushnil(L); /* no destructor, we are removing */
739   }
740   if (lua_pcall(L, 4, 0, 0) != 0)
741     fatal("%s: NSE_DESTRUCTOR error!\n%s", __func__, lua_tostring(L, -1));
742   lua_pop(L, what == 'a' ? 2 : 1);
743 }
744 
745 /* void nse_base (lua_State *L)                             [-0, +1, e]
746  *
747  * Returns the base Lua thread (coroutine) for the running thread. The base
748  * thread is resumed by NSE (runs the action function). Other coroutines being
749  * used by the base thread may be in a chain of resumes, we use the base thread
750  * as the "holder" of resources (for the Nsock binding in particular).
751  */
nse_base(lua_State * L)752 void nse_base (lua_State *L)
753 {
754   lua_getfield(L, LUA_REGISTRYINDEX, NSE_BASE);
755   lua_call(L, 0, 1); /* returns base thread */
756 }
757 
758 /* void nse_selectedbyname (lua_State *L)                  [-0, +1, e]
759  *
760  * Returns a boolean signaling whether the running script was selected by name
761  * on the command line (--script).
762  */
nse_selectedbyname(lua_State * L)763 void nse_selectedbyname (lua_State *L)
764 {
765   lua_getfield(L, LUA_REGISTRYINDEX, NSE_SELECTED_BY_NAME);
766   if (lua_isnil(L, -1)) {
767     lua_pushboolean(L, 0);
768     lua_replace(L, -2);
769   } else {
770     lua_call(L, 0, 1);
771   }
772 }
773 
774 /* void nse_gettarget (lua_State *L)                  [-0, +1, -]
775  *
776  * Given the index to a string on the stack identifying the host, an ip or a
777  * targetname (host name specified on the command line, see Target.h), returns
778  * a lightuserdatum that points to the host's Target (see Target.h). If the
779  * host cannot be found, nil is returned.
780  */
nse_gettarget(lua_State * L,int index)781 void nse_gettarget (lua_State *L, int index)
782 {
783   lua_pushvalue(L, index);
784   lua_getfield(L, LUA_REGISTRYINDEX, NSE_CURRENT_HOSTS);
785   lua_insert(L, -2);
786   lua_rawget(L, -2);
787   lua_replace(L, -2);
788 }
789 
open_nse(void)790 void open_nse (void)
791 {
792   if (L_NSE == NULL)
793   {
794     /*
795      Set the random seed value on behalf of scripts.  Since Lua uses the
796      C rand and srand functions, which have a static seed for the entire
797      program, we don't want scripts doing this themselves.
798      */
799     srand(get_random_uint());
800 
801     const lua_Number *version = lua_version(NULL);
802     double major = (*version) / 100.0;
803     double minor = fmod(*version, 10.0);
804     if (o.debugging >= 1)
805       log_write(LOG_STDOUT, "%s: Using Lua %.0f.%.0f.\n", SCRIPT_ENGINE, major, minor);
806     if (*version < 503)
807       fatal("%s: This version of NSE only works with Lua 5.3 or greater.", SCRIPT_ENGINE);
808     if ((L_NSE = luaL_newstate()) == NULL)
809       fatal("%s: failed to open a Lua state!", SCRIPT_ENGINE);
810     lua_atpanic(L_NSE, panic);
811     lua_settop(L_NSE, 0);
812 
813     lua_pushcfunction(L_NSE, nseU_traceback);
814     lua_pushcfunction(L_NSE, init_main);
815     lua_pushlightuserdata(L_NSE, &o.chosenScripts);
816     if (lua_pcall(L_NSE, 1, 0, 1))
817       fatal("%s: failed to initialize the script engine:\n%s\n", SCRIPT_ENGINE, lua_tostring(L_NSE, -1));
818     lua_settop(L_NSE, 0);
819   }
820 }
821 
script_scan(std::vector<Target * > & targets,stype scantype)822 void script_scan (std::vector<Target *> &targets, stype scantype)
823 {
824   o.current_scantype = scantype;
825 
826   assert(L_NSE != NULL);
827   lua_settop(L_NSE, 0); /* clear the stack */
828 
829   lua_pushcfunction(L_NSE, nseU_traceback);
830   lua_pushcfunction(L_NSE, run_main);
831   lua_pushlightuserdata(L_NSE, &targets);
832   if (lua_pcall(L_NSE, 1, 0, 1))
833     error("%s: Script Engine Scan Aborted.\nAn error was thrown by the "
834           "engine: %s", SCRIPT_ENGINE, lua_tostring(L_NSE, -1));
835   lua_settop(L_NSE, 0);
836 }
837 
close_nse(void)838 void close_nse (void)
839 {
840   if (L_NSE != NULL)
841   {
842     lua_close(L_NSE);
843     L_NSE = NULL;
844   }
845 }
846