Nmap windows как пользоваться

Время на прочтение5 мин

Количество просмотров431K

image

Вы когда-нибудь интересовались откуда атакующий знает какие порты открыты в системе? Или как узнать, какие приложения запущены на сервере, не спрашивая об этом администратора? Вы можете сделать все это и даже больше вместе с небольшим инструментом под названием Nmap.

Что такое Nmap? Название Nmap это сокращение от “network mapper”, сам nmap это набор инструментов для сканирования сети. Он может быть использован для проверки безопасности, просто для определения сервисов запущенных на узле, для идентификации ОС и приложений, определения типа фаерволла используемого на сканируемом узле.
Nmap это знаменитый инструмент. Как только вы узнаете больше о Nmap, вы поймете, что он делает в эпизодах таких фильмов как Матрица Перезагрузка, Ультиматум Борна, Хоттабыч, и других.
В этом руководстве будут описаны основы использования Nmap и приведены некоторые примеры, которые вы сможете использовать.

Где взять Nmap?

Если Вы используете Linux, то можете найти пакеты Nmap в репозиториях для большинства дистрибутивов. Последний релиз Nmap вышел в начале 2010, поэтому самой свежей версии может не быть в текущих стабильных ветках. Найти исходники и некоторые бинарные сборки можно на странице загрузки.Там есть и windows версия.

Основы использования Nmap.

Синтаксис Nmap следующий:

nmap Опции_сканирования Цель_сканирования.

Допустим Вы хотите сканировать узел и узнать какая операционная система на нем работает. Чтобы сделать это выполните следующее:

nmap -O target.host.com

Заметим что Nmap требует привилегий суперпользователя для запуска подобного типа сканирования. Процесс сканирования может занять около минуты, так что будьте терпеливы. Когда процесс закончится вы увидите что то похожее на это:

Starting Nmap 5.21 ( nmap.org ) at 2010-02-27 23:52 EST
Nmap scan report for 10.0.0.1
Host is up (0.0015s latency).
Not shown: 997 closed ports
PORT STATE SERVICE
53/tcp open domain
5009/tcp open airport-admin
10000/tcp open snet-sensor-mgmt
MAC Address: 00:11:24:6B:43:E2 (Apple Computer)
Device type: WAP|printer
Running: Apple embedded, Canon embedded, Kyocera embedded, Xerox embedded
OS details: VxWorks: Apple AirPort Extreme v5.7 or AirPort Express v6.3; Canon imageRUNNER printer (5055, C3045, C3380, or C5185); Kyocera FS-4020DN printer; or Xerox Phaser 8860MFP printer
Network Distance: 1 hop

Как вы видите Nmap предоставляет множество информации. Здесь он отображает предположение об операционной системе, которая была запущена на узле. В данном случае выполнялось сканирование маршрутизатора Apple Airport Extrime. В качестве дополнительного бонуса Nmap сообщил, что устройство на расстоянии одного прыжка, а также MAC адрес устройства и производителя сетевой карты, открытые порты и сколько времени выполнялось сканирование.
Ниже приведены результаты другого сканирования, домашнего компьютера с запущенной Ubuntu 9.10:

Starting Nmap 5.21 ( nmap.org ) at 2010-02-28 00:00 EST
Nmap scan report for 10.0.0.6
Host is up (0.0039s latency).
Not shown: 999 closed ports
PORT STATE SERVICE
22/tcp open ssh
MAC Address: 00:17:08:2A:D6:F0 (Hewlett Packard)
Device type: general purpose
Running: Linux 2.6.X
OS details: Linux 2.6.19 - 2.6.31
Network Distance: 1 hop

OS detection performed. Please report any incorrect results at nmap.org/submit .
Nmap done: 1 IP address (1 host up) scanned in 3.40 seconds

Здесь мы видим, что система имеет сетевую карту HP, запущено Linux между версиями 2.6.19 и 2.6.31. Кстати, Вы не сможете явно идентифицировать дистрибутив, только версию Linux ядра.

Сканирование чужих узлов.

В примерах выше для сканирования были выбраны локальный маршрутизатор и одна из рабочих станций, потому что мы имели право на их сканирование. Однако, будет плохой идеей запуск множественного сканирования чужого узла, если вы их не контролируете или не имеете прав для сканирования. Для экспериментов Nmap имеет общедоступный тестовый сервер scanme.nmap.org который Вы можете использовать.
Многие администраторы не любят несанкционированного сканирования их серверов, так что лучшим вариантом будет ограничение сканирования узлов своей локальной сети или тех для которых у вас есть права на сканирование. Также в некоторых случаях вы можете нарушить договор с вашим провайдером, при использовании некоторых особо агрессивных методов сканирования Nmap, поэтому будьте осторожны.

Сканирование нескольких узлов.

Вы можете сканировать больше чем один узел за раз, используя nmap. Если вы производите сканирование по IP-адресу вы можете определить диапазон 10.0.0.1-6 или 10.0.0.0/24.Используя диапазон 10.0.0.1-6 будут сканироваться узлы от 10.0.0.1 до 10.0.0.6. Используя определение /24 будет сканироваться весь диапазон узлов от 10.0.0.0 до 10.0.0.255. Для примера, если нужно просканировать узлы от 10.0.0.1 до 10.0.0.42 и узнать какая ОС вероятно запущена используйте:

nmap –O 10.0.0.1-42

Если у вас есть некоторый список доменных имен вместо IP адресов, вы можете разделить их в командной строке, вот так:

