Nmap linux ��� ����

Nmap linux ��� ����

This article or section needs expansion.

Nmap (“Network Mapper”) is an open source tool for network exploration and security auditing. It was designed to rapidly scan large networks, although it works fine against single hosts. Nmap uses raw IP packets in novel ways to determine what hosts are available on the network, what services (application name and version) those hosts are offering, what operating systems (and OS versions) they are running, what type of packet filters/firewalls are in use, and dozens of other characteristics. While Nmap is commonly used for security audits, many systems and network administrators find it useful for routine tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime.

Contents

Installation

Nmap has a GUI called zenmap AUR that can be installed separately, but this article will cover only command-line usage.

Usage

Specifying the target

There are a number of ways to tell Nmap the list of IP addresses to scan. The simplest form is to just pass the address or domain name:

Specifying multiple targets

Using CIDR notation, for example to scan all 256 addresses beginning with 10.1.1 :

Using the dash, for example to scan 10.1.50.1 , 10.1.51.1 and 10.1.52.1 :

Using commas (does what you expect):

List scan

The list scan option ( -sL ) is useful for making sure that correct addresses are specified before doing the real scan:

List scan simply prints the specified addresses without sending a single packet to the target.

Default options

If you specify only an IP address or domain name and no other options:

Nmap will do the following:

  1. The IP address is reverse-DNS resolved to domain name, or vice-versa in case a domain name is specified (to disable, pass -n )
  2. Ping scanning using TCP ACK:80 and ICMP. This is equivalent to -PA -PE (to disable, pass -PN )
  3. Scans the host(s)’s top 1000 most popular ports. When running as root, SYN stealth scan is used. When running as user, connect scan is used.

Ping scan

Ping scanning (host discovery) is a technique for determining whether the specified computers are up and running. Nmap performs ping scan by default before port scan to avoid wasting time on hosts that are not even connected. To instruct Nmap to only perform ping scan:

This will cause Nmap to ping every one of the specified addresses and then report the list of hosts which did respond to the ping.

Nmap uses different kinds of ping packets when run with user or root privileges and when scanning the same or different subnets:

External IP Local IP
User privileges TCP SYN at ports 80 & 443 TCP SYN at ports 80 & 443 and ARP
Root privileges TCP SYN at ports 80 & 443 and IGMP ARP

Ping scan types

Option Ping scan type
-Pn Disable ping scan entirely
-PS TCP SYN (default at port 80)
-PA TCP ACK (default at port 80)
-PU UDP
-PY SCTP INIT
-PE ICMP Echo
-PP ICMP timestamp
-PM ICMP address mask
-PO Other IP protocol
-PR ARP scan
Читайте также:  Перезапустить cinnamon linux mint

-Pn is useful when the machine is heavily firewalled, TCP 80 and 443 ports and IGMP requests are blocked, but the IP address might still have a machine listening on other less common ports.

Port scan

There are 3 main states a port can be in:

  • open — there is a program listening and responding to requests on this port
  • closed — the host replies with an «error: no program listening on this port» reply to requests to this port
  • filtered — the host doesn’t reply at all. This can be due to restrictive firewall rules, which «drop» a packet without sending a reply

In addition to these there are 3 more states that Nmap can classify a port. These are used when Nmap cannot reliably determine the state but suspects two of the three possible states:

  • open|closed ( unfiltered ) — the port is either open or closed
  • closed|filtered — the port is either closed or filtered
  • open|filtered — the port is either open or filtered

By default Nmap scans the 1000 most popular ports found in /etc/nmap/nmap-services . To specify a different number of common ports:

To specify custom port numbers, use -p :

Dashes and commas work just like in #Specifying the target. In addition, it is possible to specify all ports before/after given one by skipping the starting/ending port when using a dash. For example to scan all possible 65535 ports (except port number 0):

Scan types

Option Port scan type
-sP Ping scan only
-sS TCP SYN (stealth) (Default as root)
-sT TCP connect (Default as user)
-sA TCP ACK
-sF TCP FIN
-sX TCP FIN, SYN, ACK
-sW TCP window
-sM TCP Miamon
-sU UDP scan
-sI Idle scan
-b FTP bounce scan
-sO Other IP protocol

Anti-scanning techniques

iptables PSD module

PSD is an extension module of iptables. It is used on some linux-based commercial routers as well.

It has 4 parameters:

  • —psd-weight-threshold threshold , default value: 21

Total weight of the latest TCP/UDP packets with different destination ports coming from the same host to be treated as port scan sequence.

  • —psd-delay-threshold delay , default value: 300 (3 seconds)

