Saturday, February 16, 2019

macOS - keylogging through HID device interface

Just for fun I started to dig into how could I write a piece of software to detect rubber ducky style attacks on macOS. While I was reading through the IOKit API, and digging into the various functions and how everything works, I came across an API call, called IOHIDManagerRegisterInputValueCallback, which sounded very interesting although wasn’t related to what I was looking for. At first read it sounded that you can monitor USB device input. My first trials with the enumeration showed that the built in keyboard on a MacBook Pro is also connecting through the USB / IOHID interface. That made think if I could log keystrokes via this API call. At this point I got totally distracted from my original goal, but I will get back to that later :) Looking up the function on Apple’s website confirmed my suspicion, it says:

IOHIDManagerRegisterInputValueCallback
Registers a callback to be used when an input value is issued by any enumerated device.

Nice! Since I’m still a complete n00b to either Swift and Objective-C I tried to lookup on Google if someone wrote a key logger such this, and basically I found a good code here: macos - How to tap/hook keyboard events in OSX and record which keyboard fires each event - Stack Overflow This is very well written and you can use it as is, although it doesn’t resolve scan code to actual keys. The mapping is available in one of the header files: MacOSX-SDKs/IOHIDUsageTables.h at master · phracker/MacOSX-SDKs · GitHub With this I extended the code to use this mapping, and also write output to a file, and it works pretty nicely. I uploaded it here:

https://github.com/theevilbit/macos/tree/master/USBKeyLog

Then a googled a bit more, and came across this code, which is very-very nice, and does it way-way better then my:

The benefit of this method over the one that uses CGEventTap (common used in malware) is:
  1. you don’t need root privileges
  2. runs even on Mojave without asking for Accessibility permissions
  3. not (yet??) detected by ReiKey
The CGEventTap method is very deeply covered in Patrick Wardle's excellent videos
Patrick Wardle - YouTube
and the code is available in his GitHub repo
GitHub - objective-see/sniffMK: sniff mouse and keyboard events