nmap -O host1.target.com host2.target.com

Проверка открытых портов

Если вы запустите nmap вообще без опций и укажите какой то узел, то он будет сканировать порты и покажет все найденные открытые порты и сервисы запущенные на них. Например запустите:
nmap target.hostname.com
после чего он должен выдать что то похожее на это:

Interesting ports on target.hostname.com (10.0.0.88):
Not shown: 1711 closed ports
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
3306/tcp open mysql

Nmap done: 1 IP address (1 host up) scanned in 0.228 seconds

Nmap выдаст больше информации если использовать опцию -v (verbose).

Сканирование запущенных сервисов

Если вы хотите узнать какой сервис возможно запущен попробуйте опцию –sV. Эта опция произведет более агрессивное сканирование и попытается выяснить какая версия сервисов запущена на данном узле, а также может помочь более точно определить какая ОС запущена. Для пример запустим nmap –sV на тестовый сервер и получим следующий ответ:

Starting Nmap 5.21 ( nmap.org ) at 2010-02-28 00:15 EST
Nmap scan report for test.host.net (XX.XXX.XXX.XX)
Host is up (0.090s latency).
Not shown: 965 closed ports, 33 filtered ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 4.7p1 Debian 8ubuntu1.2 (protocol 2.0)
80/tcp open http Apache httpd 2.2.8 ((Ubuntu) PHP/5.2.4-2ubuntu5.10 with Suhosin-Patch)
Service Info: OS: Linux

Service detection performed. Please report any incorrect results at nmap.org/submit .
Nmap done: 1 IP address (1 host up) scanned in 11.43 seconds

Как вы видите, Nmap может проанализировать пакеты и определить версию запущенного приложений на SSH и HTTP портах. Здесь вы можете увидеть что опрашиваемая система это Ubuntu с Apache 2.2.8 и OpenSSH 4.7p1. Эта информация может быть полезна по ряду причин. Nmap сканирование может идентифицировать систему под управлением устаревших сервисов которые могут быть уязвимы для известных эксплойтов.

Кто в моей сети?

Не знаете сколько онлайн узлов находятся в вашей сети? Попробуйте использовать nmap –sP который запустит ping сканирование указанной сети. Для примера, nmap –sP 10.0.0.0/24 сканирует 256 узлов от 10.0.0.0 до 10.0.0.255 проверит доступны ли они и доложит об этом. Так же вы можете использовать диапазон, например:

nmap –sP 10.0.0.1-15

Zenmap

Наконец, если все эти радости командной строки не для вас, nmap имеет GUI который вы можете использовать для построения и выполнения команд. Называется Zenmap. Он позволит выбрать цель, запустить сканирование, отобразить результаты, а также сохранить их и сравнить с другими.
GUI Zenmap это хороший способ познакомиться с Nmap, но лучше знать как использовать Nmap в командной строке, если вы собираетесь работать с ним часто.
В будущем руководстве мы более глубоко познакомимся с Nmap и конкретными задачами которые вы сможете решить.

Данный пост это вольный перевод статьи Beginner’s Guide to Nmap. Спасибо за внимание.

Загрузить PDF

Загрузить PDF

