How to Get Started Writing Your Own NSE Scripts for Nmap « Null Byte :: WonderHowTo

The road to becoming a skilled white hat is paved with many milestones, one of those being learning how to perform a simpleNmapscan. A little further down that road lies more advanced scanning, along with utilizing a powerful feature of Nmap called theNmap Scripting Engine. Even further down the road is learning how to modify and write scripts for NSE, which is what we'll be doing today.Overview of NSEThe Nmap Scripting Engine is one of the most robust, yet underutilized features of Nmap, containing a hugevariety of scriptsto automate tasks beyondport scanningand basic network discovery. Some of these tasks include scripts for vulnerability detection, advanced version detection, malware detection, fuzzing, and even active exploitation.Don't Miss:Top 5 Intrusive Nmap Scripts Hackers & Pentesters Should KnowNmap can take thecommand lineargument-sCto execute a default set of scripts, but doing so can be noisy as some of these scripts are considered pretty intrusive. Users also have the option to specify which script or scripts to run by using the--scriptargument; Individual scripts can be passed as well as whole categories of scripts.One of the greatest aspects of NSE, though, is the ability for users to tweak and modify scripts to better fit their needs, as well as the power to write custom scripts from scratch. All scripts used by NSE are written in an embedded scripting language calledLua.Introduction to LuaLua is an efficient, dynamically typedscripting languagethat is both powerful and lightweight. It is very flexible in that it supports procedural, functional, and object-oriented programming. Lua is meant to be portable, so it can easily be embedded into other applications using a C API, and it can run on nearly all platforms, including Unix, Windows, mobile devices, and embedded microprocessors such as ARM. Lua has been used in many popular applications, including Adobe Photoshop Lightroom and Garry's Mod.Let's go over some basics in order to get a feel for the language. Comments begin with a double-hyphen and run to the end of the line:-- this is a comment in LuaIn the tradition of learning a new programming language, the classic "Hello world!" program can be written like so:print("Hello world!")Global variables do not need to be declared, and unlike some languages, there is no error for accessing a variable that isn't initialized — instead, the valuenilwill be returned. Local variables, on the other hand, are assigned using thelocalkeyword:print(a) -- returns nil
local b = 5
print(b) -- returns 5Control flow in Lua consists ofifandif...elsestatements for conditionals, andwhile,repeat, andforloops for iteration. Some examples follow:if condition then
	statement
else
	statement
endwhile condition do
	statement
endrepeat
	statement
until conditionfor i = x, y, z do
	statement
endFunctions in Lua operate similarly to other languages, requiring a function name, return statement, and end statement. The following is an example of a simple function that returns the bigger of two numbers:function max(a, b)
	if (a > b) then
		bigger = a
	else
		bigger  = b
	end
	return bigger
endA complete tutorial on Lua is beyond the scope of this article, but more detailed information can be foundon Lua's site. Now that we have the basics of the language down, we can begin to interact with some NSE scripts.Related Book: "Network Scanning Cookbook: Practical Network Security using Nmap and Nessus 7" by Sairam JettyWriting a Basic ScriptNSE scriptsare made up of three main sections: head, rule, and action.The head section contains mostly meta-data, such as the author, description, category, and other relevant information about the script.The rule section is where conditions are defined that allow the script to execute; This section must contain at least one of the following functions that will determine when the script will run: prerule, hostrule, portrule, or postrule.The action section is where the main functionality of the script takes place. All of the logic and instructions will go in this section.For demonstration purposes, we will compose a simple script that determines if a given port is open and outputs a relevant message. Let's begin with the head. For now, we can put in a short description and leave it at that:-- HEAD --

description = [[
This is a simple script example that determines if a port is open.
]]

author = "Null Byte"Next, we can move on to the rule section. Let's define a portrule to determine whether any given port is open or not:-- RULE --

portrule = function(host, port)
	return port.protocol == "tcp"
		and port.state == "open"
endNow, we can define the actual script logic in the action section. Let's have the script display a message for any give port that is open:-- ACTION --

action = function(host, port)
	return "This port is open!"
endThe entire script should now look something like this:-- HEAD --

description = [[
This is a simple script example that determines if a port is open.
]]

author = "Null Byte"

-- RULE --

portrule = function(host, port)
	return port.protocol == "tcp"
		and port.state == "open"
end

-- ACTION --

action = function(host, port)
	return "This port is open!"
endFrom here, we should be able to run our script to see if it works. Save the file asexample-script.nseand copy it to the/usr/share/nmap/scriptsdirectory. We can keep it simple and just uselocalhostto test our script against. We also need to pass in a port, so runservice apache2 restartin the terminal to ensure theweb serveris running, and we can now use port80. Finally, let's run the script:nmap --script example-script localhost -p 80

