Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

ts

gh
Human Interface Device Firewall Feasibility

Ri
ll
Fu
GIAC (GDSA) Gold Certification

ns
Author: Brian Davidson, bkdson@gmail.com
Advisor: Domenica Crognale

ai
et
rR
Accepted: July 24,2022

ho
Abstract

ut
,A
te
itu

The Human Interface Device Firewall (HID-F) will make the BadUSB attack far more
challenging to succeed while avoiding privacy intrusion by using machine learning
st

models paired with homomorphic encryption. Exploring the flaws of current BadUSB
In

defenses will develop a series of design principles that the HID-F must follow to avoid
the same pitfalls. Exploring essential features of an HID-F with research code and public
NS

code samples shows that an HID-F is a feasible new class of defensive cybersecurity
applications.
SA
e
Th
22
20
©

© 2022 The SANS Institute Author retains full rights.


ts
Human Interface Device Firewall Feasibility 2

gh

Ri
1. Introduction

ll
How could the malicious typed input from a keyboard be prevented from inputting

Fu
into a computer? Answering this question will also provide a solution to prevent the

ns
BadUSB attack. The proposed solution is a Human Interface Device Firewall (HID-F)

ai
that analyzes the typed content and blocks malicious content from entering the Host

et
Operating System’s applications.

rR
1.1. BadUSB Attack

ho
The BadUSB attack consists of a USB device inserted into a computer that inputs

ut
a payload into the same computer. That payload is composed of malicious keyboard

,A
commands. More recently, ransomware (Gatlan, 2022) has been a major payload as per
te
the FBI, but there is an extensive menu of other easily accessible payloads on GitHub
itu

(Hak5, 2022).
st
In

The following are some assumptions about the BadUSB attack. The purpose of
NS

these assumptions is to pose a real-world worst-case scenario.


SA

Assumptions:

• The target computer is running Windows as a host operating system.


e
Th

• The BadUSB typing is indistinguishable from human typing.


22

• The BadUSB device itself is indistinguishable from a USB Keyboard.


20

• The physical host is not accessible for hardware modification.


©

• Installing new USB Human Interface Devices is permitted for usability.

1.2. Current Defenses


Current defenses violate one or more of the assumptions listed above and thus
offer an inferior solution. Configuration-based defenses that disable USB Devices (Al-
Zarouni, 2006) render utilizing a USB keyboard unusable.

Physical presence trivializes hardware BadUSB defenses (Kyle Denney, 2019).


The physical presence of an attacker, a prerequisite of the attack, opens the door to a
physical bypass of hardware defenses.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 3

gh

Ri
At first glance, machine learning or other rules-based classification of non-human

ll
“typing” (Kyle Denney, 2019) seems effective. Experimentation or routing wirelessly to

Fu
a human such as with a Cactus WHID (Bongiorni, 2017), evades classification.

ns
A comprehensive research effort did not identify any defense that met the prior

ai
criteria. At first, some defenses seemed to come close, but source code analysis found

et
they fell short. The closest identified defense was BeamGun (Lospinoso, 2022). It fell

rR
short of the usability requirement by disallowing any new keyboards and can be evaded

ho
by having an attacking device appear to be an approved device (Dijkhuizen, 2018).

ut
The theme of all the defenses is that few of them consider the payload of

,A
keystrokes. Those who consider payload try to differentiate between a machine or a
te
human typing in the payload. None have proposed analyzing the payload itself
itu

comprehensively and solely to identify malicious payloads.


st
In

1.3. Proposed Solution


NS

The proposed solution will analyze the aggregated content of the USB keystrokes
to classify them as malicious or not malicious and then block the malicious payload. The
SA

HID-F conducts different analyses on these keystrokes, including sandbox analysis,


e

cryptoanalysis, machine learning, and signature matching. When the HID-F identifies a
Th

malicious payload, the ability to type further commands is disabled. It optionally sends an
22

alert to a central monitoring system, and the HID-F intercepts the attack before execution.
20

These are natural extensions of state-of-the-art network defense systems, such as


©

integrating machine learning with Zeek (Hoelzer, 2021). This same approach applies to
BadUSB defenses.

Utilizing stream ciphers with homomorphic encryption to operate only on cipher


text alleviates concerns such as confidentiality of typed contents. Any leaked credential
or valuable intellectual property would be a critical failure of the HID-F. The new
technique of homomorphic encryption has unlocked this new technological approach.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 4

gh

Ri
2. Threat

ll
The BadUSB attack vector is highly effective for delivering malicious payloads.

Fu
USB devices are required for usability to conduct business in the modern age. While

ns
laptop keyboards are usable, many modern businesses dock laptops with a monitor and

ai
USB keyboard. Wherever that docking occurs is an attack surface for BadUSB.

et

rR
2.1. Remote Work

ho
The pivot to hybrid and remote work has reduced the effectiveness of physical

ut
security to that of the remote worker (Pranggono, 2020). When there is one worker per

,A
worksite, the economy of scale of providing physical security to a limited number of
te
worksites breaks. It may often be cost-prohibitive to obtain the same level of physical
itu

security at an unofficial remote work site as an official business site.


st
In

Anyone who gains access to the remote workplace now has access to the USB
NS

ports of the device. Other human beings may cohabitate or be houseworkers at the remote
site. More people with access offer a broader social engineering attack surface that can
SA

