Sunday, November 29, 2015

NtUserBeginPaint Stack Memory Disclosure

Few month ago I was researching in Windows Kernel using binary diffing technique. I have discovered that it is possible to disclose portions of uninitialized kernel stack memory to user-mode applications in Windows 7-8 through the win32k!NtUserBeginPaint (*Patched*) system call. This leaks PAINTSTRUCT fields that were not filled out/overwritten properly by NtUserBeginPaint. More specifically, exactly 16 bytes of uninitialized kernel stack memory are copied to ring-3 in one of two execution contexts. User application should pass two arguments (HWND, LPPAINTSTRUCT) to NtUserBeginPaint system call. The HWND argument that has been sent in this function will first be validated with ValidateHwndEx function:

The internal win32k!BeginPaint function then filled out a local copy of the structure (PAINTSTRUCT field) on the kernel stack.


Src variable is PAINTSTRUCT field to store PAINT information. But, I have found that 16 bytes of that structure are uninitialized. When it is copied back to user-mode in its entirety, its contents disclose leftover kernel stack bytes containing potentially sensitive information (kernel address etc.).

After calling memcpy function some bytes are clearly visible in the below hex dump. These bytes are contained a number of kernel-space addresses etc.

kd> dd eax < === user space now contains kernel stack information

010af3c4  0401037d 00000000 00000000 00000000
010af3d4  000000a0 00000035 00000000 00000000
010af3e4  fffffffe 8f71f864 81970e17 ae7f7b80
010af3f4  ae7f7b8c ae7f7b80 ae7f7b74 10000000
010af404  41414141 41414141 41414141 41414141
010af414  41414141 41414141 41414141 41414141
010af424  41414141 41414141 41414141 41414141
010af434  41414141 41414141 41414141 41414141

kd> u 81970e17 
nt!KiSystemServicePostCall:
81970e17 f6456c01        test    byte ptr [ebp+6Ch],1
81970e1b 7434            je      nt!KiSystemServicePostCall+0x3a (81970e51)
81970e1d 8bf0            mov     esi,eax
81970e1f ff153041a781    call    dword ptr [nt!_imp__KeGetCurrentIrql (81a74130)]
81970e25 0ac0            or      al,al
81970e27 0f85c9010000    jne     nt!KiSystemCallExit2+0x97 (81970ff6)
81970e2d 8bc6            mov     eax,esi
81970e2f 648b0d24010000  mov     ecx,dword ptr fs:[124h]



stack contained address:
 8f71f864 <==== win32k!NtUserCreateWindowEx 
 81970e17 <==== nt!KiSystemServicePostCall address


The proof-of-concept program demonstrates the disclosure by spraying the kernel stack with a large number of 0x41 ('A') marker bytes, and then calling the affected system call. An example output is as follows:

Sunday, November 22, 2015

0xFFF – kernel mode SYSCALL

Hal hazırda yazdığım kernelin üzərində işləyirəm… Demək normal halda OS üzərində System call mexanizmini NT Kernel tərzində SSDT – SSDTS bənzəri etdim birinci fikirləşdim ki, standart IRQ (interrupt request) göndərərək –  Trap handler vasitəsi ilə (int 0x2e) birbaşa KiSystemService dispatcher çağırmaq ancaq sonra qərarımdan döndüm çünki SYSENTER/SYSEXIT instruction-larından istifadə etməyə qərar verdim və maraqlanmağa başladım.

SYSENTER/SYSEXIT Interrupt çoxluqundan qaçınmaq üçün hazırlanmış Syscall based instruction-dır.

NT architecture native api istifadə zamanı Zw və Nt prefixlərindən istifadə edir. Windows OS privilige level yoxlanılması üçün previous mode istifadə edir. Belə ki, previous mode dəyəri (user or kernel) hər dəfə trap handling icra edildiyində kernel `thread` içində  bunu saxlayır və daxil olan exception,trap,syscall imtiyaz səviyyəsini yoxlayır. Əgər system call kernel driver tərəfindən gəlirsə `probing` və `capturing` prosessləri ötülür. Həmçinin bu native APİ üçün interrupt və yaxud sysenter ehtiyyac yoxdur çünki CPU artıq doğru privilige level-dədir. NTDLL modulu tərəfindən NT və Zw prefixləri altında funksiyalar export edilir. Yalnız əgər birbaşa NtCreateFile (Native APİ) kernel mode address çağrılarsa previous mode bu əməliyyatı sonlandırar.

