RU2623883C1 - Method of implementating instructions in systemic memory - Google Patents

Method of implementating instructions in systemic memory Download PDF

Info

Publication number
RU2623883C1
RU2623883C1 RU2016105564A RU2016105564A RU2623883C1 RU 2623883 C1 RU2623883 C1 RU 2623883C1 RU 2016105564 A RU2016105564 A RU 2016105564A RU 2016105564 A RU2016105564 A RU 2016105564A RU 2623883 C1 RU2623883 C1 RU 2623883C1
Authority
RU
Russia
Prior art keywords
memory
memory area
interest
execution
original
Prior art date
Application number
RU2016105564A
Other languages
Russian (ru)
Inventor
Владислав Валерьевич Пинтийский
Дмитрий Александрович Кирсанов
Денис Вячеславович Аникин
Original Assignee
Акционерное общество "Лаборатория Касперского"
Priority date (The priority date is an assumption and is not a legal conclusion. Google has not performed a legal analysis and makes no representation as to the accuracy of the date listed.)
Filing date
Publication date
Application filed by Акционерное общество "Лаборатория Касперского" filed Critical Акционерное общество "Лаборатория Касперского"
Priority to RU2016105564A priority Critical patent/RU2623883C1/en
Application granted granted Critical
Publication of RU2623883C1 publication Critical patent/RU2623883C1/en

Links

Images

Classifications

    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F9/00Arrangements for program control, e.g. control units
    • G06F9/06Arrangements for program control, e.g. control units using stored programs, i.e. using an internal store of processing equipment to receive or retain programs
    • G06F9/46Multiprogramming arrangements
    • G06F9/48Program initiating; Program switching, e.g. by interrupt
    • GPHYSICS
    • G06COMPUTING; CALCULATING OR COUNTING
    • G06FELECTRIC DIGITAL DATA PROCESSING
    • G06F11/00Error detection; Error correction; Monitoring
    • G06F11/30Monitoring

Landscapes

  • Engineering & Computer Science (AREA)
  • Theoretical Computer Science (AREA)
  • Physics & Mathematics (AREA)
  • General Engineering & Computer Science (AREA)
  • General Physics & Mathematics (AREA)
  • Software Systems (AREA)
  • Quality & Reliability (AREA)
  • Debugging And Monitoring (AREA)

Abstract

FIELD: physics.
SUBSTANCE: method for transmitting execution of instructions from one memory area to another, in which, at least, one storage area of interest is determined in the original memory area consisting of memory areas; a memory area is created by duplicating the memory area of the original memory area of interest; all memory locations are marked in the original memory area; the execution of instructions written in the original memory area is run in any of the available memory locations in the original memory area, except for the memory area of interest; the execution of instructions is performed in the memory areas of the original memory area of the processor before creating a notification. The notification is generated, when the control of the instruction is transferred from the memory area marked with a single label to the interesting location marked with a different label; the execution of instructions is transferred from the memory area of the original memory area to the memory location of interest, but in the duplicate memory area after the notification is generated.
EFFECT: organizing the execution of instructions loaded in the system memory by alternately transferring the execution of instructions from one memory area to another, the execution of instructions in which created the notification.
11 cl, 8 dwg

Description

Область техникиTechnical field

Изобретение относится к способам управления исполнением машинных инструкций, а именно к способам передачи управления между областями памяти.The invention relates to methods for controlling the execution of machine instructions, and in particular to methods for transferring control between memory areas.

Уровень техникиState of the art

В настоящее время современные технологии, предназначенные для формирования журнала вызовов API-функций во время исполнения программы, требуют вмешательства в содержимое адресного пространства процесса или файлов на диске, например изменение кода в системных библиотеках операционной системы в памяти и на диске. Изменения заключаются во «внедрении кода», отвечающего за механизм журналирования вызовов API-функций. Основными шагами данного механизма могут являться следующие шаги:Currently, modern technologies designed to generate an API function call log during program execution require intervention in the contents of the process address space or files on the disk, for example, changing the code in the operating system system libraries in memory and on disk. The changes are in the "implementation of the code", which is responsible for the mechanism of logging calls to API functions. The main steps of this mechanism can be the following steps:

- перехват управления библиотекой (например, с помощью перехвата API функций путем изменения кода целевой функции);- interception of library management (for example, by intercepting API functions by changing the code of the target function);

- переход при вызове API в регион памяти, содержащий код обработчика, отвечающего за обработку API-функции и запись в журнал вызовов;- transition when calling the API to the memory region containing the code of the handler responsible for processing the API function and writing to the call log;

- выполнение кода обработчика системы журналирования;- execution of the code for the logging system handler;

- возврат управления библиотеке.- return to library management.

Для перехвата управления системой журналирования также могут быть использованы способы, заключающиеся в изменение адресов вызова API-функций из библиотек в таблице импорта исполняемого файла и/или помещения «промежуточной» библиотеки, к которой будет первоначальное обращение перед переходом к оригинальной вызываемой API-функции из оригинальной библиотеки.To intercept control of the journaling system, methods can also be used consisting in changing the addresses of calling API functions from libraries in the import table of the executable file and / or placing the “intermediate” library, which will be accessed before switching to the original called API function from the original libraries.

Еще одним недостатком существующих систем журналирования является то, что известные системы журналирования, как правило, имеют трудности при их реализации на различных операционных системах и их версиях. Так обновление операционной системы может привести к тому, что система журналирования перестает работать, так как потребуется доработка (адаптация) под измененную версию.Another drawback of existing journaling systems is that well-known journaling systems, as a rule, have difficulties in their implementation on various operating systems and their versions. So updating the operating system can lead to the fact that the logging system stops working, as it will require revision (adaptation) for the changed version.

Еще одним недостатком современных систем является то, что их присутствие может быть обнаружено вредоносными программами вне зависимости от их привилегий, так как практически любое «вторжение» в адресное пространство процесса может быть обнаружено.Another drawback of modern systems is that their presence can be detected by malware, regardless of their privileges, since almost any “intrusion” into the address space of a process can be detected.

На основании анализа существующего уровня техники становится ясно, что необходимо создание такой системы, которая не вносит изменения в анализируемую программу и, соответственно, не может быть обнаруженной.Based on the analysis of the current level of technology, it becomes clear that it is necessary to create such a system that does not make changes to the analyzed program and, accordingly, cannot be detected.

Раскрытие изобретенияDisclosure of invention

Настоящее изобретение предназначено для отслеживания выполнения программного кода процессором в физической памяти. Применением настоящего изобретения является формирования журнала вызовов API-функций, вызываемых во время исполнения программы.The present invention is intended to track the execution of program code by a processor in physical memory. An application of the present invention is the generation of a log of calls to API functions that are called during program execution.

Технический результат настоящего изобретения заключается в организации выполнения инструкций, загруженных в системной памяти, путем попеременной передачи выполнения инструкций из одной области памяти в другую, отличную от той, выполнение инструкций в которой создало уведомление.The technical result of the present invention is to organize the execution of instructions loaded in the system memory by alternately transferring the execution of instructions from one memory area to another, different from the execution of the instructions in which it generated a notification.

Способ передачи выполнения инструкций из одной области памяти в другую, в котором: определяют в оригинальной области памяти, состоящей из участков памяти, по меньшей мере, один интересующий участок памяти; создают область памяти дублированием интересующего участка памяти оригинальной области памяти; помечают все участки памяти в оригинальной области памяти, при этом метки для интересующего участка памяти в оригинальной области памяти отличны от меток остальных участков памяти оригинальной области памяти; запускают выполнение инструкций, записанных в оригинальной области памяти, в любом из имеющихся участков памяти в оригинальной области памяти, кроме интересующего участка памяти; осуществляют выполнение инструкций в участках памяти оригинальной области памяти процессором до создания уведомления, при этом уведомление создается при передаче управления инструкции из участка памяти, помеченного одной меткой, в интересующий участок памяти, помеченный отличной меткой; передают выполнение инструкций из участка памяти оригинальной области памяти интересующему участку памяти, но в продублированной области памяти, после создания уведомления; осуществляют выполнение инструкций в интересующем участке памяти продублированной области памяти процессором до создания уведомления, при этом уведомление создается при любой передаче управления из интересующего участка продублированной области памяти; возвращают выполнение в оригинальную область памяти в соответствующий участок памяти.A method for transmitting the execution of instructions from one memory area to another, in which: at least one memory area of interest is determined in the original memory area, consisting of memory sections; create a memory region by duplicating the memory region of interest of the original memory region; mark all the memory areas in the original memory area, while the labels for the memory area of interest in the original memory area are different from the marks of the remaining memory areas of the original memory area; start executing instructions recorded in the original memory area in any of the available memory areas in the original memory area, except for the memory area of interest; carry out the execution of instructions in the memory areas of the original memory area by the processor until a notification is generated, and a notification is generated when control is transferred from the memory area marked with one label to the memory area of interest marked with an excellent label; transmit execution of instructions from the memory area of the original memory area to the memory area of interest, but in the duplicated memory area, after creating the notification; carry out the execution of instructions in the memory area of interest of the duplicated memory area by the processor until a notification is generated, the notification being generated during any transfer of control from the area of interest of the duplicated memory area; return execution to the original memory location in the corresponding memory location.