now utilize the BadUSB attack.


e

Criminals, unethical industry adversaries, and state actors now have more options
Th

than ever to attempt malicious physical access to a computer.


22
20

2.2. Official Worksite


In-office physical security was already suffering from extreme complacency in a
©

pre-COVID-19 world (Frey, 2018). Now, physical office security has additional
challenges. Workers are less familiar with who belongs on the floor with or without
masks obscuring physical features. The timeless issue of not correctly displaying badges
worsens properly identifying unauthorized individuals in the building. Workers also are
more unfamiliar with the security posture of the office and may have difficulty adhering
to security policies.

Meanwhile, the incentive to conduct physical penetration tests has declined due to
the reduced physical footprint of workers. The cybersecurity industry has not published

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 5

gh

Ri
statistics on physical penetration test sales, but confidential discussions with industry

ll
insiders indicate that on-site physical penetration tests are often not occurring.

Fu
Coming out of a pandemic environment, we have lower adherence to

ns
cybersecurity policy and untested work sites. These sites are the original locale for

ai
BadUSB attacks and are now never easier to run.

et
rR
2.3. Human Risk

ho
The economic instability related to pandemics, recessions, and warfare
characteristic of a post-COVID-19 global environment has a clear human impact. When

ut
livelihood is at stake, bribery is much more likely in the business world (Afzali et al.,

,A
2022), which could also be generalized to the individual.
te
itu

Humans plug in USB sticks. These same people have been bribed into plugging in
st

USB sticks. These same people often plug in USB sticks that they find through
In

happenstance. Even more alarming, these same people will copy and paste commands on
NS

the internet to fix urgent problems when a pandemic downsized help desk might not be
immediately responsive – even bypassing the need for a BadUSB attack.
SA

A Human Interface Device Firewall mitigates each of these human risks.


e
Th

3. Current Defenses
22

The analysis of current BadUSB defense classes builds up a set of conditions that
20

the HID-F must comprehensively address. These defense classes are hardware, device
©

fingerprinting, machine typing detection, user interaction, and detecting malicious


processes. Even though these defenses are flawed, cybersecurity professionals should
consider utilizing them together as part of a defense-in-depth.

3.1. Hardware
Hardware-based defenses have grown less compelling in modern times.

Supply chain disruptions brought upon by just-in-time shipping result in


additional complexity in maintaining the compute inventory for a business. Adding a new
component to each device adds to the supply chain disruption risk. A delay in a hardware

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 6

gh

Ri
component’s production for defending against BadUSB would cause a delay in the entire

ll
computer’s delivery for a worker needing it.

Fu
Anyone can modify the hardware with physical access. For instance, repairing a

ns
glued USB port or replacing an in-between physical verification device is feasible.

ai
Hardware breaks. What happens if it fails open?

et
rR
It is more challenging to audit and verify that hardware is installed and operating

ho
in a remote or hybrid environment. Additionally, rolling out hardware devices to already
provisioned laptops and desktops is more logistically challenging in this situation.

ut
,A
The HID-F will not utilize hardware modifications due to these challenges.
te
3.2. Device Fingerprinting
itu

BeamGun (Lospinoso, 2022) is a perfect example of why device fingerprinting is


st

not an acceptable solution. A BadUSB device can imitate an approved (Dijkhuizen, 2018)
In

USB device to bypass BeamGun. This strategy defeats any fingerprinting defense.
NS

Fingerprinting can be considered a single mathematical function f(x) = y, that


SA

takes in fingerprint data, x, and produces a boolean result. A true result of y indicates that
e

fingerprinted device of x is in set A (allowed), while a false result indicates the device is
Th

in set B (blocked). The data, x, used to obtain a fingerprint is electrical signals transmitted
22

via the USB port.


20

To defeat fingerprinting, the BadUSB can transmit the same x as f(x)=y, which
©

results in a true Boolean result, indicating the device is in set A. BeamGun is bypassed in
this manner. Since distinguishing devices is defeatable, this research assumes that the
BadUSB device is indistinguishable from a USB keyboard.

3.3. Machine Typing Machine Learning Classification


Other defenses attempt to tell if a machine is “typing” (Kyle Denney, 2019). This
attempt is a practical step. It will identify commands that a human did not send out with
extremely high reliability. For instance, it might detect inhuman typing speed with near
100% certainty.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 7

gh

Ri
Machine Learning models that analyze the content for detecting human versus

ll
BadUSB input have a fundamental logical flaw in their application. A USB device that

Fu
uses multiple ports to split its input would defeat the analysis pinned to that port.

ns
Should the model account for multiple ports, then the attacker can just be a

ai
human. The WiFi-HID (Bongiorni, 2017) is precisely that. If an attacker can be a human

et
and send a specific input, then an automated BadUSB attack merely has to defeat the ML

rR
algorithm by imitating human input.

ho
The assumption of BadUSB “typing” being indistinguishable from human being

ut
“typing” was made for these reasons. It is a worst-case scenario, and we should expect

,A
attackers to engage in their best offense— the defender’s worst case.
te
itu

3.4. User Interaction


st

One of the more intriguing thoughts is to require human interface device


In

interaction to ‘authenticate’ a human interface device to the computer. For instance, the
NS