Delay (in hundredths of second) for the packets with different destination ports coming from the same host to be treated as possible port scan subsequence.

  • —psd-lo-ports-weight weight , default value: 3

Weight of the packet with privileged (

  • —psd-hi-ports-weight weight , default value: 1

Weight of the packet with non-priviliged (>1024) destination port.

The principle behind PSD is simple. If requests from a single IP have gained a value more than threshold in delay seconds, then the IP is classified as a port scanner. In a math expression:

Here are some examples:

  • With default parameters, if at least 7 priviliged ports are hit within 3 seconds, it is classified as a port scan.
  • With default parameters, if at least 21 non-privilged ports are hit withing 3 seconds, it is classified as a port scan.
  • With default parameters, if 4 privileged ports and 9 non-priviliged ports are hit within 3 seconds, it is classified as a port scan, because 4*3 + 9*1 >= 21 .

Avoiding detection

One of the simplest ways to avoid PSD is to simply scan slowly. For default values this parameter would suffice:

Another interesing fact about PSD is that it does not detect a request as a port scan when the ack or rst flags are set (See the function is_portscan in xt_psd.c)

Also, if you are port scanning a host and the latter has an HTTP(S) service running on it, nmap will use Mozilla/5.0 (compatible; Nmap Scripting Engine; https://nmap.org/book/nse.html) as default user agent. Your action will thus be easily detected, especially if an administrator or a robot are taking measures if such an user agent appears in the logs. Hopefully, nmap allows us to change that string easily: just pass -script-args http.useragent=»user agent you want» . Source

Читайте также:  Windows 10 winamp по умолчанию

Tips and Tricks

Limiting scan speed

Nmap scans are fast. While this is often a desirable feature, it can be counter-productive as well. For example when you want to test your system’s firewall without disabling any activated flood detection rules, or when you want to run a long-term test for a specific port/service. The following options specify how fast Nmap sends packets.

To send a packet at most every 3.333 seconds:

Alternatively, to send a packet every 3.1 seconds:

For other timing and parallelization options, see nmap(1) .

Specify targets input from a list file

Often it is necessary to scan a large number of non-adjacent addresses. Passing them on the command line is usually not convenient. For this reason Nmap supports input from a list file ( -iL ):

Addresses in the file must be separated with a whitespace.

Alternatively, Nmap can read the list from standard input (the — means standard input in many command-line programs):

Specify targets to exclude from scan

The same from a file:

Spoofing

To spoof source IP:

To spoof the source MAC address:

To spoof source port:

Speeding up the scan

By default, Nmap performs DNS/reverse-DNS resolution on targets. To tell Nmap never do any DNS resolution, pass the -n option:

This will speed the scan about 2 times.

Scan port number 0

By default port 0 is skipped from scans, even if -p — is specified. To scan it, it must be explicitly specified. For example to scan every possible port:

Remember that this port number is invalid in RFC standards. However it can be used by malware and the like to avoid more naive port scanners.

File output formats

Nmap has built-in support for for file output alongside with terminal output:

  • -oN filename

Normal output, same as the terminal output

  • -oX filename

XML output, contains very detailed information about the scan, easy to parse with software

  • -oG filename

Grepable output, deprecated

  • -oA

All of the above combined. Creates files called sitename.nmap , sitename.xml and sitename.gnmap if no filename is specified

For example to output to the terminal, to file and to XML file:

Источник

Nmap — руководство для начинающих

Многие слышали и пользовались замечательной утилитой nmap. Ее любят и системные администраторы, и взломщики. Даже Голливуд знает про нее — в фильме «Матрица» при взломе используется nmap.

nmap — это аббревиатура от «Network Mapper», на русский язык наиболее корректно можно перевести как «сетевой картограф». Возможно, это не лучший вариант перевода на русский язык, но он довольно точно отображает суть — инструмент для исследования сети и проверки безопасности. Утилита кроссплатформенна, бесплатна, поддерживаются операционных системы Linux, Windows, FreeBSD, OpenBSD, Solaris, Mac OS X.

Рассмотрим использование утилиты в Debian. В стандартной поставке дистрибутива nmap отсутствует, установим его командой

# aptitude install nmap

Nmap умеет сканировать различными методами — например, UDP, TCP connect(), TCP SYN (полуоткрытое), FTP proxy (прорыв через ftp), Reverse-ident, ICMP (ping), FIN, ACK, SYN и NULL-сканирование. Выбор варианта сканирования зависит от указанных ключей, вызов nmap выглядит следующим образом:

Для опытов возьмем специальный хост для экспериментов, созданный самими разработчиками nmap — scanme.nmap.org. Выполним от root’а
Ключи сканирования задавать необязательно — в этом случае nmap проверит хост на наличие открытых портов и служб, которые слушают эти порты.
Запустим командой:

Читайте также:  Полное обновление драйверов windows

Через несколько секунд получим результат:
Interesting ports on scanme.nmap.org (74.207.244.221):
Not shown: 998 closed ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http

Ничего необычного, ssh на стандартном порту и http на 80. Nmap распознаёт следующие состояния портов: open, filtered, closed, или unfiltered. Open означает, что приложение на целевой машине готово для принятия пакетов на этот порт. Filtered означает, что брандмауэр, фильтр, или что-то другое в сети блокирует порт, так что Nmap не может определить, является ли порт открытым или закрытым. Closed — не связанны в данный момент ни с каким приложением, но могут быть открыты в любой момент. Unfiltered порты отвечают на запросы Nmap, но нельзя определить, являются ли они открытыми или закрытыми.

# nmap -O scanme.nmap.org

Хинт: Если во время сканирования нажать пробел — можно увидеть текущий прогресс сканирования и на сколько процентов он выполнен. Через несколько секунд получаем ответ, в котором пока что интересна строчка Device type:

Device type: general purpose|WAP|webcam|storage-misc
Running (JUST GUESSING) : Linux 2.6.X|2.4.X (93%), AXIS Linux 2.6.X (89%), Linksys Linux 2.4.X (89%)
Aggressive OS guesses: Linux 2.6.17 — 2.6.28 (93%), Linux 2.6.9 — 2.6.27 (93%), Linux 2.6.24 (Fedora 8) (92%), Linux 2.6.18 (Slackware 11.0) (92%), Linux 2.6.19 — 2.6.26 (92%), OpenWrt (Linux 2.4.32) (91%), Linux 2.6.22 (91%), Linux 2.6.22 (Fedora Core 6) (90%), Linux 2.6.13 — 2.6.27 (90%), Linux 2.6.9 — 2.6.18 (90%)
No exact OS matches for host (test conditions non-ideal).

Вообще, точную версию ядра средствами nmap определить невозможно, но примерную дату «свежести» и саму операционную систему определить можно. Можно просканировать сразу несколько хостов, для этого надо их перечислить через пробел:

# nmap -O example.com example2.com

Вернемся к нашему подопытному хосту. Хочется узнать поподробнее, какой используется софт. Попробуем уточнить полученные данные с помощью ключей -sV:

# nmap -sV example.com example2.com

PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 5.3p1 Debian 3ubuntu7 (protocol 2.0)
80/tcp open http Apache httpd 2.2.14 ((Ubuntu))
Service Info: OS: Linux

Прогресс налицо — мы узнали точные названия используемых служб и даже их версии, а заодно узнали точно, какая операционная система стоит на сервере. С расшифровкой никаких проблем не возникает, все вполне понятно.

Агрессивное сканирование можно провести, указав ключ -A

# nmap -A scanme.nmap.org

Nmap выведет очень много информации, я не стану приводить пример. Сканирование может длится довольно долго, занимая несколько минут.

В локальных сетях или просто имея на руках диапазон ip адресов, удобно проверить их на занятость с помощью ключей -sP:

# nmap -sP 192.168.1.0/24

Сканирование проходит довольно быстро, так как по сути это обычный ping-тест, отвечает ли хост на ping. Следует учесть, что хост может не отвечать на ping из-за настроек фаерволла. Если нужный участок сети нельзя ограничить маской, можно указать диапазон адресов, с какого и по какой надо провести сканирование. Например, есть диапазон адресов с 192.168.1.2 до 192.168.1.5. Тогда выполним:

# nmap -sP 192.168.1.2-5

Ответ будет выглядеть так:

Host 192.168.1.2 is up (0.0023s latency)
Host 192.168.1.3 is up (0.0015s latency)
Host 192.168.1.4 is up (0.0018s latency)
Host 192.168.1.5 is up (0.0026s latency)

В моем случае все ip в данный момент были в сети.
Это далеко не все возможности nmap, но уместить их в рамках одной статьи несколько сложновато.

Если вам ближе GUI — есть замечательная утилита Zenmap — графическая оболочка для nmap, умеющая заодно и строить предполагаемую карту сети.

Хочу предупредить, что сканирование портов на удаленных машинах может нарушать закон.
UDPInflame уточнил, что сканирование портов все-таки не является противозаконным.

Источник

Оцените статью