Categorías
Hacking

Gotta Catch ‘Em All!: Bypass BadUSB restrictions

Author: Joel Serna Moreno
@JoelSernaMoreno (IoT/ICS Pentest Engineer – Titanium Industrial Security)

1.- Introduction

Since the presentation of BadUSB at Blackhat USA 2014 and, subsequently, the development of specific devices to perform these attacks, a number of tools and solutions designed to detect and block BadUSB attacks have emerged. These tools range from specialised software to physical devices that protect USB ports from malicious attacks. However, the effectiveness and reliability of these solutions vary considerably.

This article aims to show some of the security measures that these tools apply in an attempt to block BadUSB attacks, analyse them in depth to understand and identify the checks they make to decide whether a device is malicious and, consequently, show how to bypass these protection tools.

For a better understanding of the security measures implemented in the tools, we will categorise evasions into 3 levels of difficulty: low, medium and high. This categorisation is based on the possible difficulty an attacker may have in implementing and evading security tools. Free and/or open source tools will be used to explain the different existing protections. Finally, we will test the evasions implemented by the attacker against professional/commercial protection software.

Additionally, we will show the process performed to evade any anti-badUSB tool in a real environment, without the attacker knowing the type or model of USB peripheral connected to the victim’s computer or the protection software installed on the computer.

2.- Device used

We are going to implement USB protection evasions in a low-cost device called Evil Crow Cable Pro.

Evil Crow Cable Pro is a BadUSB and hardware keylogger device in mobile phone cable format. Inside it uses a RP2040 microcontroller, which, by modifying its firmware, will allow us to implement the security evasions and apply them in a real environment.

For more information and purchase links, please consult the device repository:

https://github.com/joelsernamoreno/EvilCrowCable-Pro

Figure 1 – Evil Crow Cable Pro device

3.- Bypass BadUSB restrictions (I): low level

In order to implement evasions, we must first understand how the connection between a USB device and a computer works.

When a USB device is connected to a computer, an identification process takes place. This identification is based on the information provided by the USB device regarding its interface class, interface subclass and interface protocol. These parameters help the system to understand the functionality of the device and how it should interact with it.

  • Interface class: The USB interface class indicates the primary function of the device. For example, a USB storage device will have an interface class that identifies it as a Mass Storage Device, while a keyboard or mouse will have an interface class corresponding to Human Interface Device (HID). Other examples of interface classes include audio devices, printers, cameras, etc. In the case of the USB devices we are interested in, the class value that identifies an HID device in the interface descriptors is 3.

  • Interface subclass: During the early development of the HID specification, subclasses were intended to identify protocols specific to the different types of HID class devices. While this reflects the model currently in use by the industry (all devices use protocols defined by similar popular devices), this approach was too restrictive. That is, devices would have to fit into defined subclasses and could not offer any functionality beyond that supported by the subclass. Consequently, the HID class does not use subclasses to define most protocols. Instead, a device of the HID class identifies its data protocol and the type of data provided within its Report descriptor. The HID class driver loads and parses the Report descriptor as soon as it detects the device. HID class devices use the Subclass part to indicate whether they support a predefined protocol for mouse or keyboard devices (e.g. the device can be used without the operating system being started).

  • Interface Protocol: A field in the USB interface description that indicates the protocol used by the interface. For HID devices, common values are as follows:

    • Keyboard: 1

    • Mouse: 2

Nowadays there are many tools that allow us to block or allow USB devices on a computer. One example is USBDeview. This tool allows us to block unwanted USB devices by telling it the interface class, interface subclass and interface protocol of the USB devices we want to block. Additionally, it allows us to allow the USB devices we want to use via vendor ID (VID) and product ID (PID).

  • Vendor ID: is a unique code that identifies a device’s manufacturer

  • Product ID: is a unique code that identifies the product.

For the first evasion, let’s assume that the victim’s computer has software installed and configured that blocks the use of keyboards and mice except for a specific keyboard that is normally used by the victim.

If we connect a USB keyboard other than the allowed one or a BadUSB device, USBDeview will block the use of the keyboard and/or the execution of our malicious device. The following evidence shows that the allowed USB keyboard is not blocked but the malicious device is blocked:

Figure 2 – Evil Crow Cable Pro block

To bypass this protection, if an attacker knows the VID and PID, he can configure the malicious device with this data to bypass the protection. This bypass has been categorised as low level because it is very easy to modify this data on any malicious device or any Arduino-based device.

In this case, Evil Crow Cable Pro makes use of the TinyUSB stack, which allows us to easily modify the vendor ID and product ID by adding the following lines of code in the firmware:

Figure 3 – Set VID & PID

By programming the malicious device with this configuration, we managed to impersonate the allowed USB keyboard:

Figure 4 – Bypass USBDeview

Clearly, without having physical access to the allowed USB keyboard, it is quite difficult for an attacker to know the vendor ID and product ID allowed in the protection software to pre-program the malicious device. A solution to this problem will be shown throughout this article.

The following video shows the bypass of USBDeview using Evil Crow Cable Pro configured with the vendor ID and product ID allowed by the protection tool:

4.- Bypass BadUSB restrictions (II): medium level

Due to the easy evasion of tools that block/allow a USB device via vendor ID and product ID, some security researchers proposed several more secure and difficult to evade solutions that allow blocking BadUSB devices.

One of them is the «Patito Hunter» tool developed by Miguel Angel Arroyo (@miguel_arroyo76).

https://github.com/curiozity/patitohunter

The Patito Hunter tool proposes to block the famous Rubber Ducky USB device or any other BadUSB device based on the number of interfaces a USB device has.

The research carried out by Miguel Angel Arroyo summarises that an original USB keyboard will always have a minimum of two interfaces (even three interfaces if it is a keyboard with an integrated touchpad). In contrast, a BadUSB device such as the USB Rubber Ducky will only have a single interface.

The following image shows a comparison of the interfaces that Evil Crow Cable Pro or a BadUSB device and three original USB keyboards can have:

Figure 5 – Interface comparison

At a glance we can see that Evil Crow Cable Pro has a single interface while the three original keyboards have two interfaces each.

The Patito Hunter tool is open source, which allows us to look at the code to see exactly how it applies the BadUSB device blocking:

Figure 6 – BadUSB check

Briefly, the tool obtains the descriptors and the number of interfaces of the connected USB device and displays the information on the terminal. It then calls the check_for_badusb function to identify whether the connected device is a BadUSB device or a legitimate device.

If we connect Evil Crow Cable Pro to a computer where the tool is running, we can see that the tool blocks the device correctly because it has a single interface:

Figure 7 – Evil Crow Cable Pro block

To bypass this protection we can modify the Evil Crow Cable Pro firmware to have more than one interface. Evil Crow Cable Pro uses a specific library based on TinyUSB that allows you to add multiple interfaces quite easily:

Figure 8 – Set two interfaces

Patito Hunter only checks the number of interfaces that a USB device has, but does not check the type of each interface as other tools that we will see later do. So, it is not necessary to know the type of interfaces of a allowed device, by configuring our malicious device to have more than one interface is enough to bypass this tool:

Figure 9 – Bypass PatitoHunter

The following video shows Patito Hunter bypassing using Evil Crow Cable Pro configured with more than one interface:

Unlike Miguel Angel Arroyo with his Patito Hunter tool, other researchers propose to block BadUSB devices based on the typing speed of a person or a malicious device.

BadUSB devices are capable of sending keystrokes much faster than a person. According to Wikipedia and other public sources, they indicate that the average (moderate-fast) typing speed of a person is 1 keystroke every 100 milliseconds.

Tools like BadUSB-Detection or DuckHunt propose to block any USB device if it sends each keystroke with a delay of less than 30/35 milliseconds.

https://github.com/armoured-ape/BadUSB-Detection

https://github.com/pmsosa/duckhunt

If we connect a BadUSB device to any of these tools it will be blocked because the delay between each keystroke sent is less than 30/35 milliseconds:

Figure 10 – BadUSB speed block

This security measure is very interesting because BadUSB devices seek to execute malicious commands on a computer in a very fast way to prevent the victim from stopping the attack mid-execution.

