-
Notifications
You must be signed in to change notification settings - Fork 356
/
Kd.c
2946 lines (2544 loc) · 91.9 KB
/
Kd.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file Kd.c
* @author Sina Karvandi (sina@hyperdbg.org)
* @author Alee Amini (alee@hyperdbg.org)
* @brief Routines related to kernel mode debugging
* @details
* @version 0.1
* @date 2020-12-20
*
* @copyright This project is released under the GNU Public License v3.
*
*/
#include "pch.h"
/**
* @brief initialize kernel debugger
* @details this function should be called on vmx non-root
*
* @return VOID
*/
VOID
KdInitializeKernelDebugger()
{
ULONG CoreCount = KeQueryActiveProcessorCount(0);
//
// Allocate DPC routine
//
// for (size_t i = 0; i < CoreCount; i++)
// {
// g_DbgState[i].KdDpcObject = CrsAllocateNonPagedPool(sizeof(KDPC));
//
// if (g_DbgState[i].KdDpcObject == NULL)
// {
// LogError("Err, allocating dpc holder for debuggee");
// return;
// }
// }
//
// Request pages for breakpoint detail
//
PoolManagerRequestAllocation(sizeof(DEBUGGEE_BP_DESCRIPTOR),
MAXIMUM_BREAKPOINTS_WITHOUT_CONTINUE,
BREAKPOINT_DEFINITION_STRUCTURE);
//
// Enable vm-exit on Hardware debug exceptions and breakpoints
// so, intercept #DBs and #BP by changing exception bitmap (one core)
//
BroadcastEnableDbAndBpExitingAllCores();
//
// Reset pause break requests
//
RtlZeroMemory(&g_IgnoreBreaksToDebugger, sizeof(DEBUGGEE_REQUEST_TO_IGNORE_BREAKS_UNTIL_AN_EVENT));
//
// Initialize list of breakpoints and breakpoint id
//
g_MaximumBreakpointId = 0;
InitializeListHead(&g_BreakpointsListHead);
//
// Indicate that the kernel debugger is active
//
g_KernelDebuggerState = TRUE;
}
/**
* @brief uninitialize kernel debugger
*
* @details this function should be called on vmx non-root
*
* @return VOID
*/
VOID
KdUninitializeKernelDebugger()
{
ULONG CoreCount;
if (g_KernelDebuggerState)
{
CoreCount = KeQueryActiveProcessorCount(0);
//
// Indicate that the kernel debugger is not active
//
g_KernelDebuggerState = FALSE;
//
// Reset pause break requests
//
RtlZeroMemory(&g_IgnoreBreaksToDebugger, sizeof(DEBUGGEE_REQUEST_TO_IGNORE_BREAKS_UNTIL_AN_EVENT));
//
// Remove all active breakpoints
//
BreakpointRemoveAllBreakpoints();
//
// Disable vm-exit on Hardware debug exceptions and breakpoints
// so, not intercept #DBs and #BP by changing exception bitmap (one core)
//
BroadcastDisableDbAndBpExitingAllCores();
}
}
/**
* @brief Checks whether the immediate messaging mechism is
* needed or not
* @param OperationCode
*
* @return BOOLEAN
*/
BOOLEAN
KdCheckImmediateMessagingMechanism(UINT32 OperationCode)
{
return (g_KernelDebuggerState && !(OperationCode & OPERATION_MANDATORY_DEBUGGEE_BIT));
}
/**
* @brief A test function for DPC
* @param Dpc
* @param DeferredContext
* @param SystemArgument1
* @param SystemArgument2
*
* @return VOID
*/
VOID
KdDummyDPC(PKDPC Dpc, PVOID DeferredContext, PVOID SystemArgument1, PVOID SystemArgument2)
{
UNREFERENCED_PARAMETER(Dpc);
UNREFERENCED_PARAMETER(SystemArgument1);
UNREFERENCED_PARAMETER(SystemArgument2);
LogInfo("I'm here %llx\n", DeferredContext);
}
/**
* @brief Add a DPC to dpc queue
* @param Routine
* @param Paramter
* @param ProcessorNumber
*
* @return VOID
*/
VOID
KdFireDpc(PVOID Routine, PVOID Paramter)
{
ULONG CurrentCore = KeGetCurrentProcessorNumberEx(NULL);
KeInitializeDpc(g_DbgState[CurrentCore].KdDpcObject, Routine, Paramter);
KeInsertQueueDpc(g_DbgState[CurrentCore].KdDpcObject, NULL, NULL);
}
/**
* @brief Query for process/thread interception status
* @param CoreId
* @param TracingType
*
* @return BOOLEAN whether it's activated or not
*/
BOOLEAN
KdQueryDebuggerQueryThreadOrProcessTracingDetailsByCoreId(UINT32 CoreId,
DEBUGGER_THREAD_PROCESS_TRACING TracingType)
{
BOOLEAN Result = FALSE;
PROCESSOR_DEBUGGING_STATE * DbgState = &g_DbgState[CoreId];
switch (TracingType)
{
case DEBUGGER_THREAD_PROCESS_TRACING_INTERCEPT_CLOCK_INTERRUPTS_FOR_THREAD_CHANGE:
Result = DbgState->ThreadOrProcessTracingDetails.InterceptClockInterruptsForThreadChange;
break;
case DEBUGGER_THREAD_PROCESS_TRACING_INTERCEPT_CLOCK_INTERRUPTS_FOR_PROCESS_CHANGE:
Result = DbgState->ThreadOrProcessTracingDetails.InterceptClockInterruptsForProcessChange;
break;
case DEBUGGER_THREAD_PROCESS_TRACING_INTERCEPT_CLOCK_DEBUG_REGISTER_INTERCEPTION:
Result = DbgState->ThreadOrProcessTracingDetails.DebugRegisterInterceptionState;
break;
case DEBUGGER_THREAD_PROCESS_TRACING_INTERCEPT_CLOCK_WAITING_FOR_MOV_CR3_VM_EXITS:
Result = DbgState->ThreadOrProcessTracingDetails.IsWatingForMovCr3VmExits;
break;
default:
LogError("Err, debugger encountered an unknown query type for querying process or thread interception details");
break;
}
return Result;
}
/**
* @brief calculate the checksum of recived buffer from debugger
*
* @param Buffer
* @param LengthReceived
* @return BYTE
*/
_Use_decl_annotations_
BYTE
KdComputeDataChecksum(PVOID Buffer, UINT32 Length)
{
BYTE CalculatedCheckSum = 0;
BYTE Temp = 0;
while (Length--)
{
Temp = *(BYTE *)Buffer;
CalculatedCheckSum = CalculatedCheckSum + Temp;
Buffer = (PVOID)((UINT64)Buffer + 1);
}
return CalculatedCheckSum;
}
/**
* @brief Sends a HyperDbg response packet to the debugger
*
* @param PacketType
* @param Response
* @param OptionalBuffer
* @param OptionalBufferLength
* @return BOOLEAN
*/
_Use_decl_annotations_
BOOLEAN
KdResponsePacketToDebugger(
DEBUGGER_REMOTE_PACKET_TYPE PacketType,
DEBUGGER_REMOTE_PACKET_REQUESTED_ACTION Response,
CHAR * OptionalBuffer,
UINT32 OptionalBufferLength)
{
DEBUGGER_REMOTE_PACKET Packet = {0};
BOOLEAN Result = FALSE;
//
// Make the packet's structure
//
Packet.Indicator = INDICATOR_OF_HYPERDBG_PACKET;
Packet.TypeOfThePacket = PacketType;
//
// Set the requested action
//
Packet.RequestedActionOfThePacket = Response;
//
// Send the serial packets to the debugger
//
if (OptionalBuffer == NULL || OptionalBufferLength == 0)
{
Packet.Checksum = KdComputeDataChecksum((PVOID)((UINT64)&Packet + 1),
sizeof(DEBUGGER_REMOTE_PACKET) - sizeof(BYTE));
//
// Check if we're in Vmx-root, if it is then we use our customized HIGH_IRQL Spinlock,
// if not we use the windows spinlock
//
ScopedSpinlock(
DebuggerResponseLock,
Result = SerialConnectionSend((CHAR *)&Packet,
sizeof(DEBUGGER_REMOTE_PACKET)));
}
else
{
Packet.Checksum = KdComputeDataChecksum((PVOID)((UINT64)&Packet + 1),
sizeof(DEBUGGER_REMOTE_PACKET) - sizeof(BYTE));
Packet.Checksum += KdComputeDataChecksum((PVOID)OptionalBuffer, OptionalBufferLength);
//
// Check if we're in Vmx-root, if it is then we use our customized HIGH_IRQL Spinlock,
// if not we use the windows spinlock
//
ScopedSpinlock(
DebuggerResponseLock,
Result = SerialConnectionSendTwoBuffers((CHAR *)&Packet,
sizeof(DEBUGGER_REMOTE_PACKET),
OptionalBuffer,
OptionalBufferLength));
}
if (g_IgnoreBreaksToDebugger.PauseBreaksUntilSpecialMessageSent && g_IgnoreBreaksToDebugger.SpeialEventResponse == Response)
{
//
// Set it to false by zeroing it
//
RtlZeroMemory(&g_IgnoreBreaksToDebugger, sizeof(DEBUGGEE_REQUEST_TO_IGNORE_BREAKS_UNTIL_AN_EVENT));
}
return Result;
}
/**
* @brief Sends a HyperDbg logging response packet to the debugger
*
* @param OptionalBuffer
* @param OptionalBufferLength
* @param OperationCode
* @return BOOLEAN
*/
_Use_decl_annotations_
BOOLEAN
KdLoggingResponsePacketToDebugger(
CHAR * OptionalBuffer,
UINT32 OptionalBufferLength,
UINT32 OperationCode)
{
DEBUGGER_REMOTE_PACKET Packet = {0};
BOOLEAN Result = FALSE;
//
// Make the packet's structure
//
Packet.Indicator = INDICATOR_OF_HYPERDBG_PACKET;
Packet.TypeOfThePacket = DEBUGGER_REMOTE_PACKET_TYPE_DEBUGGEE_TO_DEBUGGER;
//
// Set the requested action
//
Packet.RequestedActionOfThePacket = DEBUGGER_REMOTE_PACKET_REQUESTED_ACTION_DEBUGGEE_LOGGING_MECHANISM;
//
// Calculate checksum
//
Packet.Checksum = KdComputeDataChecksum((PVOID)((UINT64)&Packet + 1),
sizeof(DEBUGGER_REMOTE_PACKET) - sizeof(BYTE));
Packet.Checksum += KdComputeDataChecksum((PVOID)&OperationCode, sizeof(UINT32));
Packet.Checksum += KdComputeDataChecksum((PVOID)OptionalBuffer, OptionalBufferLength);
//
// Check if we're in Vmx-root, if it is then we use our customized HIGH_IRQL Spinlock,
// if not we use the windows spinlock
//
ScopedSpinlock(
DebuggerResponseLock,
Result = SerialConnectionSendThreeBuffers((CHAR *)&Packet,
sizeof(DEBUGGER_REMOTE_PACKET),
&OperationCode,
sizeof(UINT32),
OptionalBuffer,
OptionalBufferLength));
return Result;
}
/**
* @brief Handles debug events when kernel-debugger is attached
*
* @param DbgState The state of the debugger on the current core
* @param TrapSetByDebugger Shows whether a trap set by debugger or not
*
* @return VOID
*/
VOID
KdHandleDebugEventsWhenKernelDebuggerIsAttached(PROCESSOR_DEBUGGING_STATE * DbgState, BOOLEAN TrapSetByDebugger)
{
DEBUGGER_TRIGGERED_EVENT_DETAILS TargetContext = {0};
BOOLEAN IgnoreDebugEvent = FALSE;
UINT64 LastVmexitRip = VmFuncGetLastVmexitRip(DbgState->CoreId);
//
// It's a breakpoint and should be handled by the kernel debugger
//
TargetContext.Context = LastVmexitRip;
if (TrapSetByDebugger)
{
//
// *** Handle a regular trap flag (most of the times as a result of stepping) set by the debugger ***
//
//
// Check and handle if there is a software defined breakpoint
//
if (!BreakpointCheckAndHandleDebuggerDefinedBreakpoints(DbgState,
LastVmexitRip,
DEBUGGEE_PAUSING_REASON_DEBUGGEE_STEPPED,
FALSE))
{
if (g_HardwareDebugRegisterDetailsForStepOver.Address != NULL)
{
//
// Check if it's caused by a step-over hardware debug breakpoint or not
//
if (LastVmexitRip == g_HardwareDebugRegisterDetailsForStepOver.Address)
{
if (g_HardwareDebugRegisterDetailsForStepOver.ProcessId == PsGetCurrentProcessId() && g_HardwareDebugRegisterDetailsForStepOver.ThreadId == PsGetCurrentThreadId())
{
//
// It's a step caused by a debug register breakpoint step-over
//
RtlZeroMemory(&g_HardwareDebugRegisterDetailsForStepOver, sizeof(HARDWARE_DEBUG_REGISTER_DETAILS));
}
else
{
//
// Should be ignored because it's a hardware debug register that is
// likely triggered by other thread
//
IgnoreDebugEvent = TRUE;
//
// Also, we should re-apply the hardware debug breakpoint on this thread
//
SetDebugRegisters(DEBUGGER_DEBUG_REGISTER_FOR_STEP_OVER,
BREAK_ON_INSTRUCTION_FETCH,
FALSE,
g_HardwareDebugRegisterDetailsForStepOver.Address);
}
}
}
if (!IgnoreDebugEvent)
{
//
// Handle a regular step
//
KdHandleBreakpointAndDebugBreakpoints(DbgState,
DEBUGGEE_PAUSING_REASON_DEBUGGEE_STEPPED,
&TargetContext);
}
}
}
else
{
//
// It's a regular debug break event
//
KdHandleBreakpointAndDebugBreakpoints(DbgState,
DEBUGGEE_PAUSING_REASON_DEBUGGEE_HARDWARE_DEBUG_REGISTER_HIT,
&TargetContext);
}
}
/**
* @brief before halting any core, all the tasks will be applied to all
* cores including the main core
* @details these tasks will be applied in vmx-root
*
* @param DbgState The state of the debugger on the current core
*
* @return VOID
*/
VOID
KdApplyTasksPreHaltCore(PROCESSOR_DEBUGGING_STATE * DbgState)
{
//
// Check to unset mov to cr3 vm-exits
//
if (DbgState->ThreadOrProcessTracingDetails.InitialSetProcessChangeEvent == TRUE)
{
//
// Disable process change detection
//
ProcessEnableOrDisableThreadChangeMonitor(DbgState, FALSE);
//
// Avoid future sets/unsets
//
DbgState->ThreadOrProcessTracingDetails.InitialSetProcessChangeEvent = FALSE;
DbgState->ThreadOrProcessTracingDetails.InitialSetByClockInterrupt = FALSE;
}
//
// Check to unset change thread alerts
//
if (DbgState->ThreadOrProcessTracingDetails.InitialSetThreadChangeEvent == TRUE)
{
//
// Disable thread change alerts
//
ThreadEnableOrDisableThreadChangeMonitor(DbgState, FALSE);
//
// Avoid future sets/unsets
//
DbgState->ThreadOrProcessTracingDetails.InitialSetThreadChangeEvent = FALSE;
DbgState->ThreadOrProcessTracingDetails.InitialSetByClockInterrupt = FALSE;
}
}
/**
* @brief before continue any core, all the tasks will be applied to all
* cores including the main core
* @details these tasks will be applied in vmx-root
*
* @param DbgState The state of the debugger on the current core
*
* @return VOID
*/
VOID
KdApplyTasksPostContinueCore(PROCESSOR_DEBUGGING_STATE * DbgState)
{
//
// Check to apply hardware debug register breakpoints for step-over
//
if (DbgState->HardwareDebugRegisterForStepping != NULL)
{
SetDebugRegisters(DEBUGGER_DEBUG_REGISTER_FOR_STEP_OVER,
BREAK_ON_INSTRUCTION_FETCH,
FALSE,
DbgState->HardwareDebugRegisterForStepping);
DbgState->HardwareDebugRegisterForStepping = NULL;
}
//
// Check to apply mov to cr3 vm-exits
//
if (DbgState->ThreadOrProcessTracingDetails.InitialSetProcessChangeEvent == TRUE)
{
//
// Enable process change detection
//
ProcessEnableOrDisableThreadChangeMonitor(DbgState, TRUE);
}
//
// Check to apply thread change alerts
//
if (DbgState->ThreadOrProcessTracingDetails.InitialSetThreadChangeEvent == TRUE)
{
//
// Enable alert for thread changes
//
ThreadEnableOrDisableThreadChangeMonitor(DbgState, TRUE);
}
}
/**
* @brief continue the debuggee, this function gurantees that all other cores
* are continued (except current core)
* @param DbgState The state of the debugger on the current core
* @param SpeialEventResponse
* @param PauseBreaksUntilSpecialMessageSent
*
* @return VOID
*/
_Use_decl_annotations_
VOID
KdContinueDebuggee(PROCESSOR_DEBUGGING_STATE * DbgState,
BOOLEAN PauseBreaksUntilSpecialMessageSent,
DEBUGGER_REMOTE_PACKET_REQUESTED_ACTION SpeialEventResponse)
{
if (PauseBreaksUntilSpecialMessageSent)
{
g_IgnoreBreaksToDebugger.PauseBreaksUntilSpecialMessageSent = TRUE;
g_IgnoreBreaksToDebugger.SpeialEventResponse = SpeialEventResponse;
}
//
// Check if we should enable interrupts in this core or not,
// we have another same check in SWITCHING CORES too
//
VmFuncCheckAndEnableExternalInterrupts(DbgState->CoreId);
//
// Unlock all the cores
//
ULONG CoreCount = KeQueryActiveProcessorCount(0);
for (size_t i = 0; i < CoreCount; i++)
{
SpinlockUnlock(&g_DbgState[i].Lock);
}
}
/**
* @brief continue the debuggee, just the current operating core
* @param DbgState The state of the debugger on the current core
*
* @return VOID
*/
VOID
KdContinueDebuggeeJustCurrentCore(PROCESSOR_DEBUGGING_STATE * DbgState)
{
//
// In the case of any halting event, the processor won't send NMIs
// to other cores if this field is set
//
DbgState->DoNotNmiNotifyOtherCoresByThisCore = TRUE;
//
// Unlock the current core
//
SpinlockUnlock(&DbgState->Lock);
}
/**
* @brief read registers
* @param DbgState The state of the debugger on the current core
* @param ReadRegisterRequest
*
* @return BOOLEAN
*/
_Use_decl_annotations_
BOOLEAN
KdReadRegisters(PROCESSOR_DEBUGGING_STATE * DbgState, PDEBUGGEE_REGISTER_READ_DESCRIPTION ReadRegisterRequest)
{
GUEST_EXTRA_REGISTERS ERegs = {0};
if (ReadRegisterRequest->RegisterID == DEBUGGEE_SHOW_ALL_REGISTERS)
{
//
// Add General purpose registers
//
memcpy((void *)((CHAR *)ReadRegisterRequest + sizeof(DEBUGGEE_REGISTER_READ_DESCRIPTION)),
DbgState->Regs,
sizeof(GUEST_REGS));
//
// Read Extra registers
//
ERegs.CS = DebuggerGetRegValueWrapper(NULL, REGISTER_CS);
ERegs.SS = DebuggerGetRegValueWrapper(NULL, REGISTER_SS);
ERegs.DS = DebuggerGetRegValueWrapper(NULL, REGISTER_DS);
ERegs.ES = DebuggerGetRegValueWrapper(NULL, REGISTER_ES);
ERegs.FS = DebuggerGetRegValueWrapper(NULL, REGISTER_FS);
ERegs.GS = DebuggerGetRegValueWrapper(NULL, REGISTER_GS);
ERegs.RFLAGS = DebuggerGetRegValueWrapper(NULL, REGISTER_RFLAGS);
ERegs.RIP = DebuggerGetRegValueWrapper(NULL, REGISTER_RIP);
//
// copy at the end of ReadRegisterRequest structure
//
memcpy((void *)((CHAR *)ReadRegisterRequest + sizeof(DEBUGGEE_REGISTER_READ_DESCRIPTION) + sizeof(GUEST_REGS)),
&ERegs,
sizeof(GUEST_EXTRA_REGISTERS));
}
else
{
ReadRegisterRequest->Value = DebuggerGetRegValueWrapper(DbgState->Regs, ReadRegisterRequest->RegisterID);
}
return TRUE;
}
/**
* @brief read registers
* @param Regs
* @param ReadRegisterRequest
*
* @return BOOLEAN
*/
_Use_decl_annotations_
BOOLEAN
KdReadMemory(PGUEST_REGS Regs, PDEBUGGEE_REGISTER_READ_DESCRIPTION ReadRegisterRequest)
{
GUEST_EXTRA_REGISTERS ERegs = {0};
if (ReadRegisterRequest->RegisterID == DEBUGGEE_SHOW_ALL_REGISTERS)
{
//
// Add General purpose registers
//
memcpy((void *)((CHAR *)ReadRegisterRequest + sizeof(DEBUGGEE_REGISTER_READ_DESCRIPTION)),
Regs,
sizeof(GUEST_REGS));
//
// Read Extra registers
//
ERegs.CS = DebuggerGetRegValueWrapper(NULL, REGISTER_CS);
ERegs.SS = DebuggerGetRegValueWrapper(NULL, REGISTER_SS);
ERegs.DS = DebuggerGetRegValueWrapper(NULL, REGISTER_DS);
ERegs.ES = DebuggerGetRegValueWrapper(NULL, REGISTER_ES);
ERegs.FS = DebuggerGetRegValueWrapper(NULL, REGISTER_FS);
ERegs.GS = DebuggerGetRegValueWrapper(NULL, REGISTER_GS);
ERegs.RFLAGS = DebuggerGetRegValueWrapper(NULL, REGISTER_RFLAGS);
ERegs.RIP = DebuggerGetRegValueWrapper(NULL, REGISTER_RIP);
//
// copy at the end of ReadRegisterRequest structure
//
memcpy((void *)((CHAR *)ReadRegisterRequest + sizeof(DEBUGGEE_REGISTER_READ_DESCRIPTION) + sizeof(GUEST_REGS)),
&ERegs,
sizeof(GUEST_EXTRA_REGISTERS));
}
else
{
ReadRegisterRequest->Value = DebuggerGetRegValueWrapper(Regs, ReadRegisterRequest->RegisterID);
}
return TRUE;
}
/**
* @brief change the current operating core to new core
*
* @param DbgState The state of the debugger on the current core
* @param NewCore
* @return BOOLEAN
*/
BOOLEAN
KdSwitchCore(PROCESSOR_DEBUGGING_STATE * DbgState, UINT32 NewCore)
{
ULONG CoreCount = KeQueryActiveProcessorCount(0);
//
// Check if core is valid or not
//
if (NewCore >= CoreCount)
{
//
// Invalid core count
//
return FALSE;
}
//
// *** Core is valid ***
//
//
// Check if we should enable interrupts in this core or not
//
VmFuncCheckAndEnableExternalInterrupts(DbgState->CoreId);
//
// Unset the current operating core (this is not important as if we
// return from the operating function then the it will be unset
// automatically but as we want to not have two operating cores
// at the same time so we unset it here too)
//
DbgState->MainDebuggingCore = FALSE;
//
// Set new operating core
//
g_DbgState[NewCore].MainDebuggingCore = TRUE;
//
// Unlock the new core
// *** We should not unlock the spinlock here as the other core might
// simultaneously start sending packets and corrupt our packets ***
//
return TRUE;
}
/**
* @brief Notify user-mode to unload the debuggee and close the connections
*
* @return VOID
*/
VOID
KdCloseConnectionAndUnloadDebuggee()
{
//
// Send one byte buffer and operation codes
//
LogCallbackSendBuffer(OPERATION_COMMAND_FROM_DEBUGGER_CLOSE_AND_UNLOAD_VMM,
"$",
1,
TRUE);
}
/**
* @brief Notify user-mode to re-send (reload) the symbol packets
* @param SymPacket
*
* @return VOID
*/
_Use_decl_annotations_
VOID
KdReloadSymbolDetailsInDebuggee(PDEBUGGEE_SYMBOL_REQUEST_PACKET SymPacket)
{
//
// Send one byte buffer and operation codes
//
LogCallbackSendBuffer(OPERATION_COMMAND_FROM_DEBUGGER_RELOAD_SYMBOL,
SymPacket,
sizeof(DEBUGGEE_SYMBOL_REQUEST_PACKET),
TRUE);
}
/**
* @brief Notify user-mode to about new user-input buffer
* @param Descriptor
* @param Len
*
* @return VOID
*/
VOID
KdNotifyDebuggeeForUserInput(DEBUGGEE_USER_INPUT_PACKET * Descriptor, UINT32 Len)
{
//
// Send user-input buffer along with operation code to
// the user-mode
//
LogCallbackSendBuffer(OPERATION_DEBUGGEE_USER_INPUT,
Descriptor,
Len,
TRUE);
}
/**
* @brief Notify user-mode to unload the debuggee and close the connections
* @param Value
*
* @return VOID
*/
VOID
KdSendFormatsFunctionResult(UINT64 Value)
{
DEBUGGEE_FORMATS_PACKET FormatsPacket = {0};
FormatsPacket.Result = DEBUGGER_OPERATION_WAS_SUCCESSFUL;
FormatsPacket.Value = Value;
//
// Kernel debugger is active, we should send the bytes over serial
//
KdResponsePacketToDebugger(
DEBUGGER_REMOTE_PACKET_TYPE_DEBUGGEE_TO_DEBUGGER,
DEBUGGER_REMOTE_PACKET_REQUESTED_ACTION_DEBUGGEE_RESULT_OF_FORMATS,
&FormatsPacket,
sizeof(DEBUGGEE_FORMATS_PACKET));
}
/**
* @brief Notify debugger that the execution of command finished
* @param CoreId
*
* @return VOID
*/
VOID
KdSendCommandFinishedSignal(UINT32 CoreId)
{
//
// Halt other cores again
//
KdHandleBreakpointAndDebugBreakpointsCallback(CoreId,
DEBUGGEE_PAUSING_REASON_DEBUGGEE_COMMAND_EXECUTION_FINISHED,
NULL);
}
/**
* @brief Tries to get the lock and won't return until successfully get the lock
*
* @param DbgState The state of the debugger on the current core
*
* @return VOID
*/
_Use_decl_annotations_
VOID
KdHandleHaltsWhenNmiReceivedFromVmxRoot(PROCESSOR_DEBUGGING_STATE * DbgState)
{
//
// During the debugging of HyperDbg, we realized that whenever an
// event is set, one core might (and will) get the lock of the
// debugging and other cores that are triggering the same event
// go to the wait for the debugging lock
// As we send NMIs to all cores to notify them and halt them,
// a core might be in VMX-root and receive the NMI
// Handling the NMI and halting from the NMI handlers is not
// possible as the stack of the Windows' NMI handler routine
// is not big enough to handle HyperDbg's command dispatching
// routines, so if the user switches to the cores that are halted
// from an NMI handler then we ran out of stack and debugger crashes
// It is also not possible to change the stack to a bigger stack because
// we're not really interested in allocating other memories for the stack
// and also the target stack will not be a valid Windows stack as it's
// supposed to run with NMI handling routines.
//
// By the way, I conclude to let the NMI handler finish its normal
// execution and then we check for the possible pausing reasons.
//
// The pausing scenario should be checked two cases,
// 1. If the current core is stucked in spinlock of getting
// the debug lock
// 2. If the current core is making it self ready for the vm-entry
//
// In these two cases we should check for the possible halting of the core
//
//
// Handle halt of the current core as an NMI
//
KdHandleNmi(DbgState);
//
// Set the indication to false as we handled it
//
DbgState->NmiState.NmiCalledInVmxRootRelatedToHaltDebuggee = FALSE;
}
/**
* @brief Tries to get the lock and won't return until successfully get the lock
*
* @param DbgState The state of the debugger on the current core
* @param LONG Lock variable
*
* @return VOID
*/
VOID
KdCustomDebuggerBreakSpinlockLock(PROCESSOR_DEBUGGING_STATE * DbgState, volatile LONG * Lock)
{
unsigned wait = 1;
//
// *** Lock handling breaks ***
//
while (!SpinlockTryLock(Lock))
{
for (unsigned i = 0; i < wait; ++i)
{
_mm_pause();
}
//
// check if the core needs to be locked
//
if (DbgState->NmiState.WaitingToBeLocked)
{
//
// We should ignore one MTF as we touched MTF and it's not usable anymore
//
VmFuncChangeIgnoreOneMtfState(DbgState->CoreId, TRUE);
//
// Handle break of the core
//
if (DbgState->NmiState.NmiCalledInVmxRootRelatedToHaltDebuggee)
{
//
// Handle it like an NMI is received from VMX root
//
KdHandleHaltsWhenNmiReceivedFromVmxRoot(DbgState);
}
else
{
//
// Handle halt of the current core as an NMI
//
KdHandleNmi(DbgState);
}
}
//
// Don't call "pause" too many times. If the wait becomes too big,
// clamp it to the MaxWait.
//
if (wait * 2 > 65536)
{
wait = 65536;
}
else
{
wait = wait * 2;
}
}
}
/**
* @brief Handle broadcast NMIs for halting cores in vmx-root mode
*
* @param CoreId
* @param IsOnVmxNmiHandler
*
* @return VOID
*/
VOID
KdHandleNmiBroadcastDebugBreaks(UINT32 CoreId, BOOLEAN IsOnVmxNmiHandler)
{
//
// Get the current debugging state
//
PROCESSOR_DEBUGGING_STATE * DbgState = &g_DbgState[CoreId];
//
// We use it as a global flag (for both vmx-root and vmx non-root), because
// generally it doesn't have any use case in vmx-root (IsOnVmxNmiHandler == FALSE)
// but in some cases, we might set the MTF but another vm-exit receives before
// MTF and in that place if it tries to trigger and event, then the MTF is not
// handled and the core is not locked properly, just waits to get the handle
// of the "DebuggerHandleBreakpointLock", so we check this flag there
//