Introduzione a Nmap e Portscanning

Questo post recensisce utilizzo di Nmap e dimostra vari casi d'uso utilizzando Opzioni della riga di comando di Nmap. Questo post utilizza scenari pratici trattati in due Prova le stanze HackMe.

Stanza uno

Stanza due

In another update, we also covered the answers for the below rooms:

Ottieni le note sul certificato OSCP

COMPTIA Security+ Study Notes

Intro to Port Scanning with Nmap

Quando si tratta di hacking, la conoscenza è potere. Più conoscenze hai su un sistema o una rete di destinazione, più opzioni hai a disposizione. Ciò rende imperativo che venga effettuata una corretta enumerazione prima che venga effettuato qualsiasi tentativo di sfruttamento.

Supponiamo che ci sia stato assegnato un IP (o più indirizzi IP) su cui eseguire un controllo di sicurezza. Prima di fare qualsiasi altra cosa, dobbiamo farci un’idea del “paesaggio” che stiamo attaccando. Ciò significa che dobbiamo stabilire quali servizi sono in esecuzione sugli obiettivi. Ad esempio, forse uno di essi esegue un server Web e un altro funge da controller di dominio Windows Active Directory. La prima fase per stabilire questa “mappa” del paesaggio è qualcosa che si chiama scansione delle porte. When a computer runs a network service, it opens a networking construct called a “port” to receive the connection.  Ports are necessary for making multiple network requests or having multiple services available. For example, when you load several webpages at once in a web browser, the program must have some way of determining which tab is loading which web page. This is done by establishing connections to the remote webservers using different ports on your local machine. Equally, if you want a server to be able to run more than one service (for example, perhaps you want your webserver to run both HTTP and HTTPS versions of the site), then you need some way to direct the traffic to the appropriate service. Once again, ports are the solution to this. Network connections are made between two ports – an open port listening on the server and a randomly selected port on your own computer. For example, when you connect to a web page, your computer may open port 49534 to connect to the server’s port 443.

Ogni computer ha un totale di 65535 porte disponibili; tuttavia, molte di queste sono registrate come porte standard. Ad esempio, un servizio Web HTTP può essere trovato quasi sempre sulla porta 80 del server. Un servizio Web HTTPS può essere trovato sulla porta 443. Windows NETBIOS può essere trovato sulla porta 139 e SMB può essere trovato sulla porta 445. È importante notare; tuttavia, soprattutto in un'impostazione CTF, non è inaudito che anche queste porte standard vengano modificate, rendendo ancora più imperativo eseguire un'enumerazione appropriata sul target.

Quando scansione delle porte con Nmap, sono disponibili tre tipi di scansione di base. Questi sono:

  • TCP Collega scansioni (-sT)
  • Scansioni SYN “semiaperte” (-sS)
  • UDP Scansioni (-sU)
  • TCP ACK Scan: As the name implies, an ACK scan will send a TCP packet with the ACK flag set. Use the -sA option to choose this scan. 
  • Window Scan: Another similar scan is the TCP window scan. The TCP window scan is almost the same as the ACK scan; however, it examines the TCP Window field of the RST packets returned. On specific systems, this can reveal that the port is open. You can select this scan type with the option -sW
  • Custom Scan: If you want to experiment with a new TCP flag combination beyond the built-in TCP scan types, you can do so using --scanflag. For instance, if you want to set SYN, RST, and FIN simultaneously, you can do so using --scanflags RSTSYNFIN.

Inoltre esistono diversi tipi di scansione delle porte meno comuni, alcuni dei quali verranno trattati (anche se in modo meno dettagliato). Questi sono:

  • TCP Scansioni null (-sN) : The null scan does not set any flag; all six flag bits are set to zero. You can choose this scan using the -sN option. A TCP packet with no flags set will not trigger any response when it reaches an open port, as shown in the figure below. Therefore, from Nmap’s perspective, a lack of reply in a null scan indicates that either the port is open or a firewall is blocking the packet.
  • TCP Scansioni FIN (-sF): The FIN scan sends a TCP packet with the FIN flag set. You can choose this scan type using the -sF option. Similarly, no response will be sent if the TCP port is open. Again, Nmap cannot be sure if the port is open or if a firewall is blocking the traffic related to this TCP port.
  • TCP Scansioni di Natale (-sX):
  • The Xmas scan gets its name after Christmas tree lights. An Xmas scan sets the FIN, PSH, and URG flags simultaneously. You can select Xmas scan with the option -sX. Like the Null scan and FIN scan, if an RST packet is received, it means that the port is closed. Otherwise, it will be reported as open|filtered.

