Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 36 ยท Nmap Scripting Engine

Writing NSE Scripts in Lua

Learn to write a simple, safe NSE script: metadata, rules, the action function, libraries, return values and testing, with a runnable JavaScript model of the flow.

Sooner or later you will want a check that no ready-made script provides: "does our internal service answer /health with the right version?" or "is this custom banner present?" NSE makes this easy. A useful script can be fifteen lines of Lua. In this lesson you write a small, read-only check script, learn the Lua you need, and use a JavaScript model to practise the logic where Lua cannot run.

Only write scripts that inspect systems you are allowed to test. Keep them to harmless requests, and give them the correct category.

Lua and Nmap cannot run on this site. The Lua code is shown read-only with careful comments. The JavaScript blocks run on Piston and model the same steps with simple stand-in objects.

The minimum Lua you need

Lua is small. For NSE scripts you mostly need these constructs:

LUA
local name = "value"            -- local variable
local list = {"a", "b", "c"}    -- table used as a list (index starts at 1!)
local map = {port = 80, state = "open"}  -- table used as a dictionary

if map.port == 80 and map.state == "open" then
  -- code
elseif map.port == 443 then
  -- code
else
  -- code
end

for i, item in ipairs(list) do   -- loop over a list
  print(i, item)
end

local function double(x)         -- function
  return x * 2
end

local text = "a" .. "b"          -- .. joins strings
local found = string.find("hello world", "world", 1, true)  -- plain search

Three Lua habits trip up newcomers: lists start at 1, not 0; inequality is ~=, not !=; and only nil and false count as false (the number 0 is true).

A complete script: check a health endpoint

This script runs on web ports, requests /health and reports the status and the body if it looks like JSON. It is entirely read-only.

LUA
local http = require "http"
local shortport = require "shortport"
local stdnse = require "stdnse"

description = [[
Requests a health endpoint (default /health) and reports its status code.
Read-only: sends one GET request.
]]

---
-- @usage
-- nmap -p 8080 --script health-check --script-args health-check.path=/status <target>
--
-- @output
-- PORT     STATE SERVICE
-- 8080/tcp open  http-proxy
-- | health-check:
-- |   status: 200
-- |_  body: {"ok":true}
--
-- @args health-check.path  Path to request. Default: /health

author = "Lab author"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"safe", "discovery"}

portrule = shortport.http

action = function(host, port)
  local path = stdnse.get_script_args("health-check.path") or "/health"
  local response = http.get(host, port, path)

  if not response then
    return nil                     -- no output when nothing answered
  end

  local output = stdnse.output_table()
  output.status = response.status
  if response.body and #response.body < 200 then
    output.body = response.body
  end
  return output
end

Walk through it:

  1. require loads libraries. http makes requests, shortport offers ready-made port rules, stdnse helps with arguments and output.
  2. The comment block starting with --- documents usage, sample output and arguments. nmap --script-help prints it, so write it well.
  3. categories is honest: one GET request is safe and discovery.
  4. portrule = shortport.http limits the script to HTTP ports.
  5. action reads an optional argument, requests the path, and returns a table. NSE formats a table as indented lines. Returning nil prints nothing for that port.

Run it by naming the file (read-only example):

Terminal
nmap -p 8080 --script ./health-check.nse 192.0.2.10
nmap --script-updatedb      # if you copied it into the scripts folder, to register it

Modelling the script flow

Since Lua is not available, practise the logic in JavaScript. The model has fake hosts and a fake http.get. It follows the same steps: rule, argument with default, request, build output, return nothing if no answer.

Node.js Model of the health-check script

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the three kinds of result: a table of values, no output (nothing to report) and a skipped port. Real NSE behaves in exactly this way.

Return values and output tables

An action may return:

  • a string: printed as one line;
  • a table made with stdnse.output_table(): printed as an indented list and also written into XML output as structured data, which makes it easy to parse later;
  • nil: nothing is printed;
  • two values, a table and a string, where the string is the short human-readable text.

Prefer tables: automation (see Parsing XML Output) can read them.

Testing and debugging

  • nmap -d --script ./health-check.nse ... shows script errors and debug lines. -d2 and --script-trace show more.
  • Test on a loopback or lab service you own first, for example a small local web server.
  • Handle failures: a nil response, a timeout, an unexpected format. Wrap risky steps with pcall or check values before use.
  • Use stdnse.debug1("message") for debug lines instead of print.
  • Keep scripts quick; Nmap kills slow ones (--script-timeout).

A second stand-in: check version rules

Many custom scripts compare a found version with a minimum. The JavaScript below shows careful version comparison, which in Lua would use stdnse and string splitting.

Node.js Model: is the version at least the minimum?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Sharing and good manners

If you publish a script, state its category honestly, document its arguments, avoid dangerous defaults and never ship scripts that attack others. Put team scripts in a version-controlled folder and run nmap --script ./folder.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What index does the first element of a Lua list have?

    Lua tables used as lists start at index 1.
  2. 2. What does an action function that returns nil produce?

    Returning nil tells NSE there is nothing to report, so no script lines are shown for that host or port.
  3. 3. Why prefer stdnse.output_table() over a plain string?

    Output tables appear as indented text and as structured elements in XML, which is ideal for automation.
  4. 4. Which Lua operator means 'not equal'?

    Lua uses ~= for inequality. The operator != is a syntax error.
  5. 5. Which category fits a script that sends one GET request and only reads the reply?

    A read-only, single-request check does not harm services, so it belongs in safe (and often discovery).

Summary

  • A script has metadata, a rule and an action; libraries (http, shortport, stdnse) do the heavy work.
  • Learn the small amount of Lua needed: 1-based lists, ~=, .. and tables.
  • Return structured tables, return nil for no output, document usage and arguments.
  • Label categories honestly, keep requests harmless, test on systems you own.

Next: Timing and Performance Tuning