В частном случае уведомление является исключением (exception), которое создается процессором и при передаче управления из интересующего участка памяти создается исключение Page Fault Exception.In a particular case, a notification is an exception (exception) that is created by the processor and a Page Fault Exception is thrown when control is transferred from the memory section of interest.

В другом частном случае дублирование осуществляется копированием таблиц и каталогов. Продублированная область памяти может состоять из одного интересующего участка памяти, а в частном случае интересующий участок равен, по меньшей мере, одной странице.In another particular case, duplication is carried out by copying tables and directories. A duplicated memory region may consist of one region of memory of interest, and in the particular case, the region of interest is equal to at least one page.

В частном случае передают выполнение инструкций области памяти отличной от той, выполнение инструкций в которой создало уведомление, путем перезаписи адреса каталога страниц.In a particular case, the execution of instructions of a memory area other than the execution of instructions in which a notification is transmitted is transmitted by rewriting the address of the page directory.

В еще одном частном случае участки памяти в области памяти помечают путем установки атрибутов в таблице страниц для страниц, на которых отображен участок и, например, страницы интересующего участка имеют атрибут «неисполняемые», а дубликаты страниц интересующего участка имеют атрибут «исполняемые».In another particular case, the memory areas in the memory area are marked by setting the attributes in the page table for pages on which the area is displayed and, for example, the pages of the area of interest have the attribute “non-executable”, and duplicate pages of the region of interest have the attribute “executable”.

Краткое описание чертежейBrief Description of the Drawings

Сопровождающие чертежи включены для обеспечения дополнительного понимания изобретения и составляют часть этого описания, показывают варианты осуществления изобретения и совместно с описанием служат для объяснения принципов изобретения.The accompanying drawings are included to provide a further understanding of the invention and form part of this description, show embodiments of the invention, and together with the description serve to explain the principles of the invention.

Заявленное изобретение поясняется следующими чертежами, на которых:The claimed invention is illustrated by the following drawings, in which:

Фиг. 1 показывает пример компьютерной системы общего назначения;FIG. 1 shows an example of a general purpose computer system;

Фиг. 2 показывает способ описания виртуальной памяти;FIG. 2 shows a method for describing virtual memory;

Фиг. 3 показывает принцип дублирования памяти;FIG. 3 shows the principle of duplication of memory;

Фиг. 4 показывает способ дублирования виртуальной памяти;FIG. 4 shows a method of duplicating virtual memory;

Фиг. 5 показывает алгоритм подготовки и механизма передачи управления выполнения инструкций от одной виртуальной области памяти другой;FIG. 5 shows an algorithm for preparing and transferring control mechanism for executing instructions from one virtual memory region to another;

Фиг. 6 показан пример памяти процесса, который создается ОС и примеры виртуального адресного пространства;FIG. Figure 6 shows an example of the memory of a process that the OS creates and examples of virtual address space;

Фиг. 7 показаны основные шаги подготовки к работе системы журналирования;FIG. 7 shows the basic steps for preparing the logging system for work;

Фиг. 8 показаны шаги работы системы журналирования.FIG. Figure 8 shows the operation steps of the logging system.

Хотя изобретение может иметь различные модификации и альтернативные формы, характерные признаки, показанные в качестве примера на чертежах, будут описаны подробно. Следует понимать, однако, что цель описания заключается не в ограничении изобретения конкретным его воплощением. Наоборот, целью описания является охват всех изменений, модификаций, входящих в рамки данного изобретения, как это определено приложенной формулой.Although the invention may have various modifications and alternative forms, the characteristic features shown by way of example in the drawings will be described in detail. It should be understood, however, that the purpose of the description is not to limit the invention to its specific embodiment. On the contrary, the purpose of the description is to cover all changes, modifications that are included in the scope of this invention, as defined by the attached formula.

Описание изобретенияDescription of the invention

Объекты и признаки настоящего изобретения, способы для достижения этих объектов и признаков станут очевидными посредством отсылки к примерным вариантам осуществления. Однако настоящее изобретение не ограничивается примерными вариантами осуществления, раскрытыми ниже, оно может воплощаться в различных видах. Приведенное описание предназначено для помощи специалисту в области техники для исчерпывающего понимания изобретения, которое определяется только в объеме приложенной формулы.The objects and features of the present invention, methods for achieving these objects and features will become apparent by reference to exemplary embodiments. However, the present invention is not limited to the exemplary embodiments disclosed below, it can be embodied in various forms. The above description is intended to help a person skilled in the art for a comprehensive understanding of the invention, which is defined only in the scope of the attached claims.

Фиг. 1 представляет пример компьютерной системы общего назначения, персональный компьютер или сервер 20, содержащий центральный процессор 21, системную память 22 и системную шину 23, которая содержит разные системные компоненты, в том числе память, связанную с центральным процессором 21. Системная шина 23 реализована, как любая известная из уровня техники шинная структура, содержащая в свою очередь память шины или контроллер памяти шины, периферийную шину и локальную шину, которая способна взаимодействовать с любой другой шинной архитектурой. Системная память содержит постоянное запоминающее устройство (ПЗУ) 24, память с произвольным доступом (ОЗУ) 25. Основная система ввода/вывода (BIOS) 26, содержит основные процедуры, которые обеспечивают передачу информации между элементами персонального компьютера 20, например, в момент загрузки операционной системы с использованием ПЗУ 24.FIG. 1 represents an example of a general purpose computer system, a personal computer or server 20 comprising a central processor 21, a system memory 22, and a system bus 23 that contains various system components, including memory associated with the central processor 21. The system bus 23 is implemented as any prior art bus structure comprising, in turn, a bus memory or a bus memory controller, a peripheral bus and a local bus that is capable of interacting with any other bus architecture. The system memory contains read-only memory (ROM) 24, random access memory (RAM) 25. The main input / output system (BIOS) 26, contains basic procedures that ensure the transfer of information between the elements of the personal computer 20, for example, at the time of loading the operating ROM systems 24.

Персональный компьютер 20 в свою очередь содержит жесткий диск 27 для чтения и записи данных, привод магнитных дисков 28 для чтения и записи на сменные магнитные диски 29 и оптический привод 30 для чтения и записи на сменные оптические диски 31, такие как CD-ROM, DVD-ROM и иные оптические носители информации. Жесткий диск 27, привод магнитных дисков 28, оптический привод 30 соединены с системной шиной 23 через интерфейс жесткого диска 32, интерфейс магнитных дисков 33 и интерфейс оптического привода 34 соответственно. Приводы и соответствующие компьютерные носители информации представляют собой энергонезависимые средства хранения компьютерных инструкций, структур данных, программных модулей и прочих данных персонального компьютера 20.The personal computer 20 in turn contains a hard disk 27 for reading and writing data, a magnetic disk drive 28 for reading and writing to removable magnetic disks 29, and an optical drive 30 for reading and writing to removable optical disks 31, such as a CD-ROM, DVD -ROM and other optical information carriers. The hard disk 27, the magnetic disk drive 28, the optical drive 30 are connected to the system bus 23 through the interface of the hard disk 32, the interface of the magnetic disks 33 and the interface of the optical drive 34, respectively. Drives and associated computer storage media are non-volatile means of storing computer instructions, data structures, software modules and other data of a personal computer 20.

Настоящее описание раскрывает реализацию системы, которая использует жесткий диск 27, сменный магнитный диск 29 и сменный оптический диск 31, но следует понимать, что возможно применение иных типов компьютерных носителей информации 56, которые способны хранить данные в доступной для чтения компьютером форме (твердотельные накопители, флеш карты памяти, цифровые диски, память с произвольным доступом (ОЗУ) и т.п.), которые подключены к системной шине 23 через контроллер 55.The present description discloses an implementation of a system that uses a hard disk 27, a removable magnetic disk 29, and a removable optical disk 31, but it should be understood that other types of computer storage media 56 that can store data in a form readable by a computer (solid state drives, flash memory cards, digital disks, random access memory (RAM), etc.) that are connected to the system bus 23 through the controller 55.

