Registry Functions
The following are the registry functions.
Function | Description |
---|---|
GetSystemRegistryQuota | Retrieves the current size of the registry and the maximum size that the registry is allowed to attain on the system. |
RegCloseKey | Closes a handle to the specified registry key. |
RegConnectRegistry | Establishes a connection to a predefined registry handle on another computer. |
RegCopyTree | Copies the specified registry key, along with its values and subkeys, to the specified destination key. |
RegCreateKeyEx | Creates the specified registry key. |
RegCreateKeyTransacted | Creates the specified registry key and associates it with a transaction. |
RegDeleteKey | Deletes a subkey and its values. |
RegDeleteKeyEx | Deletes a subkey and its values from the specified platform-specific view of the registry. |
RegDeleteKeyTransacted | Deletes a subkey and its values from the specified platform-specific view of the registry as a transacted operation. |
RegDeleteKeyValue | Removes the specified value from the specified registry key and subkey. |
RegDeleteTree | Deletes the subkeys and values of the specified key recursively. |
RegDeleteValue | Removes a named value from the specified registry key. |
RegDisablePredefinedCache | Disables handle caching for the predefined registry handle for HKEY_CURRENT_USER for the current process. |
RegDisablePredefinedCacheEx | Disables handle caching for all predefined registry handles for the current process. |
RegDisableReflectionKey | Disables registry reflection for the specified key. |
RegEnableReflectionKey | Enables registry reflection for the specified disabled key. |
RegEnumKeyEx | Enumerates the subkeys of the specified open registry key. |
RegEnumValue | Enumerates the values for the specified open registry key. |
RegFlushKey | Writes all attributes of the specified open registry key into the registry. |
RegGetKeySecurity | Retrieves a copy of the security descriptor protecting the specified open registry key. |
RegGetValue | Retrieves the type and data for the specified registry value. |
RegLoadKey | Creates a subkey under HKEY_USERS or HKEY_LOCAL_MACHINE and stores registration information from a specified file into that subkey. |
RegLoadMUIString | Loads the specified string from the specified key and subkey. |
RegNotifyChangeKeyValue | Notifies the caller about changes to the attributes or contents of a specified registry key. |
RegOpenCurrentUser | Retrieves a handle to the HKEY_CURRENT_USER key for the user the current thread is impersonating. |
RegOpenKeyEx | Opens the specified registry key. |
RegOpenKeyTransacted | Opens the specified registry key and associates it with a transaction. |
RegOpenUserClassesRoot | Retrieves a handle to the HKEY_CLASSES_ROOT key for the specified user. |
RegOverridePredefKey | Maps a predefined registry key to a specified registry key. |
RegQueryInfoKey | Retrieves information about the specified registry key. |
RegQueryMultipleValues | Retrieves the type and data for a list of value names associated with an open registry key. |
RegQueryReflectionKey | Determines whether reflection has been disabled or enabled for the specified key. |
RegQueryValueEx | Retrieves the type and data for a specified value name associated with an open registry key. |
RegReplaceKey | Replaces the file backing a registry key and all its subkeys with another file. |
RegRestoreKey | Reads the registry information in a specified file and copies it over the specified key. |
RegSaveKey | Saves the specified key and all of its subkeys and values to a new file. |
RegSaveKeyEx | Saves the specified key and all of its subkeys and values to a new file. You can specify the format for the saved key or hive. |
RegSetKeyValue | Sets the data for the specified value in the specified registry key and subkey. |
RegSetKeySecurity | Sets the security of an open registry key. |
RegSetValueEx | Sets the data and type of a specified value under a registry key. |
RegUnLoadKey | Unloads the specified registry key and its subkeys from the registry. |
The following shell functions can be used with the registry:
The following are the initialization-file functions. They retrieve information from and copy information to a system- or application-defined initialization file. These functions are provided only for compatibility with 16-bit versions of Windows. New applications should use the registry.
Function | Description |
---|---|
GetPrivateProfileInt | Retrieves an integer associated with a key in the specified section of an initialization file. |
GetPrivateProfileSection | Retrieves all the keys and values for the specified section of an initialization file. |
GetPrivateProfileSectionNames | Retrieves the names of all sections in an initialization file. |
GetPrivateProfileString | Retrieves a string from the specified section in an initialization file. |
GetPrivateProfileStruct | Retrieves the data associated with a key in the specified section of an initialization file. |
GetProfileInt | Retrieves an integer from a key in the specified section of the Win.ini file. |
GetProfileSection | Retrieves all the keys and values for the specified section of the Win.ini file. |
GetProfileString | Retrieves the string associated with a key in the specified section of the Win.ini file. |
WritePrivateProfileSection | Replaces the keys and values for the specified section in an initialization file. |
WritePrivateProfileString | Copies a string into the specified section of an initialization file. |
WritePrivateProfileStruct | Copies data into a key in the specified section of an initialization file. |
WriteProfileSection | Replaces the contents of the specified section in the Win.ini file with specified keys and values. |
WriteProfileString | Copies a string into the specified section of the Win.ini file. |
Obsolete Functions
These functions are provided only for compatibility with 16-bit versions of Windows:
Run and RunOnce Registry Keys
Run and RunOnce registry keys cause programs to run each time that a user logs on. The data value for a key is a command line no longer than 260 characters. Register programs to run by adding entries of the form description—string=commandline. You can write multiple entries under a key. If more than one program is registered under any particular key, the order in which those programs run is indeterminate.
The Windows registry includes the following four Run and RunOnce keys:
- HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
- HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
- HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
- HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
By default, the value of a RunOnce key is deleted before the command line is run. You can prefix a RunOnce value name with an exclamation point (!) to defer deletion of the value until after the command runs. Without the exclamation point prefix, if the RunOnce operation fails the associated program will not be asked to run the next time you start the computer.
By default, these keys are ignored when the computer is started in Safe Mode. The value name of RunOnce keys can be prefixed with an asterisk (*) to force the program to run even in Safe mode.
A program run from any of these keys should not write to the key during its execution because this will interfere with the execution of other programs registered under the key. Applications should use the RunOnce key only for transient conditions, such as to complete application setup. An application must not continually recreate entries under RunOnce because this will interfere with Windows Setup.
История запуска программ и процессов в реестре Windows
Во время проведения компьютерно-криминалистической экспертизы операционной системы Windows важно понять, когда и каким образом был запущен определенный процесс. Чтобы идентифицировать эту деятельность, мы можем извлечь из целевой системы набор артефактов, полезных для сбора доказательств выполнения определенной программы.
Мы уже рассказывали как узнать какие программы запускались на компьютере. В той статье мы касались истории запуска программ в реестре Windows, но акцент больше ставили на программах. В сегодняшней статье я расскажу про ветки и ключи реестра в которых сохраняется история запуска программ и процессов Windows.
UserAssist
Каждая запущенная GUI-программа Windows оставляет историю в ключе реестра:
Этот ключ содержит два подраздела GUID (запуск исполняемого файла CEBFF5CD, запуск файла ярлыков F4E57C4B): каждый подраздел поддерживает список системных объектов, таких как программы, ярлыки и апплеты панели управления, к которым пользователь обратился.
Значения реестра в этих подразделах зашифрованы не лучшим образом. Используется шифрование ROT-13, которое заменяет один символ другим, расположенным в 13 позиции от него в таблице ASCII.
Все значения кодируются ROT-13:
BAM — это служба Windows, которая контролирует активность фоновых приложений. Эта служба существует только в новых версиях в Windows 10 начиная с обновления Fall Creators 1709.
Служба сохраняет историю запуска исполняемых файлов. Среди которой: полный путь к исполняемому файлу, который был запущен в системе, дату (время последнего исполнения), и его расположение. История запуска исполняемых файлов находится здесь:
RecentApps
Запуск последних программ отслеживается и сохраняется в ключе RecentApps:
Каждый ключ GUID — это запущенное ранее приложение.
- AppID — название запущенного приложения.
- LastAccessTime — время запуска в UTC.
- LaunchCount — количество запуска программы.
ShimCache
База данных совместимости приложений Windows используется операционной системой для определения возможных проблем совместимости приложений с исполняемыми файлами и отслеживает имя файла исполняемого файла, размер файла, время последнего изменения.
Последние 1024 программы, выполненные в операционной системе Windows, можно найти в этом ключе:
Для более подробного анализа ShimCache вы можете использовать инструмент ShimCacheParser.py.
- В Windows 7/8/10 содержится не более 1024 записей
- LastUpdateTime не существует в системах Win7/8/10
Списки переходов
Панель задач Windows 7-10 (список переходов) спроектирована таким образом, чтобы пользователи могли быстро получить доступ к элементам, которые они часто или недавно использовали.
Данные, хранящиеся в папке:
где каждый будет иметь уникальный файл, добавленный с AppID связанного приложения.
Файлы списков переходов AutomaticDestinations представляют собой OLE Compound Files, содержащие несколько потоков, из которых:
- Шестнадцатеричное число, например. «1a»
- DestList
Каждый из шестнадцатеричных нумерованных потоков содержит данные, аналогичные данным Windows Shortcut: данные могут быть извлечены и проанализированы с помощью анализатора LNK, например lnk-parse.
Prefetch
Файлы предварительной выборки Windows предназначены для ускорения процесса запуска приложения. Файлы Prefetch хранятся здесь»
и содержит имя исполняемого файла, список DLL Unicode, используемый этим исполняемым файлом, количество попыток выполнения исполняемого файла и временную метку, указывающую на последний запуск программы.
В этой папке хранится информация для последних 128 исполняемых файлов на Win7 и 1024 на Windows8 и Windows 10.
Файл предварительной выборки может анализироваться и анализироваться с использованием таких инструментов, как PeCMD
Процесс Registry
В апреле 2018 года Microsoft начала рассылать обновление Windows 10 1803. Этот апдейт добавил в систему много новых заметных обычному глазу пользователя функций (временная шкала, к примеру). Но еще больше изменений претерпела система внутри и на первый взгляд заметить все эти изменения не так уж и просто. Большое их количество вы не заметите вообще, если не являетесь разработчиком приложений или драйверов, к примеру. Внимательный пользователь, который следит за тем, какие процессы работают в его компьютере, наверняка заметил новый загадочный процесс Registry. Он появился в Диспетчере задач именно после прихода обновления Windows 10 April 2018 Update. Неизвестные и подозрительные процессы в Диспетчере задач часто являются признаком заражения компьютера вирусами, поэтому не удивительно, что у многих пользователей возникает резонный вопрос: что за процесс Registry в Диспетчере задач? На этот вопрос есть весьма простой ответ.
Для чего нужен процесс Registry
Сразу же стоит развеять сомнения и отметить, что процесс Registry не является вирусом. Он появился в вашей операционной системе из-за архитектурных изменений Window 10 1803. Microsoft постоянно пытается оптимизировать работу своего творения, улучшить его взаимодействие с железом компьютера и снизить потребление ресурсов. Появление процесса Registry обусловлено желанием компании оптимизировать использование памяти вашего ПК.
Обнаружить процесс Registry можно в двух местах. Для начала вам надо открыть Диспетчер задач и перейти на вкладку Процессы. Опуститесь немного ниже и в разделе Процессы Windows. Вы найдете тот самый процесс Registry. Объем занятой памяти не должен превышать несколько мегабайт, а нагрузка на процессор должна быть и вовсе нулевой.
Процесс Registry также можно найти на вкладке Подробности того же Диспетчера зада. Он подписан точно так же – Registry, принадлежит пользователю SYSTEM и описывается как NT Kernel & System (ядро NT и система).
Хотя Диспетчер задач не предоставляет никакой информации об этом процессе (попытка открыть расположение файла наведет вас на файл ядра ntroskrnl.exe в системной папке System32), из самого названия частично можно догадаться о предназначении процесса Registry. Registry – системный реестр Windows. Что такое системный реестр Windows? Это большие джунгли файлов, оформлены в иерархическую структуру. Эти файлы определяют работу системы и вашего программного обеспечения.
Процесс Registry является архитектурным изменением в Windows 10, созданным для хранения части информации реестра в оперативной памяти для более быстрого доступа и эффективного управления памятью. Microsoft описала этот процесс в заметках к обновлению одной из инсайдерских сборок Windows 10 во времена, когда 1803 еще находилась в разработке. Принцип его работы похож на принцип работы компрессии данных памяти. Но в этом небольшом процессе хранится не сжатые страницы, а основные ветки дерева реестра. К примеру, HKEY_LOCAL_MACHINE\SOFTWARE, HKEY_CURRENT_USER и так далее. Microsoft заявляет, что вывод сжатых данных реестра в выделенный процесс поможет уменьшить потребление оперативной памяти системным реестром Windows, что в свою очередь приведет к увеличению свободной RAM, нужной для ваших приложений, игр и других задач.
Практика показывает, что этот процесс ведет себя весьма адекватно и не вызывает нареканий со стороны пользователей. Он потребляет очень мало ресурсов (занятая доля фактически никак не влияет на производительность компьютера) и не привлекает ненужного внимания. Вам не стоит волноваться за этот процесс и уж тем более не стоит удалять его или отключать. Процесс Registry обеспечивает вам более быструю работу компьютера, поэтому дайте ему спокойно выполнять свою фоновую работу.
Пока что этот процесс новый для среды Windows и о нем нет много информации. На практике не было случаев, когда вирус маскировался под процесс Registry, но вы всегда можете проверить подлинность процесса простым нажатием правой кнопки по процессу и выбором опции Открыть расположение файла. Система должна открыть Проводник по адресу C:\Windows\System32 и выделить файл ntoskrnl.exe.
Щелкните правой кнопкой мыши по файлу и выберите Свойства. Перейдите на вкладку Подробно и проверьте подписи описания файла. Если Windows открыла не системную папку, а какое-то другое расположение, после чего выделила какой-то непонятный файл, есть вероятность, что ваш ПК заражен вредоносным ПО. В таком случае вам надо проверить компьютер на вирусы.