Starting Nmap 7.70 ( https://nmap.org ) at 2018-09-12 13:08 CDT
Nmap scan report for localhost (127.0.0.1)
Host is up (0.000087s latency).
Other addresses for localhost (not scanned): ::1

PORT   STATE SERVICE
80/tcp open  http
|_example-script: This port is open!

Nmap done: 1 IP address (1 host up) scanned in 0.30 secondsWe can see that port 80 is open on localhost and the script displays our message. This is merely a rudimentary example of what NSE scripts can actually do, but with the basics down, it makes it easier to modify existing scripts for custom needs or write even more robust scripts from scratch.More NSE ScriptingThe Nmap Scripting Engine is a powerful feature of Nmap used to expand the functionality of the core tool. In this guide, we learned a bit about Lua, the programming language that drives NSE, as well as how to structure and write a simple script for our own use. We have barely scratched the surface of what Nmap scripts can truly do, so I encourage youto dive in and get your hands dirtyso that you may be able to take full advantage of what NSE has to offer.Don't Miss:How to Easily Detect CVEs with Nmap ScriptsFollow Null Byte onTwitter,Flipboard, andYouTubeSign up forNull Byte's weekly newsletterFollow WonderHowTo onFacebook,Twitter,Pinterest, andFlipboardWant to start making money as a white hat hacker?Jump-start your hacking career with our2020 Premium Ethical Hacking Certification Training Bundlefrom the newNull Byte Shopand get over 60 hours of training from cybersecurity professionals.Buy Now (90% off) >Other worthwhile deals to check out:97% off The Ultimate 2021 White Hat Hacker Certification Bundle99% off The 2021 All-in-One Data Scientist Mega Bundle98% off The 2021 Premium Learn To Code Certification Bundle62% off MindMaster Mind Mapping Software: Perpetual LicenseCover image byComfreak/PixabayRelatedHack Like a Pro:Using the Nmap Scripting Engine (NSE) for ReconnaissanceHow To:Easily Detect CVEs with Nmap ScriptsAdvanced Nmap:Top 5 Intrusive Nmap Scripts Hackers & Pentesters Should KnowHow To:Use NMAP 7 to Discover Vulnerabilities, Launch DoS Attacks and More!How To:Enumerate NetBIOS Shares with NBTScan & Nmap Scripting EngineHack Like a Pro:Scripting for the Aspiring Hacker, Part 1 (BASH Basics)How To:Tactical Nmap for Beginner Network ReconnaissanceHack Like a Pro:Scripting for the Aspiring Hacker, Part 2 (Conditional Statements)Hack Like a Pro:How to Scan the Internet for Heartbleed VulnerabilitiesHack Like a Pro:Python Scripting for the Aspiring Hacker, Part 1How To:Perform Network-Based Attacks with an SBC ImplantNews:Banks Around the World Hit with Repeated DDoS Attacks!How To:Identify Web Application Firewalls with Wafw00f & NmapHow To:Hack UnrealIRCd Using Python Socket ProgrammingHow To:Automate Brute-Force Attacks for Nmap ScansDon't Be a Script-Kiddie part2:Building an Auto-Exploiter Bash ScriptDissecting Nmap:Part 1How To:Break into the Lucrative World of Ethical Hacking with This Reasonably Priced Course BundleHow To:Find & Exploit SUID Binaries with SUID3NUMDon't Be a Script-Kiddie part1:Introduction to Shell ScriptHack Like a Pro:Metasploit for the Aspiring Hacker, Part 14 (Creating Resource Script Files)Hack Like a Pro:Perl Scripting for the Aspiring Hacker, Part 2 (Building a Port Scanner)Hack Like a Pro:How to Scan the Globe for Vulnerable Ports & ServicesHacking macOS:How to Spread Trojans & Pivot to Other Mac ComputersHow To:Spider Web Pages with Nmap for SQLi VulnerabilitiesHow To:Use the Nmap security toolHow To:Script Writing Basics How to Structure a Film Script lHacking Reconnaissance:Finding Vulnerabilities in Your Target Using NmapHow To:How Hackers Use Your IP Address to Hack Your Computer & How to Stop ItWeekend Homework:How to Become a Null Byte ContributorNews:Null Byte Is Calling for Contributors!News:The Money Making MacroHow To:Enable Code Syntax Highlighting for Python in the Nano Text EditorHow To:Bash (Shell) Scripting for BeginnersHow To:Start With Site Setting For Snoft Article Directory ScriptForbes Exploited:XSS Vulnerabilities Allow Phishers to Hijack Sessions & Steal LoginsNews:INTRO TO SCREENWRITINGNews:Asteroids