La maggior parte di questi (ad eccezione di UDP scansioni) vengono utilizzati per scopi molto simili, tuttavia, il modo in cui funzionano differisce tra ciascuna scansione. Ciò significa che, sebbene una delle prime tre scansioni sia probabilmente la tua scelta nella maggior parte delle situazioni, vale la pena tenere presente che esistono altri tipi di scansione.

Nmap Scripting Engine

IL Nmap Scripting Engine (NSE) è un'aggiunta incredibilmente potente a Nmap, estendendone notevolmente le funzionalità. Gli script NSE sono scritti nel file Lua linguaggio di programmazione e può essere utilizzato per fare una varietà di cose: dalla scansione delle vulnerabilità all'automazione degli exploit. L'NSE è particolarmente utile per la ricognizione, tuttavia vale la pena tenere presente quanto è estesa la libreria di script.

Sono disponibili molte categorie. Alcune categorie utili includono:

  • sicuro:- Non influenzerà il bersaglio
  • invadente:- Non sicuro: potrebbe influenzare il bersaglio
  • vuln:- Scansiona le vulnerabilità
  • impresa:- Tentativo di sfruttare una vulnerabilità
  • aut:- Tentativo di ignorare l'autenticazione per i servizi in esecuzione (ad esempio, accedere a un FTP server in modo anonimo)
  • bruto:- Tentativo di forzare le credenziali per l'esecuzione dei servizi
  • scoperta:- Tentare di interrogare i servizi in esecuzione per ulteriori informazioni sulla rete (ad esempio interrogare un server SNMP).

Un elenco più esaustivo può essere trovato Qui.

Host Discovery with Nmap

We can ping every IP address on a target network and see who would respond to our ping (ICMP Type 8/Echo) requests with a ping reply (ICMP Type 0). Simple, isn’t it? Although this would be the most straightforward approach, it is not always reliable. Many firewalls block ICMP echo; new versions of MS Windows are configured with a host firewall that blocks ICMP echo requests by default. Remember that an ARP query will precede the ICMP request if your target is on the same subnet.

To use ICMP echo request to discover live hosts, add the option -PE. (Remember to add -sn if you don’t want to follow that with a port scan.) 

TCP SYN Ping

We can send a packet with the SYN (Synchronize) flag set to a TCP port, 80 by default, and wait for a response. An open port should reply with a SYN/ACK (Acknowledge); a closed port would result in an RST (Reset). In this case, we only check whether we will get any response to infer whether the host is up. The specific state of the port is not significant here.

If you want Nmap to use TCP SYN ping, you can do so via the option -PS followed by the port number, range, list, or a combination of them. For example, -PS21 will target port 21, while -PS21-25 will target ports 21, 22, 23, 24, and 25. Finally -PS80,443,8080 will target the three ports 80, 443, and 8080.

Privileged users (root and sudoers) can send TCP SYN packets and don’t need to complete the TCP 3-way handshake even if the port is open, as shown in the figure below. Unprivileged users have no choice but to complete the 3-way handshake if the port is open.

TCP ACK Ping

As you have guessed, this sends a packet with an ACK flag set. You must be running Nmap as a privileged user to be able to accomplish this. If you try it as an unprivileged user, Nmap will attempt a 3-way handshake.

By default, port 80 is used. The syntax is similar to TCP SYN ping. -PA should be followed by a port number, range, list, or a combination of them. For example, consider -PA21-PA21-25 E -PA80,443,8080. If no port is specified, port 80 will be used.

UDP Ping

Finally, we can use UDP to discover if the host is online. Contrary to TCP SYN ping, sending a UDP packet to an open port is not expected to lead to any reply. However, if we send a UDP packet to a closed UDP port, we expect to get an ICMP port unreachable packet; this indicates that the target system is up and available.

Enumeration with Nmap