User mode application-lar NTDLL.LIB ilə `link` edildikdə System servis dispatcher vasitəsi ilə Kernel mode (context switching – mode transition) keçid edilir. Ümumiyyətlə NT kernel `System servic call stub` üçün ayrıca instruction `hardcode` əvəzinə bunu shared strukturada saxlayır (KUSER_SHARED_DATA).

_KUSER_SHARED_DATA+(0x300) offsetində yerləşir System servis çağırıcısı

0:001> dt ntdll!_KUSER_SHARED_DATA

+0x000 TickCountLowDeprecated : Uint4B

+0x004 TickCountMultiplier : Uint4B

+0x008 InterruptTime    : _KSYSTEM_TIME

[…]

+0x300 SystemCall       : Uint4B <========

+0x304 SystemCallReturn : Uint4B

+0x308 SystemCallPad    : [3] Uint8B

[…]
WINDOWS Əməliyyat sistemi üzərində bu Structure (_KUSER_SHARED_DATA) statik adrese sahibdir = 0x7FFE0000.
0: kd> u ntdll!NtReadFile

ntdll!NtReadFile:

77f761e8 b8b7000000       mov     eax,0xb7

77f761ed ba0003fe7f       mov     edx,0x7ffe0300 <=====

77f761f2 ffd2             call    edx

77f761f4 c22400           ret     0x24

lkd> u poi(0x7ffe0300)

ntdll!KiFastSystemCall:

770b64f0 8bd4            mov     edx,esp

770b64f2 0f34            sysenter <========

ntdll!KiFastSystemCallRet:

770b64f4 c3              ret

770b64f5 8da42400000000  lea     esp,[esp]

770b64fc 8d642400        lea     esp,[esp]

ntdll!KiIntSystemCall:

770b6500 8d542408        lea     edx,[esp+8]

770b6504 cd2e            int     2Eh

770b6506 c3              ret
Win7 üzərində system call dispatcher olaraq sysenter istifadə edildiyini gördük.
sysenter instruction-dan danışım: CPL = 0 (privilige level 0) olan system prosedurlarını və rutinlərini sürətli çağırışını təmin edir. Bu instruction CPL = 0 (privilige level 0) üzərində olan əməliyyat sistemi və yaxud icrad edici prosedurların CPL = 3 (privilige level 3) üzərində çalışdırmaq üçün maksimum performans təşkil edir.
SYSENTER instruction icra edilmədən öncə, proqram təminatı privilige level 0 (CPL 0) code segment və code entry point təyin etməlidir, və privilige level 0 stack segment və stack pointer təyin etmək gərəktir.
intel ref:

•IA32_SYSENTER_CS — Contains a 32-bit value, of which the lower 16 bits are the segment selector for the privilege level 0 code segment. This value is also used to compute the segment selector of the privilege level 0 stack segment.

•IA32_SYSENTER_EIP — Contains the 32-bit offset into the privilege level 0 code segment to the first instruction of the selected operating procedure or routine.

•IA32_SYSENTER_ESP — Contains the 32-bit stack pointer for the privilege level 0 stack.These MSRs can be read from and written to using RDMSR/WRMSR. Register addresses are listed in Table 4-17. The addresses are defined to remain fixed for future Intel 64 and IA-32 processors.
[öz hazırladıqım kernel üzərində İVT 0x2e qeyd etmişim vector onu ləğv edərək `MSR` register daxilində dispatcher funksiya adresini qeyd etdim.]

İnterrupt və yaxud Exception generasiya edildiyində, (context switching) prosessor maşının cari vəziyyətini kernel steki üzərində saxlayır ki, interrupt icra edildikdən sonra proqram axışı cari nöqtəyə qayıdaraq icra davam etsin. Əgər thread istifadəçi modunda çalışırsa, OS threadi kernel moda keçirtmək istərsə. O zaman OS kernel stekdə trap frame yaradaraq onun üzərinə cari thread vəziyyətini (thread state) qeyd edir.
lkd> dt nt!_ktrap_frame

+0x000 DbgEbp           : Uint4B

+0x004 DbgEip           : Uint4B

+0x008 DbgArgMark       : Uint4B

+0x00c DbgArgPointer    : Uint4B

