Introducción a Nmap y escaneo de puertos

Esta publicación revisa uso de Nmap y demuestra varios casos de uso usando Opciones de línea de comando de Nmap. Esta publicación utiliza escenarios prácticos cubiertos en dos Salas TryHackMe.

habitación uno

Habitación dos

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

Obtenga notas del certificado OSCP

COMPTIA Security+ Study Notes

Intro to Port Scanning with Nmap

Cuando se trata de piratería, el conocimiento es poder. Cuanto más conocimiento tenga sobre un sistema o red de destino, más opciones tendrá disponibles. Esto hace que sea imperativo que se lleve a cabo una enumeración adecuada antes de realizar cualquier intento de explotación.

Digamos que nos han asignado una IP (o varias direcciones IP) para realizar una auditoría de seguridad. Antes de hacer cualquier otra cosa, debemos tener una idea del “paisaje” que estamos atacando. Lo que esto significa es que necesitamos establecer qué servicios se ejecutan en los objetivos. Por ejemplo, quizás uno de ellos esté ejecutando un servidor web y otro esté actuando como controlador de dominio de Windows Active Directory. La primera etapa para establecer este “mapa” del paisaje es algo llamado escaneo de puertos. 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.

Cada computadora tiene un total de 65535 puertos disponibles; sin embargo, muchos de ellos están registrados como puertos estándar. Por ejemplo, un servicio web HTTP casi siempre se puede encontrar en el puerto 80 del servidor. Se puede encontrar un servicio web HTTPS en el puerto 443. NETBIOS de Windows se puede encontrar en el puerto 139 y SMB se puede encontrar en el puerto 445. Es importante tener en cuenta; sin embargo, especialmente en una configuración CTF, no es extraño que incluso estos puertos estándar sean modificados, lo que hace aún más imperativo que realicemos una enumeración adecuada en el objetivo.

