You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

2 Días
5 Hrs
14 Min
37 Seg

Encapsulado de paquetes con Scapy

14/33
Resources

How to understand and execute Man-in-the-Middle attacks with Scapy?

A thorough understanding of how low-level Man-in-the-Middle (MITM) attacks work is essential for any cybersecurity professional. In this guide, we will learn how to execute such an attack using vulnerabilities found in routing protocols, specifically with the Scapy tool developed in Python. Scapy allows detailed packet control and provides a unique flexibility to design and modify traffic at a low level.

What is the RIP protocol and how can it be breached?

Before we dive into the operation of Scapy, it is crucial to discuss the Routing Information Protocol (RIP), which is used to automatically update routing tables in networks. Some features of the RIP protocol include:

  • Specific broadcast address: RIP sends updates to address 224.0.0.9.
  • Propagated information: Contains the advertised network address and its metric (distance in network hops).
  • Use of UDP protocol: Operates using the UDP protocol on port 520.

For an effective attack, we will analyze how RIP uses these features to send updates and thus intervene in its operation.

How to build custom packets with Scapy?

Scapy is a versatile tool that allows you to create, send and analyze packets on networks. To build a RIP packet manually, we follow the steps below:

  1. Start Scapy in Python mode: Use the interactive Python console to build the packets step by step.

  2. Building the network packet:

    from scapy.all import *
     # Creating an Ethernet frameether = Ether()
     # Creating the IP packet destined to the RIP broadcast addressip = IP(dst="224.0.0.0.9")
     # Defining the source and destination port in UDPudp = UDP(sport=520, dport=520)
     # Building and encapsulating the complete packetpacket packet =  ether/ip/udpsendp(packet,  iface="eth0").
  3. Sending the packet: Use the sendp command to send the packet through the appropriate network interface.

Upon completion of the build, the packet will be captured by a sniffer, showing the correctly structured ether, IP and UDP layers.

What are the best practices for building automated attacks?

The efficient use of tools such as Scapy not only allows the execution of security point tests but also the design of scripts that automate complex attacks:

  • Automation with scripts: Create scripts that react to specific packets, thus simplifying traffic management.
  • Integration with other tools: Design more robust attack structures by combining Scapy scripts with other security tools such as Ettercap.
  • Learn the basics of Python: Take advantage of courses such as Python at Platzi for better handling of Scapy and other automation libraries.

Conclusion

In summary, understanding how network packages are built and manipulated with tools like Scapy not only reinforces technical knowledge, but opens up a range of possibilities for creating customized and effective security projects. Mastering these concepts is essential for any professional interested in cybersecurity and network analysis. Continue to explore and hone your technical skills to stay ahead of the curve in this field.

Contributions 11

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

Para los que se preguntan como prevenir estos ataques:
-Configurar Passive interfaces en Routers (Permite decirle al protocolo de enrutamiento que evite enviar actualizaciones a determinada interfaz de red)
-Configuración de Autenticación de Protocolos (Permite que un determinado Router participe a compartir sus rutas por medio de una llave cifrada que solo los Administradores de Red deberían saber)

Aquí se puede ver claramente que estamos jugando con 3 capas del modelo OSI en Scapy
Enlace de datos

a = Ether() -> una trama ethernet
Red

b = IP (dir orgien (maquina), dir destino (broadcast rip),ttl(saltos al progarse(always 1))) -> un paquete IP
Transporte

c = UPD(puerto origen rip ,puerto destino rip 520) -> protocolo UDP capa de transporte
construir el encapsulado

packet = a/b/c
Se agrupa el contenido de la trama Ethernet

packet
<Ecabezado | Paquete IP | Payload del paquete IP>

sendp(packet,iface=‘eth0’) -> enviar el paquete por medio de la interface eth0

Encapsulado de paquetes con Scapy

Es una herramienta de bajo nivel construida con Python que nos permite hacer un encapsulado de paquetes y cambiar los parámetros de estos paquetes por aquellos que nosotros deseemos.

Para esto debemos tomar como referente el protocolo RIP (Routing Information Protocol) quien es el encargado de determinar la mejor ruta a seguir para la transmisión de paquetes.

  • Validar en Wireshark el protocolo RIP para encontrar: puertos, ips, broadcast ip, entre otra información que usaremos para construir los paquetes.

  • Accedemos a la herramienta Scapy por medio de la consola:

    scapy
    
  • Ahora, vamos a empezar con la configuración de los paquetes UDP:

    a = Ether()
    b = IP(src="192.168.10.101" , dst="224.0.0.9", ttl=1)
    c = UDP(sport=520,dport=520)
    packet = a/b/c
    sendp(packet,iface="eth0")
    
  • Validamos la aparición de un paquete UPD en el tráfico con Wireshark.

Scapy es un poderoso programa interactivo de manipulación de paquetes. Es capaz de falsificar o decodificar paquetes de una gran cantidad de protocolos, enviarlos por cable, capturarlos, emparejar solicitudes y respuestas, y mucho más. Puede manejar fácilmente la mayoría de las tareas clásicas como escanear, trazar rutas, probar, pruebas unitarias, ataques o descubrimiento de redes (puede reemplazar hping, 85% de nmap, arpspoof, arp-sk, arping, tcpdump, tshark, p0f, etc.). También funciona muy bien en muchas otras tareas específicas que la mayoría de las otras herramientas no pueden manejar, como enviar marcos no válidos, inyectar sus propios marcos 802.11, combinar técnicas (salto de VLAN + envenenamiento de caché ARP, decodificación de VOIP en canal encriptado WEP, … ), etc.

eso quiere decir que tambien se pueden modificar los protocolos tcp y modificar las banderas manualmente?

![](https://static.platzi.com/media/user_upload/lucgho-ec0ec988-efcd-4a06-84a3-fad4c9daa4a1.jpg)
Por si alguien no le sale nigún paquete de RIP en Wireshark en Kali Linux, deben instalarlo con el comando: sudo apt install frr frr-pythontools. PD: Deben tener uno de los Adaptadores de red en su MV de Kali a NAT para poder instalarlo. PD2: Cuando apagan la máquina para poder agregar un segundo adaptado de Red en Kali es muy probable que el archivo resolv.conf se borre y deban poner de nuevo lo siguiente: ![](https://static.platzi.com/media/user_upload/image-999a3bbd-c9aa-4695-824e-c377149bece5.jpg) Guardamos los cambios con CTRL + X --->y-->enter
El encapsulado de paquetes con **Scapy** proporciona una herramienta poderosa para la creación, manipulación y análisis de paquetes de red. Esto es útil para tareas de prueba de seguridad, análisis de tráfico de red y diagnóstico de problemas de red. La flexibilidad y capacidad de Scapy para interactuar con múltiples capas del modelo OSI lo convierte en una herramienta esencial para profesionales de la red y la seguridad.

Hola. Al parecer hay un error con una de las librerías de Python 3.9 y Scapy. Aparece el error: “FileNotFoundError: [Errno 2] No such file or directory: b’liblibc.a’”.

Posible solución: ejecutar en tu máquina Kali los siguientes comandos…

# cd /usr/lib/x86_64-linux-gnu/
# ln -s -f libc.a liblibc.a

Listo! Ahora intenta ejecutar nuevamente el comando scapy

Muy bien, excelente bibliografía.