Вы беспокоитесь о безопасности вашей или какой-нибудь другой сети? Защита вашего маршрутизатора от нежелательных подключений является залогом безопасности вашей сети. Одним из простых методов является Nmap или Network Mapper. Это программа сканирования, которая проверяет какие порты открыты и какие закрыты, а так же другие детали. Специалисты по безопасности используют эту программу для тестирования безопасности сети. Чтобы научиться использовать эту программу смотрите Шаг 1.

  1. Step 1 Скачайте установщик Nmap.

    Вы можете найти установщик на сайте разработчиков и скачать бесплатно. Рекомендуется скачивание именно с сайта разработчиков, чтобы избежать риск скачивания вирусов или подмененных файлов. Скачивая Nmap вы одновременно получить Zenmap, графический интерфейс для Nmap, что делает программу простой в использовании для новичков при выполнении сканирования без знания команд.

    • Программа Zenmap доступна для операционных систем Windows, Linux, и Mac OS X. Вы можете найти установщики на официальном сайте Nmap.
  2. Step 2 Установите Nmap.

    Запустите установщик сразу после окончания загрузки. Выберите компоненты для установки. Чтобы полностью воспользоваться всеми возможностями Nmap выберите все компоненты. Nmap не будет устанавливать рекламные или шпионские приложения.

  3. Step 3 Запустите программу “Nmap – Zenmap” GUI.

    Если во время установки вы оставили все пункты не тронутыми, то иконка программы должна появиться на вашем рабочем столе. Если нет, посмотрите в меню старт и запустите Zenmap.

  4. Step 4 Введите цель вашего сканирования.

    Программа Zenmap превращает сканирование сети в очень простой процесс. В первую очередь выберете цель сканирования. Вы можете ввести домен (example.com), IP-адрес (127.0.0.1), сеть (192.168.1.0/24), или комбинацию перечисленных.

    • В зависимости от загрузки и цели вашего сканирования, использование Nmap может оказаться нарушением пользовательских правил вашего интернет провайдера. Всегда проверяйте местные пользовательские правила во время использования Nmap в случаях сканирования этой программой вне вашей собственной сети.
  5. Step 5 Выберете ваш профиль.

    Профили представляют из себя группу модификаций, которые изменяют структуру сканирования. Профили позволяют быстро выбрать разные типы сканов без необходимости набора модификаций в командной строке. Выберете лучший профиль для ваших нужд:[1]

    • Intense scan — обширное сканирование. Включает распознавание операционной системы, версии, скриптов, трассировку, и имеет агрессивное время сканирования.
    • Ping scan — это сканирование, определяет онлайн статус цели вашего сканирования, и не сканирует порты.
    • Quick scan — сканирует быстрее чем обычный скан с агрессивным временем сканирования и выборку портов.
    • Regular scan — это стандартны Nmap скан без каких-либо модификаций. Результат включает пинг и открытые порты.
  6. Step 6 Нажмите Scan чтобы начать сканирование.

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

  7. Step 7 Посмотрите ваши результаты.

    После окончания скана, вы увидите сообщение “Nmap is done” в низу вкладки Nmap Output. Теперь вы можете проверить ваши результаты, в зависимости от типа выбранного скана. Все результаты собраны во вкладке Output, но, выбирая другие вкладки, вы можете более детально изучить получившийся результат.[2]

    Реклама

  1. Nmap является не большой и бесплатной программой. Вы можете скачать программу на сайте разработчика. Следуйте инструкциям исходя из вашей операционной системы:

  2. Команды Nmap работают из командной строки и показывают результаты сразу под командой. Вы можете использовать параметры, чтобы изменить структуру сканирования. Вы можете запустить сканирования из любого места прописанного в вашей командной строке.

  3. Step 3 Проведите скан нужных вам портов.

    Чтобы начать простое сканирование, напишите nmap <target>. Таким образом начнется пинг выбранной цели и сканирование портов. Этот скан очень просто распознать. Результаты будут видны на вашем экране. Возможно вам придется прокрутить наверх, чтобы увидеть результаты полностью.

    • В зависимости от загрузки и цели вашего скана, использование Nmap может оказаться нарушением правил вашего интернет провайдера. Всегда проверяйте местные пользовательские правила во время использования Nmap в случаях сканирования этой программой вне вашей собственной сети.
  4. Step 4 Проведите модифицированное сканирование.

    Вы можете использовать командные переменные, чтобы изменить параметры сканирования, в результате получая более или менее обширное сканирование. Вы можете добавить несколько переменных оставляя пробел между каждым. Переменные ставятся до цели: nmap <variable> <variable> <target>[3]

    • -sS — это скрытое сканирование SYN. Это сканирование сложнее обнаружить, чем обычное, но может занять дольше времени для завершения. Большинство новых файерволов могут обнаружить сканирование –sS.
    • -sn — это сканирование пинга. Это сканирование не использует обнаружение портов, и только проверяет онлайн статус цели.
    • -O — это сканирование определяет вид операционной системы цели.
    • -A — эта переменная включает обнаружение более обширной информации: операционная система, версия, скрипты, и трассировка.
    • -F — включает быстрое сканирование, и уменьшает количество сканируемых портов.
    • -v — эта переменная показывает большее количество результатов вашего сканирования, делая их читабельными.
  5. Step 5 Выведите результаты вашего сканирования в XML файл.

    Вы можете настроить вывод результатов вашего сканирования в XML файл и, в последствии, легко открыть их в любом веб-браузере. Чтобы это сделать используйте переменную -oX с названием файла для вывода данных. Полностью команда выглядит таким образом nmap –oX ScanResults.xml <target>.

    • Ваш XML файл будет сохранен в текущей директории работы вашей командной строки.

    Реклама

Советы

  • Интересно как проходит сканирование? Нажмите пробел, или любую кнопку, во время работы скана, чтобы посмотреть прогресс Nmap.
  • Цель не отвечает? Попробуйте добавить переменную “-P0” к вашему сканированию. В результате сканирование Nmap начнет свою работу, даже если программа «думает», что цель не существует. Это бывает полезно, когда компьютер защищён файерволом.
  • Если ваше сканирование занимает большое время (больше 20 минут), попробуйте добавить переменную “-F”, таким образом Nmap сканирование затронет только недавно использовавшиеся порты.

Реклама

Предупреждения

  • Убедитесь, что у вас есть разрешение на сканирование цели. Сканирование государственных сайтов принесет вам не мало проблем. Если вы хотите проверить сканирование, вы можете использоваться scanme.nmap.org. Это тестовый компьютер установленный создателем программы.
  • Если вы часто используете сканирование Nmap, будьте готовы ответить на вопросы от вашего интернет провайдера. Некоторые провайдеры специально проверяют трафик на сканирование Nmap. Программа является известной и часто используемой хакерами.

Реклама

Об этой статье

Эту страницу просматривали 32 216 раз.

Была ли эта статья полезной?

  • Nmap Network Scanning
  • Chapter 2. Obtaining, Compiling, Installing, and Removing Nmap
  • Windows

While Nmap was once a Unix-only tool, a Windows version was
released in 2000 and has since become the second most popular Nmap
platform (behind Linux). Because of this popularity and the fact that
many Windows users do not have a compiler, binary executables are
distributed for each major Nmap release. We support Nmap on Windows 7
and newer, as well as Windows Server 2008 and newer. We also maintain
a guide for users
who must run Nmap on earlier Windows releases.
Nmap runs equally well on Windows as on Unix in nearly every way, though there are a couple of known limitations:

  • Nmap only supports ethernet interfaces (including most
    802.11 wireless cards and many VPN clients) for raw packet scans.
    Unless you use the -sT -Pn options, RAS connections
    (such as PPP dialups) and certain VPN clients are not supported. This
    support was dropped when Microsoft removed raw TCP/IP socket support
    in Windows XP SP2. Now Nmap must send lower-level ethernet frames
    instead.

  • When using Nmap without Npcap, you cannot
    generally scan your own machine from itself (using a
    loopback IP such as 127.0.0.1 or any of its
    registered IP addresses). This is a Windows limitation that we
    have worked around in Npcap, which is included in the Windows self-installer.
    Users stuck without a Npcap installation can use a TCP
    connect scan without pinging (-sT -Pn) as that uses
    the high level socket API rather than sending raw
    packets.