+0x010 TempSegCs        : Uint2B

+0x012 Logging          : UChar

+0x013 Reserved         : UChar

+0x014 TempEsp          : Uint4B

+0x018 Dr0              : Uint4B

+0x01c Dr1              : Uint4B

+0x020 Dr2              : Uint4B

+0x024 Dr3              : Uint4B

+0x028 Dr6              : Uint4B

+0x02c Dr7              : Uint4B

+0x030 SegGs            : Uint4B

+0x034 SegEs            : Uint4B

+0x038 SegDs            : Uint4B

+0x03c Edx              : Uint4B

+0x040 Ecx              : Uint4B

+0x044 Eax              : Uint4B

+0x048 PreviousPreviousMode : Uint4B

+0x04c ExceptionList    : Ptr32 _EXCEPTION_REGISTRATION_RECORD

+0x050 SegFs            : Uint4B

+0x054 Edi              : Uint4B

+0x058 Esi              : Uint4B

+0x05c Ebx              : Uint4B

+0x060 Ebp              : Uint4B

+0x064 ErrCode          : Uint4B

+0x068 Eip              : Uint4B

+0x06c SegCs            : Uint4B

+0x070 EFlags           : Uint4B

+0x074 HardwareEsp      : Uint4B

+0x078 HardwareSegSs    : Uint4B

+0x07c V86Es            : Uint4B

+0x080 V86Ds            : Uint4B

+0x084 V86Fs            : Uint4B

+0x088 V86Gs            : Uint4B
       
 
KiFastCallEntry iki əməliyyatı yerinə yetirir.
1. trap frame yaradaraq user moda döndükdə lazım olacaq bütün informasiyaları saxlayır.
2. `System service descriptor table` üzərində  sistem servis funksiyasını taparaq çağırır.
`MSR` (model-specific register) register dəyərinə baxaq.
IA32_SYSENTER_EIP (0x176) – The kernel’s EIP for SYSENTER. This is the address of your SYSENTER entry point.