USBCheckIn (F. Griscioli, 2016) requires the BadUSB to ‘type’ in a code before
connecting to the laptop. This scheme seems secure since the BadUSB device cannot
SA

physically “see” the prompt of what to type and typically does not have a way to input a
e

specified code.
Th

Bypassing is easy by having human input before proceeding with its program,
22

such as with the Wi-FI HID. Given existing technology, it would be straightforward to
20

automate the interaction by utilizing optical character recognition on marked text with a
©

camera and inputting it before proceeding.

The only user interaction that would initially seem sufficient is the same user
interaction deemed sufficient to authenticate to that computer and any attached
networking environments (e.g., a VPN). For instance, password login with biometric
MFA seems sufficient. However, it is not.

An authentic user could grab a BadUSB on purpose, authenticate, and then the
payload executes. User Interaction is not sufficient to stop the payload in what is already
a common social engineering attack vector.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 8

gh

Ri
3.5. Detecting a Malicious Process

ll
While a BadUSB attack is occurring, it will run malicious processes. Programs

Fu
such as Windows Defender might detect downloaded or generated artifacts or even

ns
identify malicious processes in memory. The downside of these defenses is that the

ai
attacker has them too. Attackers can experiment until their payload is not detected before

et
launching their attack. This experimentation is a routine tactic that happens today to

rR
bypass defensive software.

ho
When a monitor process detects the attack, it is also too late. A security event has

ut
occurred.


,A
te
itu
st
In
NS
SA
e
Th
22
20
©

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 9

gh

Ri
4. Human Interface Device Firewall

ll

Fu
The Human Interface Device Firewall (HID-F) is an endpoint-based software

ns
application that protects the host from malicious human interface device (HID) input.
Each HID has its unique input. The mouse has mouse events. The keyboard has

ai
et
keystrokes. For this paper, only keystrokes are in scope. However, the same concepts

rR
discussed here would apply to other HID input forms.

ho
The HID-F operates by:

ut
1) Detecting whether it should be on: a USB device is inserted

,A
2) Intercepting or Sniffing keystrokes: interception is superior
te
itu

3) Analyzing the keystroke in the context of all recent keystrokes


st

4) Forwarding the keystroke to be processed (if intercepted) by the host


In

operating system if safe, otherwise shutting down HID input/output.


NS
SA
e
Th
22
20
©

Figure 1. Human Interface Device Firewall

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 10

gh

Ri
4.1. Device Detector

ll
The Device Detector is responsible for the on and off state of the entire HID-F.

Fu
When an HID is connected, it turns the HID-F on, and when it is not connected, it turns it

ns
off. Registering with the host OS will notify the HID-F of these events.

ai
On startup, an HID-F needs to know if any external HID is already connected to

et
the machine. If none are detected, the Firewall will not need to run and will not register

rR
keystrokes.

ho
An HID may connect to the computer while the HID-F is running. At that point,

ut
the Device Detector should be notified to start the Interceptor. This notification will

,A
trigger further post-processing and analysis of the keystrokes.
te
itu
The Device Detector could also be configured to assume an HID is connected.
This option would permit analysis for malicious input of integrated keyboards such as a
st
In

laptop keyboard.
NS

4.2. Interceptor
SA

The Interceptor takes keystrokes from the OS or directly as a device driver before
any other program can receive the keystroke. It then releases the keystroke back to the
e
Th

OS when the Malicious Input Engine tells the Interceptor that the keystroke is safe.
22

It is advisable to avoid writing a device driver for the Interceptor since that is
20

error-prone and fragile code. Utilizing Operating System calls will avoid the entire class
of errors from writing device drivers.
©

Sometimes users will type in passwords or other credentials. Do not store these in
plaintext – even in RAM, that would make the HID-F a glorified keylogger. The
Interceptor should use stream encryption for every keystroke. Block encryption would
involve buffering the plaintext in RAM until a block is ready, which is not applicable for
the design of a stream-based event processor such as an HID-F.

Before encrypting data, it should be normalized to its closest ASCII


representation. Some programming or scripting environments will take Unicode
characters and auto-convert them to their closest ASCII representation. Without

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 11

gh

Ri
normalizing the data, attackers could use Unicode to evade analysis. The original

ll
keystroke should also be saved for processing at the end of the data flow.

Fu
4.3. Malicious Input Engine

ns
The Malicious Input Engine (MIE) determines whether the incoming keystrokes

ai
are malicious. The system has 13 milliseconds to complete the analysis. Otherwise, a

et
rR
human user could detect input lag (Potter, 2014). Various analyses are performed in
parallel to meet the 13 milliseconds latency requirement while still determining whether

ho
the keystroke is malicious or not.

ut
Analyses to perform include:

,A
te
1. Cryptoanalysis determines if the input is a ciphertext or otherwise encoded data.
itu

2. Machine Learning Models determine if the payload represents an attack.


st

3. Signature matching checks to see if the payload is banned.


In
NS

4. Sandbox analysis involves forwarding the input to another device to attempt


execution. A remote analysis would not meet the 13 milliseconds turn-around and
SA

would not be ideal for this system. Local analysis in a container could meet the 13
e

milliseconds turn-around, but this adds the risk of container escape. Sandbox
Th

analysis could help analyze commands that are downloaded via typed-in
22

commands.
20

4.4. Encrypted Data Store


©