Scan speeds on Windows are generally comparable to those on
Unix, though the latter often has a slight performance edge. One
example of this is connect scan (-sT), which may be
slower on Windows because of different limits in the Windows
networking API. Since this is the one TCP scan that
works over all networking types (not just ethernet, like the raw packet scans),
Nmap includes a collection of Registry changes that substantially improve connect scan performance.
By default these changes are applied for you by the Nmap executable installer, and are also available in the
nmap_performance.reg file
in the nmap-<version>
directory of the Windows binary zip file (for Nmap OEM customers), and
nmap-<version>/mswin32
in the source tarball (where <version> is the
version number of the specific release). These changes increase
the number of ephemeral ports reserved for user applications (such as
Nmap) and reduce the time delay before a closed connection can
be reused. Most people simply check the box to apply these changes in the executable Nmap installer, but you can also apply them by double-clicking on
nmap_performance.reg, or by running the command
regedt32 nmap_performance.reg. To make the changes by hand, add these three Registry DWORD values to
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters:

MaxUserPort

Set a large value such as 65534 (0x0000fffe). See MS KB 196271.

TCPTimedWaitDelay

Set the minimum value (0x0000001e). See MS KB 149532.

StrictTimeWaitSeqCheck

Set to 1 so TCPTimedWaitDelay is checked.

Windows users have three choices for installing
Nmap, all of which are available from the
download page at https://nmap.org/download.html.

Windows Self-installer

Every Nmap release includes a Windows
self-installer named
nmap-<version>-setup.exe
(where <version> is the version number of the
specific release). Most Nmap users choose this option since it is so
easy. Another advantage of the self-installer is that it provides the option to install the Zenmap GUI and other tools. Simply run the installer file and let it walk you through
panels for choosing an install path and installing Npcap. The
installer was created with the open-source Nullsoft Scriptable
Install System. After it completes, read the section called “Executing Nmap on Windows” for instructions on executing Nmap on the
command-line or through Zenmap.

Command-line Zip Binaries

Note

The Zip archive is available to Nmap OEM customers only. Most users prefer installing Nmap with the self-installer discussed previously.

Every stable Nmap OEM release is also available as Windows
command-line binaries and associated files in a Zip archive. No
graphical interface is included, so you need to run
nmap.exe from a DOS/command window.
Here are the step-by-step instructions for installing and executing the Nmap .zip binaries.

Installing the Nmap zip binaries

  1. Download the .zip binaries from the link provided in your Nmap OEM order.

  2. Extract the zip file into the directory you want
    Nmap to reside in. An example would be C:\Program
    Files
    . A directory called
    nmap-<version> should be created, which includes
    the Nmap executable and data files.

  3. For improved performance, apply the Nmap Registry
    changes discussed previously.

  4. Nmap requires the free Npcap packet capture library.
    We include a recent Npcap installer which is available in the zip file
    as npcap-<version>-oem.exe,
    where <version> is the Npcap version rather
    than the Nmap version. Alternatively, you can obtain and install
    the latest version from https://npcap.com.

  5. Due to the way Nmap is compiled, it requires the
    Microsoft Visual C++ Redistributable Package of runtime
    components. Many systems already have this installed from other
    packages, but you should run vc_redist.x86.exe
    from the zip file just in case you need it.
    Pass the /q option to run these installers in quiet (non interactive) mode.

  6. Instructions for executing your compiled Nmap are
    given in the section called “Executing Nmap on Windows”.

Compile from Source Code

Most Windows users prefer to use the Nmap binary self-installer,
but compilation from source code is an option, particularly if you plan to help with Nmap development. Compilation requires
Microsoft Visual C++ 2019, which is part of their commercial Visual Studio
suite. Any of the Visual Studio 2019 editions should work, including the free
Visual Studio 2019 Community.

Some of Nmap’s dependencies on Windows are inconvenient to build. For
this reason, precompiled binaries of the dependencies are stored in
Subversion, in the directory /nmap-mswin32-aux.
When building from source, whether from a source code release or from
Subversion, check out /nmap-mswin32-aux as
described below.