0: kd> rdmsr 176msr[176] = 00000000`8053a270

0: kd> ln 8053a270

(8053a270)   nt!KiFastCallEntry   |  (8053a2fb)   nt!KiSystemService

nt!KiFastCallEntry:

b923000000      mov     ecx,23h

6a30            push    30h

0fa1            pop     fs

8ed9            mov     ds,cx

8ec1            mov     es,cx

648b0d40000000  mov     ecx,dword ptr fs:[40h]

8b6104          mov     esp,dword ptr [ecx+4]

6a23            push    23h

52              push    edx

9c              pushfd

6a02            push    2

83c208          add     edx,8

9d              popfd

804c240102      or      byte ptr [esp+1],2

6a1b            push    1Bh

ff350403dfff    push    dword ptr ds:[0FFDF0304h]

6a00            push    0

55              push    ebp

53              push    ebx

56              push    esi

57              push    edi

648b1d1c000000  mov     ebx,dword ptr fs:[1Ch]

6a3b            push    3Bh

8bb324010000    mov     esi,dword ptr [ebx+124h]

ff33            push    dword ptr [ebx]

c703ffffffff    mov     dword ptr [ebx],0FFFFFFFFh

8b6e28          mov     ebp,dword ptr [esi+28h]

6a01            push    1

83ec48          sub     esp,48h

81ed9c020000    sub     ebp,29Ch

c6863a01000001  mov     byte ptr [esi+13Ah],1

3bec            cmp     ebp,esp

7597            jne     nt!KiFastCallEntry2+0x49 (82e7a2fb)
 Super məlumat taparaq ingiliscəyə tərcümə etmişəm Azərbaycan dilində tərcümə çox çətin olduğundan.
// When a thread executes in kernel mode data segment selector is 23h

// When a thread executes in kernel mode, loaded in the FS register is to select the sub-30,

// Structure for addressing PCR 804de6f0 mov ecx, 23h

804de6f5 push 30h

804de6f7 pop fs

 // 23h-> ds; 23h-> es

804de6f9 mov ds, cx

804de6fb mov es, cx

 // Dword ptr fs: [40h] == dword ptr ds: [0FFDFF040h] {TSS}

// Dword ptr [ecx + 4] for the current thread’s kernel-mode stack pointer value 804de6fd mov ecx, dword ptr ds: [0FFDFF040h]

804de703 mov esp, dword ptr [ecx + 4]

 // ==========================================

// The current (the value of the registers before execution Sysenter) pushed onto the system stack context,

 // _KTRAP_FRAME.HardwareSegSs

804de706 push 23h

 // _KTRAP_FRAME.HardwareEsp

804de708 push edx

 // _KTRAP_FRAME.EFags

804de709 pushfd

804de70a push 2

804de70c add edx, 8

 // EFlags = 2

804de70f popfd

804de710 or byte ptr [esp + 1], 2

 // _KTRAP_FRAME.SegCs

804de715 push 1Bh

 // Ds: [0FFDF0304h] is SystemCallReturn (_KUser_Shared_Data)

// _KTRAP_FRAME.Eip

804de717 push dword ptr ds: [0FFDF0304h]

 //_KTRAP_FRAME.ErrorCode

804de71d push 0

 //_KTRAP_FRAME.Ebp

804de71f push ebp

 //_KTRAP_FRAME.Ebx

804de720 push ebx

 //_KTRAP_FRAME.Esi

804de721 push esi

 //_KTRAP_FRAME.Edi

804de722 push edi

//ebx<-_kpcr -="" .selfpcr804de723="" 0ffffffffh="" 124h="" 18h="" 1="" 3bh="" 804de729="" 804de72b="" 804de731="" 804de733="" 804de739="" 804de73c="" _ktrap_frame.segfs="" ds:="" dword="" ebp="" ebx="" esi="" esp="" h="" initialization="" initialstack="" list="" mov="" ptr="" push="" reviouspreviousmode="1" xceptionlist=""> _ KTRAP_FRAME

804de73e sub esp, 48h

 // Ebp -> _ KTRAP_FRAME

804de741 sub ebp, 29Ch

 // CurrentThread +124 = 1

804de747 mov byte ptr [esi + 140h], 1

 // Compare 804de74e cmp ebp, esp

// Not equal, the occurrence of abnormal 804de750 jne nt! KiFastCallEntry2 + 0x24 (804de6c8)

 // _KTRAP_FRAME.Dr7 = 0

804de756 and dword ptr [ebp + 2Ch], 0

 // [Esi + 2Ch] is KTHREAD.DebugActive current thread // debug flag is not equal to 0xFF indicates debugging?

804de75a test byte ptr [esi + 2Ch], 0FFh

804de75e mov dword ptr [esi + 134h], ebp

804de764 jne nt! Dr_FastCallDrSave (804de5b0)

// Ebx = _KTRAP_FRAME.Ebp804de76a mov ebx, dword ptr [ebp + 60h]

 // Edi = _KTRAP_FRAME.EIP

804de76d mov edi, dword ptr [ebp + 68h]

 // _KTRAP_FRAME.DbgArgPointer

804de770 mov dword ptr [ebp + 0Ch], edx

 // _KTRAP_FRAME.DbgArgPointer = DbgArgMark

804de773 mov dword ptr [ebp + 8], 0BADB0D00h

 //_KTRAP_FRAME.DbgEbp

804de77a mov dword ptr [ebp], ebx

 //_KTRAP_FRAME.DbgEip = _KTRAP_FRAME.EIP

804de77d mov dword ptr [ebp + 4], edi

// ==================================
       
 
Doğru System Descriptor Table tapmaq üçün KiFastCallEntry daxilində bəzi hesablama əməliyyatları aparılır.
mov ecx,23h

mov ds,cx //load the new ds

mov ebx,dword ptr ds:[0FFDFF01Ch] //EBX=KPCR.SelfPcr, ie, KPCR itself

mov esi,dword ptr [ebx+124h] //ESI=KTHREAD

mov edi,eax //EDI=system service number

shr edi,8

mov ecx, edi ; ecx now has the actual index for the SSDT

and edi,30h //EDI=SSDT index

add edi,dword ptr [esi+0E0h] //EDI=SSDT

mov edi,dword ptr [edi] //EDI=SSDT->ServiceTableBase

mov ebx,dword ptr [edi+eax*4] //EBX=service function address
Kernel Process Control Block təqdim edirəm.
typedef struct _KPCR

{

union

{

NT_TIB NtTib;

struct

{

PEXCEPTION_REGISTRATION_RECORD Used_ExceptionList;

PVOID Used_StackBase;

PVOID Spare2;

PVOID TssCopy;

ULONG ContextSwitches;

ULONG SetMemberCopy;

PVOID Used_Self;

};

};

PKPCR SelfPcr;

PKPRCB Prcb;

UCHAR Irql;

ULONG IRR;

ULONG IrrActive;

ULONG IDR;

PVOID KdVersionBlock;

PKIDTENTRY IDT;

PKGDTENTRY GDT;

PKTSS TSS;

WORD MajorVersion;

WORD MinorVersion;

ULONG SetMember;

ULONG StallScaleFactor;

UCHAR SpareUnused;

UCHAR Number;

UCHAR Spare0;

UCHAR SecondLevelCacheAssociativity;

ULONG VdmAlert;

ULONG KernelReserved[14];

ULONG SecondLevelCacheSize;

ULONG HalReserved[16];

ULONG InterruptMode;

UCHAR Spare1;

ULONG KernelReserved2[17];

KPRCB PrcbData;

} KPCR, *PKPCR;
       
 
on  = typedef struct _KTHREAD

PVOID ServiceTable;
e.g

mov eax,0x102

102 – ci sistem servis nömrəsinə məxsus funksiya = NtReadFile
lkd> ln poi(KiServiceTable + 102 * 4)

(82193023)   nt!NtReadFile
32 bit register üzərindəki (eax) sistem servis nömrəsi bu parçalardan ibarətdir:

bit 0-11: sistem servis nömrəsi çağırış üçün

bit 12-13: service descriptor table üçün istifadə edilir

bit 13-31: istifadə edilmir

Keçək dəfə mövzuda bəhs etmişdim Win iki System Descriptor Table istifadə etdiyindən.

KeServiceDescriptorTableShadow

——————————
KeServiceDescriptorTable

sistem servis nömrələrdindən 0x0-0xFFF aralıqında bütün nömrələr KeServiceDescriptorTable indexləri  olaraq istifadə edilir.

0x1000-0x1FFF aralıqları isə KeServiceDescriptorTableShadow indexləri olaraq istifadə edilir.

SSN(SYSTEM SERVİCE NUMBER) – SSDT (System Descriptor Table)
eax = 0x100F

mov edi,eax //EDI=system service number

shr edi,8 // edi>>0x8 = 10h = shifting rulezzz

and 0x10,0x30 = (0x10)d = (10000)b & (110000)b = (10000)b = (0x10)d

nt!KiFastCallEntry+0xaf:82e7a3af 83f910          cmp     ecx,10h

82e7a3b2 751a            jne     nt!KiFastCallEntry+0xce (82e7a3ce) 
Burada check edir SSDT table yoxsa Shadow Table olduğunu.
ecx = 10 olarsa Shadow Table qeyd edilir əks halda SSDT regular table qeyd edilir.


Wednesday, October 14, 2015

System Service Dispatching

System Service Dispatch ∨ (sysCALL) OS tərəfindən təyin olunmuş kernel əsaslı funksiyaları işə salır (trigger)
(pentium II əvvəlindəki x86 prosesorlar int 0x2e təlimatı əsasında trap handler işə salırdı)
Windows Based
Trap Handler – Trap – interrupt və yaxud exception yarandıqda icrada olan threadi nəzarətə götürür və sabit bir yerə (routine və s.) kontrolun köçürülməsi əməliyyatını yerinə yetirir.
Hardware/Software Interrupts --- > trap handler kontrolu INTERRUPT Service Routines (ISR)-ə transfer edir.
Hardware/Software Exceptions --- > trap handler kontrolu Exception Dispatchers (ED)-ə transfer edir.
System service calls --- > trap handler kontrolu system service function (SSF)-ə transfer edir.
                                                          Trap handler
Interrupt ————— > INTERRUPT SERVICE ROUTINE
System service call ————— > SYSTEM SERVICES
Hardware exceptions|Software Exceptions –> EXCEPTION dispatcher —> Exception handlers
Virtual addr exceptions —- > Virtual memory manager’s pager
Hardware və software exception və interrupt generasiya edə bilir. Misal üçün: ‘Bus error exception’ hardware probleminƏ görə yaranır. ‘divide-by-zero exception’ isə sofware probleminə görə yaranır. Həmçinin I/O cihazları interrupt generasiya edə bilər. Kernel özü də bir software interrupt verə bilər.
Yuxarıdakı schema-da kernel trap işləyicileri interrupts,exceptions və system service çağırışlarını göndərir. System service dispatch, System service dispatchingdə təyin olunmuş təlimatının(instruction) icrası nəticəsində işə düşür.

System Service Dispatching

x86 prosessorlarında Pentium II-dən əvvəl Windows int 0x2e (46 onluq) təlimatı (instruction) istifadə edirdi. Bu interrupt vektoru trap ilə nəticələnir. Windows IDT-da (Interrupt Descriptor Table) 46cı entry SSD-ni(System Service dispatcher) göstərir.
Fig 1.0
lkd> !idt 2e
Dumping IDT: 80b95400
898023cf0000002e:    82e9822e nt!KiSystemService
Trap icrada olan thread-in kernel mode keçidinə və system service dispatcher-a daxil olmasına səbəb olur. EAX prosessor registerinə daxil edilmiş rəqəmli arqument istənilən system servis nömrəsini göstərir. İstifadəçi moduna geri dönmək üçün, system service dispatcher iret (interrupt return instruction) istifadə edir.
x86 Pentium II və yüksək prosessorlarda, Windows systen təlimatı(instruction) istifadə edir, İntel bunu xüsusi olaraq daha sürətli system service dispatch üçün təyin edib. Windows boot zamanı kernel system service dispatch routine adresini MSR (Machine specific register-da saxlayır. System servis nömrəsi EAX prosessor registerində qeyd edilir. Bu təlimatın icrasın kernel moda keçişə və system service dispatcher işə düşməsinə səbəb olur. User moda qayitmaq üçün isə sysexit təlimatı istifadə olunur.
  1. Fig 1.0 göstərildiyi kimi 32 bit kernel debugger-da sistemlərdə system call dispatcher handler !idt 2eilə göstərilə bilir.
  2. Handler-in sysenter versiyasına baxmaq üçün rdmsr təlimatından istifadə edərək MSR 0x176 registerindən oxumaq mümkündür.
lkd> rdmsr 176
msr[176] = 00000000`82e5b300
lkd> ln 00000000`82e5b300
(82e5b300)   nt!KiFastCallEntry
SharedUserData strukturunda doğru kod üçün bir pointer saxlanaraq istifadə etmək üçün uyğun system call kodunu təyin edər. User modda NtReadFile üçün system service code buna bənzəyir.
lkd> u ntdll!NtReadFile
ntdll!NtReadFile:
77125700 b811010000      mov     eax,111h
77125705 ba0003fe7f      mov     edx,offset SharedUserData!SystemCallStub (7ffe0300)
7712570a ff12            call    dword ptr [edx]
7712570c c22400          ret     24h
System service number 0x111-dir(273 onluq), və kernel tərəfindən təyin edilmiş system dispatch code call təlimatı icra edir, onun pointeri 0x7ffe0300adresindədir. (Bu KUSER_SHARED_DATA strukturunun SystemCallStub member-nə qarşılıq gəlir, bu da 0x7FFE0000 adresindən başlayır)
#define MM_SHARED_USER_DATA_VA      0x7FFE0000
#define USER_SHARED_DATA ((KUSER_SHARED_DATA * const)MM_SHARED_USER_DATA_VA)
lkd> u 771264f0
ntdll!KiFastSystemCall:
771264f0 8bd4            mov     edx,esp
771264f2 0f34            sysenter
E.g 1.0-da göstərildiyi kimi, kernel system service dispatch table system service (servis) məlumatlarını tapmaq üçün system call number istifadə edir.
E.g 1.0:
User Mode ————-> system call —-(transition to kernel mode)—- > kernel mode
kernel mode: System service dispatcher (2) ——> System service dispatch table (2):
0System service 0
1System service 1
2System service 2
Bu table Interrupt dispatch table bənzəyir ancaq hər giriş system service əvəzinə interrupt-handling routine göstərir.
System service dispatcher KiSystemService, işə salanın argumentlərini user mod stack-dən kernel stack-ə moda copy edir daha sonra system service icra edilir. Kernel nə qədər stack byte olduğunu bilmək üçün second table istifadə edərək kopyalama tələb edir, bu table argument table adlanır.
typedef struct _SYSTEM_SERVICE_TABLE {
    PVOID *ServiceTable; //System Service Dispatch Table
    PVOID *CounterTable; //istifadə edilmir
    ULONG ServiceLimit; // SSDT table dəyərlərinin sayı
    PUCHAR ArgumentTable; // Dispatch table içindəki ki routine-lər üçün argumentləri saxlayır.
} SYSTEM_SERVICE_TABLE, *PSYSTEM_SERVICE_TABLE;
reference kimi bir şəkildə verirəm: 
(ServiceTable this the array of function pointers to kernel routines)
lkd> dps !KeServiceDescriptorTable
82f809c0  82e876f0 nt!KiServiceTable
82f809c4  00000000 //not used
82f809c8  00000191 //servicelimit
82f809cc  82e87d38 nt!KiArgumentTable
Sistem servisinə daxil edilmiş arqumentlər istifadəçi sahəsindəki buferdədirsə. Kernel-moda kod kopyalamadan öncə giriş imkanı üçün bu bufer problanmalıdır (yoxlanılmalıdır). Bu problama yalnız threadin previous modu user mode təyin edildikdə həyata keçirilir. Previous mode kernelin thread üzərində trap handler icra edildiyində və daxil olan istisnanın,trap,və yaxud syscall (sistem çağırışının) imtiyaz səviyyəsini müəyyən etmək üçün saxladığı bir dəyərdir (kernel və yaxud user). Optimallaşdırma üçün isə system çağırışının driver və yaxud kernel modun özündən gəldiyi halda probing (yoxlama) və capturing parametrləri nəzərə alınmır və bütün parametrlər etibarlı kernel mod buferlərinə işarə edilir. Kernel mode-da system çağırışları edə bilir. Hər sistem çağırışı üçün kod kernel modda olduğundan və caller kernel modda olduğu üçün siz burada interrupt və sysenter əməliyyatlarına ehtiyyac olmadığını görə bilərsiniz. Driver və yaxud kernel yalnız tələb olunan funksiyanı birbaşa işə sala bilər.

Saturday, May 23, 2015

i8042 keyboard controller




I/O Ports and I/O Memory
Every peripheral device is controlled by writing and reading its registers. Most of the time a device has several registers, and they are accessed at consecutive addresses, either in the memory address space or in the I/O address space. At the hardware level, there is no conceptual difference between memory regions and I/O regions: both of them are accessed by asserting electrical signals on the address bus and control bus (i.e., the read and write signals)* and by reading from or writing to the data bus.

Intel reference:
An I/O port can be an input port….Some I/O ports are used for transmitting data,
such as to and from the transmit and receive registers, respectively, of a serial interface device. Other I/O ports are used to control peripheral devices, such as the control registers of a disk controller.


I/O INSTRUCTIONS
The processor’s I/O instructions provide access to I/O ports through the I/O address space. (These instructions cannot be used to access memory-mapped I/O ports.) The register I/O instructions IN (input from I/O port) and OUT (output to I/O port) move data between I/O ports and the EAX register (32-bit I/O), the AX register (16-bit I/O), or the AL (8-bit I/O) register. The address of the I/O port can be given with an immediate value or a value in the DX register.


Kernel implementation:

Each device connected to the I/O bus has its own set of I/O addresses, which are usually called I/O ports.
Any : Understanding kernel - >  subject: I/O Ports page 520

Custom I/O interfaces
Just to give an idea of how much variety is encompassed by custom I/O interfaces— thus by the devices currently installed in a PC—we’ll list some of the most commonly found:
Keyboard interface Connected to a keyboard controller that includes a dedicated microprocessor. This microprocessor decodes the combination of pressed keys, generates an interrupt, and puts the corresponding scan code in an input register.

Receiving data from I/O ports :
the I/O address space provides up to 65,536 8-bit I/O ports. Two signal request 16-bit port. Four special assembly language instructions called in, ins, out, and outs allow the CPU to read from and write into an 
I/O port.
Each device are structured into a set of specialized registers: The CPU writes the commands to be sent to the device into the device control register and reads a value that represents the internal state of the device from the device status register. The CPU also fetches data from the device by reading bytes from the device input register and pushes data to the device by writing bytes into the device output
register.


|||||||||||||| ==> control register ==>
||||||||||||||
||||||||||||||  <== status register <==
|||    CPU    |||
||||||||||||||   
||||||||||||||   <== input register <==
||||||||||||||
|||||||||||||| ==> output  register ==>

||||||||||||||||||
||||||||||||||||||
||||||||||||||||||
|||     I/O DEV   ||||
||||||||||||||||||
||||||||||||||||||
||||||||||||||||||
||||||||||||||||||






readable /proc/interrupts
           CPU0
  0:        168   IO-APIC-edge      timer
  1:         59   IO-APIC-edge      i8042 <<< ====== 1 IRQ keyboard controller
  6:          3   IO-APIC-edge      floppy
  8:          1   IO-APIC-edge      rtc0
  9:          0   IO-APIC-fasteoi   acpi
 12:       5572   IO-APIC-edge      i8042 +++++ 12 IRQ line (mouse)

Dmesg =>
[    0.840639] serio: i8042 KBD port at 0x60,0x64 irq 1
[    0.840651] serio: i8042 AUX port at 0x60,0x64 irq 12
[    1.111561] input: AT Translated Set 2 keyboard as /devices/platform/i8042/serio0/input/input1

i8042 keyboard and mouse controller driver for Linux kernel

381  * i8042_start() is called by serio core when port is about to finish
382  * registering. It will mark port as existing so i8042_interrupt can
383  * start sending data through it.
384  */
385 static int i8042_start(struct serio *serio)
386 {
387         struct i8042_port *port = serio->port_data;
388 
389         port->exists = true;
390         mb();
391         return 0;
392 }
Ivoke IRQ (handling)
Reading to header file: drivers/input/serio/i8042-io.h?v=3.4
 45 #define I8042_COMMAND_REG       0x64
 46 #define I8042_STATUS_REG        0x64
 47 #define I8042_DATA_REG          0x60 < =
 
 

49 static inline int i8042_read_data(void)
 50 {
 51         return inb(I8042_DATA_REG);
 52 }

I/O Privilege Level
In systems where I/O protection is used, the IOPL field in the EFLAGS register controls access to the I/O address space by restricting use of selected instructions. This protection mechanism permits the operating system or executive to set the privilege level needed to perform I/O. In a typical protection ring model, access to the I/O address space is restricted to privilege levels 0 and 1.


Change privilege level ring3   
 #include <sys/io.h>

        #include <stdio.h>
    int main()
    {
        int x=0;
            iopl(3);
           //outb(0x42,0x60);
            printf("%x",inb(0x60));
            x++;
return 0 ;
    }
stealing ? :)

Scancodes:
The data from a keyboard comes mainly in the form of scancodes, produced by key presses or used in the protocol with the computer.

Output scancodes but translate to keyscan codes

drivers/tty/vt/keyboard.c

152 /*
153  * Translation of scancodes to keycodes. We set them on only the first
154  * keyboard in the list that accepts the scancode and keycode.
155  * Explanation for not choosing the first attached keyboard anymore:
156  *  USB keyboards for example have two event devices: one for all "normal"
157  *  keys and one for extra function keys (like "volume up", "make coffee",
158  *  etc.). So this means that scancodes for the extra function keys won't
159  *  be valid for the first event device, but will be for the second.
160  */
161 
162 struct getset_keycode_data {
163         struct input_keymap_entry ke;
164         int error;
165 };

Header file : include/uapi/linux/input.h#L91
204 /*
205  * Keys and buttons
206  *
207  * Most of the keys/buttons are modeled after USB HUT 1.12
208  * (see http://www.usb.org/developers/hidpage).
209  * Abbreviations in the comments:
210  * AC - Application Control
211  * AL - Application Launch Button
212  * SC - System Control
213  */
214 
215 #define KEY_RESERVED            0
216 #define KEY_ESC                 1
217 #define KEY_1                   2
218 #define KEY_2                   3
219 #define KEY_3                   4
220 #define KEY_4                   5
221 #define KEY_5                   6
222 #define KEY_6                   7
223 #define KEY_7                   8
224 #define KEY_8                   9
225 #define KEY_9                   10
226 #define KEY_0                   11
227 #define KEY_MINUS               12
228 #define KEY_EQUAL               13
229 #define KEY_BACKSPACE           14
230 #define KEY_TAB                 15
231 #define KEY_Q                   16
232 #define KEY_W                   17
233 #define KEY_E                   18
234 #define KEY_R                   19
235 #define KEY_T                   20
236 #define KEY_Y                   21
237 #define KEY_U                   22
238 #define KEY_I                   23
239 #define KEY_O                   24
240 #define KEY_P                   25