Still, even though we have a much more limited attack due to the speed of command execution, it is possible to bypass this protection in several ways. In the case of bypass BadUSB-Detection, we have to configure our malicious device so that there is a 30 millisecond delay between each keystroke. In the case of the DuckHunt tool we have to configure our malicious device in the same way, but this time with a delay of 35 milliseconds between each keystroke.

Knowing this allows us to configure the malicious device specifically for each tool, but… what if the attacker does not know the keystroke delay settings of the tool installed on the computer? This is where a specific functionality of Evil Crow Cable Pro comes into play.

It was mentioned at the beginning of the article that Evil Crow Cable Pro is based on the RP2040 microcontroller. Unlike other microcontrollers such as Atmega32U4 or Attiny85, the RP2040 microcontroller has two cores that can be programmed to perform different tasks. This is why Evil Crow Cable Pro is a Hardware Keylogger as well as a BadUSB device:

Figure 11 – Evil Crow Cable Pro cores

Evil Crow Cable Pro is programmed to use the first core to identify itself as a keyboard and send keystrokes to a computer. Additionally, the second core of the RP2040 is used as a USB Host so that Evil Crow Cable Pro can be a hardware keylogger and record keystrokes made by a victim on their keyboard. In short, Evil Crow Cable Pro can act as a Man In The Middle (MITM) device between the victim’s computer and the victim’s USB keyboard. There are several ways to do this attack:

Figure 12 – Evil Crow Cable Pro MITM

To bypass the write speed protection without knowing the keystroke delay configured in the protection tool, it is possible to modify the Evil Crow Cable Pro firmware to get an approximation of the victim’s write speed by using the USB Host and the victim’s keyboard keystroke log. Evil Crow Crow Cable Pro will automatically configure itself with a specific delay based on the victim’s typing speed to bypass protection and execute a payload without being blocked:

Figure 13 – Calculate delay between keystrokes

The following video shows how Evil Crow Cable Pro records the victim’s keystrokes, calculates the write speed and executes a payload on the victim’s computer without being blocked:

5.- Bypass BadUSB restrictions (III): high level

We have seen some tools that propose to block BadUSB attacks by allowing or blocking the device according to its VID, PID, number of interfaces or write speed, and we have also seen how to bypass these protections in a fairly simple way. However, we can also find much more advanced tools that can do additional checks to identify whether a USB device is allowed or has to be blocked:

  • idVendor: vendor ID, defines the vendor of the USB device

  • idProduct: product ID, defines the product from a vendor

  • bInterfaceClass: USB interface class

  • bInterfaceSubClass: USB interface sub class

  • bDeviceProtocol: USB device protocol

  • bConfigurationValue: current USB configuration

  • serial: serial number of the device

  • manufacturer: manufacturer of device

  • product: product name string

  • connect_type: hotplug: external USB device, direct: internal USB device

  • bcdDevice: USB protocol version

  • speed: USB speed value

  • bNumConfigurations: the number of available USB configurations

  • bNumInterfaces: Number of available interfaces in active configuration

  • bInterfaceNumber: interface number

  • bNumEndpoints: number of endpoints for the interface

If in a real environment we find a tool that does all these checks, it is quite difficult for an attacker to know all this information in order to pre-program the malicious device. Additionally, we may also encounter tools that do some additional checks that have not been mentioned above.

So what can we do to bypass something like this? The first thing to know is that in the end, all protection tools have to rely on some descriptor or configuration provided by the original keyboard.

If an attacker manages to spoof 100% (or almost) the original keyboard allowed by the protection software, the attacker will be able to bypass any type of tool without needing to know which tool is installed on the victim’s computer or the checks that the tool makes.

This is where the Evil Crow Cable Pro USB Host comes into play again. The idea of the attack is to get all the information and settings that an original keyboard sends to the computer, after which Evil Crow Cable Pro will automatically configure itself to completely impersonate the original keyboard.