Compiling Nmap on Windows from Source

  1. Download the Windows dependencies from Subversion with the command
    svn checkout https://svn.nmap.org/nmap-mswin32-aux.
    The build files are configured to look for dependencies in this
    checked-out directory. If you want to build the dependencies yourself
    instead, you will have to reconfigure the Visual Studio project files to
    point to the alternate directory.

  2. Decide whether to obtain the Nmap source code by downloading the latest release from nmap.org, or using a Subversion client to retrieve even newer (but less tested) code from our repository. These instructions are for the web download approach, but using Subversion instead is straightforward (see the section called “Obtaining Nmap from the Subversion (SVN) Repository”).

  3. Download the latest Nmap source distribution from https://nmap.org/download.html. It has the name
    nmap-<version>.tar.bz2 or
    nmap-<version>.tgz. Those are the same tar file compressed using bzip2 or gzip, respectively. The bzip2-compressed version is smaller.

  4. Uncompress the source code file you just downloaded. The
    source code directory and the nmap-mswin32-aux must
    be in the same parent directory.
    Recent releases of the free Cygwin distribution can handle both the .tar.bz2 and .tgz formats. Use the command tar xvjf nmap-version.tar.bz2 or tar xvzf nmap-version.tgz, respectively. Alternatively, the common WinZip application can decompress these files.

  5. Open Visual Studio and the Nmap solution file (nmap-<version>/mswin32/nmap.sln).

  6. Right click on Solution 'nmap' in the Solution Explorer sidebar and choose Configuration Manager. Ensure that the active solution configuration is Release and then close the Configuration Manager.

  7. Build Nmap by pressing F7 or choosing Build
    Solution
    from the GUI. Nmap should begin compiling, and
    end with the line -- Done -- saying
    that all projects built successfully and there were zero
    failures.

  8. The executable and data files can be found in nmap-<version>/mswin32/Release/. You can copy them to a preferred directory as long as they are all kept together.

  9. Ensure that you have Npcap installed.
    The official installer for the latest version is available at https://npcap.com/#download. Users who install via
    our binary self-installer will have Npcap installed automatically.
    Nmap OEM customers can also run
    npcap-<version>.exe from
    our zip package.

  10. Instructions for executing your compiled Nmap are
    given in the next section.

If you wish to build an Nmap executable Windows
installer or Zenmap executable,
see docs/win32-installer-zenmap-buildguide.txt in the Nmap SVN repository.

Many people have asked whether Nmap can be compiled with the
gcc/g++ included
with Cygwin or other compilers. Some users have reported success with
this, but we don’t maintain instructions for building Nmap under
Cygwin.

Executing Nmap on Windows

Nmap releases now include the
Zenmap graphical user interface for Nmap.
If you used the Nmap installer and left the Zenmap field checked,
there should be a new Zenmap entry on your desktop and Start Menu.
Click this to get started. Zenmap is fully documented in
Chapter 12, Zenmap GUI Users’ Guide. While many users love Zenmap, others prefer
the traditional command-line approach to executing Nmap. Here are
detailed instructions for users who are unfamiliar with command-line
interfaces:

  1. Open Terminal, PowerShell, or Command Prompt. If you are using MSYS2, Cygwin, or WSL,
    the necessary commands differ slightly from those shown here.

  2. Change to the directory you installed Nmap into. You can skip this step if Nmap is already in your command path (the installer adds it there by default). Otherwise, type the following commands.

    c:
    cd "\Program Files (x86)\Nmap"
    
  3. Execute nmap.exe. Figure 2.1 is a screen shot showing a simple example.

Figure 2.1. Executing Nmap from a Windows command shell

Executing Nmap from a Windows command shell

If you execute Nmap frequently, you can add the Nmap directory
(c:\Program Files (x86)\Nmap by default) to your command execution path:

  1. Open the System Properties window to the Advanced tab by running SystemPropertiesAdvanced.exe.

  2. Click the Environment
    Variables
    button.

  3. Choose Path from the
    System variables section, then hit
    edit.

  4. Add a semi-colon and then your Nmap directory (e.g. c:\Program Files (x86)\Nmap) to the end of the value.

  5. Open a new command prompt and you should be able to execute a
    command such as nmap scanme.nmap.org from any directory.

Введение

Nmap (Network Mapper) — это один из самых мощных и популярных инструментов для сетевого сканирования и аудита безопасности. Он используется как профессионалами в области кибербезопасности, так и системными администраторами для анализа сетей, поиска открытых портов, определения активных хостов и выявления потенциальных уязвимостей. Но что делает Nmap таким незаменимым? Ответ прост: его гибкость, точность и широкий спектр возможностей.

Сканирование портов — это процесс проверки состояния портов на устройстве или в сети. Порты — это «точки входа» для данных, и их состояние (открыт, закрыт, фильтруется) может многое рассказать о безопасности системы. Например, открытый порт может указывать на работающую службу, которая может быть уязвима для атак.

Цель этой статьи — дать вам полное руководство по использованию Nmap для сканирования всех портов и анализа результатов. Мы рассмотрим установку, базовые и продвинутые команды, а также практические примеры. К концу статьи вы сможете уверенно использовать Nmap для своих задач.

Выделенные серверы и VPS/VDS в Нидерландах

Оффшорные, доступные, стабильные. Оплата в крипто.

Подробнее

nmap

Nmap был создан Гордоном Лионом (Fyodor) в 1997 году и с тех пор стал стандартом для сетевого сканирования. Этот инструмент используется для:

  • Сканирования портов: определение открытых, закрытых и фильтруемых портов.
  • Обнаружения хостов: поиск активных устройств в сети.
  • Определения служб: выявление служб, работающих на открытых портах, и их версий.
  • Анализа уязвимостей: использование скриптов NSE (Nmap Scripting Engine) для поиска уязвимостей.

Nmap применяется в различных сценариях:

  • Сетевой аудит: проверка конфигурации сети и фаерволов.
  • Тестирование на проникновение: поиск уязвимостей в сетевых устройствах.
  • Мониторинг сети: регулярное сканирование для выявления изменений.

Установка Nmap

Nmap поддерживается на большинстве операционных систем. Рассмотрим установку на Windows, macOS и Linux.

Установка на Windows

1. Перейдите на официальный сайт Nmap и скачайте установочный файл.
2. Запустите установщик и следуйте инструкциям.
3. После установки откройте командную строку и введите:

nmap --version