Cuando escaneo de puertos con Nmap, existen tres tipos básicos de escaneo. Estos son:

  • tcp Conectar escaneos (-calle)
  • SYN Escaneos “medio abiertos” (-SS)
  • UDP Escaneos (-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 --scanflags. For instance, if you want to set SYN, RST, and FIN simultaneously, you can do so using --scanflags RSTSYNFIN.

Además, existen varios tipos de escaneo de puertos menos comunes, algunos de los cuales también cubriremos (aunque con menos detalle). Estos son:

  • tcp Escaneos nulos (-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 Escaneos 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 Escaneos de Navidad (-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 mayoría de ellos (a excepción de UDP escaneos) se utilizan para propósitos muy similares; sin embargo, la forma en que funcionan difiere entre cada escaneo. Esto significa que, si bien es probable que uno de los tres primeros escaneos sea su opción en la mayoría de las situaciones, vale la pena tener en cuenta que existen otros tipos de escaneo.

Nmap Scripting Engine

El Nmap Scripting Engine (NSE) es una adición increíblemente poderosa a Nmap, que amplía considerablemente su funcionalidad. Los scripts NSE están escritos en el lua lenguaje de programación y se puede utilizar para hacer una variedad de cosas: desde buscar vulnerabilidades hasta automatizar exploits para ellas. El NSE es particularmente útil para el reconocimiento; sin embargo, vale la pena tener en cuenta cuán extensa es la biblioteca de scripts.

Hay muchas categorías disponibles. Algunas categorías útiles incluyen:

  • seguro:- No afectará al objetivo
  • intruso:- No seguro: es probable que afecte al objetivo
  • vuln: - Escanear en busca de vulnerabilidades
  • explotar:- Intento de explotar una vulnerabilidad
  • autenticación:- Intente omitir la autenticación para servicios en ejecución (por ejemplo, iniciar sesión en un ftp servidor de forma anónima)
  • bruto: - Intento de fuerza bruta de credenciales para ejecutar servicios
  • descubrimiento:- Intente consultar los servicios en ejecución para obtener más información sobre la red (por ejemplo, consultar un servidor SNMP).

Puede encontrar una lista más exhaustiva aquí.

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 y -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

Evasión de firewall con Nmap

Hay una variedad de otros conmutadores que Nmap considera útiles para evadir el firewall. No los analizaremos en detalle, sin embargo, se pueden encontrar aquí.

You can also check out Firewall y Evasión IDS con NMAP | Practical Scenario post.

Los siguientes interruptores son de particular interés:

  • -F:- Se utiliza para fragmentar los paquetes (es decir, dividirlos en partes más pequeñas), lo que hace menos probable que los paquetes sean detectados por un firewall o identificación.
  • Una alternativa a -F, pero proporcionando más control sobre el tamaño de los paquetes: --mtu <number>, acepta un tamaño máximo de unidad de transmisión para usar en los paquetes enviados. Este debe ser múltiplo de 8.
  • --scan-delay <time>ms:- se utiliza para agregar un retraso entre los paquetes enviados. Esto es muy útil si la red es inestable, pero también para evadir cualquier activador de firewall/IDS basado en el tiempo que pueda haber.
  • --badsum: - esto se utiliza para generar sumas de verificación no válidas para paquetes. Cualquier pila TCP/IP real descartaría este paquete; sin embargo, los cortafuegos pueden responder automáticamente, sin molestarse en comprobar la suma de comprobación del paquete. Como tal, este conmutador se puede utilizar para determinar la presencia de 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 -mi 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.

Respuestas a las preguntas de la sala uno

¿Qué estructuras de red se utilizan para dirigir el tráfico a la aplicación correcta en un servidor?
 

¿Cuántos de estos están disponibles en cualquier computadora habilitada para la red?

 

[Investigación] ¿Cuántos de ellos se consideran “muy conocidos”? (Estos son los números "estándar" mencionados en la tarea)

Primero, ¿cómo se accede al menú de ayuda?

 

A menudo denominado escaneo sigiloso, ¿cuál es el primer interruptor listado para un 'Syn Scan'?

 

No es tan útil, pero ¿qué tal un 'Escaneo UDP'?

 

¿Qué pasa con la detección del sistema operativo?

 

¿Qué tal la detección de la versión del servicio?

 

A la mayoría de las personas les gusta ver algún resultado para saber que su escaneo realmente está haciendo cosas. ¿Qué es el indicador de detalle?

 

¿Qué pasa con "muy detallado"? (Un favorito personal)

 

A veces, guardar los resultados en un formato de documento común puede ser muy útil para generar informes. ¿Cómo guardamos los resultados en XML ¿formato?

 
Los escaneos agresivos pueden ser agradables cuando otros escaneos simplemente no obtienen el resultado que usted desea y realmente no le importa qué tan "ruidoso" sea, ¿cuál es el interruptor para habilitar esto?
 

¿Cómo configuro el tiempo al nivel máximo, a veces llamado "Insane"?

 

¿Qué pasa si quiero escanear un puerto específico?

 

¿Qué tal si quiero escanear todos los puertos?

 

¿Qué sucede si quiero habilitar el uso de una secuencia de comandos del motor de secuencias de comandos nmap? Para esto, simplemente incluya la primera parte del cambio sin la especificación de qué script ejecutar.

 

¿Qué sucede si quiero ejecutar todos los scripts fuera de la categoría de vulnerabilidad?

 

¿Qué interruptor debo incluir si no quiero hacer ping al host?

Sigamos adelante y comencemos con lo básico y realicemos un escaneo de sincronización en el cuadro provisto. ¿Cuál será este comando? sin the host IP address?

 

Después de escanear esto, ¿cuántos puertos encontramos abiertos por debajo de 1000?

 

¿Qué protocolo de comunicación se proporciona para estos puertos después del número de puerto?

 

Realice un análisis de detección de la versión del servicio, ¿cuál es la versión del software que se ejecuta en el puerto 22?

 
Realice un escaneo agresivo, ¿qué indicador no está configurado en los resultados para el puerto 80?
 

Realice un análisis de script de las vulnerabilidades asociadas con este cuadro. ¿A qué ataque de denegación de servicio (DOS) es susceptible este cuadro? Responda con el nombre de la vulnerabilidad que aparece como título de la sección en el resultado del análisis. Un escaneo de vulnerabilidad puede tardar un poco en completarse. En caso de que se quede atascado, la respuesta a esta pregunta se proporciona en la sugerencia; sin embargo, es bueno ejecutar este escaneo y acostumbrarse a usarlo, ya que puede ser invaluable.

 

Respuestas a la sala dos.

¿Qué RFC define el comportamiento apropiado para el tcp ¿protocolo?

 

Si un puerto está cerrado, ¿qué bandera debería enviar el servidor para indicarlo?

Hay otros dos nombres para un escaneo SYN, ¿cuáles son?
 

¿Puede Nmap utilizar un escaneo SYN sin permisos de Sudo (S/N)?

Si un puerto UDP no responde a un escaneo de Nmap, ¿cómo se marcará?
 

Cuando un UDP El puerto está cerrado, por convención el objetivo debe enviar de vuelta un mensaje de "puerto inalcanzable". ¿Qué protocolo utilizaría para hacerlo?

¿Cuál de los tres tipos de escaneo mostrados utiliza la bandera URG?
 

¿Por qué se utilizan generalmente los escaneos NULL, FIN y Xmas?

 

cual comun SO ¿Puede responder a un escaneo NULL, FIN o Xmas con un RST para cada puerto?

¿Cómo realizaría un barrido de ping en la red 172.16.xx (máscara de red: 255.255.0.0) usando Nmap? (notación CIDR)
¿En qué idioma están escritas las escrituras NSE?
 

¿Qué categoría de guiones sería una muy ¿Es mala idea ejecutarlo en un entorno de producción?

¿Qué argumento opcional puede ftp-anon.nse ¿Toma del guión?

Busque scripts "smb" en el /usr/share/nmap/scripts/ directorio utilizando cualquiera de los métodos demostrados.
¿Cuál es el nombre de archivo del script que determina el subyacente? SO del servidor SMB?
 

Lea este guión. ¿De qué depende?

¿Qué protocolo simple (y en el que se confía con frecuencia) a menudo se bloquea, lo que requiere el uso del -Pn ¿cambiar?
 

[Investigación] ¿Qué conmutador Nmap le permite agregar una longitud arbitraria de datos aleatorios al final de los paquetes?

¿El objetivo (MACHINE_IP)responder a solicitudes ICMP (ping) (S/N)?

 

Realice un escaneo navideño en los primeros 999 puertos del objetivo: ¿cuántos puertos se muestran abiertos o filtrados?

 

Se da una razón para esto: ¿cuál es?

Nota: La respuesta estará en los resultados de su escaneo. Piense detenidamente qué interruptores utilizar y lea la sugerencia antes de pedir ayuda.

 

Realizar un tcp Escaneo SYN en los primeros 5000 puertos del objetivo: ¿cuántos puertos se muestran abiertos?

 

Abra Wireshark (ver criílico Sala Wireshark para obtener instrucciones) y realice una tcp Conecte el escaneo al puerto 80 en el objetivo y monitoree los resultados. Asegúrate de entender lo que está pasando.

 

Implementar el ftp-anón guión contra la caja. ¿Puede Nmap iniciar sesión exitosamente en el ftp servidor en el puerto 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)

norte

How many devices can see the ARP Request?

4

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

norte

¿Cuál es la primera dirección IP que Nmap escanearía si usted la proporcionara? 10.10.12.13/29 como tu objetivo?

10.10.12.8

¿Cuántas direcciones IP escaneará Nmap si proporciona el siguiente rango? 10.10.0-255.101-125

6400

¿Cuál es el tipo de paquete que envió la computadora1 antes del ping?

ARP Request

¿Cuál es el tipo de paquete que recibió la computadora1 antes de poder enviar el ping?

ARP Response

¿Cuántas computadoras respondieron a la solicitud de 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)

norte

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

3

¿Cuál es la opción requerida para decirle a Nmap que use ICMP Timestamp para descubrir hosts en vivo?

-PP

¿Cuál es la opción requerida para indicarle a Nmap que use la máscara de dirección ICMP para descubrir hosts en vivo?

-PM

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

-PE

¿Qué escaneo de ping TCP no requiere una cuenta privilegiada?

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

Queremos que Nmap emita una búsqueda DNS inversa para todos los hosts posibles en una subred, con la esperanza de obtener información a partir de los nombres. ¿Qué opción deberíamos agregar?

-R

Room Answers | TryHackMe Nmap Basic Port Scans

¿Qué servicio utiliza el puerto UDP 53 de forma predeterminada?

DNS

Which service uses TCP port 22 by default?

SSH

¿Cuántos estados portuarios considera Nmap?

6

¿Qué estado portuario es el más interesante para descubrir como pentester?

OPEN

¿Qué 3 letras representan la bandera de reinicio?

RST

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

syn

Inicie la máquina virtual. Abra AttackBox y ejecute nmap -sT MACHINE_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

¿Cuál es la suposición de Nmap sobre el servicio recién instalado?

pop3

Inicie la máquina virtual. Se ha instalado algún software de servidor nuevo desde la última vez que lo escaneamos. En AttackBox, use la terminal para ejecutar nmap -sS MACHINE_IP. ¿Cuál es el nuevo puerto abierto?

6667

¿Cuál es la suposición de Nmap sobre el nombre del servicio?

irc

Inicie la máquina virtual. En AttackBox, use la terminal para ejecutar nmap -sU -F -v MACHINE_IP. A new service has been installed since the last scan. What is the UDP port that is now open?

53

¿Cuál es el nombre del servicio según Nmap?

domain

¿Cuál es la opción para escanear todos los puertos TCP entre 5000 y 5500?

-p5000-5500

¿Cómo puede asegurarse de que Nmap ejecute al menos 64 sondas en paralelo?

–min-parallelism=64

¿Qué opción agregarías para hacer que Nmap sea muy lento y paranoico?

-T0

Room Answers | Nmap Advanced Port Scans

En un escaneo nulo, ¿cuántas banderas se establecen en 1?

0

En un escaneo FIN, ¿cuántas banderas se establecen en 1?

1

En un escaneo navideño, ¿cuántas banderas se establecen en 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

En el escaneo de Maimon, ¿cuántas banderas se colocan?

2

En el escaneo de ventana TCP, ¿cuántas banderas se configuran?

1

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

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

¿Cuál es el nuevo número de puerto que apareció?

443

¿Hay algún servicio detrás del número de puerto recién descubierto? (sí/no)

norte

¿Qué necesitas agregar al comando? sudo nmap MACHINE_IP para que el escaneo parezca como si viniera de la dirección IP de origen 10.10.10.11 en lugar de su dirección IP?

-S 10.10.10.11

¿Qué necesitas agregar al comando? sudo nmap MACHINE_IP para que el escaneo parezca como si viniera de las direcciones IP de origen 10.10.20.21 y 10.10.20.28 además de su dirección IP?

-D 10.10.20.21,10.10.20.28

Si el segmento TCP tiene un tamaño de 64, y -ff Se está utilizando esta opción, ¿cuántos fragmentos de IP obtendrá?

4

Descubrió una impresora de red poco utilizada con la dirección IP 10.10.5.5, y decides usarlo como zombie en tu escaneo inactivo. ¿Qué argumento debería agregar a su comando Nmap?

-sI 10.10.5.5

Inicie AttackBox si aún no lo ha hecho. Después de asegurarse de haber finalizado la VM de la Tarea 4, inicie la VM para esta tarea. Espere a que se cargue por completo, luego abra la terminal en AttackBox y use Nmap con nmap -sS -F --razón MACHINE_IP to scan the VM. What is the reason provided for the stated port(s) being open?

syn-ack

Full Video WalkThroughs

Acerca del Autor

Creo notas de ciberseguridad, notas de marketing digital y cursos online. También brindo consultoría de marketing digital que incluye, entre otros, SEO, Google y meta anuncios y administración de CRM.

Ver Artículos