Компьютер 20 имеет файловую систему 36, где хранится записанная операционная система 35, а также дополнительные программные приложения 37, другие программные модули 38 и данные программ 39. Пользователь имеет возможность вводить команды и информацию в персональный компьютер 20 посредством устройств ввода (клавиатуры 40, манипулятора «мышь» 42). Могут использоваться другие устройства ввода (не отображены): микрофон, джойстик, игровая консоль, сканер и т.п. Подобные устройства ввода по своему обычаю подключают к компьютерной системе 20 через последовательный порт 46, который в свою очередь подсоединен к системной шине, но могут быть подключены иным способом, например, при помощи параллельного порта, игрового порта или универсальной последовательной шины (USB). Монитор 47 или иной тип устройства отображения также подсоединен к системной шине 23 через интерфейс, такой как видеоадаптер 48. В дополнение к монитору 47, персональный компьютер может быть оснащен другими периферийными устройствами вывода (не отображены), например, колонками, принтером и т.п.Computer 20 has a file system 36 where the recorded operating system 35 is stored, as well as additional software applications 37, other program modules 38, and program data 39. The user is able to enter commands and information into personal computer 20 via input devices (keyboard 40, keypad “ the mouse "42). Other input devices (not displayed) can be used: microphone, joystick, game console, scanner, etc. Such input devices are, as usual, connected to the computer system 20 via a serial port 46, which in turn is connected to the system bus, but can be connected in another way, for example, using a parallel port, a game port, or a universal serial bus (USB). A monitor 47 or other type of display device is also connected to the system bus 23 via an interface such as a video adapter 48. In addition to the monitor 47, the personal computer can be equipped with other peripheral output devices (not displayed), for example, speakers, a printer, etc. .

Персональный компьютер 20 способен работать в сетевом окружении, при этом используется сетевое соединение с другим или несколькими удаленными компьютерами 49. Удаленный компьютер (или компьютеры) 49 являются такими же персональными компьютерами или серверами, которые имеют большинство или все упомянутые элементы, отмеченные ранее при описании существа персонального компьютера 20, представленного на Фиг. 1. В вычислительной сети могут присутствовать также и другие устройства, например, маршрутизаторы, сетевые станции, пиринговые устройства или иные сетевые узлы.The personal computer 20 is capable of operating in a networked environment, using a network connection with another or more remote computers 49. The remote computer (or computers) 49 are the same personal computers or servers that have most or all of the elements mentioned earlier in the description of the creature the personal computer 20 of FIG. 1. Other devices, such as routers, network stations, peer-to-peer devices, or other network nodes, may also be present on the computer network.

Сетевые соединения могут образовывать локальную вычислительную сеть (LAN) 50 и глобальную вычислительную сеть (WAN). Такие сети применяются в корпоративных компьютерных сетях, внутренних сетях компаний и, как правило, имеют доступ к сети Интернет. В LAN- или WAN-сетях персональный компьютер 20 подключен к локальной сети 50 через сетевой адаптер или сетевой интерфейс 51. При использовании сетей персональный компьютер 20 может использовать модем 54 или иные средства обеспечения связи с глобальной вычислительной сетью, такой как Интернет. Модем 54, который является внутренним или внешним устройством, подключен к системной шине 23 посредством последовательного порта 46. Следует уточнить, что сетевые соединения являются лишь примерными и не обязаны отображать точную конфигурацию сети, то есть в действительности существуют иные способы установления соединения техническими средствами связи одного компьютера с другим.Network connections can form a local area network (LAN) 50 and a wide area network (WAN). Such networks are used in corporate computer networks, internal networks of companies and, as a rule, have access to the Internet. In LAN or WAN networks, the personal computer 20 is connected to the local area network 50 via a network adapter or network interface 51. When using the networks, the personal computer 20 may use a modem 54 or other means of providing communication with a global computer network such as the Internet. The modem 54, which is an internal or external device, is connected to the system bus 23 via the serial port 46. It should be clarified that the network connections are only exemplary and are not required to display the exact network configuration, that is, in reality there are other ways to establish a connection using the technical means of communication of one computer with another.

Память с произвольным доступом 25, часть системной памяти 22, которая в рамках данной заявки будет именоваться как физическая память, вся физическая память делится на физические страницы 100, пример разделения приведен на Фиг. 2. Набор адресов для адресации физической памяти образуют физическое адресное пространство. Так как размер физической памяти ограничен, для исполнения программ создана виртуальная память, набор адресов для адресации виртуальной памяти образует виртуальное адресное пространство. Под виртуальной памятью в рамках данной заявки понимается совокупность логических страниц в совокупности со структурами, которые эти страницы описывают (указатель на каталог страниц, каталог страниц, таблица страниц). Указанные структуры будут описаны ниже. В рамках данной заявки понятия виртуальное адресное пространство и виртуальная память тождественны.Random access memory 25, part of the system memory 22, which in the framework of this application will be referred to as physical memory, all physical memory is divided into physical pages 100, an example of separation is shown in FIG. 2. A set of addresses for addressing physical memory form a physical address space. Since the size of physical memory is limited, virtual memory is created for program execution, a set of addresses for addressing virtual memory forms a virtual address space. Virtual memory in the framework of this application is understood as a set of logical pages in conjunction with the structures that these pages describe (pointer to a page directory, page directory, page table). These structures will be described below. In the framework of this application, the concepts of virtual address space and virtual memory are identical.

Виртуальное адресное пространство делится на логические страницы 100а. Логическая страница имеет свой виртуальный адрес, и может быть отображена на любой физический адрес, как это показано на Фиг. 2. Таким образом, логические страницы соответствуют физическим страницам или другими словами, логические страницы отображаются на физические страницы. Логические страницы, в частном случае отображаются на физические страницы в произвольном порядке, как это изображено на Фиг. 2. В другом частном случае логические страницы тождественно отображаются на физические страницы. На одну физическую страницу может отображаться несколько логических страниц.The virtual address space is divided into logical pages 100a. The logical page has its own virtual address, and can be mapped to any physical address, as shown in FIG. 2. Thus, logical pages correspond to physical pages or in other words, logical pages are displayed on physical pages. Logical pages, in a particular case, are mapped onto physical pages in random order, as shown in FIG. 2. In another particular case, logical pages are identically mapped onto physical pages. Multiple logical pages can be displayed on one physical page.

Логические страницы 100а являются виртуальными объектами (то есть реально не существующими в отличии от физических страниц 100) и каждая такая страница имеет в частном случае два адреса:Logical pages 100a are virtual objects (that is, they do not really exist, unlike physical pages 100), and each such page in a particular case has two addresses:

- линейный - тот, по которому она расположена в адресном пространстве;- linear - the one along which it is located in the address space;

- физический - тот, на который она отображена в физической памяти компьютера 25, в некоторых случаях его может не быть.- physical - the one on which it is displayed in the physical memory of computer 25, in some cases it may not be.

Виртуальная память, это некоторый способ использования системной памяти 22 на локальном компьютере, а в частном случае - на локальном компьютере и удаленном компьютере. Благодаря страничной организации памяти возможно реализовать механизм виртуальной памяти с управлением на уровне процессора. Логическую страницу памяти можно выгрузить, например, на жесткий диск 24, при этом убрав ее содержимое из физической памяти 25, размер реально используемой виртуальной памяти значительно возрастает и уже ограничен размером доступных жестких дисков, при этом необязательно, что жесткие диски, на которые выгружаются страницы, должны располагаться на локальном компьютере.Virtual memory is some way of using system memory 22 on a local computer, and in a particular case on a local computer and a remote computer. Thanks to the page organization of memory, it is possible to implement a virtual memory mechanism with control at the processor level. The logical page of memory can be unloaded, for example, to hard disk 24, while removing its contents from physical memory 25, the size of the actually used virtual memory increases significantly and is already limited by the size of available hard disks, while it is not necessary that the hard disks onto which the pages are unloaded must be located on the local computer.

Механизм описания виртуальной памяти при обычной, 32-разрядной страничной адресации (англ. paging), представлен на Фиг. 2. Для описания страницы может использоваться структура данных, состоящая из физического адреса, на который отображена страница, и флагов(атрибутов), определяющих свойства этой страницы. Информация о 32-разрядном адресе начала страницы находится в старших 20 разрядах - они и хранятся в описании страницы. Описания страниц группируются в таблицы страниц 101. Описатели страниц - это 4-байтовые элементы (entries). Эти элементы называются PTE (Page Table Entries) и представляют собой указатели на страницы, по формату - структуры данных, которые описаны в документе «Intel® 64 and IA-32 Architectures Software Developer's Manual» (стр. 4-12 - 4-16). Таблицы страниц группируются в каталог страниц 102. Каталог страниц 102 - это массив размером в 4Кб, состоящий из 4-байтовых элементов PDE (Page Directory Entries). Каждый элемент указывает на таблицу страниц 101 и по формату почти совпадает с РТЕ. Элемент PDE определяет положение таблицы страниц, указывая адрес физической страницы памяти, а также атрибуты таблицы страниц. Формат PDE описан в документе «Intel® 64 and IA-32 Architectures Software Developer's Manual» (стр. 4-12 - 4-16). Для того чтобы процессор мог использовать страничное преобразование, ему необходимо указать адрес начала каталога страниц 103 (англ. Page Directory Base - PDB). Этот адрес хранится в регистре CR3.The mechanism for describing virtual memory in conventional 32-bit paging is shown in FIG. 2. To describe the page, a data structure consisting of the physical address to which the page is mapped and flags (attributes) defining the properties of this page can be used. Information about the 32-bit address of the beginning of the page is in the upper 20 digits - they are stored in the page description. Page descriptions are grouped into page tables 101. Page descriptors are 4-byte entries. These elements are called Page Table Entries (PTEs) and are pointers to pages, in format, the data structures described in the Intel® 64 and IA-32 Architectures Software Developer's Manual (pp. 4-12 - 4-16) . Page tables are grouped into a page directory 102. A page directory 102 is a 4Kb array of 4-byte PDEs (Page Directory Entries). Each element points to a page table 101 and is almost the same as PTE in format. The PDE element determines the position of the page table, indicating the address of the physical memory page, as well as the attributes of the page table. The PDE format is described in Intel® 64 and IA-32 Architectures Software Developer's Manual (pp. 4-12 - 4-16). In order for the processor to be able to use page conversion, it needs to specify the address of the beginning of the page directory 103 (the English Page Directory Base - PDB). This address is stored in register CR3.

Итак, для адресации в 32-разрядном адресном пространстве, для того чтобы указать номер страницы в таблице страниц, необходимо 10-разрядное значение (т.к. в таблице хранится 1024 описания страниц). Для того чтобы указать, какая именно таблица в каталоге страниц будет использоваться, также требуется 10-разрядное значение. Для того чтобы указать смещение внутри страницы, необходимо 12-разрядное значение. Если сложить размеры этих значений, то получается, что для доступа к памяти нужно задать 32-разрядную структуры данных: 10 бит - номер таблицы, еще 10 - номер страницы в таблице и 12 - смещение внутри самой страницы.So, for addressing in a 32-bit address space, in order to indicate the page number in the page table, you need a 10-bit value (since 1024 page descriptions are stored in the table). To specify which table in the page directory will be used, a 10-bit value is also required. To indicate the offset within the page, a 12-bit value is required. If we add together the sizes of these values, it turns out that to access the memory you need to set a 32-bit data structure: 10 bits is the table number, another 10 is the page number in the table and 12 is the offset inside the page itself.

В случае, когда используется режим адресации РАЕ (Physical Address Extension), добавляется дополнительный уровень иерархии - таблица каталогов страниц 104, которая содержит PDPTE (Page-Directory-Pointer-Table Entry) элементы. В данном случае CR3 регистр содержит физический адрес 105 выровненной таблицы каталогов страниц 104. Более подробно указанный режим и формат PDE, PTE, PDPTE элементов для данного режима описаны в документе «Intel® 64 and IA-32 Architectures Software Developer's Мanual»_(стр. 4-17 - 4-25).When the PAE (Physical Address Extension) mode is used, an additional hierarchy level is added - the page directory table 104, which contains the PDPTE (Page-Directory-Pointer-Table Entry) elements. In this case, the CR3 register contains the physical address 105 of the aligned page directory table 104. For more details on the specified mode and format of PDE, PTE, PDPTE elements for this mode, see the Intel® 64 and IA-32 Architectures Software Developer's Manual _ (page 4-17 - 4-25).

В случае, когда используется режим 1А-32е, к таблице страниц, каталогу страниц и таблице каталогов добавляется дополнительный уровень иерархии - таблица уровней страничной адресации 107, которая содержит PML4E (Page Map Level Entry) элементы. В данном случае CR3 регистр 106 содержит структуру, в которой указан физический адрес 108 выровненной таблицы уровней страничной адресации 107. Более подробно указанный режим и формат PDE, PTE, PDPTE, PML4E элементов для данного режима описаны в документе «Intel® 64 and IA-32 Architectures Software Developer's Manual» (стр. 4-26 - 4-39).In the case where mode 1A-32e is used, an additional hierarchy level is added to the page table, page directory and directory table — the page addressing levels table 107, which contains PML4E (Page Map Level Entry) elements. In this case, CR3 register 106 contains a structure in which the physical address 108 of the aligned page address level table 107 is indicated. The specified mode and format of PDE, PTE, PDPTE, PML4E elements for this mode are described in more detail in Intel® 64 and IA-32 Architectures Software Developer's Manual ”(pp. 4-26 - 4-39).

При запуске программы операционная система создает процесс, в рамках которого будут исполняться его потоки. Файл программы загружается в некоторую область физической памяти компьютера. В случае использования виртуальной памяти файл загружается в некоторую область виртуальной памяти, на которую система отображает некоторый пул физических адресов. Затем программа начинает выполняться, то есть процессор выполняет машинные инструкции в той последовательности, в какой они записаны в файле программы. Процесс, создаваемый операционной системой, является, по сути, контейнером ресурсов, необходимых для выполнения кода программы. В частном случае в многозадачной операционной системе каждому процессу соответствует собственное виртуальное адресное пространство. Из описания механизма адресации виртуального адресного пространства следует, что чтобы получить доступ к виртуальному адресному пространству процесса, необходим доступ к регистру управления CR3 106. Управляя структурами и их элементами, к которым получают доступ на основании информации содержащейся в регистре управления CR3 106, управляют виртуальным адресным пространством процесса. В частном случае реализации, при 32-разрядной адресации, каждый процесс имеет свой каталог страниц, и, соответственно, при переключении между процессами осуществляется перезапись CR3 регистра 106, который хранит физический адрес выровненного каталога страниц. Программе совсем не обязательно определять все страницы, таблицы и элементы каталога, достаточно определить только те, которые реально будут использоваться и динамически добавлять или убирать новые описания в процессе работы.When the program starts, the operating system creates a process in which its threads will be executed. The program file is loaded into some area of the computer's physical memory. In the case of using virtual memory, the file is loaded into some area of virtual memory onto which the system maps a pool of physical addresses. Then the program starts to run, that is, the processor executes the machine instructions in the order in which they are written in the program file. The process created by the operating system is, in fact, a container of resources needed to execute the program code. In the particular case of a multitasking operating system, each process has its own virtual address space. It follows from the description of the virtual address space addressing mechanism that access to the virtual address space of a process requires access to the CR3 106 control register. By controlling the structures and their elements that are accessed based on the information contained in the CR3 106 control register, the virtual address process space. In the particular case of implementation, with 32-bit addressing, each process has its own page directory, and, accordingly, when switching between processes, the CR3 register 106 is overwritten, which stores the physical address of the aligned page directory. The program does not have to define all the pages, tables and catalog items, it is enough to determine only those that will actually be used and dynamically add or remove new descriptions in the process.

На Фиг. 3 изображена часть системной памяти 22 в некоторой области 301 которой записаны инструкции для выполнения. Под областью памяти в одном частном случае понимается область физической памяти, в другом частном случае под областью памяти понимается область системной памяти, на которую отображены логические страницы, то есть область виртуальной памяти. Для осуществления подконтрольного выполнения программы в оригинальной области памяти 301 определяют интересующий участок. Интересующим участком области памяти является любой участок области памяти, при передаче управления инструкциям которого необходимо создать уведомление. В частной интерпретации интересующий участок- это некоторый участок в некоторой области памяти, который выделяют среди других на основании некоторых признаков, определяющих содержание участка, его расположение, назначение. Интересующими участками в частном случае являются участки области памяти, содержащие программные инструкции, при передаче управления которым необходимо проверить состояние регистров, для того чтобы оценить последовательность выполнения программных инструкций. Также интересующий участок может объединять набор инструкций, предназначенных для выполнения некоторого действия (обращение к жесткому диску, передача информации по сети и т.д.).In FIG. 3 shows part of the system memory 22 in a certain area 301 of which instructions for execution are recorded. The memory area in one particular case refers to the area of physical memory, in another particular case, the memory area refers to the area of system memory onto which logical pages are displayed, that is, the area of virtual memory. To carry out controlled execution of the program in the original memory area 301 determine the area of interest. The region of memory region of interest is any region of the memory region, when transferring control to the instructions of which it is necessary to create a notification. In a private interpretation, a site of interest is a site in a certain memory area that is distinguished from others on the basis of some features that determine the site’s content, location, and purpose. In the particular case, the sections of interest are the sections of the memory area containing program instructions, when transferring control to which it is necessary to check the status of the registers in order to evaluate the sequence of execution of program instructions. Also, the area of interest can combine a set of instructions designed to perform some action (accessing the hard drive, transferring information over the network, etc.).

Далее осуществляют дублирование участков оригинальной области памяти, где дублируют, по меньшей мере, интересующий участок 303. Дублирование памяти осуществляют разными способами. В одном частном случае осуществляется непосредственное копирование инструкций и данных участка в другую область памяти 301а, как это изображено на Фиг. 3. Таким образом, в физической памяти появляются участки с идентичным содержимым. В другом частном случае копирование данных не происходит, создаются новые каталоги 102 и таблицы страниц 101, указывающие на те же самые области физической памяти (Фиг. 4).Next, duplicate sections of the original memory region are carried out, where at least the region of interest 303 is duplicated. The memory is duplicated in different ways. In one particular case, direct copying of instructions and section data to another memory area 301a is carried out, as shown in FIG. 3. Thus, areas with identical contents appear in the physical memory. In another particular case, data is not copied; new directories 102 and page tables 101 are created that point to the same areas of physical memory (Fig. 4).

Далее помечают участки памяти в оригинальной области памяти 301, при этом метки для интересующих участков 303 отличны от меток остальных участков 304 оригинальной области. В качестве меток может использоваться модификация байт инструкций участка памяти. В другом частном случае сами инструкции и данные никак не изменяются, а меняются атрибуты в структурах, описывающих эти участки. Например, страницам интересующего участка выставляют атрибут неисполняемые, а страницам остальных участков выставляют атрибут исполняемые. Также можно использовать атрибуты чтения/записи и другие. На следующем шаге помечают участки в продублированной области памяти 301а, при этом метки для интересующего участка отличны от меток остальных участков продублированной области памяти 301а. В одном частном случае для продублированного участка 303а применяются те же самые метки, что и для оригинального 303, в другом частном случае применяются другие метки. Например, в оригинальной области памяти страницам интересующего участка 303 выставляют атрибут «неисполняемые», а страницам других участков 304 оригинальной области выставляют атрибут «исполняемые», участки которые имели атрибут «неисполняемые», сохранят этот атрибут. Для продублированной области 301а выполняют инверсию атрибутов, где страницам интересующего участка выставляют атрибут «исполняемые», а страницам остальных участков выставляют атрибут «неисполняемые». Далее выбирается область памяти для выполнения инструкций, которые она содержит процессором.Next, the memory sections are marked in the original memory area 301, while the marks for the regions of interest 303 are different from the marks of the remaining sections 304 of the original region. As labels, a modification of the bytes of instructions in the memory section can be used. In another particular case, the instructions themselves and the data do not change at all, but the attributes in the structures describing these sections change. For example, the pages of the site of interest are set to the non-executable attribute, and the pages of the remaining sections are set to the executable attribute. You can also use read / write attributes and others. In the next step, the areas in the duplicated memory area 301a are marked, and the labels for the area of interest are different from the marks of the remaining parts of the duplicated memory area 301a. In one particular case, for the duplicated section 303a, the same marks apply as for the original 303, in another particular case other marks apply. For example, in the original memory area, the pages of the region 303 of interest are set to the attribute “non-executable”, and the pages of other sections 304 of the original region are set to the “executable” attribute, the sections which had the “non-executable” attribute will retain this attribute. For the duplicated area 301a, an inversion of attributes is performed, where the pages of the area of interest are set to the attribute “executable”, and the pages of the remaining sections are set to the attribute “not executable”. Next, a memory area is selected to execute the instructions that it contains by the processor.

После вышеописанных манипуляций осуществляют выполнение инструкций в выбранной области памяти процессором, до появления уведомления, где уведомление создается при передаче управления инструкции из участка, помеченного одной меткой, в участок области, помеченный отличной меткой. Такими уведомлениями могут быть, по меньшей мере, исключения и прерывания. Прерывания и исключения - события, означающие что где-то в системе (оборудовании) или внутри текущей выполняющейся программы или задачи возникло состояние, требующее немедленного внимания процессора. Прерывания и исключения приводят к принудительной передаче управления от текущей выполняемой программы или задачи к специальной программной процедуре или задаче, называемой обработчиком прерывания или обработчиком исключения. Действие в ответ на прерывание или исключение - обработка прерывания или исключения.After the above-described manipulations, instructions are executed in the selected memory area by the processor, until a notification appears, where a notification is created when control is transferred from the section marked with one mark to the section of the mark marked with an excellent mark. Such notifications may include at least exceptions and interruptions. Interrupts and exceptions are events that mean that somewhere in the system (equipment) or inside the currently running program or task, a condition has occurred that requires immediate attention from the processor. Interruptions and exceptions lead to a forced transfer of control from the current program or task to a special program procedure or task called an interrupt handler or exception handler. Action in response to an interrupt or exception - handling the interrupt or exception.

Исключения возникают, когда процессор определяет возникновение ошибки в процессе выполнения инструкции. Возможные варианты прерываний и исключений описаны в документе «Intel® 64 and IA-32 Architectures Software Developer's Manual» (p. 6-1 - 6-68).Exceptions occur when the processor determines the occurrence of an error during the execution of an instruction. Possible interruptions and exceptions are described in the Intel® 64 and IA-32 Architectures Software Developer's Manual (p. 6-1 - 6-68).

В частном случае обработкой полученного уведомления является передача выполнения инструкций области памяти отличной от той, в которой создано уведомление. Например, если выполнение осуществлялось в оригинальной области памяти 301, выполнение передают дублированной области памяти 301а, и если выполнение осуществлялось в дублированной области памяти 301а, выполнение передают оригинальной области памяти 301 или другой продублированной области памяти. Передача выполнения осуществляется разными способами, в зависимости от способа, которым осуществлялось дублирование участков оригинальной области памяти. В одном частном случае изменяется адрес следующей инструкции выполнения, а в другом частном случае все адреса остаются неизменными, изменяется лишь значение регистра управления CR3 106, как это показано на Фиг. 4.In the particular case, the processing of the received notification is the transfer of execution of instructions of the memory area different from the one in which the notification was created. For example, if execution was performed in the original memory region 301, execution was transferred to the duplicated memory region 301a, and if execution was performed in the duplicated memory region 301a, execution was transferred to the original memory region 301 or other duplicated memory region. The transfer of execution is carried out in different ways, depending on the method by which duplicate sections of the original memory area were carried out. In one particular case, the address of the next execution instruction is changed, and in another particular case, all addresses remain unchanged, only the value of control register CR3 106 changes, as shown in FIG. four.

На Фиг. 5 представлен алгоритм передачи управления выполнения инструкций от одной виртуальной области памяти, другой. На этапе 500 определяют в оригинальной виртуальной области памяти интересующий участок памяти, который состоит, по меньшей мере, из одной логической страницы. На следующем этапе 501 создают, по меньшей мере, еще одну виртуальную область памяти, которая в частном случае отображена на те же физические страницы, что и оригинальная виртуальная область памяти. Для этого создают каталог страниц и, по меньшей мере, одну таблицу страниц. Для создания виртуальной области памяти, в частном случае копируют РТЕ и PDE оригинальной виртуальной области.In FIG. 5 shows an algorithm for transferring control of execution of instructions from one virtual memory area to another. At step 500, a region of memory of interest, which consists of at least one logical page, is determined in the original virtual memory region. In the next step 501, at least one more virtual memory region is created, which in a particular case is displayed on the same physical pages as the original virtual memory region. To do this, create a directory of pages and at least one page table. To create a virtual memory area, in the particular case, the PTE and PDE of the original virtual area are copied.

Далее, на этапе 502, помечают участки в оригинальной виртуальной области памяти, при этом метки для интересующего участка отличны от меток остальных участков оригинальной области, в частном случае для этого используется бит NX в структуре РТЕ: в частном случае для страниц интересующего участка бит может быть установлен, для страниц других участков данный бит сбрасывается, в другом частном случае для страниц интересующего участка бит сбрасывается, для страниц других участков данный бит устанавливается. После установки меток в оригинальной области на этапе 503 помечают участки, в по меньшей мере одной, созданной продублированной области памяти, при этом метки для интересующего участка отличны от меток остальных участков продублированной области памяти. В частном случае на данном шаге применяется тот же механизм установки NX бита, что и для оригинального участка. В частном случае применяется инверсия, то есть если в оригинальной области памяти NX бит для страниц интересующего участка сброшен, то в дубликате оригинальной области для страниц интересующего участка данный бит устанавливается. В других частных случаях для меток страниц участков используются другие биты PDE и РТЕ структур, например, R/W бит. Еще в одном частном случае биты комбинируются, например, для оригинальной виртуальной области используют бит NX, для дубликатов виртуальной области R/W бит.Next, at step 502, areas in the original virtual memory area are marked, while the labels for the area of interest are different from the labels of the remaining areas of the original area, in this particular case, the NX bit in the PTE structure is used: in the particular case, for pages of the area of interest, the bit can be set, for pages of other sections, this bit is reset, in another particular case, for pages of the section of interest, the bit is reset, for pages of other sections, this bit is set. After setting the marks in the original region, in step 503, the regions in at least one of the created duplicated memory regions are marked, and the marks for the region of interest are different from the marks of the remaining sections of the duplicated memory region. In the particular case, at this step, the same NX bit setting mechanism is used as for the original section. In the particular case, inversion is applied, that is, if in the original NX memory region the bit for the pages of the region of interest is cleared, then in the duplicate of the original region for the pages of the region of interest this bit is set. In other special cases, other bits of the PDE and PTE structures, for example, the R / W bit, are used for page page labels. In another particular case, the bits are combined, for example, for the original virtual area use the NX bit, for duplicates of the virtual area R / W bit.

На этапе 504 выбирают область памяти, для выполнения записанных в ней инструкций. В зависимости от целей для которых используют переключение между областями (журналирование, отладка, противодействие эксплуатации уязвимостям и т.д.) выбирают оригинальную область памяти или одну из продублированных областей памяти.At step 504, a memory region is selected to execute the instructions recorded therein. Depending on the purposes for which switching between areas is used (logging, debugging, anti-exploitation of vulnerabilities, etc.), the original memory area or one of the duplicated memory areas is selected.

На этапе 505 осуществляют выполнение инструкций в выбранной области памяти процессором до появления уведомления, где уведомление создается при передаче управления инструкции из участка, помеченного одной меткой, в участок области, помеченный другой меткой. В частном случае при использовании в качестве метки NX бита таким уведомлением будет исключение страничного нарушения (#PF - Page-Fault Exception). Это уведомление создается при передаче управления от инструкций участка области памяти, для страниц которого бит NX сброшен, инструкции участка области памяти для страниц которого бит NX установлен.At step 505, instructions are executed in the selected memory area by the processor until a notification appears, where a notification is generated when control is transferred from the area marked with one label to the area marked with another label. In a particular case, when using an NX bit as a label, such a notification will be a page violation exception (#PF - Page-Fault Exception). This notification is generated when control is transferred from the instructions of the section of the memory area for the pages of which the NX bit is cleared, the instructions of the section of the memory area for the pages of which the NX bit is set.

На заключительном этапе 506 передают выполнение инструкций области памяти отличной от той, выполнение инструкций в которой создало уведомление. В частном случае передача управления осуществляется путем перезаписи содержимого CR3, тип перезаписываемого содержимого определяется режимом адресации (paging mode).At the final step 506, execution of instructions of a memory area other than the execution of instructions in which a notification is generated is transmitted. In the particular case, the transfer of control is carried out by overwriting the contents of CR3, the type of rewritable content is determined by the addressing mode (paging mode).

Вышеописанный алгоритм передачи выполнения в частном случае применяется в системах журналирования, предназначенных для формирования журнала вызовов API-функций, вызываемых во время исполнения программы. Процесс имеет виртуальное адресное пространство (ВАП), в которое загружаются необходимые секции файлов программы, а также связанные с ним динамические библиотеки DLL. Во время исполнения программного кода происходят вызовы API-функций из различных библиотек DLL, которые и должны быть внесены в журнал вызовов API-функций.The above-described execution transfer algorithm in a particular case is used in journaling systems designed to generate a log of calls to API functions that are called during program execution. The process has a virtual address space (VAP) into which the necessary sections of the program files are loaded, as well as the dynamic DLLs associated with it. During the execution of the program code, API function calls from various DLLs take place, which should be entered into the API function call log.

На Фиг. 6а показан пример памяти процесса, который создается ОС. В памяти процесса для наглядности отдельно выделены участки, которые содержат программные инструкции модулей и библиотек, например, модуль «ΕΧΕ», содержащий программные инструкции исполняемого файла, при запуске которого был создан процесс, различные динамические библиотеки (Unknown.dll, other known.dll, kernel32.dll и Ntdll.dll). Также имеются участки «other memory» и «process heap», в данных участках могут содержаться любые вспомогательные данные.In FIG. 6a shows an example of the memory of a process that is created by the OS. For illustrative purposes, sections in the process memory are separately selected that contain program instructions for modules and libraries, for example, the ΕΧΕ module containing program instructions for the executable file, when the process was launched, various dynamic libraries (Unknown.dll, other known.dll, kernel32.dll and Ntdll.dll). There are also “other memory” and “process heap” sections, these sections can contain any auxiliary data.

Стоит отметить, что, так как библиотек огромное количество (Фиг. 6а не отражает всего многообразия библиотек), то для системы журналирования все библиотеки разделяют только на две группы, интересующие и неинтересующие. Интересующие библиотеки в области памяти образуют интересующие участки памяти 303 и 303а, неинтересующие библиотеки совместно с другими модулями составляют все остальные участки памяти 304 и 304а. Примерами интересующих библиотек являются библиотеки «kemel32.dll» и «Ntdll.dll». Примерами неинтересующих библиотек являются библиотеки «Unknown.dll» и «Other known.dll». Может быть сформирован список интересующих динамических библиотек, в котором будут содержаться библиотеки необходимые для журналирования. Как правило, список самых популярных и часто используемых всеми процессами библиотек может охватить работу всех остальных. Соответственно, все остальные библиотеки будут являться неинтересующими.It is worth noting that, since there are a huge number of libraries (Fig. 6a does not reflect the whole variety of libraries), for a journaling system all libraries are divided into only two groups of interest and uninteresting. Libraries of interest in the memory area form the memory regions of interest 303 and 303a, the uninteresting libraries, together with other modules, comprise all other memory regions 304 and 304a. Examples of libraries of interest are the kemel32.dll and Ntdll.dll libraries. Examples of uninteresting libraries are the Unknown.dll and Other known.dll libraries. A list of dynamic libraries of interest can be generated, which will contain the libraries necessary for journaling. As a rule, the list of the most popular and often used by all processes libraries can cover the work of everyone else. Accordingly, all other libraries will be uninteresting.

На Фиг. 6б и Фиг. 6в приведены примеры ВАП, одно ВАП является оригинальным (Фиг. 6б), второе дубликат оригинального ВАП (Фиг. 6в). В частном варианте реализации для формирования списка вызовов API-функций система журналирования во время запуска исполняемого файла вместо оригинально ВАП создает два новых ВАП. В другом частном случае реализации создаются два новых ВАП, но при этом используется совместно с ними и оригинальное ВАП, которое в дальнейшем будет предоставляться ОС в случае ее обращения к ВАП.In FIG. 6b and FIG. 6c shows examples of VAPs, one VAP is original (Fig. 6b), the second is a duplicate of the original VAP (Fig. 6c). In a particular embodiment, to create a list of calls to API functions, the logging system creates two new VAPs instead of the original VAP during the launch of the executable file. In another special case of implementation, two new VAPs are created, but at the same time the original VAP is used in conjunction with them, which will be subsequently provided to the OS if it is accessed by the VAP.

Таким образом, производится разделение памяти процесса на две части. В первом оригинальном ВАП 301, интересующие участки 303 помечаются как неисполняемые, способом, описанным выше, вызовы экспортируемых функций библиотек, программные инструкции которых содержаться в страницах интересующего участка будут журналироваться. В оставшиеся участки 304, например, ЕХЕ-модуль или неинтересующие библиотеки DLL помечаются как исполняемые. В дубликате ВАП 301а осуществляется инверсия, интересующие участки 303а помечаются как исполняемые, оставшиеся участки 304а помечаются как неисполняемые.Thus, the process memory is divided into two parts. In the first original VAP 301, sections of interest 303 are marked as unfulfilled, in the manner described above, calls to exported library functions whose program instructions are contained in the pages of the section of interest will be logged. In the remaining sections 304, for example, the EXE module or uninteresting DLLs are marked as executable. In the duplicate of the VAP 301a, an inversion is performed, the sections of interest 303a are marked as executable, the remaining sections 304a are marked as non-executable.

Стоит отметить, что вне зависимости от ВАП содержимое памяти процесса всегда остается одним и тем же (то есть целостность адресного пространства не нарушается). Изменяются только атрибуты у соответствующих таблиц/страниц. Данное утверждение верно только для режима User Mode, в котором происходит физическое разделение памяти. Разделение заключается в том, что для каждой копии ВАП будут созданы свои каталоги страниц и таблицы страниц, а в частном случае таблицы каталогов и таблицы уровней страничной адресации со своими значением регистра управления CR3. Одна и та же физическая страница отображена в двух каталогах, но с разными атрибутами для библиотек, вызовы которых необходимо журналировать. Таким образом, переключение между ВАП производится за счет перезаписи (смены содержимого) регистра управления CR3.It is worth noting that, regardless of the VAP, the contents of the process memory always remain the same (that is, the integrity of the address space is not violated). Only the attributes of the corresponding tables / pages are changed. This statement is true only for the User Mode, in which the physical separation of memory occurs. The separation consists in the fact that for each copy of the VAP their own page directories and page tables will be created, and in a particular case, directory tables and page level table tables with their own CR3 control register value. The same physical page is displayed in two directories, but with different attributes for libraries whose calls must be logged. Thus, switching between the VAPs is done by overwriting (changing the contents) of the CR3 control register.

Для того чтобы система журналирования могла управлять ВАЛ (переключать работу между ВАП), производят расстановку флагов (NX-бит) в разделе атрибутов каждой страницы для соответствующих страниц в каждом ВАП. NX-бит является специальным флагом, в соответствии с которым определяется возможность исполнения программного кода, размещенного на данной странице памяти, или возникновения исключения (Page Fault, далее #PF) в случае попытки исполнения кода. Под «#PF» понимается исключение, которое возникает при попытке выполнения программного кода из страницы памяти, для которой такое выполнение запрещено. За счет установки данных NX-битов достигается возможность переключения созданных ВАП в момент вызова API-функции. Стоит отметить, что вызовы будут журналироваться при переключении из оригинального ВАП 301 в дубликат ВАП 301а, а также при переключении и в обратную сторону будут журналироваться возвращаемое значение и некоторые выходные параметры функций. Данный принцип позволяет исполнять в дубликате ВАП 301а только интересующие динамические библиотеки, а в оригинальном ВАП 301 весь остальной исполняемый код.In order for the journaling system to be able to control the VAL (switch work between VAPs), the flags are set (NX-bit) in the attributes section of each page for the corresponding pages in each VAP. The NX-bit is a special flag, according to which the ability to execute program code located on this memory page, or an exception (Page Fault, hereinafter #PF) in case of attempt to execute the code, is determined. By “#PF” is meant the exception that occurs when trying to execute program code from a memory page for which such execution is prohibited. By setting these NX bits, it is possible to switch the created VAPs at the time of calling the API function. It is worth noting that calls will be logged when switching from the original VAP 301 to a duplicate of the VAP 301a, as well as when switching to the opposite direction, the return value and some output parameters of the functions will be logged. This principle allows only dynamic libraries of interest to be executed in a duplicate of VAP 301a, and the rest of the executable code in the original VAP 301.

Рассмотрим механизм исполнения программы и работу системы журналирования. Система журналирования содержит список интересующих библиотек, а также формирует некую «карту библиотек», которая содержит информацию, по меньшей мере, об адресах точек входа в библиотеки.Consider the program execution mechanism and the operation of the logging system. The journaling system contains a list of libraries of interest, and also forms a kind of “library map”, which contains information, at least, about the addresses of the library entry points.

На Фиг. 7 показаны основные шаги подготовки к работе системы журналирования. В начале запуска исполняемого файла на этапе 700 система журналирования перехватывает управление на этапе 701 и формирует два ВАП, оригинальный ВАП 301 и дубликат ВАП 301а. на этапе 702. Далее на этапе 703 определяют интересующие библиотеки и их страницы. Во время формирования двух ВАП в каждом из них в атрибутах страниц, принадлежащих интересующим библиотекам и страницах принадлежащих всему остальному коду, производится расстановка NX-битов, этап 704. Далее возвращается управление ОС, этап 705.In FIG. 7 shows the basic steps for preparing the logging system for operation. At the beginning of the launch of the executable file at step 700, the journaling system takes control at step 701 and generates two VAPs, the original VAP 301 and a duplicate VAP 301a. at step 702. Next, at step 703, the libraries of interest and their pages are determined. During the formation of two VAPs in each of them, in the attributes of the pages belonging to the libraries of interest and the pages belonging to the rest of the code, the NX bits are arranged, step 704. Next, the OS control returns, step 705.

На Фиг. 8 показаны шаги работы системы журналирования во время формирования журнала вызовов API-функций. Предположим, что во время выполнения исполняющегося файла производится вызов какой-либо API-функции из интересующей библиотеки. Например, это вызов функции «CreateFile», которая находится в динамической библиотеке «kernel32.dll». Соответственно, во время передачи управления (перехода) по указанному адресу обращения для дальнейшего выполнения функции возникает исключение PageFault (#PF) в соответствии с заранее расставленными NX-битами. Данная ситуация связана с тем, что исполнение происходит в оригинальном ВАП 301, а как писалось выше, в атрибутах страниц для интересующих библиотек были установлены NX-биты, которые указывают на невозможность выполнения кода в данных страницах оригинального ВАП. Далее с помощью обработчика исключений производится анализ контекста исключения #PF с целью определения причины возникновения данного исключения и определения адреса API-функции, которую вызвали. Таким образом, анализ заключается в поиске API-функции, которая соответствует адресу памяти, куда был обращен вызов, по таблице API-функций (которая заранее была создана). После определения API-функции информация о ней заносится в журнал вызовов API-функций, и производится переключение с оригинального ВАП 301 на дубликат ВАП 301а, где производится дальнейшей выполнение кода интересующей библиотеки, а точнее выполнение определенной API-функции.In FIG. Figure 8 shows the steps of the logging system during the generation of the API function call log. Suppose that during the execution of an executable file some API function is called from the library of interest. For example, this is a call to the "CreateFile" function, which is located in the "kernel32.dll" dynamic library. Accordingly, during the transfer of control (transition) to the specified access address for the further execution of the function, a PageFault (#PF) exception occurs in accordance with the pre-set NX bits. This situation is related to the fact that execution takes place in the original VAP 301, and as described above, NX bits were set in the page attributes for the libraries of interest, which indicate that the code cannot be executed in these pages of the original VAP. Next, using the exception handler, the #PF exception context is analyzed to determine the cause of this exception and determine the address of the API function that was called. Thus, the analysis consists in searching for an API function that corresponds to the memory address where the call was addressed by the table of API functions (which was created in advance). After determining the API function, information about it is recorded in the API function call log, and switching from the original VAP 301 to a duplicate VAP 301a is performed, where the code of the library of interest is further executed, or rather, the execution of a specific API function.

После того, как API-функция выполнила свою задачу, происходит выход из нее, то есть обратный переход к программному коду исполняемого файла (если посмотреть на Фиг. 6, то переход от модуля «Logging.dll» к модулю «Ехе»). Но в связи с тем, что в дубликате ВАП 301а данный регион памяти является неисполняемой, то возникает исключение #PF. Данный #PF также анализируется для определения причины возникновения. Во время анализа определяется, что происходит возврат из API-функции, например, с помощью информации об адресе перехода. В этом случае, происходит переключение ВАП с дубликата 301а на оригинальное 301, в котором и происходит дальнейшей выполнение программного кода. После того как опять выявляется вызов API-функции, все шаги по смене ВАП повторяются. И так до тех пор, пока выполняется программный код.After the API function has completed its task, it exits from it, that is, the transition back to the program code of the executable file (if you look at Fig. 6, then the transition from the "Logging.dll" module to the "Exe" module). But due to the fact that in the duplicate of VAP 301a this memory region is not executable, an exception #PF arises. This #PF is also analyzed to determine the cause. During the analysis, it is determined that there is a return from the API function, for example, using information about the transition address. In this case, the VAP switches from the duplicate 301a to the original 301, in which the further execution of the program code occurs. After the call to the API function is again detected, all steps to change the VAP are repeated. And so on until the program code is executed.

Стоит отметить, что одной из особенностей технологии является то, что система не меняет содержимое памяти, а вмешивается только в механизмы ОС по работе с памятью.It is worth noting that one of the features of the technology is that the system does not change the contents of the memory, but intervenes only in the OS mechanisms for working with memory.

В заключение следует отметить, что приведенные в описании сведения являются примерами, которые не ограничивают объем настоящего изобретения, определенного формулой. Специалисту в данной области становится понятным, что могут существовать и другие варианты осуществления настоящего изобретения, согласующиеся с сущностью и объемом настоящего изобретения.In conclusion, it should be noted that the information provided in the description are examples that do not limit the scope of the present invention defined by the claims. One skilled in the art will recognize that there may be other embodiments of the present invention consistent with the spirit and scope of the present invention.

Claims (19)

1. Способ передачи выполнения инструкций из одной области памяти в другую, в котором:1. The method of transferring the execution of instructions from one memory area to another, in which: а) определяют в оригинальной области памяти, состоящей из участков памяти, по меньшей мере, один интересующий участок памяти;a) determine in the original region of memory, consisting of sections of memory, at least one region of memory of interest; б) создают область памяти дублированием интересующего участка памяти оригинальной области памяти, определенного на шаге а);b) create a memory region by duplicating a region of memory of interest in the original memory region defined in step a); в) помечают все участки памяти в оригинальной области памяти, при этом метки для интересующего участка памяти в оригинальной области памяти отличны от меток остальных участков памяти оригинальной области памяти;c) mark all the memory areas in the original memory area, while the labels for the memory area of interest in the original memory area are different from the marks of the remaining memory areas of the original memory area; г) запускают выполнение инструкций, записанных в оригинальной области памяти, в любом из имеющихся участков памяти в оригинальной области памяти, кроме интересующего участка памяти;d) start the execution of instructions recorded in the original memory area, in any of the available memory areas in the original memory area, except for the memory area of interest; д) осуществляют выполнение инструкций в участках памяти оригинальной области памяти процессором до создания уведомления, при этом уведомление создается при передаче управления инструкции из участка памяти, помеченного одной меткой, в интересующий участок памяти, помеченный отличной меткой;e) carry out the execution of instructions in the memory areas of the original memory area by the processor until a notification is generated, and a notification is generated when control is transferred from the memory area marked with one label to the memory area of interest marked with an excellent label; е) передают выполнение инструкций из участка памяти оригинальной области памяти интересующему участку памяти, но в продублированной области памяти, после создания уведомления на шаге д);f) transmit the execution of instructions from the memory area of the original memory area to the memory area of interest, but in the duplicated memory area, after creating a notification in step e); ж) осуществляют выполнение инструкций в интересующем участке памяти продублированной области памяти процессором до создания уведомления, при этом уведомление создается при любой передаче управления из интересующего участка продублированной области памяти;g) carry out the execution of instructions in the memory area of interest of the duplicated memory area by the processor until a notification is generated, and a notification is generated during any transfer of control from the area of interest of the duplicated memory area; з) возвращают выполнение в оригинальную область памяти в соответствующий участок памяти.h) return execution to the original memory area in the corresponding memory area. 2. Способ по п. 1, в котором уведомление является исключением (exception).2. The method of claim 1, wherein the notification is an exception. 3. Способ по п. 2, в котором при передаче управления из интересующего участка памяти создается исключение Page Fault Exception.3. The method according to claim 2, in which when transferring control from a region of memory of interest, a Page Fault Exception is thrown. 4. Способ по п. 3, в котором дублирование осуществляется копированием таблиц и каталогов.4. The method according to p. 3, in which duplication is carried out by copying tables and directories. 5. Способ по п. 1, в котором продублированная область памяти состоит из одного интересующего участка памяти.5. The method of claim 1, wherein the duplicated memory region consists of one region of memory of interest. 6. Способ по п. 1, в котором передают выполнение инструкций области памяти, отличной от той, выполнение инструкций в которой создало уведомление, путем перезаписи адреса каталога страниц.6. The method according to claim 1, in which the execution of instructions of a memory area other than that of the execution of instructions in which a notification is transmitted is transmitted by overwriting the address of the page directory. 7. Способ по п. 1, в котором интересующий участок равен, по меньшей мере, одной странице.7. The method according to p. 1, in which the area of interest is equal to at least one page. 8. Способ по п. 1, в котором участки памяти в области памяти помечают путем установки атрибутов в таблице страниц для страниц, на которых отображен участок.8. The method according to claim 1, in which the memory areas in the memory area are marked by setting the attributes in the page table for the pages on which the area is displayed. 9. Способ по п. 8, в котором страницы интересующего участка имеют атрибут «неисполняемые».9. The method according to claim 8, in which the pages of the site of interest have the attribute "non-executable". 10. Способ по п. 9, в котором дубликаты страниц интересующего участка имеют атрибут «исполняемые».10. The method according to claim 9, in which duplicate pages of the site of interest have the attribute "executable". 11. Способ по п. 10, где исключение создается процессором.11. The method of claim 10, wherein the exception is thrown by the processor.
RU2016105564A 2016-02-18 2016-02-18 Method of implementating instructions in systemic memory RU2623883C1 (en)

