Продолжаем цикл статей о противодействии классу вирусов-шифровальщиков в корпоративной среде. В предыдущих частях мы рассмотрели настройку защиты на файловых серверах с помощью FSRM и использования теневых снимков дисков для быстрого восстановления данных после атаки. Сегодня речь пойдет о способе предотвращения запуска исполняемых файлов вирусов-шифровальщиков (в том числе обычных вирусов и троянов) на ПК пользователей.
Помимо антивируса, еще одним барьером для предотвращения запуска вредоносного ПО на компьютерах пользователей могут быть политики ограниченного использования программ. В среде Windows это могут быть технология Software Restriction Policies или AppLocker. Мы рассмотрим пример использования Software Restriction Policies для защиты от вирусов.
Software Restriction Policies (SRP) предоставляют возможность разрешать или запрещать запуск исполняемых файлов с помощью локальной или доменной групповой политики. Метод защиты от вирусов и шифровальщиков с помощью SRP предполагает запрет запуска файлов из определенных каталогов в пользовательском окружении, в которые, как правило, попадают файлы или архивы с вирусом. В подавляющем большинстве случаев файлы с вирусом, полученные из интернета или из электронный почты оказываются внутри каталога %APPDATA% профиля пользователя (в нем же находится папки %Temp% и Temporary Internet Files). В этом же каталоге хранятся распакованные временные копии архивов, когда пользователь не глядя открывает архив полученный по почте или скачанный с интернета.
При настройке SRP могут быть использованы две стратегии:
- Разрешить запуск исполняемых файлов на компьютере только из определенных папок (как правило, это каталоги %Windir% и Program Files / Program Files x86) – это самый надежный метод, но требует длительного периода отладки и выявления нужного ПО, которое не работает в такой конфигурации
- Запрет запуска исполняемых файлов из пользовательских каталогов, в которых в принципе не должно быть исполняемых файлов. Именно в этих каталогах в большинстве случаев оказываются файлы вируса при появлении на компьютере. Кроме того, у пользователя, не обладающего правами администратора, просто отсутствуют права на запись в каталоги системы кроме своих собственных. Поэтому вирус просто не сможет поместить свое тело куда-либо кроме директорий в профиле пользователя.
Мы рассмотрим создание SRP по второму варианту, как достаточно надежному и менее трудоемкому во внедрении. Итак, создадим политику, блокирующую запуск файлов по определенным путям. На локальном компьютере это можно сделать с помощью консоли gpedit.msc, если политика должна использоваться в домене, нужно в консоли Group Policy Management (gpmc.msc) создать новую политику и назначить ее на OU с компьютерами пользователей.
Примечание. Настоятельно рекомендуем перед внедрением SRP политик, протестировать их работу на группе тестовых компьютерах. В случае обнаружения легитимных программ, которые не запускаются из-за SRP, нужно добавить отдельные разрешительные правила.
В консоли редактора GPO перейдите в раздел Computer Configuration -> Windows Settings -> Security Settings . Щелкните ПКМ по Software Restriction Policies и выберите New Software Restriction Policies.
Выберите раздел Additional Rules, и создайте новое правило New Path Rule.
Создадим правило, запрещающее запуск исполняемых файлов с расширением *.exe из каталога %AppData%. Укажите следующие параметры правила:
- Path: %AppData%\*.exe
- Security Level: Disallowed
- Description: Блокировка запуска exe файлов из папки %AppData%
Аналогичным образом нужно создать запрещающие правила для путей, перечисленных в таблице. Т.к. переменные окружения и пути в Windows 2003/XP и Windows Vista/выше отличаются, в таблице указаны значения для соответствующих версий ОС. Если у вас в домене еще остались Windows 2003/XP, для них лучше создать отдельную политики и назначить ее на OU с компьютерами с использованием WMI фильтра GPO по типу ОС.
| Описание | Windows XP и 2003 | Windows Vista/7/8/10, Windows Server 2008/2012 |
| Запрет запуска файлов из %LocalAppData% | %UserProfile%Local Settings*.exe | %LocalAppData%\*.exe |
| Запрет запуска файлов из вложенных каталогов %AppData%: | %AppData%\*\*.exe | %AppData%\*\*.exe |
| Запрет запуска файлов из вложенных каталогов %LocalAppData% | %UserProfile%\Local Settings\*\*.exe | %LocalAppData%\*\*.exe |
| Запрет запуска exe файлов из архивов, открытых с помощью WinRAR | %UserProfile%\Local Settings\Temp\Rar*\*.exe | %LocalAppData%\Temp\Rar*\*.exe |
| Запрет запуска exe файлов из архивов, открытых с помощью 7zip | %UserProfile%\Local Settings\Temp\7z*\*.exe | %LocalAppData%\Temp\7z*\*.exe |
| Запрет запуска exe файлов из архивов, открытых с помощью WinZip | %UserProfile%\Local Settings\Temp\wz*\*.exe | %LocalAppData%\Temp\wz*\*.exe |
| Запрет запуска exe файлов из архивов, открытых с помощью встроенного архиватора Windows | %UserProfile%\Local Settings\Temp\*.zip\*.exe | %LocalAppData%\Temp\*.zip\*.exe |
| Запрет запуска exe файлов из каталога %temp% | %Temp%\*.exe | %Temp%\*.exe |
| Запрет запуска exe файлов из вложенных каталогов %temp% | %Temp%\*\*.exe | %Temp%\*\*.exe |
| Опционально. Запрет запуска exe фалов из любых каталогов в профиле пользователя .
Важно. с эти правилом нужно быть внимательным, т.к. некоторое ПО, например плагины браузеров, установщики – хранят свои исполняемые файлы в профиле. Для таких программ нужно будет сделать правило исключения SRP |
%UserProfile%\*\*.exe | UserProfile%\*\*.exe |
Вы можете добавить собственные каталоги. В нашем примере получился примерно такой список запрещающих правил SRP.
Как правило, также следует запретить запуск других расширений потенциально опасных файлов (*.bat,*.vbs, *.js, *.wsh и т.п.), ведь вредоносный код может находиться не только в *.exe файлах. Для этого нужно изменить пути в правилах SPR , удалив вхождения *.exe. Таким образом, будет запрещен запуск всех исполняемых файлов и файлов сценариев в указанных каталогах. Список «опасных» расширений файлов задается в параметрах политики SRP в разделе Designated File Types. Как вы видите, в нем уже есть предустановленный список расширений исполняемых файлов и скриптов. Можете добавить или удалить определенные расширения.
Осталось проверить действие политики Software Restriction Policies на клиентском компьютере. Для этого обновите политики командой gpupdate /force и попробуйте запустить исполняемый *.exe файл из любого из указанных каталогов. Должно появиться сообщение об ошибке:
Your system administrator has blocked this program. For more info, contact your system administrator.
Попытки запуска исполняемых файлов из защищенных каталогов, которые были блокированы политиками SRP можно отслеживать с помощью журнала событий Windows. Интересующие нас события находятся в разделе Application, и имеют Event ID 866, с источником SoftwareRestrictionPolicies и примерно таким текстом:
Access to C:\Users\root\AppData\Local\Temp\71E88B1F-3073-436E-A3D8-D577E72DA049\dismhost.exe has been restricted by your Administrator by location with policy rule {31f4dcb9-d39b-4df3-b682-1b83892c6db4} placed on path C:\Users\root\AppData\Local\Temp\*\*.exe.
Совет. В том случае, если политика мешает запуску нужного доверенного приложения, можно добавить это файл в исключения политики (создав новое правило, указывающее на этот *.exe файл со значением Unrestricted).
Итак, мы показали общий пример техники использования политики ограниченного использования программ (SRP или Applocker) для блокировки вирусов, шифровальщиков и троянов на компьютерах пользователей. Рассматриваемая методик позволяет существенно усилить степень защиты систем от запуска вредоносного кода пользователями.
This article is aims to be a comprehensive guide to creating a secure Software Restriction Policy and is quite a long read – we recommend you bookmark it now so you have it to hand when you need it.
Securing your environment is a huge deal these days. Whereas we have all for a very long time concentrated on maximizing performance – looking at how we create the best possible “user experience” – security is another big concern for consultants, architects and administrators. Ensuring that an attacker cannot move laterally through a compromised network is crucial – if penetration occurs, we need to make sure that it is as difficult as possible for the attacker to broaden the scope of their attack and gain a deeper foothold into your environment. All breaches involve some form of pivoting which generally involves running utilities which shouldn’t be allowed to run in hardened environments.
Controlling what a user can execute is a pivotal part of this approach. In an “open” environment, an attacker within your network can introduce their own executables and scripts, opening up possibilities for further compromise and move closer towards the Holy Grail of accessing all of your data and infrastructure. But if you are strictly controlling what users can execute, not only do you block the attacker from escalation, but you can also identify possible indicators of compromise simply by the very action of attempting to run these items. So not only does effective application control protect you, it adds a further layer of alerting that can spot an attack in its early stages.
- Before We Begin
- Whitelisting and blacklisting
- Tools for application whitelisting
- Understanding the user environment
- Differences between SRP and AppLocker and MDAC
- Software Restriction Policies
- Global options
- Security levels
- Additional Rules
- Path Rules versus Certificate versus Network Zone versus Hash
- Loopholes in system folders
- SRP discovery mode
- Software Restriction Policies in action
- AppLocker
- AppLocker setup
- AppLocker in Action
- Extending AppLocker functionality with third-party products
- Microsoft Defender Application Control
- Summary
Before We Begin
If you find this post useful you’re going to love our weekly newsletter. Every monday we send the best 5 Active Directory security links we’ve read each week. Stuck on something? Just search your inbox for our newsletter plus your term and you’ll usually find an answer.
Get the best Active Directory security news, tips and tweaks every Monday.
Whitelisting and blacklisting
Simply put, blacklisting is where you stop users running “known bad” applications. For instance, you could blacklist executables such as PowerShell, the Registry Editor, known exploit tools like Metasploit or utilities that hackers might leverage such as the PSTools suite. But the problem with blacklisting is pretty obvious – you are reliant on knowledge of every possible executable that a hacker might use, and need to then add it to your blacklist. You become tied into a game of whack-a-mole, an arms race of constantly updating the list of threats to be kept at bay.
Whitelisting, on the other hand, removes a lot of the overhead from this by using the opposite approach. Instead of listing out the “known bad” executables, whitelisting operates by blocking *everything* except applications you specifically know that users need to execute in their day-to-day jobs – a “known good” list instead. If a new tool is identified that you want to prevent users from running, there is no update required – a whitelist blocks unknown executables by default.
There are nuances within the whitelisting approach that we will discuss. You can block by path, by certificate/publisher, by network zone, or even by file hash. Each one of these options has pros and cons attached to them. There are also differences in deployment and management that you will want to consider.
Tools for application whitelisting
There are many application whitelisting solutions out there available from third parties. However, if you are using an enterprise version of Windows and/or Active Directory, there are two options that will always be available to you at no extra cost. We will discuss later on about certain third-party tools that can extend the functionality of these core Microsoft offerings, but for now, we will concentrate specifically on these built-in tools. The older version (which shipped with Windows XP) is called Software Restriction Policies (SRPs), and its slightly newer, more updated cousin is called Application Control Policies (AppLocker). There is an even newer tool in the arsenal as well, called Microsoft Defender Application Control (MDAC).
There were two black- and whitelisting GPOs that predated SRPs, AppLocker and MDAC – Don’t run specified Windows applications and Run only specified Windows applications. Both of these sit in User Configuration | Policies | Administrative Templates | System and were the only options available for Windows 2000. However, they only apply to processes started from File Explorer directly – running programs from the command prompt, Task Manager, PowerShell or from any other already-running process allowed these GPOs to be bypassed, therefore, we will not discuss their usage here.
Note: We are using the term whitelisting and blacklisting in this post because it’s still the preferred terminology used by Microsoft. After this we will revert to using our preferred synonyms: block list and allow list.
Understanding the user environment
However, before you begin to formulate an application whitelisting policy, it is very important to understand precisely the sets of applications that your users need to use. Blocking without preparation can easily lead to chaos as line-of-business applications stop functioning, and this will have a terrible knock-on effect for your user experience. You should never implement application whitelisting without proper planning and testing!
Obviously, you need to have enterprise versions of the Windows OS on your clients and be running a version of Active Directory that supports either SRPs or AppLocker (if you are going to deploy centrally via GPOs). You can deploy SRPs and AppLocker policies without AD, but it would involve configuring local policies on each machine and therefore has a very big overhead. For the purposes of this article, we will assume that deployment is being done via AD (although the policy settings would be the same if done locally).
For the auditing aspect, you can either use the audit features provided by SRPs or AppLocker, or you can use a third-party monitoring tool. The audit features in SRPs are (practically) non-existent, but there is a proper Audit Mode in AppLocker. However, in an ideal world a central monitoring tool would be best, in order to give you full visibility of what is being run. If you are using a SIEM (Security Information Event Management) tool you can possibly parse the entries that AppLocker or SRPs produce without having to deploy a specific monitoring tool. It is up to you which approach you choose to build the initial list of “allowed” applications. For posterity, SRP produces log files, AppLocker produces event log entries, and a third-party monitoring tool should provide proper reports. If you were looking at third-party tools, then there are many out there – uberAgent, ControlUp, eG Innovations, Goliath Technologies, SCCM, Lakeside SysTrack, Nexthink are some of the ones I have worked with, but there are many, many more.
The techniques described here allow you to whitelist certain key system areas (like the Program Files folder) without needing to formulate an exhaustive list of executables that lie within them, so the process can be slightly less intimidating than it first may seem. However, it is vitally important that you capture all required executables, as some of them run from places you might not expect (such as Teams, Chrome, DropBox, Slack, etc.)
An example of a non-standard application launch being blocked
Differences between SRP and AppLocker and MDAC
MDAC is intended to eventually replace AppLocker and SRPs, but for now, it is undergoing development. For now, it is recommended to use WDAC alongside AppLocker or SRP until it develops to such a state as to fully replace them. The main drawback is that WDAC cannot currently apply policies for different users or groups on shared computers. As a best practice, you should enforce WDAC at the most restrictive level possible for your organization, and then you can use AppLocker or SRP to further fine-tune the restrictions.
MDAC shows some of its inadequacies in these situations: –
- Applying different policies for different users or groups
- Mixed Windows OS environments
- Avoiding the restriction of DLLs and drivers
However, longer-term MDAC will replace both AppLocker and SRPs. It already has some features that work above the capabilities of AppLocker and SRP, such as restricting kernel-mode drivers and preventing administrators from being able to turn off the protection.
When comparing AppLocker and SRP, they have a number of functional differences, as listed below:
| Application control function | SRP | AppLocker |
| Scope | SRP policies can be applied to all Windows operating systems beginning with Windows XP and Windows Server 2003. | AppLocker policies apply only to Windows Server 2008 R2, Windows Server 2012 , Windows 7, Windows 8, Windows 8.1, Windows 10, Server 2016 and Server 2019. |
| Policy creation | SRP policies are maintained through Group Policy and only the administrator of the GPO can update the SRP policy. The administrator on the local computer can modify the SRP policies defined in the local GPO. | AppLocker policies are maintained through Group Policy and only the administrator of the GPO can update the policy. The administrator on the local computer can modify the AppLocker policies defined in the local GPO.
AppLocker permits customization of error messages to direct users to a Web page for help. |
| Policy maintenance | SRP policies must be updated by using the Local Security Policy snap-in (if the policies are created locally) or the Group Policy Management Console (GPMC). | AppLocker policies can be updated by using the Local Security Policy snap-in (if the policies are created locally), or the GPMC, or the Windows PowerShell AppLocker cmdlets. |
| Policy application | SRP policies are distributed through Group Policy. | AppLocker policies are distributed through Group Policy. |
| Enforcement mode | SRP works in the “deny list mode” where administrators can create rules for files that they do not want to allow in this Enterprise whereas the rest of the file are allowed to run by default.
SRP can also be configured in the “allow list mode” such that the by default all files are blocked and administrators need to create allow rules for files that they want to allow. |
AppLocker by default works in the “allow list mode” where only those files are allowed to run for which there is a matching allow rule. |
| File types that can be controlled | SRP can control the following file types:
– Executables – Dlls – Scripts – Windows Installers SRP cannot control each file type separately. All SRP rules are in a single rule collection. |
AppLocker can control the following file types:
– Executables – Dlls – Scripts – Windows Installers – Packaged apps and installers AppLocker maintains a separate rule collection for each of the five file types. |
| Designated file types | SRP supports an extensible list of file types that are considered executable. Administrators can add extensions for files that should be considered executable. | AppLocker does not support this. AppLocker currently supports the following file extensions:
– Executables (.exe, .com) – Dlls (.ocx, .dll) – Scripts (.vbs, .js, .ps1, .cmd, .bat) – Windows Installers (.msi, .mst, .msp) – Packaged app installers (.appx) |
| Rule types | SRP supports four types of rules:
– Hash – Path – Signature – Internet zone |
AppLocker supports three types of rules:
– Hash – Path – Publisher |
| Editing the hash value | SRP allows administrators to provide custom hash values. | AppLocker computes the hash value itself. Internally it uses the SHA1 Authenticode hash for Portable Executables (Exe and Dll) and Windows Installers and a SHA1 flat file hash for the rest. |
| Manage Packaged apps and Packaged app installers | Unable | .appx is a valid file type which AppLocker can manage. |
| Targeting a rule to a user or a group of users | SRP rules apply to all users on a particular computer. | AppLocker rules can be targeted to a specific user or a group of users. |
| Support for rule exceptions | SRP does not support rule exceptions | AppLocker rules can have exceptions which allow administrators to create rules such as “Allow everything from Windows except for Regedit.exe”. |
| Support for audit mode | SRP does not support audit mode. A limited logging mode can be configured (see later) but it is somewhat unreliable. | AppLocker supports audit mode which allows administrators to test the effect of their policy in the real production environment without impacting the user experience. Once you are satisfied with the results, you can start enforcing the policy. |
| Support for exporting and importing policies | SRP does not support policy import/export. | AppLocker supports the importing and exporting of policies. This allows you to create AppLocker policy on a sample computer, test it out and then export that policy and import it back into the desired GPO. |
| Rule enforcement | Internally, SRP rules enforcement happens in the user-mode which is less secure. | Internally, AppLocker rules for Exes and DLL files are enforced in the kernel-mode which is more secure than enforcing them in the user-mode. |
Software Restriction Policies
Let’s start by looking at the old-timer, Software Restriction Policies. Software Restriction Policies are not as granular as AppLocker rules, in that they cannot be applied to specific groups of users (so, for instance, allowing UserA to run an application, whereas UserB cannot, is not possible with SRPs).
Software Restriction Policies can be run in either a blacklist or a whitelist configuration. It relies on a “Default” rule setting with “Additional rules” that then override the defaults. So, if you wanted a “blacklist” configuration, you would set the default to Unrestricted and configure Additional Rules for executables you wanted to block. For a “whitelist” configuration, you set the default to Disallowed and configure Additional Rules for executables you want to run.
Let’s have a look at how we would set up a simple Software Restriction Policy in a whitelist configuration.
Firstly, create a Group Policy Object and link it to the OU containing the computer objects that you wish to apply the SRP to.
Browse to Computer Configuration | Policies | Windows Settings | Security Settings | Software Restriction Policies. Right-click the node and choose New Software Restriction Policies
This will then create the rules for you underneath the main node.
Global options
In the right-hand pane, you will see a number of options you can configure at a global level
Security Levels and Additional Rules we know about and will come to in a moment. Firstly, though, right-click on Enforcement and choose Properties, and you will see this dialog
The first option should generally be set to “All software files except libraries”. If you start applying application controls to DLL files, you may find problems as you will need to list all libraries used by a program. Now if you have the “additional rules” correctly configured, then that doesn’t include DLL files from the Program Files or Windows\System* directories, but even so, it can be a lot of overhead and potentially problematic. I would only turn on DLL-level checking in high-security environments where you have total control over every file in use.
The second option, Apply to all users or all users except local administrators, is up to you to decide. If you are in an environment where administrators routinely log on to and perform troubleshooting on client devices, then make them exempt from the SRP rules. However, if you are in an environment where all troubleshooting is done remotely via a privileged-access station (which, ideally, it should be), then you can apply the restrictions to administrators as well. Alternatively, you can whitelist all of the administrator tools as well, but bear in mind that because SRPs are not flexible by user this will allow ordinary users to run these tools also. One thing to bear in mind here is that if you select “all users except local administrators” this means that installations, for instance, can be triggered by right-clicking and choosing Run As Administrator. Choose the option that makes the most sense for your environment.
The final option is whether to enforce certificate rules. If, in the Additional Rules section, you are using certificate-based checking, then you will need to enforce them here. The caveat about performance refers to the need to check a certificate revocation list (CRL) every time a program is run. It also means that the CRL (usually held online) needs to be accessible from the client, so environments with internet access blocked may struggle if this option is enforced. Choose the option that matches your requirements.
Next, right-click on Designated File Types and choose Properties.
This dialog shows you what file extensions are considered to be “executable code” by the SRP. Notice that .exe, .dll and .vbs are considered executable by default and cannot be removed. All of the others in the list can be removed, or added to.
There are a couple of notes worth calling out. Firstly, that .ps1 is not listed as an executable file, so you may want to add that (PowerShell script – for the record PS modules are not listed either). Also, .lnk is listed as an executable type, so even if you have an executable that is allowed, the actual shortcut (because that’s what .lnk files are, shortcuts) will not be allowed to run that points to the executable. I normally remove .lnk from the list and add other modern filetypes that I feel are necessary to manage.
The final option is for management of Trusted Publishers. This can allow or disallow whether users or administrators can manage adding trusted publishers (for instance, if they were to download an application from a publisher’s site). It also, optionally, allows you to enforce a CRL on the trusted certificates. Again, choose the options which are relevant to how you wish to manage the environment.
Security levels
Next, browse into the Security Levels folder and you will see three settings.
The default is set to Unrestricted, which is a “blacklist” model. Right-click on Disallowed and choose “Set as default”. You will get a warning – just click on Yes.
“Basic User” is a setting which does not work any more, so do not use it. In modern Windows environments “Basic User” simply functions the same as “Disallowed” does.
This now means that everything will be blocked, subject to a) the options configured under your global rules, and b) any Additional Rules configured with a security level of Unrestricted.
Additional Rules
In a whitelist situation, you configure Additional Rules with a Security Level of Unrestricted to allow executables to run.
When you create a new SRP, the following two paths are listed as Additional Rules:-
These odd-looking Registry/variable Path Rules are meant to allow any executables from the SYSTEMROOT or PROGRAMFILES variables. However, these paths predate the arrival of x64 computing and often will mean anything in the x86 Program Files folder will be blocked. I delete the default Path Rules and replace them with those shown below:-
This ensures that files in the system areas can execute without needing to provide an exhaustive list prior to deployment. Make sure that the “Security Level” is set to Unrestricted – this is how you configure a whitelist. Using “Disallowed” is for a blacklist approach and if you inadvertently combine this with a global “Disallowed” policy you will break the devices it applies to!
Population of the Additional Rules section is where your understanding of execution areas will become paramount. For instance, in our image we use App-V applications. These applications do not execute from Program Files or the SystemRoot areas – they have their own cached location. If we try to launch one, we see the standard SRP block screen (below)
If you then check in the Event Viewer under Application log and look for an event ID 865, it will tell you the path of the executable which was prevented from running
We can see here that all of our App-V apps run from C:\ProgramData\Microsoft\AppV\Client. So we need to add a new Additional Rule that allows this path. Notice we have substituted the environment variable ALLUSERSPROFILE for the c:\ProgramData path
Once this is saved into the GPO SRP and a group policy refresh takes place, we should find we can now execute the App-V apps. One thing worth noting with SRPs, though, is that often the user has to log out and back in before the updated policy will take effect.
So now only executables residing in our specified paths can be run. For instance, I can run regedit.exe without issue, because it is in the %SYSTEMROOT% folder…
…but if I then copy regedit.exe to the %USERPROFILE% path and try to run it, it now fails
Path Rules versus Certificate versus Network Zone versus Hash
Simply allowing Paths is the most basic way to allow executables to run. However, this can potentially be subverted by an attacker creating files within the allowed Paths, even with the same name as expected executables, if you have restricted by exact name.
You can further tighten the security by restricting by other methods. Certificate rules allowing you to allow executables to run only if they are signed with an allowed publisher’s certificate.
Network Zone rules allow you to specify particular internet or intranet locations that MSI files can be executed from. This rule is quite niche and I would not generally recommend its usage.
The most useful from a security perspective is the Hash rule. This actually takes a hash generated from a specific executable and ensures that this hash is matched before an executable is allowed to run. This is very useful in high-security environments where you may be interested in also stopping compromised administrator accounts from executing untrusted code. However, there are caveats. The list of hashes must be updated every time an application is patched – so, if you allow Teams.exe to run via a Hash rule, and then a new version of Teams is downloaded, the hash value will need to be updated before it can run.
I generally use SRPs with a combination of Path and Hash/Certificate rules. Path rules are allowed for the installation and system directories, as the only people who can modify files in these locations belong to the Administrators group. If you have executables that need to run from outside these locations (maybe a piece of software that executes from the USERPROFILE location, as far too many do these days), then use a Hash rule to allow it (or use a Certificate rule if the executable is regularly changed, or downloaded afresh at each launch). Don’t forget, if SRP rules conflict, Hash rules take priority over all others.
However, if you are in a high-security environment where Administrators also need to be subject to the rules, then creating Hash rules for every executable would be the way to proceed. This is a high-maintenance approach but it ensures that a compromised admin account cannot circumvent the rules – only the users who can add new Hash rules into Active Directory would be able to achieve this.
Loopholes in system folders
Sometimes Windows allows users Write access to system folders. This means that potentially, a user could drop out an executable into one of these folders and execute it, bypassing the rules because of the default allow configured for the system folders. There are multiple layers of defence that may protect you from this – antivirus, Windows file blocking, SmartScreen, etc. – but given that our job is to anticipate attacks that sometimes bypass these layers, it is an avenue worth testing.
Examples of these folders (on Windows 10) include
- C:\Windows\tracing
- C:\Windows\Registration\CRMLog
- C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
- C:\Windows\System32\spool\drivers\color
- C:\Windows\SysWOW64\Microsoft\Crypto\RSA\MachineKeys
- C:\Program Files (x86)\Google\Chrome\Application\SetupMetrics
- C:\Windows\Tasks
- C:\Windows\System32\Tasks
You can use the SysInternals tool accesschk to identify folders that users have write access into.
If it is found that users can move executables to these folders and run them, then you would need to create new Path rules with “Disallowed” set as the security level to override the Unrestricted rules. An example is shown below
This will then enforce the blocking of any executable content from the folders that users can place files within.
SRP discovery mode
As mentioned before, SRPs really don’t have a “discovery” or “audit” mode that can help with the initial view of what executables your users access. What you can do is turn on a Registry key that performs SRP logging. Create a GPO Preferences Registry Item that adds the following value:-
- Action – Replace
- Hive – HKLM
- Key Path – SOFTWARE\Policies\Microsoft\Windows\Safer\CodeIdentifiers
- Value Name – LogFileName
- Value Type – REG_SZ
- Value data – path to the log file (local to the machine, preferably)
Then, switch the Security Level back to Unrestricted and delete all of the Additional Rules. Be very careful here – if you delete the Additional Rules and leave the Security Level as Disallowed, you will effectively have broken your machine. You will be unable to even run a gpupdate to reverse the settings, so make sure you have a backup or snapshot before doing this!
This will then log out to the specified file as rules are allowed to run but be warned – this process seems a little hit and miss.
Software Restriction Policies in action
For an example of the SRP in action, we will get a user to try to execute MimiKatz (a well-known Windows exploit tool).
We can see the user trying to run the executable from the network, from a local location, and then show the event logs that indicate the executable was blocked by SRP
There is also the capability for a savvy attacker to try and load the mimikatz library from an allowed executable, such as regedit.exe. If the attacker could copy the dll into the system, and then add it to the Security Support Provider list by editing the Registry (which would require admin privileges), it would be possible to leverage the functionality of tools like mimikatz in a way that would bypass the “standard” SRP. Below, we can see the loaded library compromising a Windows domain admin password after being loaded.
If this attack vector is feasible, then the “block libraries” function from the global options would be the way to protect against it.
Once we have applied the “block libraries” option at the global level, the mimikatz dll can no longer be loaded and therefore passwords are not intercepted.
We know this is effective because the kiwissp.log file which holds the output from the dll is no longer present on the system. However, an annoying feature of SRPs is that when a library is blocked, no data is written to the event logs. You may get application errors within the user interface as below, but no logging is maintained as to what has been blocked from loading.
AppLocker
AppLocker is, as already stated, a slightly more granular approach to application whitelisting. AppLocker is configured in the same way, by using Group Policy Objects.
AppLocker setup
As a pre-requisite for any AppLocker deployment, the Application Identity service must be started on the target devices. This can be done within the image or alternatively via GPO.
The actual GPOs themselves to initiate AppLocker are located in Computer Configuration | Policies | Windows Settings | Security Settings | Application Control Policies | AppLocker
Similar to SRPs, you begin by configuring the level of “rule enforcement”. You can “enforce” for standard executables, Windows Installer files, Scripts, or “Packaged Apps” (which refers to Universal Windows Platform apps). The main difference from SRPs is that you have the option to configure “Audit only” rather than the blanket “Enforce rules” option. It is recommended to always run in “Audit only” mode for a period of time so that you can identify what is being run, what needs to be blocked and what may need to be allowed.
Like SRPs, the base rules also have a “DLL rules” option similar to SRPs. This allows you to control libraries as well as standard executable content.
Beneath the base AppLocker node where you configure the enforcement level, you have separate nodes for Executable, Windows Installer, Script or Packaged App Rules. This operates the same way as SRPs – you can configure Allow or Deny Rules here to override those configured at the base level.
You can also create Automatically Generated Rules (so, for instance, you can point at a particular folder and the AppLocker rules will be generated for all content in that folder). Like SRPs, you can either use Path or Hash for the generated rules.
You can also create “Default Rules”, again, much the same as SRPs in that it will automatically generate rules for common areas like Program Files and the Windows folder
Now, AppLocker is a bit cleverer than SRPs in that both the x86 and x64 Program Files directories are allowed by the “Program Files” default rule. However, folders such as the App-V programs folder, are not within the Default Rules and would need to be added.
The added granularity of AppLocker starts to show here though – as well as creating rules here, and applying them as Publisher, Path or Hash, you can also apply the rules only to specific users or groups of users, or you can configure exceptions to the rule as well.
Exceptions allow you to allow specific content that would normally be caught by the rule
You can see right away that the flexibility of AppLocker makes it infinitely more preferable to a standard SRP. You can get very granular with what you allow or deny, and configure settings targeted to specific users without having to get into any GP-level targeting. It can allow you to configure a very flexible approach.
In the same way, you also need to be very careful with the auditing and testing to ensure that you don’t block any content that users will need. Running with the “Audit only” feature turned on over a period of time will allow you to build lists of what users are using and what you need to block. This will also drive the selection of Path, Publisher or Hash rules to see what is appropriate for your environment.
If you run in Audit Mode it is very important to regularly collect and review the AppLocker event logs to see what is being restricted. You will find these at Windows Logs | Applications and Services Logs | Microsoft | Windows | AppLocker. Look for 8002 (allowed execution) events and 8003 (which would have been a disallowed execution, but was allowed because of Audit Mode). If you are deploying at scale, collecting and collating these events centrally is a very good idea.
Once you’ve identified what you need to allow to run, then you can create your rules and switch to Enforced.
A word of warning – don’t get tempted to block all “Packaged apps”. Whilst nobody cares much for UWP apps, blocking them through AppLocker can have side-effects. UWP apps includes Cortana, Settings, and the Start Menu! So if you want to block Packaged Apps – make sure you configure the Default Rules!
Once you’ve switched to Enforced you should see hard blocks appearing for things outside of your configured execution scopes.
With regard to AppLocker, many of the principles discussed in the SRPs section apply – we have just added the capacity for a proper audit mode and much more targeted granularity of the settings.
AppLocker in Action
Again, let’s show a user trying to copy mimikatz.exe down to their local profile and executing it.
This time you will generate an 8004 error in the event log indicating a hard block.
As we did in the SRPs section, the same “advanced” attack vector (loading the mimikatz dll with local admin access) can be used to try and harvest passwords. Again, the resolution is to turn on dll execution blocking to prevent the library from being loaded.
With AppLocker, when you turn on dll execution, you get a fifth section available for use:
And if you configure this correctly, you can then stop the unsanctioned library from loading. Unlike SRPs, though, AppLocker successfully logs both allowed and disallowed library loading in the event log under the relevant IDs.
Extending AppLocker functionality with third-party products
There are many products out there that either leverage or extend the AppLocker functionality.
Citrix Workspace Environment Management (WEM) replicates most of the AppLocker power but allows you to target it in a more granular fashion, therefore applying AppLocker rules based around more specific conditions than is available natively in Group Policy. Citrix WEM is available as an on-premises or cloud service as part of specific Citrix license entitlements.
PolicyPak Least Privilege Manager allows you more options around controlling execution, by allowing you to whitelist apps for certain users in certain situations where execution may be desirable (or even allowing them to elevate their access to complete certain tasks). PolicyPak is a licensed extension for Group Policy.
Ivanti User Workspace Manager Application Control (formerly AppSense AM) combines the advanced targeting you get in WEM with the execution control you get in PolicyPak. Whilst this does not leverage the AppLocker engine directly and instead uses its own filter driver, the concept of stopping execution is the same. The UWM suite is a user environment management family of products and Application Control is available as part of this or on its own. Application Control is a pretty advanced product that allows much more finely-tuned control and features.
Microsoft Defender Application Control
Microsoft Defender Application Control (formerly Windows Defender Application Control) is an evolution of AppLocker designed to avoid the most glaring issue with AppLocker – that system processes and device driver execution cannot be controlled. MDAC was one of the features that was formerly known as “Device Guard” in Windows 10. It currently runs on Windows 10 or Server 2016 and higher (although the 1903+ version of Windows 10 is recommended for full features).
MDAC policies apply to the device as a whole rather than users but introduce some cutting-edge new features for application whitelisting:-
- Using attributes of the codesigning certificates to allow or disallow execution
- Using advanced features of the executable, such as filename, version, hash or metadata
- The application’s actual reputation, sourced from an online security repository
- The parent process that launched the application
Whilst it does not yet offer the flexibility that AppLocker does, it seems certain that MDAC will evolve to supersede AppLocker in the coming years. For now, if you have devices that can support MDAC, it is recommended to use MDAC as the baseline and AppLocker to fine-tune the requirements. Eventually, MDAC will become the standard that AppLocker is now.
Currently, though, bear in mind that it is pretty new and there will be bumps in the road. I’ve heard tales of it breaking InTune app deployments and some minor issues with Office add-ins.
Summary
So, what’s my advice around application whitelisting?
Firstly – do it! Whitelisting gives you so much more protection, even if you can only do rudimentary path-based whitelisting. ANYTHING that puts obstacles in the way of an attacker increases your security posture. The more hoops they have to jump through, the more chance you have of spotting them before they can move laterally and do damage.
Obviously, plan carefully. There’s nothing guaranteed to put users off a solution faster than making their lives as misery with it. Audit your environment carefully and make sure you have at least 80-90% of the applications covered before you go live.
SRPs are really long in the tooth these days, so generally I wouldn’t recommend using them. Especially with even AppLocker looking like it will eventually be replaced, leaning on SRPs, dated as they are, is not recommended. The lack of proper auditing should be enough to put anyone off.
AppLocker is pretty much the tech of the moment – it is granular, well-documented, reliable, and flexible. Whether on its own or used alongside something like WEM or PolicyPak or even replaced entirely by a product like Ivanti Application Control, it is not to be sniffed at. In a traditional environment where you have a blend of operating system types, AppLocker is probably the right choice for you.
However, if you’re pretty up-to-date, then a blend of MDAC and AppLocker will do better. The advanced security features of MDAC will eventually replace AppLocker and adopting these sooner rather than later will be good. MDAC has not reached maturity yet, but when it does, expect it to subsume AppLocker pretty rapidly. Be ready for that switch moment!
Try pwncheck. our password audit tool, it’s completely free to download and run. Provides you with the number of pwned users in just a few seconds.
Test Drive Pwncheck
The best way to find out if pwncheck is right for you is to try it out. Use the download button below to try Pwncheck’s free version with absolutely zero strings attached, no form entry required.
If you’d like to test drive the full version fill in the form and we’ll send you a single-use evaluation licence (normally $150, €120 or £100).
В этой статье рассмотрим ещё один механизм, который ограничивает запуск программ в Windows, а именно Software Restriction Policies (SRP).
Механизм «Software Restriction Policies (SRP)» доступен в локальных политиках безопасности (secpol.msc) и может распространятся глобальными политиками в домене.
Чтобы создать политику, нужно нажать правой кнопкой мышки:
После чего появятся правила связанные с данной технологией:
Правила связанные с SRP
Выше у нас появились три правила:
- Применение (Enforcement) — настраивает применение политик к программам или библиотекам и определяет применение политик только к пользователям или к администраторам в том числе:
- Назначенные типы файлов (Designated File Types) — хранит расширения файлов, которые считаются исполняемым кодом:
- Доверенные издатели (Trusted Publishers) — а это правило управляет тем, кто может выбирать, какие из сертификатов являются доверенными:
Дополнительные правила
Если перейти в каталок «Дополнительные правила«, то там вы увидите созданные правила и сможете создать новые. Возможно создать правила для: сертификата, хэша, зоны сети (зоны Internet Explorer), пути.
Уровни безопасности
Дальше, при создании правила, нужно связать его с определенным уровнем безопасности:
- Запрещено (Disallowed) — программы запускаться не будут, вне зависимости от прав доступа пользователя;
- Обычный пользователь — разрешает выполнение программ, но только без прав администратора;
- Неограниченный (Unrestricted) — доступ к ресурсам определяется правами пользователя.
Эксперимент
- Запустите оснастку secpol.msc и перейдите к узлу «Политики ограниченного использования программ.
- Если политики не определены, то создайте новые политики.
- Создайте основанную на пути к файлу запрещающую политику для %SystemRoot%\System32\Notepad.exe в дополнительных правилах:
4. Попробуйте запустить «Блокнот» (notepad.exe).
Ваша попытка приведет к выводу сообщения, в котором говорится, что вы не можете выполнить указанную программу:
Важное уточнение
Если ваш компьютер включен в домен, то локальные групповые политики будут переписаны групповыми, это следует учитывать при работе с Software Restriction Policies.
Вернуться к оглавлению
Если понравилась статья, подпишись на мой канал в VK или Telegram.
Политика программных ограничений Software Rectriction Policy (SRP) позволяет администраторам определять, какие приложения пользователи могут запускать под Windows
Пользователи постоянно загружают и запускают приложения, с которыми им не положено работать, в связи с чем в сети организации может устанавливаться вредоносное программное обеспечение. Управлять тем, какие программные средства пользователи устанавливают на своих компьютерах, в среде Windows на удивление непросто. Первый компонент решения этой проблемы состоит в том, чтобы в большинстве случаев пользователям предоставлялся наименьший объем полномочий, т. е. чтобы они не выступали в роли администраторов или опытных пользователей. Второй элемент головоломки — контроль списка программ, которые пользователи могут запускать.
Во многих решениях от независимых поставщиков реализуются функции белых или черных списков приложений. Иначе говоря, создаются списки приложений, которые можно (если они внесены в белый список) или нельзя (если они внесены в черный список) запускать на исполнение. Таким образом, затрудняется применение конечными пользователями программных кодов с «незваными гостями», которые могут нанести ущерб сети организации. Однако в целях управления исполнением приложений можно использовать политику ограниченного применения программ (SRP, известную также как Safer). Хотя в SRP не реализованы некоторые возможности решений от независимых поставщиков, например заранее составленные каталоги сигнатур приложений, используемые для блокировки или разрешения запуска последних, данная политика предоставляет возможности, которые во многих ИТ-подразделениях еще не реализованы или применяются не в полном объеме.
Как функционирует SRP
SRP применима в средах Windows Server 2008, Windows Vista, Windows Server 2003 и Windows XP. К этой функции можно обратиться через редактор групповых политик Group Policy Editor (GPE) либо в разделеComputer ConfigurationWindows Settings Security Settings, как показано на экране 1, либо в разделе User ConfigurationWindows SettingsSecurity Settings. SRP доступна как локальный объект групповых политик (GPO), так и GPO доменов. Однако, как локальный GPO, эта функция доступна лишь в качестве средства управления компьютерами. Вся мощь политик SRP проявляется в тех случаях, когда они развертываются через доменные GPO на целом ряде систем с помощью встроенных механизмов назначения групповой политики.
SRP дает возможность определять правила ограниченного использования приложений внутри GPO, и эти правила транслируются на клиентскую систему по обычным каналам групповой политики. Операционная система Windows хранит эти правила в реестре и обращается к ним всякий раз при выполнении процесса. Если соответствующее правило существует, приложение запускается или блокируется — в зависимости от того, внесено оно в белый или в черный список. SRP не применяет санкций к уже выполняющимся приложениям, даже если групповая политика применила соответствующие правила. Чтобы правило вступило в действие, необходимо перезапустить приложение.
Настройки SRP
Проиллюстрировать возможности использования SRP лучше всего на примере типового сценария. Допустим, на системе пользователя выполняется Microsoft Office и несколько деловых приложений. Я хочу, чтобы этот пользователь мог выполнять только санкционированные мною приложения, и поэтому собираюсь реализовать в политике SRP белый список.
Настройки SRP лучше всего хранить в особом объекте GPO, отдельно от других настроек политики, чтобы в случае необходимости их можно было быстро отключить. Требуется принять решение: будут ограничения использоваться применительно к компьютерам или применительно к пользователям. В первом случае ограничения на запуск приложений касаются любого пользователя, применяющего учетные записи компьютеров в службе Active Directory (AD), которые получают данные ограничения; такой вариант приемлем, к примеру, при использовании SRP на серверах терминалов. Ограничения «на пользователя» применяются к данному набору объектов «пользователь» в AD и налагаются на этих пользователей вне зависимости от того, с каких систем они регистрируются.
Итак, мы решили, к каким объектам будут применяться политики. Теперь нужно активизировать политики и приступить к их настройке. Прежде всего, запустим консоль управления групповыми политиками Group Policy Management Console (GPMC) и создадим новый объект GPO программных ограничений.
Правой кнопкой мыши щелкните на вновь созданном GPO внутри контейнера Group Policy Objects консоли GPMC и в меню выберите пункт Edit. На экране появится окно редактора GPE с выделением интересующего нас объекта GPO.
Перейдите на узел Software Restriction Policies в раздел Computer Configuration, чтобы определять политики применительно к компьютерам, или в раздел User Configurations — для определения политик «на пользователя». Правой кнопкой мыши щелкните на узле Software Restriction Policies и в контекстном меню выберите пункт New Software Restriction Policies. На правой панели экрана появится группа папок и элементов политик (см. экран 1). Возможно, вы получите сообщение о том, что политики вступят в силу только после перезагрузки системы (это верно для Windows Server 2008). Данное сообщение не вполне соответствует действительности, так как для того, чтобы начать загрузку этих политик, не требуется перезагрузка ни клиента, ни сервера.
Первое решение, которое необходимо принять применительно к этим новым элементам, касается того, какой список вы будете формировать — белый или черный. Белые списки дают возможность получить более безопасную среду, ибо они блокируют выполнение любых программ, кроме тех, что указаны явным образом. С другой стороны, для управления белыми списками требуются дополнительные усилия в зависимости от числа приложений в корпоративной сети, от того, как часто меняется список, и от того, какие методы используются для идентификации приложений. В рамках нашего примера мы будем создавать белый список.
Дважды щелкните на папке Security Levels, расположенной на правой панели редактора GPE. В системах Windows 2003 и Windows XP эта папка содержит два узла: Disallowed и Unrestricted. В Windows Server и Vista добавляется третий узел — Basic User. Узел Unrestricted (режим черного списка) имеет небольшую пометку, указывающую на то, что данный режим применяется по умолчанию. Чтобы перейти в режим белого списка, дважды щелкните на узле Disallowed и нажмите кнопку Set as Default. На экране появится запрос на подтверждение; подтвердите ваш выбор и закройте диалоговое окно, чтобы продолжить работу.
Basic User — это функция, добавленная в версии Windows Vista. В режиме Basic User у пользователей, которые являются администраторами своих рабочих станций или доменов AD, из всех приложений, выполняемых на их системах, удаляются административные маркеры. В сущности, они лишаются возможности выполнять какие-либо программы с полномочиями администраторов. Незаметно для пользователей функция SRP модифицирует маркер процесса в каждом приложении, запущенном пользователем, добавляя инструкцию об отмене разрешения представителям следующих групп безопасности:
- администраторы;
- администраторы сертификатов;
- администраторы схемы;
- администраторы предприятия;
- администраторы доменов.
Basic User можно представить как механизм для выявления ситуаций, когда администраторы действительно выступают в роли администраторов. Возможно, в вашей организации имеется ряд компьютеров, содержащих конфиденциальные данные о клиентах, и администраторам время от времени приходится регистрироваться на этих системах. В таких случаях вы можете установить режим Basic User в качестве режима по умолчанию для упомянутых систем, чтобы пользователи не могли выполнять приложения с расширенными полномочиями.
Указание параметров SRP
Пришло время установить кое-какие общие параметры. Если вы перейдете обратно в папку верхнего уровня внутри данной политики, то увидите три узла: Enforcement, Designated File Types и Trusted Publishers. Дважды щелкните на узле Enforcement. На экране появится диалоговое окно Enforcement Properties, показанное на экране 2. Это окно дает возможность выбрать режим SRP при обработке ее правил.
Первый параметр диалогового окна позволяет выбрать одну из двух возможностей: SRP реализует правила применительно к приложениям или к приложениям и всем зависимым от них библиотекам DLL. По умолчанию (прежде всего, из соображений быстродействия) используется вариант с реализацией правил только применительно к вызывающему приложению. Однако, если у вас вызывают беспокойство файлы DLL как возможные каналы для атаки, можете распространить действие правил и на них, выбрав пункт All Software Files.
Параметр Enforcement Properties позволяет указывать, требуется ли применять политики SRP, перечисленные в данном объекте GPO, ко всем пользователям вообще, или ко всем, за исключением членов локальной группы администраторов. По умолчанию администраторы исключаются, а значит, не подвергаются заданным ограничениям. Используйте этот режим по умолчанию, если только не возникнет потребность в том, чтобы к администраторам применялись те же правила, что и к обычным пользователям.
Определите расширения файлов, которые SRP будет рассматривать как исполняемые типы в узле Designated File Types. Первоначально вы увидите ожидаемые расширения файлов: .exe,.bat,.msi и т. д. К этому списку можно добавлять расширения других типов файлов, которыми предстоит управлять. Но если, к примеру, вы уже создаете правило, блокирующее работу программы Microsoft Excel, включать в список расширение .xls не имеет смысла.
Третий параметр узла Software Restriction Policies — это параметр Trusted Publishers. Данный узел дает возможность управлять характеристиками элементов управления ActiveX. Вы можете предоставить или не предоставлять пользователям право определять издателя того или иного элемента управления ActiveX как надежного. Если такое право получают обычные пользователи, вы в итоге лишаете себя возможности отслеживать, какие издатели элементов ActiveX заслуживают доверия.
Кроме того, параметр Trusted Publishers позволяет определять, должна ли система Windows проверять, не отозваны ли сертификаты и действительны ли отметки времени перед тем, как устанавливать элемент управления ActiveX, подписанный тем или иным пользователем. Если издатели ваших легитимных элементов управления ActiveX добросовестно поддерживают актуальность своих сертификатов, задействовать этот параметр, по-видимому, не стоит.
Типы правил для управления выполнением приложений
Теперь давайте заглянем в самое сердце SRP — а именно рассмотрим правила, регулирующие выполнение реального приложения. В SRP предусмотрено четыре типа правил:
- правила для хеша;
- правила для пути;
- правила сертификата;
- правила для сетевой зоны.
Вероятно, в 99% случаев вы будете использовать в своих целях правила для хеша или правила для пути. Правила сертификата дают возможность санкционировать или ограничивать выполнение в зависимости от того, подписан ли код тем или иным издателем. К сожалению, многие создатели легитимных приложений не подписывают свой код, поэтому сфера применения данного правила ограничена.
Правила для сетевой зоны позволяют администратору контролировать использование файлов Windows Installer; в сущности, речь идет о возможности определения, из какой зоны браузера Internet Explorer должны поступать файлы .msi, которые может выполнять пользователь. Увы, как правило, вредоносные программы не поступают к нам с удобными файлами Windows Installer, поэтому данная функция имеет весьма ограниченное применение. Но если по какой-то причине у вас возникнет потребность ограничить возможность установки файлов .msi, это правило вам пригодится.
Мы еще не касались правил для хеша и правил для пути. Давайте посмотрим, как они работают и как мы можем использовать их.
Правила для хеша
Как уже говорилось, при использовании белых списков блокируется запуск всех исполнимых файлов, кроме тех, которые получают явную санкцию на выполнение. Существует два способа формирования правил, санкционирующих запуск исполнимых файлов. Правило для хеша — это способ идентификации приложения по уникальному хешу, сгенерированному средствами SRP. Первоначально в качестве применяемого по умолчанию алгоритма хеширования специалисты Microsoft использовали алгоритм MD5, но в версии Windows Vista переключились на более новый алгоритм SHA-256. При создании правила хеша в средах Server 2008 или Windows Vista операционная система сохраняет обе версии хеша для обеспечения обратной совместимости.
При использовании правил для хеша администратор получает возможность управлять приложениями, невзирая на все уловки, предпринимаемые пользователями для обхода ограничений. Это значит, что правила для хеша, по-видимому, наиболее полезны в сценариях с черными списками. Представим себе такую ситуацию. Вы хотите, чтобы пользователи не могли запускать игру Solitaire (sol.exe) в среде Windows XP. Вам нужно в редакторе GPE создать новое правило для хеша. Правой кнопкой мыши щелкните на узле Additional Rules, расположенном на правой панели, и в раскрывшемся меню выберите пункт New Hash Rule. В диалоговом окне New Hash Rule нажмите кнопку Browse и выберите элемент C:WindowsSystem32sol.exe. После этого щелкните ОК. Как показано на экране 3, теперь можно для уровня безопасности вызвать настройку Disallowed, чтобы пользователи не могли запускать данное приложение.
Теперь, даже если пользователи перенесут исполнимый файл sol.exe в другое место или дадут ему другое имя, правило для хеша обеспечит соблюдение наложенного вами ограничения. Правила для хеша полезны при использовании с приложениями, которые изменяются не слишком часто; нужно иметь в виду, что, если приложение изменяется вследствие применения обновления или программного исправления, изменяется и значение хеша приложения, так что вам придется вновь формулировать правило для хеша. Отмечу, что при указании исполнимого файла, который следует контролировать, нужно использовать ту версию приложения, которая установлена на целевых системах. Так, если вы хотите ограничить использование игры Solitaire на системах Windows XP SP3, найдите в списке соответствующую версию исполнимого файла, выполняемого на системе Windows XP SP3, и пусть SRP вычисляет хеш на ее основе.
Правила для пути
Правила для пути — самые полезные и мощные из всех четырех типов правил SRP. Используя их, вы можете указать путь к файлам с целью разрешить или запретить их выполнение (или перевести систему в режим Basic User), и все приложения, расположенные по этому адресу, переводятся под управление SRP. Создать правило для пути просто, достаточно в редакторе GPE правой кнопкой мыши щелкнуть на папке Additional Rules и в раскрывшемся меню выбрать пункт New Path Rule, а затем ввести путь к каталогу, где требуется создать правило.
Главное достоинство правил для пути состоит в том, что они могут принимать множество форм. Правило для пути может быть весьма простым, например:
Sol.exe or Sol.* or S*.*
Это правило лишает пользователей возможности выполнения файла sol.exe, исполнимых файлов с именем Sol и любыми файловыми расширениями, а также всех находящихся в папке Designated File Types программ, названия которых начинаются с буквы s. Разумеется, правило для пути может содержать и фактический путь к файлу, например C:Program FilesMicrosoft Office. В этом примере правило будет регулировать использование всех приложений, размещенных внутри папки Microsoft Office, включая дочерние папки. В правилах для пути можно также указывать пути в соответствии с положениями соглашения об именовании UNC. Так, вы можете указать, что выполняться будут только приложения, находящиеся по адресу MyServerApps. Отмечу, что правило для пути MyServerApps разрешается в любое представление этого же пути (например, 10.5.1.1Apps, или P:, где P указывает на MyServerApps).
Наконец — и, возможно, это самый эффективный способ работы с правилами — вы можете создавать правила пути для реестра. Мы не всегда знаем, где именно установлено то или иное приложение. К примеру, по умолчанию программа Yahoo! Messenger устанавливается в каталоге C:Program FilesYahoo!Messenger, но пользователь мог сохранить ее в другом месте. Как создать правило, применимое к приложению вне зависимости от того, в каком каталоге оно установлено? Вот здесь-то нам на помощь и приходят правила пути реестра.
Правило пути реестра — это ссылка на адрес в реестре, который указывает на путь в файловой системе. В нашем примере при установке приложения Messenger это приложение создает в разделе HKEY_LOCAL_MACHINESOFTWAREYahoo Essentials параметр реестра MainDir, который содержит путь к каталогу, где размещается Messenger. Правило пути реестра создается для того, чтобы приложение Yahoo! Messenger не могло запускаться, т. е. с той же целью, с какой создаются другие правила для пути. На экране 4 показано, как будет выглядеть такое правило.
Обратите внимание, что вводить нужно весь путь реестра вплоть до значения, содержащего путь к файлу, на который вы хотите наложить ограничение; при этом путь реестра должен быть заключен в символы процента (%). В реестре это значение отображается как C:Program FilesYahoo!. При оценке правила для пути SRP просматривает реестр в поисках пути к приложению Messenger и управляет всеми приложениями, расположенными на этом пути.
Еще одна замечательная сфера применения правил пути реестра — блокировка выполнения кода, который пользователь загрузил в виде присоединенного файла или с помощью Web-браузера. Пример: вы хотите, чтобы пользователи не выполняли приложения внутри браузера Internet Explorer без предварительного сохранения соответствующего файла. Когда пользователь нажимает кнопку Open в диалоговом окне загрузки, IE использует путь к временному каталогу загрузки в разделе реестра HKEY_LOCAL_MACHINESOFTWAREMicrosoft WindowsCurrentVersionInternet SettingsCachePathsDirectory. Если вы создадите правило пути реестра к данному каталогу и присвоите ему значение Disallowed, ни один из типов приложений, находящихся в папке Designated File Types, не сможет выполняться из этого приглашения Open.
Правила для пути, созданные Microsoft
Когда вы будете впервые создавать новую политику SRP внутри объекта GPO, то заметите, что операционная система Windows автоматически создает правила пути реестра на узле Additional Rules внутри редактора GPE. Эти заранее созданные правила пути реестра определяют все приложения внутри каталогов C:Windows, а также C:Program Files (или по всему маршруту на пути к этим хорошо известным папкам) как не подвергающиеся ограничениям. Думаю, специалисты Microsoft сделали это для того, чтобы администраторы, впервые составляя белый список, не совершали непреднамеренной ошибки и не препятствовали корректному выполнению компонентов операционной системы.
Тем не менее вам все-таки лучше не упускать из виду эти заранее составленные правила, ибо, если вы попытаетесь создать настоящий белый список, то вряд ли захотите дать санкцию на выполнение всех программ, находящихся в каталогах C:Windows и C:Program Files. Если вы решите удалить эти заранее заданные правила, обязательно проведите тщательное тестирование. Более того, если вы хотите изменить их, я рекомендую удалять только правило Program Files и оставить без изменения правило C:Windows; таким образом вы исключите возможность блокировки приложений, играющих ключевую роль в функционировании операционной системы.
Взаимодействие политик SRP
Если вы определяете политики SRP в нескольких объектах GPO, необходимо знать, как они будут взаимодействовать друг с другом. Если говорить об общих параметрах (применяется ли модель белый список или черный список, какие типы файлов используются, каковы настройки надежных издателей и т. д.), важно иметь в виду, что фактически будет применяться та настройка, которая обрабатывается последней в процессе обработки групповой политики на клиентской системе. Однако, в сущности, происходит слияние правил. Ситуация может оказаться весьма запутанной: к примеру, правило для пути и правило для хеша могут войти в противоречие друг с другом. В этом случае в силу вступает более конкретное правило.
Рассмотрим пример. Допустим, у нас имеется правило для хеша, блокирующее запуск файла C:Windows
egedit.exe, и правило для пути, санкционирующее выполнение всех программ, размещенных в каталоге C:Windows. Применяться будет правило для хеша: оно более конкретно, ибо указывает на определенный файл. Таким образом, файл regedit.exe будет заблокирован, даже если все остальные файлы каталога C:Windows получат санкцию на выполнение. Главный вывод: старайтесь избегать «наложения» правил при работе с несколькими GPO.
Включите в арсенал SRP
SRP — мощный механизм управления выполнением приложений на системах Windows, не требующий использования дорогостоящих решений от независимых поставщиков. Для реализации этого механизма нужно проделать определенную работу, и он не обеспечивает защиты от неумелого обращения, зато администратор может творчески подойти к делу и подобрать соответствующие правила для пути и даже для хеша, а также правила сертификата, чтобы создать среду, в которой пользователи могут запускать лишь проверенные программы. Я рекомендую всем администраторам, которые стараются искоренить привычку пользователей загружать и запускать непроверенные коды, взять на вооружение политики SRP и попытаться тем самым повысить безопасность работы в своих сетях.
Даррен Мар-Элиа (dmarelia@windowsitpro.com) — редактор Windows IT Pro, технический директор и учредитель компании SDM Software
WINDOWS
Introduction
In today’s digital landscape, cybersecurity is paramount. Organizations are increasingly turning to various tools and features within operating systems to safeguard their networks and data. One such feature in Windows is Software Restriction Policies (SRP), a crucial component in the Windows security architecture. This article delves into the concept of SRP, its configuration through Group Policy and Local Security Policy, and best practices for implementation.
What are Software Restriction Policies?
Software Restriction Policies (SRP) are a security feature in Windows that help administrators control the execution of software on systems. SRPs can be used to define what software is allowed or disallowed to run, thereby minimizing the risk of malware and unauthorized applications.
Key Features of SRP
-
Execution Control: SRP allows for detailed rules that specify which applications can run on a system.
-
Policy Enforcement: Enforced at the operating system level, ensuring policies are applied before any application executes.
-
Integration with Active Directory: SRPs can be deployed across an entire Windows domain when configured in Group Policy.
-
Flexibility: Supports a variety of restrictions based on file path, file hash, publisher, and network zone.
How to Configure Software Restriction Policies
Software Restriction Policies can be configured using Group Policy for multiple users or machines on a Windows network and using Local Security Policy for standalone systems.
Configuring SRP via Group Policy
-
Open Group Policy Management Console:
-
Press
Windows + R, typegpmc.msc, and hit Enter.
-
-
Create a GPO:
-
Right-click on your domain or organizational unit (OU) and select Create a GPO in this domain, and Link it here…. Name it appropriately (e.g., “Software Restriction Policies”).
-
-
Edit the GPO:
-
Right-click on the newly created GPO and select Edit.
-
-
Navigate to Software Restriction Policies:
-
Go to
Computer Configuration>Policies>Windows Settings>Security Settings>Software Restriction Policies.
-
-
Create New Policies:
-
If no policies exist, right-click on Software Restriction Policies and select New Software Restriction Policies.
-
-
Define Security Levels:
-
Right-click on Security Levels and set the desired levels (Unrestricted, Disallowed, etc.).
-
-
Set Up Rules:
-
Right-click on Additional Rules to create rules based on various factors, including:
-
Path Rules: Specify directories or file paths.
-
Hash Rules: Create rules based on cryptographic hashes of executable files.
-
Certificate Rules: Allow or disallow applications based on their signing certificate.
-
Network Zone Rules: Control applications downloaded from the Internet.
-
-
-
Apply and Update Group Policies:
-
Once the necessary rules are set up, ensure that the GPO is applied, and run
gpupdate /forceon affected machines to apply the settings immediately.
-
Configuring SRP via Local Security Policy
-
Open Local Security Policy:
-
Press
Windows + R, typesecpol.msc, and hit Enter.
-
-
Navigate to Security Settings:
-
Go to
Local Policies>Software Restriction Policies.
-
-
Create New Policies:
-
Similar to Group Policy, right-click and select New Software Restriction Policies.
-
-
Configure the Policies:
-
Set security levels and create rules as described in the Group Policy section.
-
Best Practices for Implementing Software Restriction Policies
Implementing SRP effectively requires careful planning. Here are some best practices to keep in mind:
-
Start with Basic Policies: Initially, implement broad restrictions (e.g., disallow all but trusted applications) and gradually refine the policies according to organizational needs.
-
Regularly Update Policies: Continually review and update SRPs as new software is deployed or as security threats evolve.
-
Monitor and Audit: Regularly monitor the effectiveness of the policies. Use Windows Event Logs to check for blocked applications and potential security breaches.
-
Educate Users: Inform users about the reasons behind SRPs and encourage them to report unusual software behavior.
-
Test Before Deployment: Test SRPs in a controlled environment before rolling them out organization-wide to mitigate unintended disruptions.
Conclusion
Software Restriction Policies (SRP) are an invaluable tool for enhancing security within Windows environments. By effectively configuring SRPs through Group Policy or Local Security Policy, administrators can significantly reduce the risk of unauthorized software execution, thus protecting sensitive data and maintaining system integrity. Adopting best practices and continuously monitoring SRP effectiveness will further bolster an organization’s defense against evolving threats in the cybersecurity landscape. As software threats continue to advance, leveraging tools like SRP will remain crucial for any robust security strategy.
Suggested Articles
WINDOWS
WINDOWS
WINDOWS
WINDOWS
WINDOWS
WINDOWS