e mentioned the different techniques we can use for scanning in Task 1. Before we explain each in detail and put it into use against a live target, we need to specify the targets we want to scan. Generally speaking, you can provide a list, a range, or a subnet. Examples of target specification are:

  • list: MACHINE_IP scanme.nmap.org example.com will scan 3 IP addresses.
  • range: 10.11.12.15-20 will scan 6 IP addresses: 10.11.12.1510.11.12.16,… and 10.11.12.20.
  • subnet: MACHINE_IP/30 will scan 4 IP addresses.

You can also provide a file as input for your list of targets, nmap -iL list_of_hosts.txt

Evasione del firewall con Nmap

Esistono numerosi altri switch che Nmap considera utili per l'evasione del firewall. Non li esamineremo in dettaglio, tuttavia è possibile trovarli Qui.

You can also check out Firewall ed evasione IDS con NMAP | Practical Scenario post.

Particolarmente degni di nota sono i seguenti interruttori:

  • -F:- Utilizzato per frammentare i pacchetti (ovvero dividerli in parti più piccole) rendendo meno probabile che i pacchetti vengano rilevati da un firewall o ID.
  • Un'alternativa a -F, ma fornendo un maggiore controllo sulla dimensione dei pacchetti: --mtu <number>, accetta una dimensione massima dell'unità di trasmissione da utilizzare per i pacchetti inviati. Questo dovere essere un multiplo di 8.
  • --scan-delay <time>ms:- utilizzato per aggiungere un ritardo tra i pacchetti inviati. Ciò è molto utile se la rete è instabile, ma anche per eludere eventuali trigger firewall/IDS basati sul tempo che potrebbero essere in atto.
  • --badsum:- questo viene utilizzato per generare checksum non validi per i pacchetti. Qualsiasi stack TCP/IP reale eliminerebbe questo pacchetto, tuttavia i firewall potrebbero potenzialmente rispondere automaticamente, senza preoccuparsi di controllare il checksum del pacchetto. Pertanto, questo interruttore può essere utilizzato per determinare la presenza di un firewall/IDS.

Spoofed Scan with Nmap

In brief, scanning with a spoofed IP address is three steps:

  1. Attacker sends a packet with a spoofed source IP address to the target machine.
  2. Target machine replies to the spoofed IP address as the destination.
  3. Attacker captures the replies to figure out open ports.

In general, you expect to specify the network interface using -e and to explicitly disable ping scan -Pn. Therefore, instead of nmap -S SPOOFED_IP MACHINE_IP, you will need to issue nmap -e NET_INTERFACE -Pn -S SPOOFED_IP MACHINE_IP to tell Nmap explicitly which network interface to use and not to expect to receive a ping reply. It is worth repeating that this scan will be useless if the attacker system cannot monitor the network for responses.

When you are on the same subnet as the target machine, you would be able to spoof your MAC address as well. You can specify the source MAC address using --spoof-mac SPOOFED_MAC. This address spoofing is only possible if the attacker and the target machine are on the same Ethernet (802.3) network or same WiFi (802.11).

Spoofing only works in a minimal number of cases where certain conditions are met. Therefore, the attacker might resort to using decoys to make it more challenging to be pinpointed. The concept is simple, make the scan appear to be coming from many IP addresses so that the attacker’s IP address would be lost among them. As we see in the figure below, the scan of the target machine will appear to be coming from 3 different sources, and consequently, the replies will go the decoys as well.

Fragemented Scan with Nmap

Nmap provides the option -F to fragment packets. Once chosen, the IP data will be divided into 8 bytes or less. Adding another -F (-f -f O -ff) will split the data into 16 byte-fragments instead of 8. You can change the default value by using the --mtu; however, you should always choose a multiple of 8.

To properly understand fragmentation, we need to look at the IP header in the figure below. It might look complicated at first, but we notice that we know most of its fields. In particular, notice the source address taking 32 bits (4 bytes) on the fourth row, while the destination address is taking another 4 bytes on the fifth row. The data that we will fragment across multiple packets is highlighted in red.