A basic example can be done with the USBDeview tool, let’s assume that the tool is configured to block all keyboards except a keyboard with a specific vendor ID and product ID. If an attacker wants to bypass this protection without knowing that USBDeview is installed on the victim’s machine and without knowing the vendor ID and product ID of the original allowed keyboard, he can perform the following attack:

  1. The attacker tries to connect Evil Crow Cable Pro and the execution of the payload is blocked by the protection tool (in this case USBDeview).

  1. The attacker disconnects the original USB allowed keyboard from the victim computer and connects it to the USB Host of the Evil Crow Cable Pro.

 

  1. Evil Crow Cable Pro clones the original USB keyboard, then the attacker disconnects the original USB keyboard from the Evil Crow Cable Pro USB Host.

 

  1. The attacker disconnects Evil Crow Cable Pro from the victim computer and reconnects it to apply the original keyboard spoofing.

 

  1. The payload is executed on the victim’s computer.

 

The following image shows the basic information of an original USB keyboard (including vendor ID and product ID) captured by the malicious device:

Figure 14 – Basic information

Just as it is possible to get the basic information of an original USB keyboard, our malicious device can also get absolutely all the configuration of the keyboard, including number of interfaces, types and descriptors of each interface, etc; and self-configure itself to do a complete impersonation:

Figure 15 – Advanced information

By getting all the information from the USB keyboard allowed with the Evil Crow Cable Pro USB Host, we can modify the firmware to automatically configure our malicious device and impersonate the allowed USB keyboard. Now let’s look at this attack in more professional/commercial tools.

6.- Bypass BadUSB restrictions (IV): professional/commercial software

Now we are going to use keyboard impersonation to bypass some professional/commercial tools.

  • 1.- Kaspersky Endpoint Security

The first tool we are going to analyze is Kaspersky Endpoint Security antivirus. This antivirus contains a specific module called BadUSB Prevention that proposes to block BadUSB attacks by asking a pin code every time a USB device is connected to the computer, it should be noted that for the USB device to be allowed, the pin code must be entered with the USB keyboard that we want to use on the computer.

Figure 16 – BadUSB Prevention module

The first weakness of this protection is that the pin code is only requested once. As soon as the user authorises the USB device, the protection software does not ask for the pin code again even if the computer is completely rebooted.

Because of this, an attacker can bypass the protection if he knows the USB device allowed in the protection software or can perform a complete impersonation of the allowed device as we have seen in the previous section. After analyzing Kaspersky’s BadUSB Prevention module, we have identified that in order to allow or block a connected USB device it performs the following checks:

  • Vendor ID/Product ID

  • Serial number

  • Number of interfaces (checks number, but does not check type)

Additionally, Kaspersky’s protection software identifies if the connected USB device has a serial port. Original keyboards will never have a serial port like Evil Crow Cable Pro or any arduino-based device can have. So, we have to keep in mind that to bypass this tool we have to disable the serial port of our malicious device.

Considering the 3 checks it performs, making use of the keyboard cloning and spoofing method we have seen in the previous section, an attacker can easily bypass this tool due to the fact that it only asks for the pin once. This way, by spoofing the original allowed keyboard, our malicious device will be able to execute payloads on the victim machine.

In case there is no USB device allowed, Evil Crow Cable Pro is a hardware keylogger. If we use a weaponized USB keyboard and the victim plugs it into his computer, we can execute the payload after the victim has entered the security pin with our weaponized keyboard.

  • 2.- CoSoSys Endpoint Protector

The second software we are going to analyse is CoSoSys Endpoint Protector. This software is very similar to USBDeview, it allows you to whitelist/blacklist to block or allow USB devices.

Figure 17 – Endpoint Protector

Like Kaspersky Endpoint Security, CoSoSys Endpoint Protector checks the Vendor ID, Product ID and the number of interfaces, but adds an additional check. In addition to checking the number of interfaces a USB device has, it also checks the device’s interface types, which makes bypass a bit more elaborate.

To bypass this tool the procedure is the same as we have seen in the previous tool, if an attacker manages to 100% impersonate the original keyboard allowed he can easily bypass the tool.

  • 3.- ManageEngine Device Control Plus

Finally, let’s look at Manage Engine’s Device Control Plus software.

Figure 18 – Device Control Plus