The Encrypted data store takes the stream of encrypted data and transforms it into
a ciphertext ready for homomorphic processing of data. The constant append operation
on the encrypted data store means it must maintain two parts of the ciphertext in memory:
the aged ciphertext and the dynamic ciphertext. The dynamic ciphertext is re-encrypted
until it forms a complete block and is then moved to the end of the aged ciphertext.

The data store should also normalize data as a background process. A payload of
200 megabytes of text being entered and then deleted would evade a straightforward
analysis. When this is detected, replace the aged text with a normalized aged text that

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 12

gh

Ri
removes deleted text. Subsequent analysis of keystrokes is conducted on the normalized

ll
aged text.

Fu
The data model is responsible for mapping the dataset context to block context

ns
switching evasions. Switching scope to a temporary application, such as notepad.exe, and

ai
then back to a command shell would also be accounted for in the encrypted data store. In

et
this scenario, it may need to know the context of the currently focused window and

rR
maintain different data sets for each focused window. It would need to forward the

ho
focused window’s data set when analysis occurs.

ut
The context will need to normalize for other evasions, such as using the clipboard

,A
or analyzing the contents of a file that would potentially be loaded into memory from a
te
command. A robust data model will make evading the HID-F more difficult.
itu
st

4.5. Enforcer
In

The Enforcer prevents the attack by acting before the enter keystroke is sent from
NS

a malicious payload. Depending on the host OS’s capabilities and user preference, many
enforcement options exist.
SA

The strongest option is to shut down the USB connection to the HID that sent the
e
Th

malicious input. A shutdown must also block the enter key. Enacting this would involve
calling the Host OS system functions or writing a device driver. Writing a device driver
22

opens a new class of vulnerabilities and is not advised.


20

Another strong option is to lock the OS. Locking is a well-supported and


©

straightforward operation. In Windows, it is the most reliable enforcement action and


thus should always succeed. For instance, by design, the BlockInput function is bypassed
by control-alt-delete (Microsoft, 2021). Control-alt-delete is then followed by alt-k to
lock a Windows host OS.

4.5.1. Weak Enforcer Approaches


There are some approaches to enforcement that are unreliable.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 13

gh

Ri
Block some keyboard input. This may prevent the attack from firing off, but it is

ll
not a guarantee due to the unreliability of choosing what input to block. Also, mouse

Fu
events or mixed HID input could still successfully deliver the malicious payload.

ns
Alert only. By then, the damage is done. Maliciously typed payloads are either

ai
malicious or obfuscated, so false positives should be rare. Why alert when we can stop?

et
Alerting can be part of the Enforcer, but it is not a preventative action.

rR
Use the delete or backspace key to erase the data with nothing else. Once the

ho
data has been delivered, then assuming deletion is sufficient. The data could be saved in a

ut
file, the clipboard, or a custom application buffer. Deletion of the data is unreliable and
cannot be the sole approach.
,A
te
Alert the user. What if the user tries to cause the issue or is not present?
itu
st

4.6. Design Principals


In

The components of the HID-F must follow these design principles to maintain
NS

active users and value to the business:


SA

• Encryption of all user keystrokes. Leaked credentials or intellectual property will


result in the HID-F being flagged as a vulnerable application.
e
Th

• Latency is less than 13 milliseconds. The HID-F must not interfere with the user’s
22

typing activities.
20

• Authentic USB devices must function as expected. USB devices should remain
©

functional. Therefore, device drivers for the HID-F should be avoided since they are
complex software to maintain as universally interoperable with authentic USB
devices.

• Prevent malicious payloads from executing. Here is the primary purpose of the HID-
F. Without it, the software is essentially nonfunctional.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 14

gh

Ri
5. Experiment Design and Research Code

ll
5.1. Experiments

Fu
These software application experiments were made to understand the feasibility of

ns
writing a Human Interface Device Firewall (HID-F). Each experiment validates a proof-

ai
of-concept code toward a required feature.

et
rR
5.1.1. Intercept Keystrokes

ho
The experiment starts by plugging in a USB device and typing “AAA” into
notepad.exe. Success is indicated by the As only appearing in the debug console and not

ut
,A
in notepad.exe.
te
This experiment validates the Interceptor’s functionality.
itu

5.1.2. Sniff Keystrokes


st

This experiment is the same as the Interceptor one but has different success
In

criteria. Success is indicated by the As appearing in the debug console and notepad.exe.
NS

This experiment validates the Interceptor’s degraded functionality. If Intercepting fails,


SA

but Sniffing succeeds, an HID-F can still exist.


e

5.1.3. Detect Devices


Th

The Device Detector functions by observing all connected HID. The experiment
22

starts with an HID connected before executing the research program. It should then log
20

that an HID is connected. Then disconnecting and reconnecting the HID should display
©

messages that the HID was disconnected and reconnected as each action occurs.

5.1.4. Disconnect HID


The strongest action the Enforcer can take is to disconnect the HID(s) that wrote
malicious code. In this experiment, the software application starts up and disconnects the
USB device. In five minutes, the USB device attempts to type in “AAA.” If all AAAs are
not registered by the sniffing program, intercepting program, or the notepad.exe, then this
is a success. The success of the Disconnect HID experiment indicates that the Enforcer
can take the strongest protection actions.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 15

gh

Ri
The five-minute delay enables the setup and execution of the research script. A