Description of port scanning output with Nmap

  1. Open: indicates that a service is listening on the specified port.
  2. Closed: indicates that no service is listening on the specified port, although the port is accessible. By accessible, we mean that it is reachable and is not blocked by a firewall or other security appliances/programs.
  3. Filtered: means that Nmap cannot determine if the port is open or closed because the port is not accessible. This state is usually due to a firewall preventing Nmap from reaching that port. Nmap’s packets may be blocked from reaching the port; alternatively, the responses are blocked from reaching Nmap’s host.
  4. Unfiltered: means that Nmap cannot determine if the port is open or closed, although the port is accessible. This state is encountered when using an ACK scan -sA.
  5. Open|Filtered: This means that Nmap cannot determine whether the port is open or filtered.
  6. Closed|Filtered: This means that Nmap cannot decide whether a port is closed or filtered.

Risposte alle domande dalla stanza uno

Quali costrutti di rete vengono utilizzati per indirizzare il traffico verso la giusta applicazione su un server?
 

Quanti di questi sono disponibili su qualsiasi computer abilitato alla rete?

 

[Ricerca] Quanti di questi sono considerati “noti”? (Questi sono i numeri “standard” menzionati nell’attività)

Innanzitutto, come si accede al menu di aiuto?

 

Spesso definita scansione invisibile, qual è il primo interruttore elencato per una "scansione sincronizzata"?

 

Non altrettanto utile, ma che ne dici di una "Scansione UDP"?

 

E il rilevamento del sistema operativo?

 

Che ne dici del rilevamento della versione del servizio?

 

Alla maggior parte delle persone piace vedere qualche output per sapere che la loro scansione sta effettivamente facendo qualcosa, qual è il flag di verbosità?

 

Che ne dici di "molto prolisso"? (Un preferito)

 

A volte salvare l'output in un formato di documento comune può essere davvero utile per la creazione di report su come salvare l'output xml formato?

 
Le scansioni aggressive possono essere utili quando altre scansioni semplicemente non ottengono l'output desiderato e non ti interessa davvero quanto sei "rumoroso", qual è l'interruttore per abilitarle?
 

Come faccio a impostare il timing al livello massimo, a volte chiamato "Insane"?

 

E se volessi scansionare una porta specifica?

 

Che ne dici se volessi scansionare ogni porta?

 

Cosa succede se desidero abilitare l'utilizzo di uno script dal motore di scripting nmap? Per questo basta includere la prima parte dello switch senza specificare quale script eseguire.

 

Cosa succede se voglio eseguire tutti gli script fuori dalla categoria di vulnerabilità?

 

Quale opzione dovrei includere se non voglio eseguire il ping dell'host?

Andiamo avanti e iniziamo con le basi ed eseguiamo una scansione sincronizzata sulla scatola fornita. Quale sarà questo comando? senza the host IP address?

 

Dopo aver eseguito la scansione, quante porte troviamo aperte sotto le 1000?

 

Quale protocollo di comunicazione viene fornito per queste porte dopo il numero di porta?

 

Esegui una scansione per il rilevamento della versione del servizio, qual è la versione del software in esecuzione sulla porta 22?

 
Esegui una scansione aggressiva, quale flag non è impostato nei risultati per la porta 80?
 

Esegui una scansione dello script delle vulnerabilità associate a questa scatola, a quale attacco Denial of Service (DOS) è suscettibile questa scatola? Rispondi con il nome della vulnerabilità fornito come titolo della sezione nell'output della scansione. Il completamento di una scansione vulnerabile può richiedere del tempo. Nel caso in cui rimani bloccato, la risposta a questa domanda è stata fornita nel suggerimento, tuttavia, è bene eseguire comunque questa scansione e abituarsi a usarla poiché può essere preziosa.

 

Risposte alla stanza due

Quale RFC definisce il comportamento appropriato per il TCP protocollo?

 

Se una porta è chiusa, quale flag dovrebbe inviare il server per indicarlo?

Esistono altri due nomi per una scansione SYN, quali sono?
 

Nmap può utilizzare una scansione SYN senza i permessi Sudo (S/N)?

Se una porta UDP non risponde ad una scansione Nmap, come verrà contrassegnata?
 

Quando un UDP la porta è chiusa, per convenzione la destinazione dovrebbe restituire un messaggio di "porta irraggiungibile". Quale protocollo utilizzerebbe per farlo?

