What parts make up an NSE script file, and how do prerule, hostrule, portrule and postrule decide when its action runs?
answer
- a Lua file with descriptive fields
- a rule is a true-or-false function
- four rules for four phases
- the return type shapes the output
- categories are indexed in script.db
basics
~20 sAn NSE script is a Lua file with descriptive fields such as description and categories, at least one rule function and an action. The action runs only when a rule returns true: prerule before scanning, hostrule per host, portrule per port, postrule at the end.
solid answer
~40 sThe file sets descriptive fields (`description`, `categories`, and optionally `author`, `license` and `dependencies`), defines one or more rule functions, and defines `action`. The rules are `prerule()`, `hostrule(host)`, `portrule(host, port)` and `postrule()`; the action runs only if its rule returns true. A `portrule` is evaluated for ports in the `open`, `open|filtered` or `unfiltered` states and usually tests the port number or detected service name, often through the `shortport` library. The action returns a table, a string or `nil`; a table becomes structured output in normal and XML formats, and `nil` prints nothing. Because scripts are not sandboxed, a script is read before it is allowed on a production scan.
code
lua · 23 lineslocal shortport = require "shortport"
local stdnse = require "stdnse"
description = [[
Inventory helper: reports the port, protocol and service name Nmap
already detected on likely HTTP ports. Sends no probes of its own.
]]
author = "Example Security Team"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"safe", "discovery"}
-- Rule: run for TCP ports that look like HTTP by port number or service name
portrule = shortport.http
-- Action: return a table, which Nmap formats for -oN and -oX output
action = function(host, port)
local out = stdnse.output_table()
out.port = port.number
out.protocol = port.protocol
out.service = port.service
return out
endgo deeper
Recall that an NSE script is a Lua file with a description, categories, a rule and an action, and that the rule decides whether the action runs.
Explain the four rules and their arguments, what a portrule is evaluated for, what the action may return, and that script.db indexes the categories.
Describe how you review a script before approval: compare the label with the action, check the libraries it uses, narrow its rule and rehearse on a lab target.
Define a governance path for custom scripts: who reviews them, where they are stored and indexed, and how a changed script is re-approved.
## Anatomy of the file An NSE script is a Lua file. Its top level assigns a handful of descriptive fields (names must be lowercase), defines the rule or rules that say when it runs, and defines the `action` function that does the work. - `description`: what the script tests for and what the user should know. The first paragraph should be a short synopsis fit to show on its own, and `--script-help` prints the description. - `categories`: an array-style table, such as `{"safe", "discovery"}`, case-insensitive and in any order. The author writes it; `scripts/script.db` indexes it for selection. - `author` and `license`: optional and not used by NSE, which gives credit and licence terms. - `dependencies`: optional array of script names that should run earlier **if they are also selected**. It never causes a script to be selected; it only orders them, and NSE reports the resulting groups as runlevels. - Rule functions and `action`. ## The four rules and the phases A rule is a Lua function that returns true or false. Nmap runs the action only when the rule is true. A script must contain at least one. | Rule | Arguments | When it is evaluated | Typical use | |---|---|---|---| | `prerule()` | none | once, before any scan phase | broadcast queries, target generation | | `hostrule(host)` | host table | after each batch of hosts is scanned | host-wide checks | | `portrule(host, port)` | host and port tables | for each port in `open`, `open\|filtered` or `unfiltered` state | service checks | | `postrule()` | none | once, after all hosts | summaries, cross-host checks | A script may have several rules and so run in more than one phase. The environment variable `SCRIPT_TYPE` tells it which rule activated it. The book's example is `ssh-hostkey`, which has a service rule that reads each key and a `postrule` that reports duplicate keys across all hosts. Service scripts, the ones with a `portrule`, are the most common type. A `+` before the name in `--script` forces a script to run regardless of its rule. The `shortport` library supplies ready-made port rules. `shortport.http`, for instance, matches the common HTTP ports and service names. ## The action and its output `action` takes the same arguments as the rule that fired. Its return value decides what is printed: 1. A **table** of name-value pairs is formatted automatically into structured output for normal (`-oN`) and XML (`-oX`) results. 2. A **string** is shown directly in normal output and stored as an XML attribute. 3. **`nil`** produces no output at all. Scripts that have nothing important to report are expected to return nothing, which is why a quiet script and a script that did not run look the same in the report. ## Reading a script before it runs Scripts are not run in a sandbox and can damage or expose what they touch, so an unreviewed third-party script does not belong on a production scan. A review takes a few minutes: 1. Compare `description` and `categories` with what `action` actually does. The label is the author's claim and nothing more. 2. List the libraries it requires and what network calls they make; a script that contacts a third party should carry `external`. 3. Read the rule. A narrow `portrule` keeps the probes on the intended ports. 4. Check whether it can add targets or follow links off the host. 5. Run it against a lab target and read the target's own logs. 6. After adding a script or changing its categories, run `--script-updatedb` so the index matches. ## Script types in the book's terms The Nmap book names four types by the phase they run in: **prerule** scripts run before any scan phase and know nothing about the targets, **host** scripts run once per host that matches `hostrule`, **service** scripts run per port that matches `portrule`, and **postrule** scripts run after all targets. For choosing between the two ends, the book's standard is that a script doing host discovery or any other network operation should use `prerule`, while `postrule` is reserved for reporting data and statistics gathered during the scan. Host scripts do not receive a port table, although they can still ask Nmap for port states through library calls. ## Where this stops This is the structure of a script and how to review one. Writing scripts that break into or disable systems is outside this question and outside what an assessor needs to know to approve or reject a script.
- What does a script's dependencies field do?It lists scripts that should run before this one, if they are also selected. It does not select them; selection still comes from --script. NSE derives an ordering from it and shows the groups as numbered runlevels in its output. Up through Nmap 5.10BETA2 the field did not exist and authors set a runlevel by hand.
- How can one script run in more than one phase?It defines several rule functions. Each rule that returns true runs the action once in its phase, and the `SCRIPT_TYPE` variable tells the action which rule fired. `ssh-hostkey` uses a portrule to read each server's key and a postrule to report duplicates across all scanned hosts.
- A categories field is enforced by Nmap and cannot misdescribe the action
- A portrule script also runs against closed and filtered ports
- Listing a script in dependencies makes Nmap run it
- An action must return a string; tables are not allowed
- NSE scripts are sandboxed, so reading one before use is unnecessary