Если вы увидите версию Nmap, значит, установка прошла успешно.

Установка на macOS

Используйте Homebrew для установки:

brew install nmap

Установка на Linux

Для Debian/Ubuntu:

sudo apt install nmap

Для CentOS/RHEL:

sudo yum install nmap

Основы работы с Nmap

Nmap имеет простой синтаксис команд. Основная структура команды:

nmap [опции] [цель]

Пример простого сканирования:

nmap 192.168.1.1

Эта команда сканирует 1000 наиболее популярных портов на устройстве с IP-адресом 192.168.1.1.

Типы сканирования

  • TCP-сканирование (-sT): сканирует TCP-порты, устанавливая полное соединение.
  • SYN-сканирование (-sS): более быстрый и скрытный метод, который не завершает соединение.
  • UDP-сканирование (-sU): для сканирования UDP-портов, которые часто используются для DNS, DHCP и других служб.

Сканирование всех портов

Для сканирования всех портов (от 1 до 65535) используйте команду:

nmap -p- 192.168.1.1

Опция -p- указывает Nmap сканировать все порты. Для ускорения процесса можно добавить опцию -T4:

nmap -p- -T4 192.168.1.1

Это увеличит скорость сканирования, но может снизить точность.

Анализ результатов сканирования

После завершения сканирования Nmap выводит отчет. Пример:


PORT     STATE SERVICE
22/tcp   open  ssh
80/tcp   open  http
443/tcp  open  https

Здесь:

  • PORT: номер порта и протокол.
  • STATE: состояние порта (open, closed, filtered).
  • SERVICE: служба, работающая на порте.

Для детализации используйте опции -sV (определение версий служб) и -O (определение ОС):

nmap -sV -O 192.168.1.1

Продвинутые техники сканирования

Nmap поддерживает скрипты NSE (Nmap Scripting Engine), которые расширяют его функциональность. Например, для поиска уязвимостей используйте:

nmap --script vuln 192.168.1.1

Для обхода фаерволов можно использовать фрагментацию пакетов:

nmap -f 192.168.1.1

Безопасность и этика использования Nmap

Использование Nmap без разрешения владельца сети может быть незаконным. Всегда получайте разрешение перед сканированием. Как сказал известный эксперт по безопасности Брюс Шнайер:

«Безопасность — это процесс, а не продукт.»

Инструменты для визуализации результатов

Zenmap — это графический интерфейс для Nmap. Он позволяет визуализировать результаты сканирования и сохранять их в файлы (XML, CSV). Скачайте Zenmap с официального сайта.

Практические примеры и кейсы

Пример 1: Сканирование домашней сети

nmap 192.168.1.0/24

Эта команда сканирует все устройства в сети 192.168.1.0/24.

Пример 2: Сканирование веб-сервера

nmap -p 80,443 example.com

Частые ошибки и советы по оптимизации

  • Не используйте слишком высокую скорость сканирования (-T5), это может привести к ложным результатам.
  • Проверяйте, что у вас есть права администратора при сканировании.

Выводы

Мы изучили, как использовать Nmap для сканирования всех портов и анализа результатов. Вы узнали, как устанавливать Nmap, выполнять базовые и продвинутые команды, а также интерпретировать вывод. Регулярное сканирование сетей помогает поддерживать их безопасность и предотвращать угрозы.

FAQ

Как выбрать правильные опции для сканирования?

Начните с базовых команд, таких как nmap [цель], и постепенно добавляйте опции, такие как -sV или -O.

Что делать, если сканирование занимает слишком много времени?

Используйте опцию -T4 для ускорения, но помните, что это может снизить точность.

Дополнительные ресурсы

  • Официальная документация Nmap.
  • Книга «Nmap Network Scanning» от Fyodor.

Попробуйте ScaniteX бесплатно!

Автоматизированная платформа для сканирования открытых портов и обнаружения активных сервисов в режиме онлайн.

Начните 24ч пробный период (промокод FREE10), чтобы протестировать все функции сканирования для безопасности вашего бизнеса.

Получить бесплатный триал

Просмотров: 560

nmap logo

Nmap is a network mapping tool. It provides a range of powerful scanning options. Many network administrators use Nmap to scan open ports & services on a network, guessing the operating system on the targeted machine, monitoring hosts, and discovering different services with their version information. In this article, you will see how Nmap on windows works.

Nmap is free and open-source software that was created by Gordon Lyon. Nmap is utilized to find out hosts and services on a network by transmitting some packages over the targeted network. Nmap was once limited only to Linux operating systems, but now it is available for Windows and macOS too.

Note: If you want to use Nmap on Windows without the need of installing bare-metal Linux or a virtual machine utilizing the power of WSL 2, we have an entire tutorial series covering how to do that.

Table of Contents

  • Why should you use Nmap
  • Nmap Installation Process
  • Nmap features
  • Zenmap for Windows
  • Different scan types in Nmap
  • Scanning TCP/UDP ports with Nmap on windows
    • Scanning all ports
    • Scanning specific TCP ports within a range
    • Faster Scan option
    • Scanning TCP ports without a range
    • Scanning UDP ports within a range
    • Scanning all UDP ports
    • Scanning TCP/UDP at once within a specific range
  • Other common Nmap commands
    • Scanning OS & service detection
    • Detecting vulnerabilities using Nmap
    • Saving your Nmap results
    • Detecting Malware on the remote hosts
  • Conclusion