Priority Applications (1)

Application Number Priority Date Filing Date Title
RU2016105564A RU2623883C1 (en) 2016-02-18 2016-02-18 Method of implementating instructions in systemic memory

Applications Claiming Priority (1)

Application Number Priority Date Filing Date Title
RU2016105564A RU2623883C1 (en) 2016-02-18 2016-02-18 Method of implementating instructions in systemic memory

Related Parent Applications (1)

Application Number Title Priority Date Filing Date
RU2014141808/08A Division RU2580016C1 (en) 2014-10-17 2014-10-17 Method for transfer of control between memory areas

Publications (1)

Publication Number Publication Date
RU2623883C1 true RU2623883C1 (en) 2017-06-29

Family

ID=59312659

Family Applications (1)

Application Number Title Priority Date Filing Date
RU2016105564A RU2623883C1 (en) 2016-02-18 2016-02-18 Method of implementating instructions in systemic memory

Country Status (1)

Country Link
RU (1) RU2623883C1 (en)

Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
RU2239228C2 (en) * 2001-07-05 2004-10-27 Всероссийский научно-исследовательский институт автоматики Method for distributing time of central processor between tasks in automatized system for controlling technological processes
US20070277023A1 (en) * 2003-06-24 2007-11-29 Reinhard Weiberle Method For Switching Over Between At Least Two Operating Modes Of A Processor Unit, As Well Corresponding Processor Unit
EP2320318A1 (en) * 1999-01-28 2011-05-11 ATI Technologies ULC Executing programs for a first computer architecture on a computer of a second architecture
WO2011076120A1 (en) * 2009-12-25 2011-06-30 Shanghai Xin Hao Micro Electronics Co. Ltd. High-performance cache system and method
US20140068612A1 (en) * 2012-09-06 2014-03-06 Assured Information Security, Inc. Facilitating execution of a self-modifying executable