Quale dei tre tipi di scansione mostrati utilizza il flag URG?
 

Perché vengono generalmente utilizzate le scansioni NULL, FIN e Xmas?

 

Quale comune sistema operativo può rispondere ad una scansione NULL, FIN o Xmas con un RST per ogni porta?

Come eseguiresti un ping sweep sulla rete 172.16.xx (Netmask: 255.255.0.0) utilizzando Nmap? (Notazione CIDR)
In quale lingua sono scritti gli script NSE?
 

Quale categoria di script sarebbe a molto cattiva idea eseguirlo in un ambiente di produzione?

Quale argomento opzionale può essere utilizzato da ftp-anon.nse prendere la sceneggiatura?

Cerca gli script "smb" nel file /usr/share/nmap/scripts/ directory utilizzando uno dei metodi dimostrati.
Qual è il nome file dello script che determina il sottostante sistema operativo del server PMI?
 

Leggi questo script. Da cosa dipende?

Il quale protocollo semplice (e spesso utilizzato) viene spesso bloccato, richiedendo l'uso del file -Pn interruttore?
 

[Ricerca] Quale switch Nmap ti consente di aggiungere una lunghezza arbitraria di dati casuali alla fine dei pacchetti?

L'obiettivo (MACCHINA_IP)rispondere alle richieste ICMP (ping) (S/N)?

 

Esegui una scansione di Natale sulle prime 999 porte del target: quante porte risultano aperte o filtrate?

 

C'è una ragione per questo: qual è?

Nota: La risposta sarà nei risultati della scansione. Pensa attentamente a quali interruttori utilizzare e leggi il suggerimento prima di chiedere aiuto!

 

Eseguire a TCP Scansione SYN sulle prime 5000 porte del target: quante porte risultano aperte?

 

Apri Wireshark (vedi Quello di Cryillic Sala Wireshark per istruzioni) ed eseguire a TCP Collega la scansione alla porta 80 del bersaglio, monitorando i risultati. Assicurati di capire cosa sta succedendo.

 

Distribuire il ftp-anon sceneggiatura contro la scatola. Nmap può accedere con successo al file FTP server sulla porta 21? (Sì/No)

 Room Answers | TryHackMe Nmap Live Host Discovery

How many devices can see the ARP Request?

4

Did computer6 receive the ARP Request? (Y/N)

N

How many devices can see the ARP Request?

4

Did computer6 reply to the ARP Request? (Y/N)

N

Qual è il primo indirizzo IP che Nmap scansionerebbe se lo fornissi 10.10.12.13/29 come obiettivo?

10.10.12.8

Quanti indirizzi IP verranno scansionati da Nmap se fornisci il seguente intervallo 10.10.0-255.101-125

6400

Qual è il tipo di pacchetto inviato dal computer1 prima del ping?

ARP Request

Qual è il tipo di pacchetto ricevuto dal computer1 prima di poter inviare il ping?

ARP Response

Quanti computer hanno risposto alla richiesta ping?

1

What is the name of the first device that responded to the first ARP Request?

Router

What is the name of the first device that responded to the second ARP Request?

computer5

Send another Ping Request. Did it require new ARP Requests? (Y/N)

N

How many devices are you able to discover using ARP requests?

3

Qual è l'opzione richiesta per dire a Nmap di utilizzare il timestamp ICMP per scoprire host live?

-PP

Qual è l'opzione richiesta per dire a Nmap di utilizzare la maschera di indirizzo ICMP per scoprire host live?

-PM

What is the option required to tell Nmap to use ICMP Echo to discover live hosts?

-PE

Quale scansione ping TCP non richiede un account privilegiato?

TCP SYN PING

Which TCP ping scan requires a privileged account?

TCP ACK PING

What option do you need to add to Nmap to run a TCP SYN ping scan on the telnet port?

-PS23

Vogliamo che Nmap effettui una ricerca DNS inversa per tutti i possibili host su una sottorete, sperando di ottenere alcune informazioni dai nomi. Quale opzione dovremmo aggiungere?

-R

Room Answers | TryHackMe Nmap Basic Port Scans

Quale servizio utilizza la porta UDP 53 per impostazione predefinita?

DNS

Which service uses TCP port 22 by default?

SSH