👀 This Tutorial has some related Articles!
👉 Part 1 – Nmap Basics
👉 Part 2 – Nmap Host Discovery
👉 Part 3 – Advanced Nmap Commands
👉 Part 4 – Nmap NSE Scripts
👉 Part 5 – Nmap on Windows

Why should you use Nmap

Nmap is a network mapping tool with a ton of other useful features. Many security researchers and pentester use this open-source tool. Nmap is also a favorite tool for both black and white hat hackers.

A hacker with good knowledge can create images of your network topology. Scanning your network can help you to make yourself more secure and spot the flaws in your system. You can check for any unauthorized devices that are connected to your network, you can find ports that are meant to be closed but are open for some reason, and to point out the users that are running any unauthorized services on your network.

Nmap Installation Process

Installing Nmap on Windows is extremely easy. You have to follow some short steps to use this powerful tool.

  1. Go to the following web address nmap.org/download.html and download the latest stable version
  2. Once the setup is downloaded from their website, now you have to browse to the downloaded “.exe” setup file. Right-click on the file and run it as an administrator.
  3. Now the installation process will start, read the license agreement thoroughly and only accept the license agreement if you agree, by clicking the “I agree” button.
  4. Now choose the components that you want to install with Nmap but choosing them all is recommended. Click on the “Next” button.
  5. The installation location for Nmap will be C:\Program Files (x86)\Nmap, but you can change the Installation folder to wherever you want. Now click on the “Install” button.
  6. Now the actual installation process will start, and all files will be extracted. Once it is done, your Nmap is ready to use now.

Nmap features

This powerful tool carries many features that can be used by a hacker to get a lot of information about their targeted machine.

  • Identify open ports.
  • Network Inventory.
  • Map a network.
  • Exploiting and finding a vulnerability.
  • Host uptime monitoring.
  • Network security audit.
  • Detecting OS.
  • Detect service and version.

Network Mapping – It can be beneficial for you to check the devices present on a network including all the routers, servers, and switches, and to verify how they are connected physically. Nmap on Windows has the capability to show a whole map of the network.

Nmap on Windows

Detecting OS – Nmap can also be used for OS footprinting. You can check the operating system running on your targeted device, including the vendor name and the version of the system. It can also give you an estimate for the ‘devices’ up-time.

Security Auditing – After footprinting the OS and knowing the applications running on the system, network managers now discover the vulnerability that can lead to specific flaws.

Discovering services – By using Nmap you can do more than just find hosts on the network, you can also check their behavior and whether they are acting as web servers or mail servers and information regarding the version of the software they are using.

Zenmap for Windows

Zenmap offers you a graphical user interface for all the tasks you would normally perform in Nmap by using the command line. Zenmap offers you some extraordinary features that you do not see in the classic Nmap, for example, a network topology map.

Nmap on Windows

You are provided with more options in this GUI version. You can save your scan results with the Nmap format (.nmap) or in the XML (.xml) format.

This incredible GUI of Nmap is available for Windows, and it is very beneficial for users who do not want to play with the CLI interface of Nmap.

Different scan types in Nmap

There are different types of scans that can be performed by using Nmap. The Nmap user performs these scans for various purposes.

TCP Scan

TCP scan performs a three-way handshake from your device to the targeted device. Someone with minimal effort can easily detect the TCP scan, and your IP address of the sender can be logged by the services efficiently.

UDP Scan

UDP is used to check whether there is any port that is listening for the upcoming requests on the targeted machine. You may get a false report in your scan results, as there is no mechanism to respond positively. The UPD scans can be used to uncover any hidden trojan or any RPC services. These scans are not very fast because the machines handle this kind of traffic slowly.

SYN Scan

It is a type of TCP scan. The syn packets are crafted by using Nmap itself, and this syn packet is used to initiate a TCP connection. Nmap results are based upon these special Syn packets. These packets themselves do not establish a connection, but they are utilized to produce scan results on Nmap.

ACK Scan

To check if ports are filtered or not, ACK scans are used. This type of scan can be beneficial if you want to check for the firewalls. If there is simple packet filtering, then it will allow an established connection with the help of ACK bit set.

FIN Scan

The FIN scan is most likely the SYN scan. If the targeted machine receives FIN input, then most of them will send the reset packet (RST) back.

NULL Scan

As the name suggests, the NULL scan sets all the header fields to zero (null). These kinds of packets are not authentic, and some of the targets do not know how to handle this packet. These targets could be your windows machine, and when you scan them using NULL packets, they produce undependable results.

XMAS Scan

XMAS scan has the same nature as the NULL scan, as both of these are hard to detect. The implementation of the TCP stack will prevent windows from responding to the Xmas scans. The XMAS scans are used to operate the FIN, URG, and PSH flag present in the TCP header.

RPC Scan

These kinds of scans are utilized to find the systems that reply to the RPC (Remote procedure call) services. It can allow the commands to run on a specific machine remotely. RPC services can also be used to run on many different ports; that’s why it becomes difficult to tell whether the RPC services are working or not. RPC scan should be done often to check the running RPC services.

IDLE Scan

From all of the above scans for Nmap on Windows or Linux, the IDLE scan is the stealthiest of them all. The attackers mostly use the IDLE scan for malicious attacks. Some specific conditions are necessary to perform this scan.

Scanning TCP/UDP ports with Nmap on windows

One of the best usages of Nmap is to scan ports on the network. By default, there are 1000 ports that Nmap can automatically scan, and you can change that port range according to your scan requirements.

Scanning all ports

In Nmap, we can specify the port range by using the “-p” option. The maximum or highest port number is 65535. If we want to scan all TCP ports, then we can use -p0-65535 option:

nmap -p- 127.0.0.1Code language: CSS (css)
Nmap on Windows

Scanning specific TCP ports within a range

In Nmap, we can specify the port range by using the “-p” option. The maximum or highest port number is 65535. If we want to scan all TCP ports, then we can use -p1-10 option:

nmap -p1-500 127.0.0.1Code language: CSS (css)
nmap specific TCP ports

Faster Scan option

If you want your scan to finish fast, then you can use the fast scan option. The regular scan will consume a lot of time, whereas a fast scan option will do it in less time. Use this option if your situation is not critical. You can use -T5 parameter for the quickest level scan of Nmap:

nmap -p- -T5 127.0.0.1Code language: CSS (css)
nmap fast scan

Scanning TCP ports without a range

There is another way of scanning TCP ports without specifying the range of ports. It will scan for the common 1000 ports:

nmap 127.0.0.1Code language: CSS (css)
nmap tcp scan

Scanning UDP ports within a range

In Nmap when you scan ports, TCP is scanned per default. In order to scan UDP ports, you have to specify the UDP scan in the statement. You can use -sU for scanning UDP ports.^:

nmap -sU -p 1-500 127.0.0.1Code language: CSS (css)
nmap specific UDP scan

Scanning all UDP ports

Scanning UDP without range is similar to scanning TCP without range. You use the same -p- option to scan UDP ports without specifying a range:

nmap -sU -p - -T5 127.0.0.1Code language: CSS (css)
nmap UDP all ports

👀 This Tutorial has some related Articles!
👉 How to get started in Cyber Security – The Complete Guide
👉 How to get started with Bug Bounties
👉 Terminal Customization Series
👉 Best Ethical Hacking Books
👉 Download Kali Linux Safe & Easy
👉 Best Ethical Hacking Tools
👉 Install VSCode on Kali Linux
👉 Dual Boot Kali Linux with Windows
👉 Install Kali Linux on VirtualBox – Complete Beginner Guide
👉 Top Things to do after installing Kali Linux
👉 WiFi Adapter for Kali Linux – The Ultimate Guide
👉 Nmap Beginner Guide Series
👉 Metasploit Tutorial Series
👉 Burp Suite Beginner Guide

Scanning TCP/UDP at once within a specific range

You can also scan both TCP/UDP by using a single statement. You have to use -sU for UDP ports and TCP ports ‘; you’ll use the -sT option:

nmap -sT -sU -p 1-500 127.0.0.1Code language: CSS (css)
nmap specific tcp and udp scan

Other common Nmap commands

There are a ton of commands that you cannot master in a day, but there are some common and useful commands that you can use instantly. These commands are the basic ones. You can go advance, once you have learned the basics of it. Have a look at some of the most common yet useful commands.

Scanning OS & service detection

You can enable service detection and OS detection by using the -A option and to allow fast scanning we can use -T4 with it. Here is an example:

nmap -T4 -A 127.0.0.1Code language: CSS (css)
nmap OS detection

Detecting vulnerabilities using Nmap

One of the most significant Nmap features that allow you to go beyond your expectations is that you can use the “Nmap scripting engine” through which you can execute a set of pre-defined scripts, and you can write your won scripts as well in Lua programming language.

NSE (Nmap Scripting Engine) is essential to use when you have to perform a full vulnerability scan. You have to automate everything during a scan that’s why we use scripts.

To perform a vulnerability test, you can use:

nmap -T5 --script vuln 127.0.0.1Code language: CSS (css)
nmap vulnerability scan

Saving your Nmap results

You can save your results after the scan in Nmap. You can save them in two formats i.e Nmap (.nmap) format or XML (.xml) format. While exporting the results from the Nmap, you have to use the following command statement:

nmap -oN output.txt example.comCode language: CSS (css)
nmap save output text

You can export the results as an XML document as well:

nmap -oX output.xml example.comCode language: CSS (css)
nmap save output xml

Detecting Malware on the remote hosts

Nmap has the capability to run different tests to check for Malware or backdoor on some popular operating system services like Proftpd, IRC, SMTP, and SMB. It also offers a module that checks for any malicious file signs in Virustotal databases.

To perform a very simple & straight scan:

nmap -sV --script http-malware-host 127.0.0.1Code language: CSS (css)
nmap malware scan

By using ‘google’s malware check:

nmap -p 80 --script HTTP-google-malware 127.0.0.1Code language: CSS (css)
nmap google malware scan

Conclusion

Nmap for Windows is one of the most important and robust tools used for gathering network information and performing operations using NSE. You can stick to Nmap and learn more about it to be a professional. The significance of this tool is enough that every security researcher has heard its name. If you want to be a cybersecurity expert, then you should consider using this tool that carries a lot of flexibility and strength in itself. This beginner’s guide will surely help you to make your base strong so that you can move to advance steps. We also have a series of Nmap tutorials, you may have a look at it to learn more about it here.

👀 This Tutorial has some related Articles!
👉 Part 1 – Nmap Basics
👉 Part 2 – Nmap Host Discovery
👉 Part 3 – Advanced Nmap Commands
👉 Part 4 – Nmap NSE Scripts
👉 Part 5 – Nmap on Windows

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как загрузиться с установочной флешки windows 10
  • Как сделать пользователя администратором в windows 10 без прав администратора
  • Не работает микрофон на ноутбуке на windows 10 в танках
  • Список пользователей windows 10 powershell
  • Утилита для уменьшения windows