ll
fully automated HID-F would not need this delay.

Fu
5.1.5. Prevent Bad Input

ns
The Malicious Input Engine is validated by typing in the payload “echo bad” into

ai
cmd.exe and observing that the command does not execute. If this succeeds, a Machine

et
Learning Model can later replace the matching of “echo bad” and become an analysis

rR
component of the Malicious Input Engine.

ho
ut
5.2. Research Code and Scripts

,A
A C++ win32 application was developed to answer the experiment questions. The
Windows event loop handled messages for RawInput and DeviceChange.
te
itu

5.2.1. RawInput API


st

RawInput is used for sniffing and detecting HID devices. To register for
In

RawInput messages (WM_INPUT), code the following in WM_CREATE (Microsoft,


NS

2021).
SA

RAWINPUTDEVICE rid;
rid.usUsagePage = 0x01; // HID_USAGE_PAGE_GENERIC
e
Th

rid.usUsage = 0x06; // HID_USAGE_GENERIC_KEYBOARD


rid.dwFlags = RIDEV_NOLEGACY | RIDEV_INPUTSINK;
22

rid.hwndTarget = hWnd;
20
©

if (RegisterRawInputDevices(&rid, 1, sizeof(rid)) == false){


OutputDebugString(L"Registration failed.\n");
} else {
OutputDebugString(L"Registration success\n");
}

From then on handle WM_INPUT messages in WndProc in order to sniff


keystrokes.

case WM_INPUT: {
UINT dwSize = NULL;

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 16

gh

Ri
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, NULL, &dwSize,

ll
sizeof(RAWINPUTHEADER));

Fu
LPBYTE lpb = new BYTE[dwSize];
if (lpb == NULL) {

ns
break;

ai
}

et
GetRawInputData((HRAWINPUT)lParam, RID_INPUT, lpb, &dwSize,

rR
sizeof(RAWINPUTHEADER));

ho
PRAWINPUT raw = (PRAWINPUT)lpb;
UINT Event;

ut
Event = raw->data.keyboard.Message;

,A
WCHAR currentKey = MapVirtualKey(raw->data.keyboard.VKey,
te
MAPVK_VK_TO_CHAR);
itu

WCHAR keyChar[2];
st

keyChar[0] = currentKey;
In

keyChar[1] = 0;
NS

delete[] lpb; // free this now


if (Event == WM_KEYDOWN) {
SA

if (currentKey < 32) { // control characters


if ((currentKey != 9) && (currentKey != 13)) {
e
Th

break;
}
22

}
20

if (currentKey > 126) { // out of ascii range


©

break;
}
if (currentKey == 13) { // enter key
OutputDebugString(L"\r\n");
break;
}
OutputDebugString(keyChar);
}
break;
}

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 17

gh

Ri
Detecting the number of keyboards at startup uses the following code. Using two

ll
calls to GetRawInputDeviceList, first, it must detect the number of devices (nDevices),

Fu
and then it can fill in the data with a second call (Microsoft, 2022).

ns
UINT nDevices = 0;

ai
GetRawInputDeviceList(NULL, &nDevices,

et
sizeof(RAWINPUTDEVICELIST));

rR
WCHAR szOutput[256];