Unfortunately this software is the least secure of all the software we have looked at in this article. Device Control Plus only checks the Vendor ID and Product ID, it does not check the number of interfaces, type or other descriptors as we have seen above.

To bypass this tool the procedure is the same, by spoofing the allowed USB keyboard it is possible to run our payload on the victim’s machine.

7.- Conclusions

In this article we have seen how to bypass some BadUSB attack protections that can be found in open source software developed by security researchers and «professional/commercial» software.

In short, most protection software allows and/or blocks a USB device by checking the «malicious» device against the allowed USB device itself. As attackers, by successfully cloning and impersonating the allowed USB device we manage to bypass most of these tools, even without knowing which protection tool is installed on the victim’s computer.

To provide a more reliable solution, there are specific hardware devices that can protect our computers from these attacks, for example the AuthUSB SafeDoor device.

Figure 19 – AuthUSB SafeDoor

This type of device has its own operating system and different protection and antivirus tools that scan any type of USB device connected to the device, blocking any direct attack on your computer.

Happy Hacking 😀

Categorías
Hacking Networking Services - Software Web Applications

Nuevo máster en Burp Professional para Hacking web

Desde el día de hoy, se encuentra disponible el nuevo máster en Burp Professional para Hacking web. Es una formación online completa sobre todas las opciones disponibles en la versión profesional de Burp Suite.

Vas a aprender a configurar las herramientas de Burp Professional con el máximo nivel de detalle.

Burp Suite no es una herramienta gratuita, pero, si te dedicas al pentesting web, merece la pena adquirir la licencia y, de hecho, muchas empresas tienen licencias de este producto para sus trabajadores.

Dado que llevo usando Burp Professional en mi día a día desde hace mucho tiempo, he decidido publicar este máster, el cual es un trabajo completo en el que condenso mi experiencia usando esta suite y las mejores prácticas para:

  1. No perder tiempo lanzando escaneos que no generan resultados, afinando al máximo el escáner para reducir falsos positivos
  2. Configurar el entorno de la mejor manera posible y evitar quebraderos de cabeza con los issues generados, las extensiones y otros elementos.
  3. Aplicar los ajustes necesarios para que no se «cuelgue» cada vez que tengas que realizar alguna tarea pesada
  4. Conocer cuáles son las extensiones más potentes y cómo usarlas. Aprenderás a usar las extensiones que sí te aportan beneficios en tus auditorias o CTFs. No perderás tiempo probando cientos de extensiones que, en definitiva, hacen todas lo mismo.
  5. Aprende a aplicar técnicas de Hacking avanzadas utilizando Burp Professional sobre entornos de pruebas de nivel medio y avanzado.

El máster es completamente práctico, lo vas a poder replicar en tu propio entorno mediante aplicaciones web vulnerables por diseño y en los laboratorios de nivel experto disponibles en la Web Security Academy de PortSwigger.

Se encuentra dividido en 3 niveles:

  1. Burp Professional para Hacking web – Nivel 1: Tools
  2. Burp Professional para Hacking web – Nivel 2: Escaneos
  3. Burp Professional para Hacking web – Nivel 3: Advanced

Cada uno de estos niveles se puede adquirir por separado, pero te aconsejo que te apuntes a los tres mediante el máster completo porque te sale más económico y, así, no te pierdes ninguna de las lecciones de cada nivel.

El máster se encuentra en preventa a partir de hoy y hasta el 19 de mayo del 2024.

Si te interesa, te recomiendo que te apuntes para que puedas aprovechar el descuento, tanto en el máster completo como en cada uno de los niveles.

 


 

Recuerda que tienes todas las formaciones y packs de The Hacker Way.

Las mejores formaciones en castellano que podrás encontrar y al mejor precio.
No lo digo yo, puedes ver las reseñas en el sitio web y ahora también en TrustPilot.

Cientos de alumnos han aprovechado los cursos online en THW y tú también podrías ser uno de ellos: https://thehackerway.es/cursos

Además de los cursos y la comunidad THW, tenemos el Plan Starter en Ciberseguridad (PSC) con el que no solo aprenderás Hacking ético, además adquirirás las habilidades necesarias para trabajar en el sector de la ciberseguridad.
Ya seas un trabajador en activo o busques una primera experiencia, en THW podemos ayudarte mediante el plan PSC. Tienes más información en este enlace

