Читаем Windows® Internals, Sixth Edition, Part 1 полностью

Although hotpatches use internal kernel mechanisms, their actual implementation is no different from cold patches. The patch is delivered through Windows Update, typically as an executable file containing a program called Update.exe that performs the extraction of the patch and the update process. For hotpatches, however, an additional hotpatch file, containing the .hp extension, will be present. This file contains a special PE header called .HOT1. This header contains a data structure describing the various patch descriptors present inside the file. Each of these descriptors identifies the offset in the original file that needs to be patched, a validation mechanism (which can include a simple comparison of the old data, a checksum, or a hash), and the new data to be patched. The kernel parses the descriptors and applies the appropriate modifications. In the case of a protected process (see Chapter 5 for more information on processes) and other digitally signed images, the hotpatch must also be digitally signed in order to prevent fake patches from being applied to sensitive files or processes.

Note

Because the hotpatch file also includes the original data, the hotpatching mechanism can also be used to uninstall a patch at run time.

Compile-time hotpatching support works by adding 7 additional bytes to the beginning of each function—4 are considered part of the end of the previous function, and 2 are part of the function prolog—that is, the function’s beginning. Here’s an example of a function that was built with hotpatching information:lkd> u nt!NtCreateFile - 5 nt!FsRtlTeardownPerFileContexts+0x169: 82227ea5 90 nop 82227ea6 90 nop 82227ea7 90 nop 82227ea8 90 nop 82227ea9 90 nop nt!NtCreateFile: 82227eaa 8bff mov edi,edi

Notice that the five nop instructions don’t actually do anything, while the mov edi, edi at the beginning of the NtCreateFile function are also essentially meaningless—no actual state-changing operation takes place. Because 7 bytes are available, the NtCreateFile prologue can be transformed into a short jump to the buffer of five instructions available, which are then converted to a near jump instruction to the patched routine. Here’s NtCreateFile after having been hotpatched:lkd> u nt!NtCreateFile - 5 nt!FsRtlTeardownPerFileContexts+0x169: 82227ea5 e93d020010 jmp nt_patch!NtCreateFile (922280e7) nt!NtCreateFile: 82227eaa ebfc jmp nt!FsRtlTeardownPerFileContexts+0x169 (82227ea5)

This method allows only the addition of 2 bytes to each function by jumping into the previous function’s alignment padding that it would most likely have at its end anyway.

There are some limitations to the hotpatching functionality:

Patches that third-party applications such as security software might block or that might be incompatible with the operation of third-party applications

Patches that modify a file’s export table or import table

Patches that change data structures, fix infinite loops, or contain inline assembly code


Kernel Patch Protection

Some 32-bit device drivers modify the behavior of Windows in unsupported ways. For example, they patch the system call table to intercept system calls or patch the kernel image in memory to add functionality to specific internal functions. Shortly after the release of 64-bit Windows for x64 and before a rich third-party ecosystem had developed, Microsoft saw an opportunity to preserve the stability of 64-bit Windows. To prevent these kinds of changes, x64 Windows implements Kernel Patch Protection (KPP), also referred to as PatchGuard. KPP’s job on the system is similar to what its name implies—it attempts to deter common techniques for patching the system, or hooking it. Table 3-29 lists which components or structures are protected and for what purpose.

Table 3-29. Components Protected by KPP

Component

Legitimate Usage

Potential Malicious Usage

Ntoskrnl.exe, Hal.dll, Ci.dll, Kdcom.dll, Pshed.dll, Clfs.sys, Ndis.sys, Tcpip.sys

Kernel, HAL, and their dependencies. Lower layer of network stack.

Patching code in the kernel and/or HAL to subvert normal operation and behavior. Patching Ndis.sys to silently add back doors on open ports.

Global Descriptor Table (GDT)

CPU hardware protection for the implementation of ring privilege levels (Ring 0 vs. Ring 3).

Ability to set up a callgate, a CPU mechanism through which user (Ring 3) code could perform operations with kernel privileges (Ring 0).

Interrupt Descriptor Table (IDT)

Table read by the CPU to deliver interrupt vectors to the correct handling routine.

Перейти на страницу:

Похожие книги

Самоучитель UML
Самоучитель UML

Самоучитель UMLПервое издание.В книге рассматриваются основы UML – унифицированного языка моделирования для описания, визуализации и документирования объектно-ориентированных систем и бизнес-процессов в ходе разработки программных приложений. Подробно описываются базовые понятия UML, необходимые для построения объектно-ориентированной модели системы с использованием графической нотации. Изложение сопровождается примерами разработки отдельных диаграмм, которые необходимы для представления информационной модели системы. Цель книги – помочь программистам освоить новую методологию разработки корпоративных программных приложений для последующего применения полученных знаний с использованием соответствующих CASE-инструментов.

Александр Васильевич Леоненков , Александр Леоненков

Зарубежная компьютерная, околокомпьютерная литература / Программирование / Прочая компьютерная литература / Книги по IT
Об интеллекте
Об интеллекте

В книге "Об интеллекте" Джефф Хокинс представляет революционную теорию на стыке нейробиологии, психологии и кибернетики и описывающую систему "память-предсказание" как основу человеческого интеллекта. Автор отмечает, что все предшествующие попытки создания разумных машин провалились из-за фундаментальной ошибки разработчиков, стремившихся воссоздать человеческое поведение, но не учитывавших природу биологического разума. Джефф Хокинс предполагает, что идеи, сформулированные им в книге "Об интеллекте", лягут в основу создания истинного искусственного интеллекта - не копирующего, а превосходящего человеческий разум. Кроме этого книга содержит рассуждения о последствиях и возможностях создания разумных машин, взгляды автора на природу и отличительные особенности человеческого интеллекта.Книга рекомендуется всем, кого интересует устройство человеческого мозга и принципы его функционирования, а также тем, кто занимается проблемами разработки искусственного интеллекта.

Джефф Хокинс , Джеф Хокинс , Сандра Блейксли , Сандра Блэйксли

Зарубежная компьютерная, околокомпьютерная литература / Технические науки / Прочая компьютерная литература / Образование и наука / Книги по IT