Patent Citations (5)

* Cited by examiner, † Cited by third party
Publication number Priority date Publication date Assignee Title
EP2320318A1 (en) * 1999-01-28 2011-05-11 ATI Technologies ULC Executing programs for a first computer architecture on a computer of a second architecture
RU2239228C2 (en) * 2001-07-05 2004-10-27 Всероссийский научно-исследовательский институт автоматики Method for distributing time of central processor between tasks in automatized system for controlling technological processes
US20070277023A1 (en) * 2003-06-24 2007-11-29 Reinhard Weiberle Method For Switching Over Between At Least Two Operating Modes Of A Processor Unit, As Well Corresponding Processor Unit
WO2011076120A1 (en) * 2009-12-25 2011-06-30 Shanghai Xin Hao Micro Electronics Co. Ltd. High-performance cache system and method
US20140068612A1 (en) * 2012-09-06 2014-03-06 Assured Information Security, Inc. Facilitating execution of a self-modifying executable

Similar Documents

Publication Publication Date Title
RU2580016C1 (en) Method for transfer of control between memory areas
US10157268B2 (en) Return flow guard using control stack identified by processor register
Ligh et al. The art of memory forensics: detecting malware and threats in windows, linux, and Mac memory
KR102255767B1 (en) Systems and methods for virtual machine auditing
KR102047558B1 (en) Virtual disk storage techniques
US10846145B2 (en) Enabling live migration of virtual machines with passthrough PCI devices
US5303378A (en) Reentrant protected mode kernel using virtual 8086 mode interrupt service routines
US7213247B1 (en) Protection domains for a computer operating system
Tang et al. Exploring control flow guard in windows 10
US10261895B2 (en) System and method for transferring execution of a computer program
US20120216007A1 (en) Page protection ordering for lockless write tracking
US10489185B2 (en) Hypervisor-assisted approach for locating operating system data structures based on attribute matching
US11693722B2 (en) Fast memory mapped IO support by register switch
CN114327777B (en) Method and device for determining global page directory, electronic equipment and storage medium
US20180267818A1 (en) Hypervisor-assisted approach for locating operating system data structures based on notification data
JP2006294028A (en) System for providing direct execution function, computer system, method and program
US10592267B2 (en) Tree structure for storing monitored memory page data
RU2623883C1 (en) Method of implementating instructions in systemic memory
US11200175B2 (en) Memory accessor invailidation
US11726922B2 (en) Memory protection in hypervisor environments
EP3252610B1 (en) System and method of transfer of control between memory locations
US20230350710A1 (en) Fast memory mapped io support by register switch
US20240095363A1 (en) Method, device, and electronic apparatus for securely passing data
Hardware et al. CO620 Research Project

Legal Events

Date Code Title Description
MM4A The patent is invalid due to non-payment of fees

Effective date: 20191018

NF4A Reinstatement of patent

Effective date: 20201013