¡Un saludo y Happy Hack!
Adastra.

Categorías
Ciberinteligencia devsecops Hacking

Plan Starter en Ciberseguridad (PSC): El AntiBootcamp de la ciberseguridad

Hace algunas semanas hemos lanzado el AntiBootcamp en ciberseguridad, el cual, como ya te imaginas, es todo lo contrario a lo que te ofrecen algunas academias que se dedican a vender ese tipo de formación.

¿En qué consiste?

Es un plan de formación completo y personalizado con enfoque en dos áreas: La parte técnica, que consiste en aprender lo necesario para trabajar en ciberseguridad y, por otro lado, la parte de «soft-skills» con ejercicios prácticos para que aprendas a destacar en los procesos de selección o mejores tu estrategia profesional.

Esto es a grandes rasgos.

Para que entiendas el motivo de llamarle «AntiBootcamp», mira la siguiente tabla comparativa:

Academias en España vendiendo Bootcamps en ciberseguridad AntiBootcamp en ciberseguridad: Plan PSC de THW
€7000 o más Menos de €2000.
3 meses y se olvidan de ti. Si te he visto no me acuerdo. 6 meses y te acompañamos hasta que consigas el objetivo planteado en el momento de iniciar el plan.
Clases a 20 personas o más. Acceso a todos los cursos disponibles en THW y los que se publicarán a lo largo del 2024. Además, tendrás clases personalizadas, uno a uno, sobre los temas en los que necesites refuerzo.
Conocimientos básicos sobre informática y nociones generales de ciberseguridad. Conocimientos específicos sobre lo que necesitas para trabajar en ciberseguridad.
Las personas que trabajan en esos sitios carecen de contactos y experiencia en el sector de la ciberseguridad. Se dedican a venderte el curso, ese es su negocio.
Buscan un sitio donde impartir las clases, un profesor para que te enseñe cosas básicas y te cobran un pastizal por ello. No hacen nada más por ti. 
Tenemos contactos y experiencia contrastada en el sector. Nos dedicamos a proyectos reales en ciberseguridad y desarrollo seguro, no solo a vender cursos.
Se acabó el bootcamp.
«Lo has hecho muy bien, campeón, ¡enhorabuena!
Te deseamos suerte en tu búsqueda de trabajo»
Te preparamos para afrontar entrevistas técnicas y de RRHH mediante ejercicios y simulaciones con profesionales del sector.
/dev/null Estaremos a tu lado hasta que consigas el objetivo planteado al inicio del programa. El plan no termina hasta que alcances el objetivo previsto.
/dev/null Si es lo que deseas, te ponemos en contacto con empresas que buscan un perfil como el tuyo y te ayudamos con ejercicios prácticos orientados a mejorar tus «soft skills».
/dev/null Acompañamiento continuo y ayuda en la elaboración de tu estrategia profesional.

Seguramente con esto te queda mucho más clara la finalidad del «AntiBootcamp» y lo que nos diferencia del resto de academias que venden cursos caros.

Vas a contar con profesionales del sector de RRHH que te ayudarán a identificar tus debilidades y fortalezas en los procesos de selección.

Te diremos exactamente cómo mejorar tu empleabilidad y, no solo eso, nos implicaremos contigo desde el primer momento.

Si en tu caso concreto, buscas mejorar profesionalmente, ya sea en la empresa en la que te encuentras o quieres moverte a otra, también podemos ayudarte a conseguir ese objetivo.

Si te interesa, pero tienes dudas, puedes ponerte en contacto enviando un email a info@thehackerway.com

Por último, cerramos esta convocatoria del plan el 30 de abril del 2024, por lo que te recomiendo que te apuntes o contactes con nosotros antes de esa fecha.

Aunque la convocatoria cierra ese día, una vez adquieres el PSC, puedes elegir la fecha de inicio con total flexibilidad.

¡Nos vemos en el AntiBootcamp!

¡Un saludo y Happy Hack!
Adastra.