- Изоляция AppContainer
- Изоляция учетных данных
- Изоляция устройств
- Изоляция файлов
- Сетевая изоляция
- Изоляция процессов
- Изоляция окна
- AppContainer Process Isolation on Windows 10 #14548
- Comments
- felixrieseberg commented Sep 11, 2018
- Getting Electron ready for AppContainer
- AppContainer Isolation
- Credential Isolation
- Device Isolation
- File Isolation
- Network Isolation
- Process Isolation
- Window Isolation
- Системный изолятор. Изолируем процессы в Windows средствами Less Privileged App Container (LPAC)
- Содержание статьи
- Создаем Less Privileged App Container
- Пишем LPAC loader для любого приложения
- Продолжение доступно только участникам
- Вариант 1. Присоединись к сообществу «Xakep.ru», чтобы читать все материалы на сайте
- AppContainers for Windows 8: What Are They and How Can You Create Them?
- What is an AppContainer?
- Creating an AppContainer
- Creating a process in the AppContainer
- Granting an application access to resources
- Conclusion
- Apriorit — Specialized Software Development Company
Изоляция AppContainer
Изоляция является основной целью среды выполнения AppContainer. Изолируя приложение от ненужных ресурсов и других приложений, можно избежать возможных сделок для вредоносной манипуляции. Предоставление доступа на основе минимальных привилегий запрещает приложениям и пользователям доступ к ресурсам за пределами их прав. Управление доступом к ресурсам защищает процесс, устройство и сеть.
Большинство уязвимостей в Windows начинаются с приложения. Некоторые распространенные примеры включают приложение, которое выходит из браузера, или отправку неправильного документа в Internet Explorer, а также использование подключаемых модулей, таких как Flash. Чем больше этих приложений можно изолировать в AppContainer, тем безопаснее устройство и ресурсы. Даже если уязвимость в приложении используется злоумышленниками, приложение не сможет получить доступ к ресурсам, превышающим возможности, предоставленные AppContainer. Вредоносные приложения не могут перехватить остальную часть компьютера.
Изоляция учетных данных
Управляя удостоверениями и учетными данными, AppContainer предотвращает использование учетных данных пользователя для получения доступа к ресурсам или входа в другие среды. Среда AppContainer создает идентификатор, использующий объединенные идентификаторы пользователя и приложения, поэтому учетные данные уникальны для каждого связывания пользователей и приложений и приложение не может олицетворять пользователя.
Изоляция устройств
Изоляция приложения от ресурсов устройства, таких как пассивные датчики (камера, микрофон, GPS) и денежные насосы (3G/4G, телефонный звонок), среда AppContainer предотвращает вредоносное использование устройства. Эти ресурсы заблокированы по умолчанию, и при необходимости им можно предоставить доступ. В некоторых случаях эти ресурсы дополнительно защищаются с помощью «брокеров». Некоторые ресурсы, такие как клавиатура и мышь, всегда доступны для AppContainer и резидентных приложений.
Изоляция файлов
Управляя доступом к файлам и реестру, среда AppContainer не может изменять файлы, которые им не нужно. Доступ для чтения и записи может быть предоставлен конкретным постоянным файлам и разделам реестра. Доступ только для чтения менее ограничен. Приложение всегда имеет доступ к резидентным файлам памяти, созданным специально для этого AppContainer.
Сетевая изоляция
Изоляция приложения от сетевых ресурсов, выходящих за пределы выделенного, AppContainer не позволит приложению изменять свое окружение и злонамеренно использовать сетевые ресурсы. Детализированный доступ может быть предоставлен для доступа к Интернету, доступа к интрасети и работы в качестве сервера.
Изоляция процессов
Изолирование объектов ядра приложения, среда AppContainer предотвращает влияние приложения на работу других процессов приложения или на них влияет. Это предотвращает неправильное автономное приложение от повреждения других процессов в случае исключения.
Изоляция окна
Изолируя приложение от других окон, среда AppContainer не повлияет на другие интерфейсы приложений.
AppContainer Process Isolation on Windows 10 #14548
Comments
felixrieseberg commented Sep 11, 2018
Using tools like electron-windows-store , Electron can be packaged as an appx app and run in the same environment as Windows Store apps, commonly known as UWP apps. They’re still exe binaries, they’re just running as part of a package and with a package identity attached.
While those applications are running within a scoped amount of virtualization (namely, filesystem and registry redirection), they’re not actually running in a process isolation sandbox like their proper UWP siblings. Their capability is therefore .
With RS5 (October 2018 Update), Windows 10 introduces «partial trust» that’ll allow applications running in the desktop bridge to make use of the same app container process isolation security proper UWP applications.
Getting Electron ready for AppContainer
- Get final appxmanifest.xml for partial trust applications from Microsoft
- Create a simple test harness to create and test partial trust Electron apps
- Verify which APIs need UWP additions to function within sandbox
- Extend non-functional APIs with UWP APIs
We know, as an example, that shell.* APIs do not work. We’ll need to augment those APIs to use UWP counterparts when isRunningInDesktopBridge() returns true . We need to audit every single API and make sure that they either work fine or are documented as non-functional.
The text was updated successfully, but these errors were encountered:
AppContainer Isolation
Isolation is the primary goal of an AppContainer execution environment. By isolating an application from unneeded resources and other applications, opportunities for malicious manipulation are minimized. Granting access based upon least-privilege prevents applications and users from accessing resources beyond their rights. Controlling access to resources protects the process, the device, and the network.
Most vulnerabilities in Windows start with the application. Some common examples include an application breaking out of its browser or sending a bad document to Internet Explorer as well as exploitation of plugins, such as flash. The more these applications can be isolated in an AppContainer, the safer the device and resources are. Even if vulnerability in an app is exploited, the app cannot access resources beyond what is granted to the AppContainer. Malicious apps cannot take over the rest of the machine.
Credential Isolation
Managing identity and credentials, the AppContainer prevents the use of user credentials to gain access to resources or login to other environments. The AppContainer environment creates an identifier that uses the combined identities of the user and the application, so credentials are unique to each user/application pairing and the application cannot impersonate the user.
Device Isolation
Isolating the application from device resources, such as passive sensors (camera, microphone, GPS), and money pumps (3G/4G, dial phone) the AppContainer environment prevents the application from maliciously exploiting the device. These resources are blocked by default and can be granted access as necessary. In some cases these resources are further protected by ‘brokers’. Some resources, such as keyboard and mouse, are always available to the AppContainer and resident application.
File Isolation
Controlling file and registry access, the AppContainer environment prevents the application from modifying files that it should not. Read-write access can be granted to specific persistent files and registry keys. Read-only access is less restricted. An application always has access to the memory resident files created specifically for that AppContainer.
Network Isolation
Isolating the application from network resources beyond those specifically allocated, AppContainer prevents the application from ‘escaping’ its environment and maliciously exploiting network resources. Granular access can be granted for Internet access, Intranet access, and acting as a server.
Process Isolation
Sandboxing the application kernel objects, the AppContainer environment prevents the application from influencing, or being influenced by, other application processes. This prevents a properly contained application from corrupting other processes in the event of an exception.
Window Isolation
Isolating the application from other windows, the AppContainer environment prevents the application from affecting other application interfaces.
Системный изолятор. Изолируем процессы в Windows средствами Less Privileged App Container (LPAC)
Содержание статьи
Сендбокс-изоляция часто применяется в защитных приложениях, а также на ее основе строятся компоненты антивирусов, называемые HIPS (Host-based Intrusion Prevention System), и отдельные приложения для изолированных сред типа Sandboxie. Такие защитные механизмы реализованы через драйвер-фильтр режима ядра. Он сложен в написании и тестировании, имеет громадное количество шаблонного кода и должен перехватывать значительное количество функций NTAPI, чтобы менять их параметры на лету, таким образом создавая песочницу внутри файловой системы.
Существует более простой способ устроить изоляцию произвольных приложений. Инженеры Microsoft уже позаботились об этом и интегрировали интересный механизм в ядро Windows. Его суть заключается в том, что система жестко ограничивает доступ к устройствам (таким как микрофон, камера, GPS или модуль 4G), файлам в системе (иногда — даже для чтения) и процессам (ограничиваются межпроцессные взаимодействия). Также ограничения накладываются на работу с сетью (например, на открытие портов или сокетов), обращения к сетевому реестру и оконному интерфейсу других приложений.
Когда приложение запущено внутри LPAC, все разрешения ему требуется выдавать явно. Это весьма полезный механизм с точки зрения безопасности, если в приложении есть уязвимости, которые злоумышленник может использовать для повышения привилегий и доступа к другим ресурсам. Если уязвим, например, браузер, то такую атаку можно выполнить удаленно. Кроме того, когда запускаешь неизвестное приложение, неплохо было бы обезопасить себя от несанкционированных действий с его стороны, научившись запускать приложения в контейнере LPAC.
Создаем Less Privileged App Container
Прежде чем запускать приложение, нам нужно создать сам контейнер. В этом нам поможет функция WinAPI CreateAppContainerProfile . Вот ее прототип:
И сам код создания контейнера:
В случае ошибки неплохо было бы проверить, не создан ли наш контейнер ранее; если создан, то мы получим его SID. Вот прототип функции WinAPI, которая выясняет SID уже созданного контейнера:
Далее код реализации проверки. Как видишь, он очень прост.
Так или иначе мы получаем SID контейнера.
Security Identifier (SID) — идентификатор безопасности, структура данных в Windows, которая может идентифицировать системные объекты, например элементы управления доступом (Access Control Entries, ACE), токены доступа (Access Token), дескрипторы безопасности (Security Descriptor). SID всегда начинается с буквы S, далее идут числа, которые обозначают номер редакции ОС, источники выдачи, удостоверяющие центры и другую информацию.
Пишем LPAC loader для любого приложения
Итак, контейнер LPAC создан, SID получен. Теперь наша задача — заставить Windows запустить произвольное приложение в этом контейнере. Но сначала нам необходимо разобрать процесс запуска приложений и понять, как можно задавать определенные атрибуты запуска и какие системные структуры отвечают за это.
Для запуска приложений в Windows используется функция WinAPI CreateProcess с массой параметров, и именно эта функция имеет ключевое значение в нашей задаче. Давай посмотрим на ее прототип и разберем основные параметры.
Продолжение доступно только участникам
Вариант 1. Присоединись к сообществу «Xakep.ru», чтобы читать все материалы на сайте
Членство в сообществе в течение указанного срока откроет тебе доступ ко ВСЕМ материалам «Хакера», позволит скачивать выпуски в PDF, отключит рекламу на сайте и увеличит личную накопительную скидку! Подробнее
AppContainers for Windows 8: What Are They and How Can You Create Them?
Sandboxes are perfect tools for software developers to test new code, safely run programs, execute commands without affecting the application or system itself, and ensure proper security of the system under development. Furthermore, they’re helpful when you need to find malware or check suspicious programs that may contain viruses without any risk of infecting the system under test.
There are numerous types of sandboxes for various operating systems and platforms. This time, we consider the Windows sandboxing mechanism called AppContainer, which was introduced in Windows 8 to sandbox Windows Store apps.
In this article, we describe the capabilities of AppContainers and share our tips on how to create a Windows AppContainer, launch a process in it, and provide the AppContainer with access to required objects.
Written by: Egor Olehnovich, Software Developer, Apriorit Driver Development Team
What is an AppContainer?
Before we start creating AppContainers and running processes in them, let’s define what AppContainers are and why we need them.
The AppContainer environment is a restrictive process execution environment that protects applications and processes from hacking. This technology first appeared in Windows 8 and was developed for managing processes within the Universal Windows Platform (UWP).
AppContainers are sandboxes that isolate the runtime environment for a process or any code that runs in that process. Their goal is to block any possibility for malicious code to get inside the process address space.
Thanks to the isolation an AppContainer provides, an application only has access to the required resources specified by the developer. Even if malicious code manages to find and exploit a vulnerability in the launched AppContainer, it still has no chance to affect the rest of the system.
To ensure proper isolation, the AppContainer creates a security identifier (SID) that combines the identifiers of the user and the application. Therefore, credentials are unique for each user and application, meaning that an application can’t pass itself off as a user.
By isolating user data, we aim to prevent the use of such data to get access to system resources or get further into the system. AppContainers isolate credentials, devices, files, networks, and windows. Let’s explore this in detail:
- Device isolation means that applications in an AppContainer can’t access the camera, microphone, GPS, 3G/4G/5G modules, etc. However, the keyboard and mouse are always accessible for an application in an AppContainer regardless of the specified access permissions.
- File isolation blocks or restricts access to files and the registry, but you can grant access to certain files or a registry branch if needed. Moreover, an application launched in an AppContainer always has full access to memory resident files created specifically for that application.
- Network isolation involves isolating the application from any network resources, the internet, and the intranet. However, you can grant full access to any resources as required.
- Process isolation means that objects of the operating system kernel are put in the sandbox to protect other processes from interference.
- Window isolation means the AppContainer doesn’t let an application interfere with other windowed applications.
Processes in the AppContainer run with a low priority level, which means they don’t have access to most objects, as the integrity level for objects is medium by default. Moreover, the named objects created in the AppContainer are stored in the object manager catalog based on the AppContainer SID. Therefore, the code inside the AppContainer can’t cause any severe damage to other processes.
Being isolated, an AppContainer is protected from outside influence and can’t interfere with any objects or processes that run outside of the AppContainer.
AppContainers were designed specifically for Windows Store applications. But they also can be used for running applications that aren’t built for the UWP, ensuring the same level of security and isolation.
Now that we’ve clarified the theoretical part, let’s explore how to create an AppContainer and launch a process in it.
Creating an AppContainer
First, we need to create an AppContainer and receive the AppContainer SID.
For non-UWP applications, we can choose any string — for example, c++ std::string containerName = “MyContainer”. Selecting the same string will lead to the same SID, which means we can use this string to run several processes in one container.
As the first step, let’s create an AppContainer profile:
Knowing the containerName parameter, we can define whether the AppContainer exists or not. If the function results in an error, most likely the AppConatiner profile already exists.
In the AppContainer profile already exists, we have to extract the SID from it. Here’s an example on how to do that:
Creating a process in the AppContainer
Before we create a process in the AppContainer, we have to do some preparations.
The absolute minimum we need to do to create an AppContainer and launch a process in it is initialize a process attribute list. To do this, we can use the SECURITY_CAPABILITIES structure, which defines the security capabilities of the AppContainer. Using it, we indicate that we want to create a process inside the AppContainer.
Also, we can specify the permissions for the AppContainer, such as internet access, library access, and other features defined by the Windows runtime environment.
Here’s an example of how to manage the primary initialization of the required data and memory allotment for the structures needed to launch the process:
We have specified zero permissions for now. This means that once the application is launched, it will not have access to any resources. We have done this on purpose, and a bit further, we’ll show you how new permissions can be added on the go without rebooting the application.
Now we’re ready to create a process:
This way, we execute a process that has no access rights and is specified by the exePath command in the application container.
Granting an application access to resources
To provide our application with access to required resources (files, network, etc.), we need to follow these five steps:
1. Receive the container SID (if we don’t know it yet):
2. Initialize the EXPLICIT_ACCESS_W structure, which grants the required access to the process:
3. Get the security descriptor for the specified object.
A security descriptor is a data structure that consists of security information about securable objects. To generate a security descriptor for the specified object, use the following code:
4. Create a new access control list (ACL).
An ACL is a list of permissions attached to an object. Below is an example of how you can create a new ACL:
5. Set security information for the specified object:
After completing these steps, the processes in our container will gain access to the specified resources. Also, we don’t need to reboot the application to do this, which is a big plus.
Conclusion
Creating an AppContainer for Windows and using it for sandboxing processes and applications isn’t a great challenge. We hope this blog post answered all your questions about the nature of AppContainers and their functionality.
At Apriorit, we’re always ready to share our expertise and provide professional consultations on web application development. Don’t hesitate to contact us if your project requires help from an experienced team.
Apriorit — Specialized Software Development Company
We provide expert software engineering services to technology companies worldwide for over 18 years.