What nmap scanning switch employs the use of default scripts during a scan
What nmap scanning switch employs the use of default scripts during a scan
How to Use Nmap Script Engine (NSE) Scripts in Linux
Nmap is a popular, powerful and cross-platform command-line network security scanner and exploration tool. It can also help you get an overview of systems that connected your network; you can use it to find out all IP addresses of live hosts, scan open ports and services running on those hosts, and so much more.
One of the interesting features of Nmap is the Nmap Script Engine (NSE), which brings even more flexibility and efficiency to it. It enables you to write your own scripts in Lua programming language, and possibly share these scripts with other Nmap users out there.
There are four types of NSE scripts, namely:
Then these scripts are grouped under various categories including those for authentication (auth), discovering of hosts (broadcast), brute force attacks to guess authentication credentials (brute), discovering more about a network (discovery), causing a denial of service (dos), exploiting some vulnerability (exploit), etc. A number of scripts belong to the default category.
Note: Before we move any further, you should take a note of these key points:
To see the location of all available NSE scripts, run the locate utility on the terminal, like this:
The syntax for enabling scripts is as follows:
Sample Output
To use a script for the appropriate purpose, you can, first of all, get a brief description of what it actually does, for instance, http-headers.
Sample Output
Loading NSE Scripts To Perform Nmap Scans
You can select or load scripts to perform a scan in different methods explained below.
Using Script Name
Once you know what a script does, you can perform a scan using it. You can use one script or enter a comma-separated list of script names. The command below will enable you to view the HTTP headers configured on the webserver at the target host.
Using Categories
You can also load scripts from one category or from a comma-separated list of categories. In this example, we are using all scripts in the default and broadcast category to carry out a scan on the host 192.168.56.1.
Using * Wildcard
This is useful when you want to select scripts with a given name pattern. For example to load all scripts with names starting with ssh, run the command below on the terminal:
Load Scripts Using Wildcards-
Using Boolean Expressions
You can also select scripts using boolean expressions which you can build using the and, or, and not operators. And names in a Boolean expression may be a category, a filename from script.db, or all.
The following command will load scripts from the default or broadcast categories.
Which is equivalent to:
To load all scripts omitting those in the vuln category, run this command on the terminal.
The next command looks a little complicated but it is easy to understand, it selects scripts in the default, or broadcast categories, leaving out those with names starting with ssh-:
Importantly, it is possible to combine categories, script names, a directory containing your custom scripts, or a boolean expression to load scripts, like this:
Passing Arguments to NSE Scripts
Below is an example showing how to pass arguments to scripts with the –script-args option:
To pass a port number, use the -p nmap option:
The above command runs an audit of the MySQL database server security configuration against parts of the CIS MySQL v1.0.2 benchmark. You can as well create your own useful custom audit files for other MySQL audits.
That’s it for now. You can find more information on the Nmap man page or check out NSE Usage.
To get started with writing your own NSE scripts, check out this guide: https://nmap.org/book/nse-tutorial.html
Conclusion
Nmap is a really powerful and useful tool that every system or network administrator needs in his/her security arsenal – NSE simply adds more efficiency to it.
In this article, we introduced you to the Nmap Script Engine and looked at how to find and use the various available scripts under different categories. If you have any questions, do not hesitate to write back to us via the comment form below.
If You Appreciate What We Do Here On TecMint, You Should Consider:
TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
We are thankful for your never ending support.
Nmap Cheatsheet
My collection of nmap scan types, mostly used switches and their description.
About Nmap
Nmap is used for network discovery and security auditing. In short, nmap displays exposed services on a target machine along with other useful information such as the version and OS detection. It’s also open-source!
Nmap Scan Types
TCP Connect
TCP Connect scan completes the 3-way handshake.
If a port is open, the operating system completed the TCP three-way handshake and the port scanner immediately closes the connection to avoid DOS. This is “noisy” because the services can log the sender IP address and might trigger Intrusion Detection Systems.
UDP Scan
This scan checks to see if there are any UDP ports listening.
Since UDP does not respond with a positive acknowledgment like TCP and only responds to an incoming UDP packet when the port is closed, this type of scan can sometimes show false positives. However, it can also reveal Trojan horses running on high UDP ports and hidden RPC services. It may be quite slow since some machines intentionally slow down responses to this kind of traffic to avoid being overwhelmed. Machines running Windows OS, however, do not implement this slowdown feature, so you should be able to use UDP to scan Windows hosts normally.
SYN Scan
SYN scan is another form of TCP scanning.
Rather than using the operating system’s network functions, the port scanner generates raw IP packets itself, and monitors for responses. This scan type is also known as “half-open scanning” because it never actually opens a full TCP connection. The port scanner generates an SYN packet. If the target port is open, it will respond with an SYN-ACK packet. The scanner host responds with an RST packet, closing the connection before the handshake is completed. If the port is closed but unfiltered, the target will instantly respond with an RST packet. There is debate over which scan is less intrusive on the target host. SYN scan has the advantage that the individual services never actually receive a connection.
FIN Scan
This is a stealthy scan, like the SYN scan, but sends a TCP FIN packet instead.
Most but not all computers will send an RST packet back if they get this input, so the FIN scan can show false positives and negatives, but it may get under the radar of some IDS programs and other countermeasures.
ACK Scan
Ack scanning determines whether the port is filtered or not.
This is especially good when attempting to probe for the existence of a firewall and its rulesets. Simple packet filtering will allow established connections (packets with the ACK bit set), whereas a more sophisticated stateful firewall might not.
NULL Scan
Another very stealthy scan that sets all the TCP header flags to off or null.
This is not normally a valid packet and some hosts will not know what to do with this. Windows operating systems are in this group, and scanning them with NULL scans will produce unreliable results. However, for non-Windows servers protected by a firewall, this can be a way to get through.
XMAS Scan
Similar to the NULL scan except for all the flags in the TCP header is set to on.
Windows machines won’t respond to this due to the way their TCP stack is implemented. Xmas scans derive their name from the set of flags that are turned on within a packet. These scans are designed to manipulate the PSH, URG and FIN flags of the TCP header.
RPC Scan
This special type of scan looks for machines
answering to RPC (Remote Procedure Call) services.
RPC, which allows remote commands to be run on the machine under certain conditions, can be a dangerous service. Since RPC services can run on many different ports, it is hard to tell from a normal scan which ones might be running RPC. This scan will probe the ports found open on a machine with commands to show the program name and version if RPC is running. It’s not a bad idea to run one of these scans every so often just to find out if and where you have these services running.
IDLE Scan
It is a super stealthy method whereby the scan packets are
bounced off an external host.
You don’t need to have control over the other host but it does have to set up and meet certain requirements. You must input the IP address of our “zombie” host and what port number to use. It is one of the more controversial options in Nmap since it really only has a use for malicious attacks.
Nmap Script and Version Scan
Nmap provides script scanning which gives nmap very flexible behavior to get more information and test about the target host. This feature is called Nmap Scripting Engine (NSE). NSE gives user the ability to write scripts for test. Lua is programming language supported by NSE. NSE have some vulnerability detection scripts too.
NSE have categories to make things tidy. Here are these categories
Now some action is required to gain experience about NSE
Enable Script Scan
Enable Script Scan
List Of Available NSE Scripts
Now we want to use specific script for our scan but first we should list and get information about these script Nmap have a web page where all scripts are listed.
List Of Available NSE Scripts
To get details information we click mysql-info script as an example.
Here we can see that mysql-info script is part of default, discovery and safe categories and there is a summary about the script and sample of useage
These scripts can be found in local system directory /usr/share/nmap/nselib/
List Of Available NSE Scripts
Run Specific Script
By default default category scripts are fired while nmap scan but if we want to run specific script we can specify the script name or category name like below.
Run Specific Script
As we see only our specified script is fired.
Run Specific Category Script
We can specify the whole scripts in a category the same as script by providing category name. Be aware that my system is a test system so I specify dangerous categories. In this example we run intrusive category scripts.
Run Specific Category Script
Exclude Script Category
While specifying script category we can specify a category to exclude like below.
Exclude Script Category
Specify Multiple Categories
Multiple categories can be specified like below.
Specify Multiple Categories
Provide Script Arguments
Some scripts need arguments to work. Arguments can be provided like below.
Here we provides 3 arguments;
Provide Scripts Arguments From File
Providing scripts arguments can be done from terminal but how can we accomplish providing script arguments from file because we may want to run nmap as batch process. First we will create file which holds arguments and their values. File named nmap-arg and looks like below.
Get Script Help
We have looked how to get information about scripts from web above. But we may not accessibility to the web page always or it may not a practical way for us. Here we will get help from command line about a NSE script.
Get Script Help
Get Script Category Help
Getting help about script category is the same as single script help.
Debug Scripts
Some times we can not be sure if things go as we expected. We can get more verbose output about scripts by debugging them while running like below.
Debug Scripts
Руководство по работе со скриптами Nmap Scripting Engine
Для многих из нас, чьи рабочие задачи хотя бы некоторое время были тесно связаны с информационной безопасностью, Nmap давно стал привычным и полезным инструментом. Он также незаменим, как теплое одеяло холодной зимней ночью. За тем лишь исключением, что Nmap — это чертовски эффективное одеяло.
Nmap — это популярный и мощный кроссплатформенный сканер сетевой безопасности, запускаемый из командной строки, с помощью которого вы можете чрезвычайно эффективно провести исследование любой сети. Он также может помочь вам получить обзор систем, которые подключились к вашей сети; вы можете использовать его, чтобы узнать IP-адреса всех «живых» хостов, сканировать открытые порты и сервисы, запущенные на этих хостах, а также многое-многое другое.
Без сомнения, Nmap является самым универсальным сканером портов из существующих ныне. Да, вы можете найти более быстрые сканнеры, но нет ни одного настолько полезного и попросту незаменимого для решения многих-многих ваших задач. И подавляющее большинство профессионалов в области информационной безопасности безапелляционно согласятся с этим утверждением.
Однако гораздо меньше людей знает, что одной из самых интересных особенностей Nmap является возможность использовать скрипты NSE, которые обеспечат вашему любимому инструменту сетевой безопасности еще большую гибкость и эффективность. С их помощью вы сможете делать то, чего даже от такого очень продвинутого сканера портов, как Nmap, вы никак не ожидали получить.
Давайте более детально посмотрим на скрипты NSE, и, возможно, их потенциал сможет приятно вас удивить.
Что такое скрипты NSE?
NSE расшифровывается как Nmap Scripting Engine (Скриптовый движок Nmap), и его возможности позволяют вам (да, именно вам) написать на программном языке Lua собственную дополнительную функциональность для сканера портов Nmap, а также, при желании, поделиться этими скриптами с другим пользователям Nmap. Таким образом, у вас есть возможность использовать разнообразный и постоянно расширяющийся набор скриптов, которые поставляются вместе с Nmap, либо самостоятельно написать свои скрипты под свои собственные нужды.
Другими словами, помимо стандартной проверки открытых портов сканером Nmap, вы, задействовав NSE, имеете возможность получить также расширенную информацию о сервисах, запущенных на нем. Так, например, с помощью скриптов NSE вы можете провести более глубокий анализ ваших сетевых сервисов и увидеть, насколько правильно они сконфигурированы, какая информация доступна, не используются ли слабые учетные данные и т. д. Фактически, скрипты NSE превращают Nmap в гибкую платформу для взаимодействия с сетевыми сервисами.
Возможности скриптов Nmap Scripting Engine
Команда разработчиков сканера портов Nmap задумывала и создавала скриптовый движок прежде всего для решения таких задач, как:
1. Исследование сети
Это область основного практического применения Nmap. Некоторые скрипты призваны облегчить, оптимизировать и ускорить работу вашего любимого сканера портов. Некоторые примеры их использования включают в себя выполнение таких задач, как:
2. Более изощренный вариант определения версий
Система Nmap для определения версий сервисов и приложений способна распознать тысячи различных сервисов с помощью зондов и сопоставления сигнатур регулярных выражений, но и она не всемогуща. К примеру, идентификация сервиса Skype v2 требует два независимо работающих друг от друга зонда, чьи возможности по определению версий не отличаются высокой гибкостью. Также Nmap способен распознать часть SNMP-сервисов, если попытается перебрать несколько сотен community имен методом грубой силы. Для решения обеих вышеприведенных задач не слишком удобно использовать стандартные методы определения версий Nmap, но обе они легко выполняются с помощью NSE. По этой причине система определения версий сейчас вызывает по умолчанию NSE для решения задачи определения версии при обработки некоторых сложных сервисов.
3. Поиск уязвимостей
Когда обнаруживается новая уязвимость, она становится общеизвестной, и специалистам по сетевой безопасности нужно срочно просканировать свои сети, чтобы быстро идентифицировать уязвимые системы, до того, как это сделают за них плохие парни. Хотя Nmap и не является полноценным сканером уязвимостей, мощный потенциал NSE позволяет ему осуществлять проверки уязвимостей даже с учетом очень жестких требований. К примеру, когда ошибка Heartbleed в криптографическом программном обеспечении OpenSSL поставила под угрозу сотни тысяч систем по всему миру, разработчики Nmap отреагировали написанием скрипта ssl-heartbleed detection в течение двух дней.
4. Обнаружение бэкдоров
Многие киберзлоумышленники, а также некоторые автоматические черви оставляют бэкдоры, чтобы на будущее обеспечить себе лазейку для осуществления более легкого проникновения в вашу систему. Часть из этих бэкдоров можно обнаружить с помощью стандартной процедуры определения версий Nmap на основе сопоставления сигнатур регулярных выражений, но для надежного обнаружения многих более сложных червей и бэкдоров требуются расширенные возможности NSE. В частности, NSE применяется для обнаружения бэкдора DoublePulsar, использующего уязвимость в реализации протокола SMB, бэкдор-версий для IRC-сервера UnrealIRCd, а также FTP-серверов vsftpd и ProFTPd.
5. Обнаружение уязвимостей
Реализованный на основе скриптового языка общего назначения, NSE может быть даже использован для создания эксплойтов, которые помогут вам обнаружить уязвимости еще до того, как информация об их существовании станет общедоступной. Такая возможность добавления пользовательских скриптовых эксплойтов может быть чрезвычайна полезна некоторым людям (прежде всего тестерам проникновения). Однако, полноценной платформой для создания сигнатур и эксплойтов, наподобие Metasploit, NSE все же не является.
Какие категории скриптов NSE существуют?
В настоящее время существует 598 скриптов NSE, которые вы можете найти в папке «scripts» — поддиректории основного каталога Nmap. Для большей производительности все скрипты проиндексированы в базе данных «scripts/script.db», где указано, к какой категории или категориям принадлежит каждый скрипт.
В зависимости от целевого применения, а также для упрощения их использования, скрипты NSE сгруппированы по разным категориям. В настоящее время определены следующие категории скриптов NSE: auth, broadcast, brute, default. discovery, dos, exploit, external, fuzzer, intrusive, malware, safe, version и vuln (имена категорий не чувствительны к регистру). Ниже приведено более детальное представление каждой категории:
Правила использования скриптов NSE
Скрипты, в зависимости от их функциональной направленности, а также фазы сканирования, в ходе которой они выполняются, разделены на четыре типа (некоторые скрипты могут поддерживать сразу несколько типов операций):
Примечание: многие скрипты могут запускаться как prerule script, так и как postrule script. В этих случаях рекомендуется использовать функциональность prerule во избежание несогласованности.
Подписывайтесь на рассылку, делитесь статьями в соцсетях и задавайте вопросы в комментариях!
What nmap scanning switch employs the use of default scripts during a scan
The Nmap Scripting Engine (NSE) is one of Nmap’s most powerful and flexible features. It allows users to write (and share) simple scripts (using the Lua programming language ) to automate a wide variety of networking tasks. Those scripts are executed in parallel with the speed and efficiency you expect from Nmap. Users can rely on the growing and diverse set of scripts distributed with Nmap, or write their own to meet custom needs.
Tasks we had in mind when creating the system include network discovery, more sophisticated version detection, vulnerability detection. NSE can even be used for vulnerability exploitation.
Scripts are not run in a sandbox and thus could accidentally or maliciously damage your system or invade your privacy. Never run scripts from third parties unless you trust the authors or have carefully audited the scripts yourself.
The Nmap Scripting Engine is described in detail in Chapter 9, Nmap Scripting Engine and is controlled by the following options:
Runs a script scan using the comma-separated list of filenames, script categories, and directories. Each element in the list may also be a Boolean expression describing a more complex set of scripts. Each element is interpreted first as an expression, then as a category, and finally as a file or directory name.
There are two special features for advanced users only. One is to prefix script names and expressions with + to force them to run even if they normally wouldn’t (e.g. the relevant service wasn’t detected on the target port). The other is that the argument all may be used to specify every script in Nmap’s database. Be cautious with this because NSE contains dangerous scripts such as exploits, brute force authentication crackers, and denial of service attacks.
File and directory names may be relative or absolute. Absolute names are used directly. Relative paths are looked for in the scripts of each of the following places until found:
—datadir |
$NMAPDIR |