Quanti stati portuali considera Nmap?

6

Quale stato di porto è il più interessante da scoprire come pentester?

OPEN

Quali 3 lettere rappresentano il flag di ripristino?

RST

Which flag needs to be set when you initiate a TCP connection (first packet of TCP 3-way handshake)?

syn

Avvia la VM. Apri AttackBox ed esegui nmap -sT MACCHINA_IP via the terminal. A new service has been installed on this VM since our last scan. Which port number was closed in the scan above but is now open on this target VM?

110

Qual è l'ipotesi di Nmap riguardo al servizio appena installato?

pop3

Avvia la VM. Dall'ultima scansione è stato installato un nuovo software server. Su AttackBox, usa il terminale per eseguire nmap -sS MACCHINA_IP. Qual è la nuova porta aperta?

6667

Qual è l'ipotesi di Nmap riguardo al nome del servizio?

irc

Avvia la VM. Su AttackBox, usa il terminale per eseguire nmap -sU -F -v IP_MACCHINA. A new service has been installed since the last scan. What is the UDP port that is now open?

53

Qual è il nome del servizio secondo Nmap?

domain

Qual è l'opzione per scansionare tutte le porte TCP tra 5000 e 5500?

-p5000-5500

Come puoi garantire che Nmap eseguirà almeno 64 sonde in parallelo?

–min-parallelism=64

Quale opzione aggiungeresti per rendere Nmap molto lento e paranoico?

-T0

Room Answers | Nmap Advanced Port Scans

In una scansione nulla, quanti flag sono impostati su 1?

0

In una scansione FIN, quanti flag sono impostati su 1?

1

In una scansione di Natale, quanti flag sono impostati su 1?

3

Start the VM and load the AttackBox. Once both are ready, open the terminal on the AttackBox and use nmap to launch a FIN scan against the target VM. How many ports appear as open|filtered?

7

Repeat your scan launching a null scan against the target VM. How many ports appear as open|filtered?

7

Nella scansione Maimon, quanti flag sono impostati?

2

Nella scansione della finestra TCP, quanti flag sono impostati?

1

You decided to experiment with a custom TCP scan that has the reset flag set. What would you add after --scanflag

RST

The VM received an update to its firewall ruleset. A new port is now allowed by the firewall. After you make sure that you have terminated the VM from Task 2, start the VM for this task. Launch the AttackBox if you haven’t done that already. Once both are ready, open the terminal on the AttackBox and use Nmap to launch an ACK scan against the target VM. How many ports appear unfiltered?

4

Qual è il nuovo numero di porta apparso?

443

C'è qualche servizio dietro il numero di porta appena scoperto? (Sì/No)

N

Cosa devi aggiungere al comando sudo nmap MACHINE_IP per far apparire la scansione come se provenisse dall'indirizzo IP di origine 10.10.10.11 invece del tuo indirizzo IP?

-S 10.10.10.11

Cosa devi aggiungere al comando sudo nmap MACHINE_IP per far sì che la scansione appaia come se provenisse dagli indirizzi IP di origine 10.10.20.21 E 10.10.20.28 oltre al tuo indirizzo IP?

-D 10.10.20.21,10.10.20.28

Se il segmento TCP ha una dimensione di 64, e -ff viene utilizzata l'opzione, quanti frammenti IP otterrai?

4

Hai scoperto una stampante di rete usata raramente con l'indirizzo IP 10.10.5.5e decidi di usarlo come zombie nella tua scansione inattiva. Quale argomento dovresti aggiungere al tuo comando Nmap?

-sI 10.10.5.5

Avvia AttackBox se non l'hai già fatto. Dopo esserti assicurato di aver terminato la VM dall'attività 4, avvia la VM per questa attività. Attendi il caricamento completo, quindi apri il terminale sull'AttackBox e utilizza Nmap con nmap -sS -F --reason MACHINE_IP to scan the VM. What is the reason provided for the stated port(s) being open?

syn-ack

Full Video WalkThroughs

Circa l'autore

Creo note sulla sicurezza informatica, note di marketing digitale e corsi online. Fornisco anche consulenza di marketing digitale, inclusi ma non limitati a SEO, annunci Google e Meta e amministrazione CRM.

Visualizza articoli