-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDriver.c
114 lines (98 loc) · 2.34 KB
/
Driver.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*******
Undefined Instruction Emulator Framework
Kernel-mode driver for Windows 7 x86
psrok1 @ 2016
********/
#include "Driver.h"
// Get IDTR register
IDTR GetIDTR() {
IDTR idtr;
__asm {
cli; // Lock interrupts
sidt idtr;
sti; // Unlock interrupts
}
return idtr;
}
// Get address of ISR for specified service
__forceinline ISR GetISR(PIDT desc_table, UINT8 serv_no) {
_asm cli;
ISR routine = (ISR)((desc_table[serv_no].offs_hi << 16) + desc_table[serv_no].offs_lo);
_asm sti;
return routine;
}
// Set address of ISR for specified service
__forceinline void SetISR(PIDT desc_table, UINT8 serv_no, ISR isr) {
IDTDescriptor* desc = &(desc_table[serv_no]);
UINT32 i_isr = (UINT32)isr;
_asm cli; // lock
desc->offs_hi = i_isr >> 16;
desc->offs_lo = i_isr & 0xFFFF;
_asm sti; // unlock
}
ISR old_israddr = NULL;
// UD exception handler
__declspec(naked) HookRoutine() {
__asm {
// Store context
pushfd;
pushad;
// Get fault address
lea eax, [esp + 0x24];
// Push pointer to stored context
push esp;
// Push fault address
push eax;
// Call handler
mov esi, offset HandleUndefInstruction;
call esi;
// If handler refuses to handle exception: try next
test eax, eax;
jz unhandledExc;
// If exception is handled:
// Restore context and return from interrupt
popad;
popfd;
iretd;
unhandledExc:
// If exception isn't handled:
// Jumping to system handler
popad
popfd
jmp old_israddr
}
}
// Install custom UD handler
void InstallHookISR(ISR hook_addr) {
IDTR idtr = GetIDTR();
ISR israddr = GetISR(idtr.desc_table, 0x06);
if (old_israddr == israddr)
return; // Already hooked
old_israddr = israddr;
SetISR(idtr.desc_table, 0x06, hook_addr);
}
// Restore system UD handler
void UninstallHookISR() {
if (!old_israddr)
return; // Not hooked
IDTR idtr = GetIDTR();
SetISR(idtr.desc_table, 0x06, old_israddr);
old_israddr = 0;
}
/********************/
/* Entry/Exit point */
/********************/
void DriverUnload(PDRIVER_OBJECT pDriverObject)
{
UNREFERENCED_PARAMETER(pDriverObject);
UninstallHookISR();
DbgPrint("Driver unloaded\n");
}
NTSTATUS DriverEntry(_In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath)
{
UNREFERENCED_PARAMETER(RegistryPath);
DriverObject->DriverUnload = DriverUnload;
InstallHookISR(HookRoutine);
DbgPrint("Driver loaded\n");
return STATUS_SUCCESS;
}