### The Adventures of a KeyStroke ###### An in-depth look into Keyloggers on Windows Emre TINAZTEPE ----- # What you will learn? ###### ¡ Completing this training, you will be able to: ¡ Use a kernel debugger for malware analysis, ¡ Understand the threats posed by keyloggers, ¡ Detect / Remove all kinds of keyloggers, ¡ Understand how a keylogger works in greatest detail, ¡ Be prepared to Advanced Persistent Threats! ¡ We will cover a lot of OS Internal structures. ¡ Without dealing with OS Internals, you can’t be sure that your system is clean. ###### 2 ----- # Who am I? ###### ¡ Emre TINAZTEPE ¡ Ex military: ¡ Maltepe Military High School (21 / 421) ¡ Turkish War Academy (8 / 838) ¡ Passed half of his life in the army (First Lieutenant) ¡ Resigned 3 years ago. ¡ Low level guy who likes to deal with OS Internals ¡ Currently leading a Malware Analysis Team ¡ Responsible of malware analysis and mobile av dev. ###### 3 ----- # Methodology ###### ¡ Hard to easy because it all starts at hardware L ¡ If you have question, just interrupt me. ¡ Hands on labs combined with theory. ¡ Labs are made in a Win 7 x32 machine. ###### 4 ----- # Why keyloggers? ###### ¡ Because keyboard is the device you command your computers. ¡ Logging keys from a PC provides the malware authors with great power. ¡ Best way to gather intelligence. ¡ Russia is said to be switching to “typing machines” in critical institutions. ¡ Best way to get rich J ###### 5 ----- # Before we begin ###### ¡ Please download these files: ¡ Materials: http://bit.ly/1aLVnOI (pass: infected) ¡ Labs: http://bit.ly/16FZ73t ¡ Please turn your AV/Windows Defender OFF! ###### 6 ----- # VirtualBox ###### 7 ----- # Window Detective ###### 8 ----- # API Monitor ###### 9 ----- # Rootkit Unhooker ###### 10 ----- # GMER / Tuluka ###### 11 ----- # Process Explorer ###### 12 ----- # Windbg ###### 13 ----- # Windbg Cheat Sheet ###### ¡ lm : Lists loaded modules (drivers, dlls) ¡ !process -1 0 : Displays current process � ¡ !process 0 0 winlogon.exe : Displays info for the process � ¡ .process EPROCESS : Switches to the process (implicit) ¡ bp ADDRESS : Puts a breakpoint at the address ¡ g,p,t : Go, Step, Trace ¡ bl : Lists the breakpoints ¡ bc INDEX : Clears the BP indicated by the index ¡ bd INDEX : Disables BP temporarily ¡ .echo : Outputs a string ###### 14 ----- # Windbg Cheat Sheet ###### ¡ .cls : Clears the screen ¡ u ADDRESS / SYMBOL : Unassembles the address ¡ uf ADRESS OF FUNCTION : Unassembles the whole func. ¡ db ADDRESS : Dumps the address. ¡ ? poi(ADDRESS) : Displays the address pointed by. ###### 15 ###### ¡ !pic / !ioapic : Displays information about interrupt controllers. ¡ !drvobj \Driver\kbdclass 0x7: Display the specified driver. ¡ !devobj OBJECT : Display information about device obj. ----- # Let’s infect ourselves ###### ¡ Restart RED VM, make sure it is not in “KERNEL DEBUG” mode. ¡ Go to Materials/Keyloggers directory ¡ Double click “Elite Keylogger.exe” ¡ Install with default settings (Click NEXT multiple times) ¡ Choose “Allow” in case Windows Defender consents. ¡ Restart the VM in non debug mode. ###### 16 ###### ¡ Write “unhide” on start menu and provide a password at least 3 chars long. ¡ Fire up a “Notepad” and write your name in it. ¡ Please also provide your Credit Card number JJJ ¡ Do not save it please, it is safer ??? ----- # You are infected now L ###### ¡ We will see how to detect keyloggers in the following ours. ¡ For the moment, please restore your VM to snapshot ###### 17 ###### “Informatics” and start your VM in “Kernel Debugging” Mode. ----- # Ready to dive? ###### 18 ----- # An overview of a mother board ###### CPU Front Side Bus (FSB) North Bridge Internal Bus (IB) Peripherals ###### 19 ----- # An overview of a mother board ###### ¡ Bus is a communication system that transfers data between components inside a computer, ¡ FSB is the CPU's connection to the North Bridge and through it to rest of the system, ¡ North Bridge is a high-speed hub that in most systems connects the CPU to the graphics card and to RAM, ¡ South Bridge is a slower-speed hub that connects the CPU to the rest of the system. ###### 20 ----- # South Bridge (SB) ###### ¡ It is also named as “Input/Output Controller Hub”. ¡ Responsible from the peripheral device connections such as USB, PCI, PS/2, Sound and etc. ¡ Why two bridges? ¡ Same as the idea of having RAM, Cache, Register ¡ Simpler design which is easy to modify in terms of IO capabilities. ¡ It is what you actually connect your keyboard to. ###### 21 ----- # PS/2 Keyboard Controller ###### ¡ A component of a mainboard which handles the connection between a motherboard and a PS/2 keyboard. ###### 22 ----- # PS/2 Keyboard ###### ¡ Just a limited computer system which scans a wireframe continuously for finding a closed/opened circuit. ###### 23 ----- # PS/2 Keyboard ###### ¡ The PS/2 Keyboard is a device that talks to a PS/2 controller using serial communication. ¡ The PS/2 Keyboard accepts commands and sends responses to those commands, and also sends scancodes indicating when a key was pressed or released. ¡ The keyboards processor includes its own timer, 33 instruction set, and can even access 128K of external memory. 16 Byte Buffer ###### 24 ----- # Talking to a Keyboard? ###### ¡ A PS/2 Keyboard accepts many types of commands, ¡ Each command is one byte, ¡ Some commands have data byte/s which must be sent after the command byte, ¡ The keyboard typically responds to a command by sending either an "ACK" (to acknowledge the command) or a "Resend" (to say something was wrong with the previous command) back. ###### 25 ----- # Talking to a Keyboard? ###### - Commands must be sent one at a time (IN/OUT), - Some commands have data byte/s which must be sent after the command byte, - 0xFE (resend) expects a command to be sent again, while 0xFA (ACK) means command is successfully processed. ###### 26 ----- ###### PS/2 Keyboard Controller/Encoder Ports IO Port Access Type Purpose Keyboard Encoder 0x60 Read Read Input Buffer 0x60 Write Send Command Keyboard Controller 0x64 Read Status Register 0x64 Write Send Command - Port 0x60 is what we use for reading and writing data to/from the keyboard device, - The Status Register contains various flags that indicate the state of the PS/2 controller such as the state of input/output buffers, - The Command Port (0x64) is used for sending commands to the PS/2 Controller (not to PS/2 Devices). ###### 27 |IO Port|Access Type|Purpose| |---|---|---| |Keyboard Encoder||| |0x60|Read|Read Input Buffer| |0x60|Write|Send Command| |Keyboard Controller||| |0x64|Read|Status Register| |0x64|Write|Send Command| ----- ###### Some of the PS/2 Keyboard Encoder Commands ###### 28 |Command|Description|Data| |---|---|---| |0xED|Set LEDs|Bit0: ScrollLock Bit1: NumberLock Bit2: CapsLock| |0xEE|Echo|For diagnostic purposes.| |0xF0|Get/set current scan code set|0: Get current scan code set 1: Set scan code set 1 2: Set scan code set 2 3: Set scan code set 3| |0xF4|Enable scanning|-| |0xF5|Disable scanning|Discard key presses or mouse movements. Used especially while identifying the attached PS/2 device in order to prevent messing up the identification process.| ----- # Scancodes and Code Sets ###### ¡ A scan code set is a set of codes that determine when a key is pressed or repeated, or released. Scancode Make Code Release Code ###### 29 ###### Scancode ----- # Scancodes and Code Sets ###### ¡ There are 3 scan code sets, normally on PC compatible systems the keyboard itself uses scan code set 2 and the keyboard controller translates this into scan code set 1 for compatibility. Microsoft Keyboard Scan Code Specification Document ###### 30 ----- # How to read scancodes? ###### ¡ Poll the Bit 0 of status register and then read the data from port 0x60 ¡ To much CPU time! ¡ Multiple PS/2 devices lead to problems for differentiating the data. ¡ Wait for an interrupt to occur ¡ Much better! ¡ Wait for an IRQ 1 / IRQ 12 (wait for the next slideJ) ###### 31 ----- # What is an interrupt? ###### ¡ Interrupt is a signal to the processor emitted by hardware or software indicating an event that needs immediate attention. Do this and let me know when it’s done! I am a little bit busy J It’s done! ###### 32 ###### CPU ###### Let’s see what you have. ###### Device (Harddisk, Keyboard) ----- # Why called as “IRQ”? ###### ¡ Each peripheral device requests to “Interrupt the CPU” this is why it is a “Request” which may or may not be handled by the CPU. ¡ Question: What happens when multiple devices send an IRQ at the same time? ¡ Answer: The one with a higher IRQL gets processed while the others keep waiting. ###### 33 ----- # Interrupt Handling ###### ¡ One of the best advantages of an interrupt driven device is the ability to overlap device’s processing time with the CPU’s activity. Process a lengthy operation Device CPU t1 t2 Issue an operation ###### 34 ----- # Where do I connect my device? ###### ¡ Question: If we have 2 or more devices attached to our mainboard, how will we differentiate one device’s interrupt from the other? ¡ Answer: Each motherboard has an at least one Programmable Interrupt Controller (PIC / APIC) into which your external devices get connected. You do not have to do anything, all is done seamlessly by this electronic circuit. ###### 35 ----- ### Programmable Interrupt Controller ###### ¡ OMG! What is an interrupt controller? ¡ One of the most important chips making up the x86 architecture, ¡ Without it, the x86 architecture would not be an interrupt driven architecture, ¡ The function of the PIC is to manage hardware interrupts and send them to the appropriate system interrupt. ¡ This way, no polling needed J ###### 36 ----- ### APIC ###### ¡ More sophisticated interrupt handling and the ability to send interrupts between processors. ¡ In an APIC-based system, each CPU is made of a "core" and a "local APIC". Core Local APIC CPU ###### 37 ###### Core Local APIC ----- ### I/O APIC ###### ¡ The external I/O APIC is part of Intel’s system chip set. Its primary function is to receive external interrupt events from the system and its associated I/O devices and relay them to the local APIC as interrupt messages. ¡ It is programmed by the OS before enabling interrupt handling mechanism. Local APIC Local APIC I/O APIC Local APIC Interrupt Messages ###### 38 ###### Local APIC ###### External Devices ###### I/O APIC ###### Local APIC ----- ### What magic CPU does to handle IRQs? ###### ¡ There is no magic, we tell it what to do. ¡ We create a table of function pointers and tell the CPU where it resides. ¡ This table is called as “Interrupt Descriptor Table” and the address for this table is hold by a register called IDTR (IDT register). IDTR ###### 39 |Col1|Handler 0|Col3| |---|---|---| ||Handler 1|| ||Handler 2|| ||Handler 3|| ||Handler 4|| ###### Handler 0 Handler 1 Keyboard Interrupt Handler Handler 2 Handler 3 Handler 4 IDT RAM ----- ### Intel x86 CPU Modes ###### ¡ 3 + 1 Modes of operation is supported by CPU. ¡ Real Mode ¡ Virtual 8086 Mode ¡ Protected Mode ¡ System Management Mode ###### 40 ----- ### Real Mode ###### ¡ Also called real address mode. ¡ Real mode is characterized by a 20-bit segmented memory address space and unlimited direct software access to all memory, I/O addresses and peripheral hardware. ¡ Real mode provides no support for memory protection, multitasking, or code privilege levels. ¡ Before the release of the 80286, which introduced Protected mode, real mode was the only available mode for x86 CPUs. ¡ In the interests of backwards compatibility, all x86 CPUs start in real mode when reset. ###### 41 ----- ### Protected Mode ###### ¡ Also called protected virtual address mode. ¡ It allows system software to use features such as virtual memory, paging and safe multi-tasking designed to increase an operating system's control over application software. Protected Power ON Real Mode Mode Create some tables for Virtual Memory and set PE bit in CR0 register ###### 42 |Power ON Real Mode|Col2|Col3| |---|---|---| ||Create some|| ###### Protected Mode ----- ### Virtual 8086 Mode ###### ¡ Also called virtual real mode. ¡ Allows the execution of real mode applications that are incapable of running directly in protected mode while the processor is running a protected mode operating system. ###### 43 ----- ### System Management Mode ###### ¡ Is an operating mode in which all normal execution (including the operating system) is suspended, and special separate software (usually firmware or a hardware-assisted debugger) is executed in high- privilege mode. ¡ SMM is a special-purpose operating mode provided for handling system-wide functions like: ¡ Handle system events like memory or chipset errors, ¡ Manage system safety functions, such as shutdown on high CPU temperature and turning the fans on and off, ¡ Emulate motherboard hardware that is unimplemented or buggy. ###### 44 ----- ### More on SMM ###### ¡ A powerful mode of CPU which can even preempt the whole OS!!! ¡ SMM is entered via the SMI (system management interrupt) ¡ SMM is a really good place to execute malicious software without modifying the structures created by OS. Here comes the karate kick! ###### 45 ----- ### #1 SMM Rootkits ###### 46 ----- ### An overview of SMM Rootkits ###### ¡ Did you know that you can see the keystrokes even before they are handled by “Interrupt Handler”? ###### 47 ###### Normal Path Infected Path ###### Normal Path ----- ### The implementation ###### 1. Use SMRAM Control Register (SMRAMC) ¡ Check bit D_OPEN (is SMRAM visible to outside code) ¡ Check bit D_LCK (is SMRAMC is read-only, if yes a reset is needed) 2. If D_LCK bit is clear: 1. Set D_OPEN bit to make SMRAM visible to protected mode code, 2. Copy the SMM Handler code to the handler portion of SMRAM defined by Intel Docs, 3. Clear D_OPEN bit and set D_LCK bit to protect our evil code J 3. We are invisible! ###### 48 ----- ###### Routing IRQ 1 to Malicious SMM Handler 1. Modify the I/O APIC in such a way that when ever a user presses a key, our SMM code is executed, 2. SMM Handler reads the scan code, logs it and sends a special command to keyboard for overcoming the problem of a popped up scancode. 3. This in turn makes the next data written into the keyboard buffer available for OS Keyboard Interrupt handler, 4. Send an IPI to ourself for handling an emulated IRQ 1! 5. Let the OS think it is a real scancode generated by the keyboard encoder J ###### 49 ----- ###### Pros & Cons 1. Pros 1. Totally invisible to the OS! 2. No need to change any OS created structures. 3. Very hard to detect. 2. Cons 1. Works only with PS/2 2. Limited to single processor system 3. D_LCK bit is already set on modern systems L ###### 50 ----- ### #2 IDT Hooking ###### 51 ----- ###### Structure of an Interrupt Descriptor Table 1. Protected Mode counterpart of Real Mode Interrupt Vector Table (IVT), 2. Contains at most 256 entries. 3. Each entry is 8 bytes long and they are structured as defined below: nt!_KIDTENTRY +0x000 Offset : Uint2B +0x002 Selector : Uint2B +0x004 Access : Uint2B +0x006 ExtendedOffset : Uint2B ###### 52 ----- ###### Keyboard Interrupt is not mapped to IDT#1??? 1. Where is IRQ 1 mapped? Which IDT Entry??? ¡ “IOAPIC makes IRQ and remaps IRQ to IDT.” ###### 53 ###### kd> !ioapic � IoApic @ FEC00000 ID:1 (11) Arb:0 Inti00.: 00000000`000100ff Vec:FF FixedDel Ph:00000000 edg high m Inti01.: 01000000`00000991 Vec:91 LowestDl Lg:01000000 edg high Inti02.: 00000000`000100ff Vec:FF FixedDel Ph:00000000 edg high m Inti03.: 00000000`000100ff Vec:FF FixedDel Ph:00000000 edg high m kd> !idt –a 31: 84866058 i8042prt!I8042KeyboardInterruptService (KINTERRUPT 84866000) NO I/O APIC 91� : 84864058 i8042prt!I8042KeyboardInterruptService (KINTERRUPT 84864000) 2. Methods for retrieving the vector address: ¡ Use APIC ¡ Scan kernel memory ¡ Use the kernel API function (HalGetInterruptVector) ----- ###### How to read scancode? 1. It’s as easy as executing an “in al,60h” instruction J ¡ IN instruction empties the data, we need to put it back into its place for system’s use. ###### 54 ###### 2. Here is an excerpt from the Keyboard Controller command set: Command 0xd2: Write keyboard output buffer Write the keyboard controllers output buffer with the byte next written to port 0x60, and act as if this is a keyboard generated data. ----- ###### Here is the method ###### 55 ###### Record the keystroke into a buffer and execute the special keyboard controller command for putting it back into place ----- ### #3 Hacking KINTERRUPT ###### 56 ----- ###### Structure of a KINTERRUPT ###### 57 ----- ###### Where does this code come from? ###### 58 ###### 1. KINTERRUPT->DispatchCode is actually a modified version of KiInterruptTemplate. 2. Can be easily modified for different kinds of interrupts such as KiChainedDispatch, KiFloatingDispatch. ----- ###### What does a DispatchCode do? Acquire the Raise the IRQL Release the Call the SpinLock of to Lower IRQL SpinLock of ServiceRoutine ServiceRoutine DEVICE_IRQL ServiceRoutine ###### This is the point where “Interrupt Servicing” takes place! i8042KeyboardInterruptService ###### 59 Acquire the Raise the IRQL Release the Call the SpinLock of to Lower IRQL SpinLock of ServiceRoutine ServiceRoutine DEVICE_IRQL ServiceRoutine Release the SpinLock of ServiceRoutine ----- ###### How to intercept 1. Put an inline hook into DispatchCode’s prolog, ###### 60 ###### 2. Create a new KINTERRUPT object and make EDI point to it, 3. Replace the ServiceRoutine field of KINTERRUPT, 4. Inline hook the ServiceRoutine. ----- ###### Windows Driver Model ¡ A layered design with support for adding drivers into the stack dynamically. ¡ Great design for management. ¡ Allows another driver to filter some other driver’s packets. ###### 61 ----- ###### Keyboard Device Stack ###### 62 ----- ###### What is an IRP? ###### 63 ###### ¡ A structure which is used by the I/O manager for defining a request targeted to a device. ¡ Reading a file, writing to a file and much more operation is handled with IRPs. ¡ Each IRP has a Major code which makes it possible to call appropriate handler for that IRP. ###### Upper Driver ###### Lower Driver ----- ###### i8042prt.sys 1. Port driver for 8042 compatible keyboard and mouse devices. ###### 64 ###### 2. Handles the interrupt for a keyboard device and delivers it to the system. 3. Contains good candidates for a keylogger. ----- ###### i8042prt.sys ###### 65 ###### I8042prt.sys I8042KeyboardIsrDpc I8042KeyboardInterruptService I8042KeyboardIsrDpc I8042KeyboardInterruptService ----- ###### i8042prt.sys Overview ###### 66 I8xWriteDataToKeyboardQueue ###### Adds the INPUT data into keyboard input data queue Call IsrHookCallback if one is I8xGetByteAsynchronous I8xQueueCurrentKeyboardInput I8xWriteDataToKeyboardQueue registered ###### May also terminate the Adds the INPUT data into ISR by modifying ###### Uses Globals.Read method internally I8xGetByteAsynchronous ###### Queues a DPC for giving a chance to class driver for processing the input data at DISPATCH LEVEL ----- ### #4 i8042prt!Globals Hack ###### 67 ----- ###### i8042prt.sys GLOBALS structure ###### 68 ----- ###### A look into i8042prt!Globals 8d94c601 ffb0a0000000 push dword ptr [eax+0A0h] � 8d94c607 ff15cc40958d call dword ptr [i8042prt!Globals+0xc (8d9540cc)] 8d94c60d 8807 mov byte ptr [edi],al 8d94c60f 0fb6c0 movzx eax,al kd> dps i8042prt!Globals 8d9540c0 85799cd8 8d9540c4 8594cab8 8d9540c8 85a52c88 8d9540cc 8281a094 hal!READ_PORT_UCHAR 8d9540d0 8281a0fc hal!WRITE_PORT_UCHAR 8d9540d4 00720070 8d9540d8 859b3c80 ###### 69 ###### Replace it with your own J ----- ###### Globals Read Data Hook ###### 70 ###### kd> bl * 0 d 8d94c57c 0001 (0001) i8042prt!I8xGetByteAsynchronous+0x81 "r al;g;" 1 d 8d94c599 0001 (0001) i8042prt!I8xGetByteAsynchronous+0x9e "r al;g;" 2 e 8d94c60d 0001 (0001) i8042prt!I8xGetByteAsynchronous+0x112 "r al;g;" 0 3d 0 3d 0 3d 9 1d 1e 1d 9e 1d 1f 1d 9f 1d 20 1d a0 1d � 21 1d a1 1d 22 1d a2 1d 23 1d Here we have the keystrokes, also little noisy but can be parsed with a simple script. ###### 0 3d 0 3d 0 3d 9 1d 1e 1d 9e 1d 1f 1d 9f 1d 20 1d a0 1d � 21 1d a1 1d 22 1d a2 1d 23 1d ----- ### #5 I8xGetByteAsynchronous ###### 71 ----- ###### I8xGetByteAsynchronous ¡ Defined as I8xGetByteAsynchronous(CCHAR KeyboardType,UCHAR*ScanCode) ¡ Pretty good place to hook. ¡ Internally uses Global.Read ###### 72 ----- ### #6 Hacking IsrHookCallback ###### 73 ----- ###### IsrHookCallback ¡ Used by upper level drivers to modify the scancode in the ISR routine. ¡ Gets called right after scan code is retrieved from the keyboard controller. ###### 74 ----- ###### Hack IsrHookCallback ¡ As easy as modifying DEVICE_EXTENSION of port device: ¡ DeviceObject->DeviceExtension->IsrHookCallback ¡ Right after that, keys will start flowing into our callback! ¡ Callback can even stop the ISR’s processing. ###### 75 ----- ### #7 Hacking ClassService ###### 76 ----- ###### What does I8xQueueCurrentKeyboardInput do? ¡ Queues a DPC for further processing. ###### 77 ###### ¡ DPC calls DeviceExtension->ConnectData.ClassService function for delivering the scan code information to the class driver. ¡ Question: Can’t we hook that? ¡ Answer: Definitely yes! ¡ How: Replace the ClassService function with your own J ----- ###### I8xQueueCurrentKeyboardInput ¡ Queues a DPC object for further processing the input data. ###### 78 ###### ¡ This gives class drivers or any upper level drivers a chance to process the input data structure, even modify it! ¡ As soon as IRQL drops to DISPATCH_LEVEL, DPC gets executed and calls the callback supplied by Class Driver. I8042KeyboardIsrDpc ----- ###### DPC – Deferred Procedure Call ¡ Time is a precious thing! ¡ Do what ever you can to make hardware feel better and queue a procedure to be called when everything is OK. ###### 79 ###### ¡ This prevents keeping a CPU at a high IRQL level for a long time. ----- ### #8 I8xWriteDataToKeyboardQueue ###### 80 ----- ###### I8xWriteDataToKeyboardQueue ¡ A great candidate for hooking! ###### 81 ###### ¡ Gets the INPUT data as it’s second parameter and writes that into it’s internal data queue. ¡ Flags describe whether the key is down or up. ----- ### #9 Filter Drivers ###### 82 ----- ###### How to filter? ¡ Meaning of layer in malware authors slang: ¡ “A point for injecting evil” ¡ Two methods: ¡ IoAttachDevice API: The IoAttachDevice routine attaches the ###### 83 ###### caller's device object to a named target device object, so that I/O requests bound for the target device are routed first to the caller. NTSTATUS IoAttachDevice( _In_ PDEVICE_OBJECT SourceDevice, _In_ PUNICODE_STRING TargetDevice, _Out_ PDEVICE_OBJECT *AttachedDevice ); ¡ Registry hacks for devices. Set UpperFilter and LowerFilters. Upper filter drivers go between the operating system and the main driver, and lower filter drivers go between the main driver and the hardware. ----- ###### Let’s check for Keyboard Filters ###### 84 ###### 1. Go to Materials/Applications copy RegShot directory to your Desktop. 2. Execute “regshot.exe” 3. Set output path to “Desktop” 4. Click on “1[st] Shot” -> “Shot” 5. Install “Zemana AntiLogger Free.exe” 6. Go to regshot again and click “2[nd] Shot” -> “Shot” 7. Click “compare” 8. Search for “UpperFilters” (Upper filters for keyboard device)  9. Copy the GUID and google it. Guess what does it define? 10. Restart the machine in DEBUG MODE and execute: 1. !drvobj \Device\kbdclass 2. !devstack SECOND OBJECT ADDRESS ----- ### #10 IRP Handler Hooking ###### 85 ----- ###### Keyboard Class Driver ¡ \Driver\kbdclass ¡ Represents a Keyboard Device either USB or PS/2. ¡ Used exclusively by the Raw Input Thread (RIT) (coming next). ###### 86 ----- ###### Look at the difference ¡ KbdClass has a READ routine while the Port Driver doesn’t! Why? ###### 87 ----- ###### Here is why ¡ Port driver doesn’t provide a read routine because it expects a “Keyboard Class Service Callback” to be registered by a class driver. ¡ Class driver gets the requests from the RIT and waits for KeyboardClassServiceCallback to get called by the keyboard port driver’s ISR DPC. ¡ This callback is registered by sending an IRP carrying a structure called as CONNECT_DATA with an IOCTL_INTERNAL_KEYBOARD_CONNECT code. ¡ This in turn makes the port driver record this callback routine for calling whenever an interrupt occurs. ¡ When ever the service callback gets called by port driver’s DPC, class driver completes the request of RIT which makes the RIT send another request. ###### 88 ----- ###### KeyboardClassServiceCallback ¡ Routine which dequeues an IRP each time it gets called by the port driver’s ISR DPC. ¡ As soon as data is copied to the IRP, it completes the IRP with STATUS_SUCCESS. ###### 89 ----- ### #12 Inline hooking for ClassCallback ###### 90 ----- ###### Hook the class callback ¡ We have already hacked this callback routine but in a different way. It was just a replacement of a pointer in ConnectData structure residing in port driver’s DeviceExtension. ¡ This time, another approach. ¡ Put an inline hook into KeyboardClassServiceCallback which will make us the king of scancodes J ¡ As easy as putting a 5 byte prolog into the routine. ###### 91 ----- ###### Let’s talk about “Raw Input Thread” ¡ A thread of csrss.exe which continuously makes a read request to keyboard class device. ¡ It is the guy who retrieves keystrokes from the class driver and posts them to appropriate queues. ¡ It’s mainly a loop which makes a request and waits for that request to complete which in turn makes another request and so forth… ¡ Key method here is StartDeviceRead which sends a �� read request to class driver asynchronously with an APC object. ###### 92 ----- ###### How it functions? ###### 93 Make an async read request **StartDeviceRead** ###### Calls ProcessKeyboardInput Go to step one Process the keyboard data in APC routine ----- ### #13 Hacking Device Templates ###### 94 ----- ###### What is a Device Template? ¡ A structure for keeping device specific attributes such as keyboard and mouse. ¡ This is where the word “KbdClass” comes from J ¡ Also contains a function pointer which is responsible for processing the Keyboard or Mouse input hence the name : “ProcessKeyboardInput” ###### 95 ----- ###### Device Template ###### 96 ----- ###### It’s dump time ###### 97 ----- ### #14 Hook ProcessKeyboardInput ###### 98 ----- ###### ProcessKeyboardInput ###### 99 ###### ProcessKeyboardInputWorker � ----- ###### Inside ProcessKeyboardInput ¡ Find the first call to worker function. ¡ EBX points to scancode, ¡ Worker function is also a good target. � ###### 100 ----- ### #15 Hook ProcessKeyboardInputWorker ###### 101 ----- ###### Inline Hook ProcessKeyboardInputWorker ¡ Pretty obvious J ¡ You can easily see that it is a 3 parameter function with the 1[st] parameter as ScanCode. ###### 102 ----- ### #16 Hacking xxxProcessKeyEvent ###### 103 ----- ###### xxxProcessKeyEvent ¡ Called by ProcessKeyboardInputWorker until each input event gets consumed. ¡ Lets take a look at the parameters: ¡ Pointer to a Keyboard Event structure, ¡ An ULONG_PTR value carrying extra information, ¡ A flag indicating if key is from hardware or not. ¡ Performs some language specific operations. ###### 104 ----- ###### Break on xxxProcessKeyEvent ###### 105 ----- ###### Virtual Key vs. Scan Code #### Scancode Virtual Key ###### Hardware Dependent Independent ###### 106 ----- ###### Virtual Key vs. Scan Code ###### 107 ----- ###### xxxProcessKeyEvent ###### 108 ###### xxxProcessKeyEvent ----- ###### Raw Key State Table ¡ Just a simple array holding UP / DOWN states of keys. ¡ Represents the physical state of keyboard. ¡ Let’s put a BP on it. ###### 109 ----- ###### Hook UpdateRawKeyState ¡ Two params: ¡ VirtualKey ¡ Key State (Make / Break) ###### 110 ----- ### #17 RawKeyState Sniffer ###### 111 ----- ###### Sniffing Raw Key State Table ###### 112 ###### ¡ Can be easily retrieved by disassembling UpdateRawKeyState. ¡ First LEA instruction points to it, ¡ AV buster J ----- ###### Raw Key State Sniffer ¡ Put a BP on UpdateRawKeyState ¡ 2 bits for each VKEY (Down/Up – Toggled) ###### 113 ----- ###### Raw Key State Sniffer Demo ¡ Put a BP on UpdateRawKeyState end address. Offset: gafRawKeyState + (VK * 2 bits) ###### 114 ----- ### #18 Hacking xxxKeyEvent ###### 115 ----- ###### xxxKeyEvent ¡ Very critical function! ¡ Performs the POST operation of key into input queue. ¡ Called by xxxProcessKeyEvent for every input event. ###### 116 ###### ¡ Responsible from calling window hooks (wait for next slides) ¡ Params: ¡ Virtual Key with flags, ¡ ScanCode ----- ###### xxxKeyEvent ###### 117 ##### Call Low Update Level Async Key Post Input Keyboard State Message Hook Table ##### Post Input Message ----- ###### xxxKeyEvent ¡ Very critical function! ¡ Performs the POST operation of key into input queue. ¡ Called by xxxProcessKeyEvent for every input event. ¡ Responsible of calling window hooks (wait for next slides) ¡ Params: ¡ Virtual Key with flags, ¡ ScanCode ###### 118 ----- ### #19 Hacking UpdateAsyncKeyState ###### 119 ----- ###### UpdateAsyncKeyState ¡ Looks same as the method for UpdateRawKeyState ¡ Async keystate table could also be sniffed. ###### 120 ----- ### #20 Hacking PostInputMessage ###### 121 ----- ###### PostInputMessage ¡ What it does? ¡ Calls StoreQMessage for saving the message into queue.  Another target for hooking J ¡ Foreground thread queue receives the input event. ###### 122 ----- ###### PostInputMessage ¡ Put a BP on PostInputMessage. ###### 123 ----- ###### Here comes the second part J ###### 124 ###### ¡ Thread now has an input event in it’s queue. Kernel is over! ¡ What’s next? ----- ###### Create Window API ¡ Creates a window with a Window Class. ¡ What is a window class? ###### 125 ----- ###### Classes vs. Windows ###### 126 ## Window 3 ###### Window Procedure ###### Window Class ## Window 3 ## Window 1 ## 2 ----- ###### WNDPROC Function ¡ Function defined as: LRESULT CALLBACK WindowProc( _In_ HWND hwnd, _In_ UINT uMsg, _In_ WPARAM wParam, _In_ LPARAM lParam ); ###### 127 ###### ¡ Every window has one WNDPROC. This is the entry point for window messages. ----- ### #21 Hacking Window Procedures ###### 128 ----- ###### WNDPROC Function ###### 129 ###### ¡ We can either inline hook the WndProc or we can set a new WndProc by using GetWindowLong / SetWindowLong APIs. ----- ### #22 Subclassing a Window ###### 130 ----- ###### Subclassing ###### 131 ###### ¡ MSDN Blog: When you subclass a window, you set the window procedure to a function of your choosing, and you remember the original window procedure so you can pass it to the CallWindowProc function when your subclass function wants to pass the message to the original window procedure. Window Class Window Subclass Procedure (Log The Keystroke) Call The Original Window Procedure ###### Window Class ----- ###### Subclassing ¡ SetWindowSubclass API is pretty good for that. ###### 132 ###### ¡ CallWndProc could be used for retrieving keys from subclassed windows. ----- ###### Classes vs. Windows ###### 133 ## Window ###### Window Class ## Window 3 ## Window 1 ## 2 ----- ###### Message Loops ###### 134 ###### ¡ Each UI Thread has one message loop for processing window messages. ¡ http://msdn.microsoft.com/en-us/library/windows/desktop/ ms644928(v=vs.85).aspx ----- ### #23 Hacking GetMessage / PeekMessage ###### 135 ----- ###### GetMessage / PeekMessage ###### 136 ###### ¡ Used for getting a message from the thread’s message queue. ###### BOOL WINAPI GetMessage( _Out_ LPMSG lpMsg, _In_opt_ HWND hWnd, _In_ UINT wMsgFilterMin, _In_ UINT wMsgFilterMax ); BOOL WINAPI PeekMessage( _Out_ LPMSG lpMsg, _In_opt_ HWND hWnd, _In_ UINT wMsgFilterMin, _In_ UINT wMsgFilterMax, _In_ UINT wRemoveMsg ); ###### Blocking Non-Blocking ----- ###### GetMessage / PeekMessage ¡ Sniff GetMessage API call. ###### 137 ----- ### #24 Hacking Translate and Dispatch ###### 138 ----- ###### TranslateMessage / DispatchMessage ¡ Sniff TranslateMessage / DispatchMessage API calls. ###### 139 ----- ###### TranslateMessage ¡ Translate to what? ###### 140 ###### WM_CHAR ----- ###### DispatchMessage ¡ Calls the Window Procedure of a Window Class. ¡ Hooking it will definitely give you a lot power. ###### 141 ----- ### #25 Hacking Counterparts ###### 142 ----- ###### Kernel Mode Counterparts ###### 143 ###### ¡ The APIs which are used for message handling and delivering such as DispatchMessage,GetMessage, PeekMessage. ¡ All of them have their kernel mode counterparts starting with NtUser*. NtUserGetMessage, NtUserPeekMessage, NtUserTranslateMessage. ¡ These could be inline hooked by kernel mode keyloggers. ¡ Best example for this is “Elite Keylogger” (newest versions) ¡ Pretty effective! ----- ###### Inspecting Kernel Mode Counterparts ###### 144 ###### ¡ Anti-rootkits such as GMER, KernelDetective or Tuluka could be used for detecting these kind of modifications. ----- ### #26 SSDT Shadow Hooking ###### 145 ----- ###### What is SSDT Shadow? ¡ Just a simple table residing in win32k.sys module. ¡ Holds the addresses of system services. ###### 146 ###### ¡ This table is the glue between user mode APIs and the kernel mode counterparts. ¡ Hooking this table is so easy, and also effective. ----- ###### How it is used? NtUserGetMessage SSDT Shadow sysenter W32pServiceTable User Mode Kernel Mode ###### 147 |NtUserGetMessage sysenter|SSDT Shadow NtUserGetMessage| |---|---| ###### NtUserGetMessage ----- ###### How to check? ¡ We can use anti-rootkits ###### 148 ###### ¡ Windbg can also be used for displaying SSDT Shadow Table. ----- ###### Conversion Functions ¡ MapVirtualKey / MapVirtualKeyEx ¡ ToAscii / ToAsciiEx ¡ VkKeyScan / VkKeyScanEx ###### 149 ----- ### #27 GetKeyState / GetAsyncKeyState ###### 150 ----- ###### GetKeyState / GetAsyncKeyState ###### 151 ###### ¡ APIs for determining the state of a key at some point time. ¡ Difference is: ¡ GetKeyState is more specific and doesn’t reflect the interrupt-level state information, ¡ GetAsyncKeyState reflects the interrupt-level state of keys. ¡ One of the most widely used technique by keyloggers. ----- ### #28 GetKeyboardState ###### 152 ----- ###### GetKeyboardState ¡ API for determining the state of a keyboard. ¡ Fills an array of virtual keys. ¡ One of the most widely used method used by keyloggers. ###### 153 ----- ### #29 Text Output APIs ###### 154 ----- ###### Text Output APIs ¡ APIs used by applications to output text. ¡ Examples: ¡ TextOut ¡ ExtTextOut ¡ DrawText / DrawTextEx ###### 155 ----- ### #30 GetWindowText ###### 156 ----- ###### GetWindowText ¡ Can be used within an injected thread. ###### 157 ###### ¡ Copies the text of the specified window's title bar (if it has one) into a buffer. If the specified window is a control, the text of the control is copied. However, GetWindowText cannot retrieve the text of a control in another application. ----- ### #31 WM_GETTEXT Message ###### 158 ----- ###### WM_GETTEXT Message ¡ Can be used for retrieving another applications window content. ###### 159 ----- ### #32 SetWindowsHookEx ###### 160 ----- ###### SetWindowHookEx ¡ Another term for saying “Keylogger” J ###### 161 ###### ¡ Definitely the MOST WIDELY USED technique for keylogging!!! ¡ Nearly %95 of keyloggers use it J ----- ###### Why? ###### 162 ###### ¡ It is a way for providing callbacks to developers but widely used by malware authors. ¡ Have pretty much variations such as “Low Level Hook”, “Get Message Hook” and etc. ----- ###### Hook Types ¡ WH_CALLWNDPROC : Installs a hook procedure that monitors messages before the system sends them to the destination window procedure. ###### 163 ###### ¡ WH_CALLWNDPROCRET : Installs a hook procedure that monitors messages after they have been processed by the destination window procedure. ¡ WH_CBT : Installs a hook procedure that receives notifications useful to a Computer Based Training (CBT) application. ¡ WH_DEBUG : Installs a hook procedure useful for debugging other hook procedures. ----- ###### Hook Types ###### 164 ###### ¡ WH_GETMESSAGE : Installs a hook procedure that monitors messages posted to a message queue. ¡ WH_JOURNALRECORD : Installs a hook procedure that records input messages posted to the system message queue. ¡ WH_KEYBOARD : Installs a hook procedure that monitors keystroke messages. ¡ WH_KEYBOARD_LL : Installs a hook procedure that monitors low-level keyboard input events. ----- ###### Low Level Hooks ¡ Starting from this slide ¡ What is a Hook Function? ¡ Only low level hooks are allowed in Raw Input Thread. ¡ Ability to block some input events using these hooks. ¡ Will be described separately. ###### 165 ----- ### #33 DirectX Keylogger ###### 166 ----- ###### DirectX ¡ Not widely used but a good way for logging keystrokes. ###### 167 ----- ###### How? ¡ Pretty easy to implement with DirectInputCreateEx API. ¡ CreateDevice API is used for keyboard device creation. ###### 168 ----- ### #34 Browser Extensions ###### 169 ----- ###### Browser Extensions ¡ Sneaky creatures! ###### 170 ###### ¡ Not widely used but a great for bypassing security measures. ----- ###### Inspecting ¡ XPI files are just zip files. ¡ Unzip it and analyze what it does. ###### 171 ----- ###### Demos ¡ Go to Materials/Keyloggers folder: ¡ Analyze martin.exe ¡ Analyze AKLT_3.0.exe ¡ Analyze refog_personal_manager.exe” ¡ Analyze Elite Keylogger ¡ Analyze java keylogger ¡ Analyze Free Keylogger ###### 172 ----- # Thanks ###### 173 ----- ###### 174 # Questions? -----