ho
StringCchPrintf(szOutput, 256, TEXT("%d raw devices
detected\n"), nDevices);

ut
OutputDebugString(szOutput);

,A
PRAWINPUTDEVICELIST pRawInputDeviceList = new
te
RAWINPUTDEVICELIST[sizeof(PRAWINPUTDEVICELIST) * nDevices];
itu

GetRawInputDeviceList(pRawInputDeviceList, &nDevices,
st

sizeof(RAWINPUTDEVICELIST));
In

int keyboards = 0;
for (int i = 0; i < nDevices; i++) {
NS

if (pRawInputDeviceList[i].dwType == RIM_TYPEKEYBOARD) {
SA

keyboards++;
}
e
Th

}
StringCchPrintf(szOutput, 256, TEXT("%d keyboards
22

detected\n"), keyboards);
20

OutputDebugString(szOutput);
delete[] pRawInputDeviceList;
©

5.2.2. Device Change API

The DeviceChange messages detect the connection and disconnection of HID. To


Register for Device Change messages (WM_DEVICECHANGE), use the following code
snippet (Microsoft, 2021).

static HDEVNOTIFY hDeviceNotify;


DEV_BROADCAST_DEVICEINTERFACE NotificationFilter;

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 18

gh

Ri
GUID GUID_USB_SERIAL_HOST_PNP = { 0x8a, 0x25dbce51, 0x6c8f,

ll
0xc8, 0x4a72, 0x6d,0xb5,0x4c,0x2b,0x4f,0x35 };

Fu
ZeroMemory(&NotificationFilter, sizeof(NotificationFilter));

ns
NotificationFilter.dbcc_size =

ai
sizeof(DEV_BROADCAST_DEVICEINTERFACE);

et
NotificationFilter.dbcc_devicetype =

rR
DBT_DEVTYP_DEVICEINTERFACE;

ho
NotificationFilter.dbcc_classguid = GUID_USB_SERIAL_HOST_PNP;

ut
*hDeviceNotify = RegisterDeviceNotification(
hWnd,
,A
te
&NotificationFilter,
itu

DEVICE_NOTIFY_WINDOW_HANDLE
st

);
In

5.2.3. Keyboard Hooking API


NS

Setting a Windows Hook for keyboard inspection will intercept the keyboard
SA

events before the applications on the host OS do. The first step is registering a Windows
Hook (Microsoft, 2021) for keyboard events on program startup.
e
Th

HHOOK keyboardHook{ NULL };


22

...
case WM_CREATE: {
20

keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc,


©

NULL, 0);
}
Next, a KeyboardProc (Microsoft, 2018) must be set up to handle the events
registered from WindowsHookEx. Grabbing the keyboard state and storing it as a string
will allow for further post-processing by an enforcer component.

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM


lParam)
{
WCHAR szBuf[1024];
static std::stringstream keys;

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 19

gh

Ri
ll
if (nCode < 0) { // skip message

Fu
return CallNextHookEx(keyboardHook, nCode,
wParam, lParam);

ns
}

ai
et
if (wParam == WM_KEYDOWN) {

rR
KBDLLHOOKSTRUCT *keyboard = (KBDLLHOOKSTRUCT*)lParam;

ho
BYTE keyState[256];
GetKeyboardState(keyState);

ut
char keyPressedOut;

,A
ToAscii(keyboard->vkCode, keyboard->scanCode,
te
keyState, (LPWORD)&keyPressedOut, 0);
itu
st

if (keyPressedOut > 31 && keyPressedOut < 127) {


In

StringCchPrintf(szBuf, 1024, TEXT("%d\n"),


NS

keyPressedOut);
OutputDebugString(szBuf);
SA

keys << (char)keyPressedOut;


}
e
Th

if (keyPressedOut == 13) {
22

OutputDebugStringA("Intercepted: ");
20

OutputDebugStringA(keys.str().c_str());
©

keys = std::stringstream("");
}

keyPressedOut = 0;
}
return CallNextHookEx(keyboardHook, nCode, wParam, lParam);
}
The CallNextHookEx will forward to the OS at the very end for further
processing. This is needed for the keyboard to function as intended.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 20

gh

Ri
5.2.4. Prevent Bad Input

ll
Either the RawMessages, when sniffing, or Keyboard hooking, when

Fu
intercepting, feed into a buffer. The contents of every keystroke are analyzed in the

ns
buffer to see if the signature matches “echo bad.” The enter key is intercepted and

ai
blocked from further processing on finding a match.

et
The key point to remember is that the input that would go through with an ‘enter’

rR
key needs to be processed. This requires stripping out non-content characters such as

ho
newline and carriage return. Otherwise, the Malicious Input Engine could be defeated by

ut
multiple non-content-modifying characters such as multiple new lines.

,A
The following code is modified from the previous section to inspect the contents
te
to match the signature “echo bad.” On a match, it would block it. In a production-ready
itu

version, that equality check would be replaced with a call to a comprehensive Malicious
st

Input Engine for detection, “echo bad” is a proof of concept replacement.


In

if (keyPressedOut > 31 && keyPressedOut < 127 &&


NS

keyPressedOut != 13 && keyPressedOut != 10) {


SA

keys << (char)keyPressedOut;


e

}
Th

if (keyPressedOut == 13) {
22

std::string keysOut = keys.str();


20

if (keysOut == "echo bad") {


©

OutputDebugStringA("Malicious input
detected, skipping it.\n");

return 1;

...

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 21

gh

Ri
5.2.5. Disconnect USB

ll
There are two options for disconnecting USB devices. The first is to utilize

Fu
CM_Request_Device_EjectW after calling CM_Request_Device_List and

ns
CM_Request_Device_List_Size to get the correct device information. This API call will

ai
unplug a USB device ‘safely’ if it supports it. USB Keyboards usually do not support

et
this, and thus they will fail to unplug.

rR
The other option is to follow the Window driver sample for the DevCon utility for

ho
its disconnect command (Microsoft, 2022). DevCon uses SetupDiSetClassInstaller with

ut
DIF_REMOVE to successfully and reliably remove USB devices. For the experiment,

,A
the Microsoft DevCon utility will demonstrate the feasibility of the disconnect function.
te
An implementation of the Enforcer would have to utilize SetupDiSetClassInstaller
itu

similarly to DevCon.
st

The following steps will remove USB devices.


In

1. Install and locate a devcon.exe that matches the host system architecture. For 64-
NS

bit, the path is typically similar to C:\Program Files (x86)\Windows


SA

Kits\10\Tools\10.0.22621.0\x64
e

2. Run the following command (and additional commands below) in an


Th

administrator cmd.exe prompt: devcon find usb *


22

3. Save the output as a baseline


20

4. Plug in the USB device to test removal and rerun the command: devcon find
©

usb *

5. Save the previous step’s output for comparison.

6. Compare the two, and you will notice some additional devices, such as
HID\VID_0951&PID_16BF&MI_02&COL03\7&20B47351&0&0002
: HID-compliant vendor-defined device
USB\VID_0951&PID_16BF&MI_02\6&2F8DC78&0&0002
: USB Input Device
USB\VID_0951&PID_16BF&MI_01\6&2F8DC78&0&0001
: USB Input Device

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 22

gh

Ri
USB\VID_0951&PID_16BF&MI_00\6&2F8DC78&0&0000

ll
: USB Input Device

Fu
i. Run the following command to remove each device: devcon remove

ns
“@HID\VID_0951&PID_16BF&MI_02&COL03\7&20B47351&0&0002”

ai
... “@USB\VID_0951&PID_16BF&MI_00\6&2F8DC78&0&0000”

et
Note: each device id is prefixed with an @ and quotes surround it. The ellipsis

rR
indicates the remaining device IDs to uninstall. Also, the DevCon disable

ho
command is unreliable, while the remove command is what needs to be used.

ut

,A
te
itu
st
In
NS
SA
e
Th
22
20
©

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 23

gh

Ri
6. Results

ll
A Wifi Duck (spacehuhntech, 2022) and a USB keyboard were each used to

Fu
repeat each experiment. The WifiDuck was the BadUSB treatment, and a USB keyboard

ns
was the human treatment. Research code executed the experiments: interception, sniffing,

ai
detecting, and preventing bad input. DevCon utility from Microsoft executed the

et
disconnecting HID experiment. All research results indicate success for each experiment

rR
and treatment.

ho
Sniffing showed keystrokes logged in both the debug console and the notepad

ut
application.

,A
Interception showed keystrokes only in the debug console and not in the notepad.
te
itu

Detecting a USB device displayed debug console messages corresponding with


st

the events of unplugging and plugging in USB devices. On startup, keyboard devices
In

were detected.
NS

Disconnecting USB devices was the most difficult of all the experiments. Many
SA

APIs for USB devices are meant explicitly for USB storage devices, making this proof of
concept code more difficult to produce. The DevCon utility requires a deep read to
e
Th

understand its proper usage truly. Fortunately, Microsoft has shared the DevCon source
code to document how the API for disconnecting a USB device works.
22

Disconnecting USB devices with devcon.exe was straightforward when following


20

the methodology described in the Research Code and Scripts section above. After
©

following the instructions for devcon.exe, keyboard input did not get through to the host
OS applications.

The experiment of preventing the “echo bad” payload from being followed by a
new line character worked as expected. The payload was displayed in cmd.exe but never
got executed by an “enter” key. When running the research software, the sniffing code
never got a chance to print the payload to the debug console meaning the “enter” key was
intercepted. The lack of interaction with the sniffer further strengthens the evidence that
the malicious payload was successfully blocked.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 24

gh

Ri
The feasibility of a Human Interface Device Firewall (HID-F) is proven. Every

ll
component’s primary feature is codable in the Windows Operating System using low-

Fu
level Win32 systems programming.

ns
ai
7. Recommendations and Implications

et
Until an HID-F is available for business use, it is essential for the Security

rR
Awareness Programs at businesses to explain the importance of locking computers at

ho
home and not plugging in unapproved USB devices. At the same time, businesses should

ut
reinforced education of what USB devices are approved. If lacking a policy on what USB

,A
devices are approved, then the business should make one while keeping in mind that
te
some USB devices are needed to conduct business.
itu

Managing human risk is critical to minimizing the likelihood of BadUSB as an


st

insider threat. Background checks of employees with privileged access should be rerun
In

periodically, especially during a recession. Offering background checks of hired


NS

household employees (e.g., nannies) and reminding them to lock their computers when a
SA

house cleaner comes by are ways to minimize the insider threat risk of BadUSB attacks.
International travel with business devices should be prohibited or limited depending on
e
Th

the business’s risk profile.


22

How should host-based defenses be utilized? While not perfect, the fingerprinting
20

approach of software such as BeamGun (Lospinoso, 2022) and host-based monitoring for
malicious processes are the best practices until a more comprehensive solution to
©

BadUSB is available. Once an HID-F is available, it should be evaluated for use.

8. Implications for Further Research


Operating systems such as ChromeOS, macOS, Android, Android TV, iOS, and
Linux would be logical next steps for feasibility studies or white papers on HID-F. These
operating systems have a non-trivial market share and accept USB input. Each has
different methods of attack and compute resources available.

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 25

gh

Ri
Expanding the scope of the research beyond USB to include other input methods

ll
is critical. The visual keyboard of Windows and BlueTooth keyboards are other

Fu
keyboards to consider. Video game controllers and even Virtual Reality keyboards are

ns
emerging peripherals to consider. Should the clipboard be analyzed before pasting it?

ai
Could a mouse input firewall be developed next?

et
A rigorous cryptographic analysis of append operations on homomorphic

rR
ciphertext would improve the confidentiality of the HID-F operating on sensitive data.

ho
These operations need low latency due to the 13 milliseconds required for a human to

ut
detect the input lag. Longer key press delays would be noticeable to end users due to the

,A
nature of human perception. te
Machine Learning Models to identify malicious commands is a straightforward
itu

next step. This paper is not focusing on Machine Learning since there is a healthy and
st

broad research interest in using Machine Learning to identify malicious payloads. The
In

exciting spin of this research is to conceptually direct these models towards keyboard
NS

input.
SA

Thought was taken into how an attacker would try to evade, obfuscate, or escape
e

an HID-F. Like any system, there is undoubtedly a flaw in HID-F despite all the care to
Th

minimize flaws. Research into the theoretical weaknesses of an HID-F would benefit its
22

effectiveness at preventing attacks.


20

The latency requirements of 13 milliseconds may require performance analysis


©

for analytical modeling. Memory and CPU utilization may need optimization to avoid
impacting the end user's computing experience. Hardware offloading of processing is a
performance improvement option that also opens up new security considerations.

9. Conclusion
The Human Interface Device Firewall (HID-F) solves the BadUSB attack vector
more comprehensively than current defenses. A focus on usability, reliability, and
payload analysis differentiates this class of software from any previous defense to

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 26

gh

Ri
BadUSB. The HID-F goes further than BadUSB defense and protects against all

ll
keyboard input – including employees typing malicious commands by hand.

Fu
We live in a post-COVID-19 world where remote and hybrid employees are

ns
commonplace. Defending the distributed workplace is far more complex, and BadUSB is

ai
an easy attack vector in this distributed workplace. The HID-F represents an evolution in

et
the defenses against BadUSB.

rR
ho
ut
,A
te
itu
st
In
NS
SA
e
Th
22
20
©

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 27

gh

Ri
References

ll
Fu
Afzali et al. (2021). Economic uncertainty and corruption: Evidence from public and

ns
private firms. Journal of Financial Stability Volume 57.

ai
Al-Zarouni, M. (2006). The Reality of Risks from Consented use of USB Devices . 4th

et
rR
Australian Information Secuirtyu Management Conference. Perth, Western

ho
Australia.

ut
Bongiorni, L. (2017, May 1). WHID Injector: How to Bring HID Attacks to the Next

,A
Level. Retrieved from Security Affairs:
te
itu

https://securityaffairs.co/wordpress/58587/hacking/whid-injector-bring-hid-
st

attacks.html
In

Dijkhuizen, N. v. (2018). Keynterceptor: Press any key to continue. HITBSecConf.


NS

Amsterdam.
SA

F. Griscioli, M. P. (2016). USBCheckIn: Preventing BadUSB Attacks by. 14th Annual


e
Th

Conference on Privacy, Security and Trust , (pp. 493-496).


22

Frey, S. (2018). How to Eliminate the Prevailing Ignorance and Complacency Around
20

Cybersecurity. In M. a. Bartsch, Cybersecurity Best Practices (pp. 1-10).


©

Springer.

Gatlan, S. (2022, January 7). FBI: Hackers use BadUSB to target defense firms with

ransomware. Retrieved from Bleeping Computer:

https://www.bleepingcomputer.com/news/security/fbi-hackers-use-badusb-to-

target-defense-firms-with-ransomware/

Hak5. (2022, June). usbrubberducky-payloads. Retrieved from GitHub:

https://github.com/hak5/usbrubberducky-payloads

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 28

gh

Ri
Hoelzer, D. (2021, October 9). Applying Machine Learning to Network Anomalies.

ll
Retrieved from Youtube: https://youtu.be/PdddO1-jeQQ

Fu
Kyle Denney, E. E. (2019). USB-Watch: A Dynamic Hardware-Assisted USB Threat

ns
ai
Detection Framework. In Security and Privacy in Communication Networks (Vol.

et
304).

rR
Lospinoso, J. (2022, June 11). Beam Gun. Retrieved from Github:

ho
ut
https://github.com/JLospinoso/beamgun

,A
Microsoft. (2018, March 30). KeyboardProc callback function. Retrieved from MSDN:
te
https://docs.microsoft.com/en-us/previous-
itu

versions/windows/desktop/legacy/ms644984(v=vs.85)
st
In

Microsoft. (2018, March 30). MSDN. Retrieved from KeyboardProc callback function:
NS

https://docs.microsoft.com/en-us/previous-
SA

versions/windows/desktop/legacy/ms644984(v=vs.85)
e
Th

Microsoft. (2021, October 13). BlockInput function (winuser.h). Retrieved from MSDN:

https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-
22
20

blockinput
©

Microsoft. (2021, March 28). https://docs.microsoft.com/en-

us/windows/win32/inputdev/using-raw-input. Retrieved from MSDN:

https://docs.microsoft.com/en-us/windows/win32/inputdev/using-raw-input

Microsoft. (2021, January 7). MSDN. Retrieved from Using Hooks:

https://docs.microsoft.com/en-us/windows/win32/winmsg/using-hooks

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.
ts
Human Interface Device Firewall Feasibility 29

gh

Ri
Microsoft. (2021, January 4). Registering for device notification. Retrieved from MSDN:

ll
https://docs.microsoft.com/en-us/windows/win32/devio/registering-for-device-

Fu
notification

ns
ai
Microsoft. (2022, May 20). GetRawInputDeviceList function (winuser.h). Retrieved from

et
MSDN: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-

rR
winuser-getrawinputdevicelist

ho
ut
Microsoft. (2022, June 12). Windows Drivers Samples - devcon. Retrieved from Github:

,A
https://github.com/microsoft/Windows-driver-
te
samples/blob/main/setup/devcon/cmds.cpp
itu

Potter, M. W. (2014). Detecting meaning in RSVP at 13 ms per picture. Attention,


st
In

Perception, & Psychophysics, 270–279.


NS

Pranggono, B. a. (2020). COVID-19 pandemic cybersecurity issues. Internet Technology


SA

Letters.
e
Th

spacehuhntech. (2022, July 21). WiFiDuck. Retrieved from GitHub:

https://github.com/spacehuhntech/wifiduck
22
20
©

Brian Davidson, bkdson@gmail.com


© 2022 The SANS Institute Author retains full rights.

You might also like