- Service Host
- Creating a service host
- Security
- Changes to Service Host grouping in Windows 10
- Separating SvcHost services
- Exceptions
- Memory footprint
- Что такое Service Host процесс (svchost.exe) и почему их так много?
- Что такое Service Host процесс
- Почему запущено так много Service Host процессов
- Что мне делать со всей этой информацией?
- Проверка связанных служб в диспетчере задач
- Проверка связанных сервисов с помощью Process Explorer
- Может ли этот процесс быть вирусом?
Service Host
The service host is the runtime environment for hosting a service within a process.
A service can configure one or more endpoints inside a service host.
Creating a service host
Before creating a service host, a service needs to define its endpoints. An endpoint in service host is specified in the WS_SERVICE_ENDPOINT structure and it is defined by the following information:
- An address, which is the physical URI on which the service will be hosted.
- A WS_CHANNEL_TYPE structure that specifies the type of the underlying channel for the endpoint.
- A WS_CHANNEL_BINDING structure that specifies the binding of the channel.
- A WS_SECURITY_DESCRIPTION structure that contains the security description for the endpoint.
- A WS_SERVICE_CONTRACT structure that represents the service contract for the endpoint.
- A WS_SERVICE_SECURITY_CALLBACK structure that specifies an authorization callback function for the endpoint.
- A WS_SERVICE_ENDPOINT_PROPERTY structure that contains an array of service endpoint properties.
Only one-way contracts are supported for SOAP over UDP, represented by WS_UDP_CHANNEL_BINDING in the WS_CHANNEL_BINDING enumeration.
After an endpoint is defined, it can be passed to the WsCreateServiceHost function, which takes an array of pointers to WS_SERVICE_ENDPOINT structures.
An application can optionally provide an array of service properties to WsCreateServiceHost to configure custom settings on the service host.
An application opens the service host to start accepting client requests.
After opening the service host, the application can close it if there are no more operations that require it. Note that this does not release its resources, and that it can be reopened with a subsequent call to WsResetServiceHost.
After closing the service host, an application may reset the service host for reuse.
When the application is done with the service host it can free the resources associated with the service host by calling the WsFreeServiceHost function. Note that WsCloseServiceHost must be called before calling this function.
For information on attaching a custom state to the service host, see User Host State
For information on authorization in a service host for a given endpoint, see Service Authorization.
For iinformation on implementing service operations and service contracts for a service, see the service operations and service contracttopics.
Security
An application can use the followin properties to control the amount of resources the service host allocates on behalf of the application:
Secure defaults are chosen for each of these properties, an application must be careful if it wishes to modify these properties. Beyond the above-mentioned properties, channel, listener and message specific properties can also be modified by the application. Refer to the security considerations of these components before modifying any of these settings.
In addition, the following application design considerations should be carefully evaluated when using WWSAPI service host API:
- When using MEX, applications should be careful not to disclose any sensitive data. As a mitigation, if the nature of the data being exposed through MEX is sensitive, applications may choose to configure the MEX endpoint with a secure binding requiring authentication at the very least and implement authorization as part of the endpoint using the WS_SERVICE_SECURITY_CALLBACK.
- By default rich error information through faults is disabled on service host by WS_SERVICE_PROPERTY_FAULT_DISCLOSURE property. It is upon the discretion of the application to send rich error information as part of the fault. However, this can result in information disclosure and thus it is recommended that this setting is only changed for debugging scenarios.
- Beyond validation performed for Basic Profile 2.0 and XML serialization, service host performs no validation on the data content received as part of service operation parameters. It is the responsibility of the application to perform all parameter validations on its own.
- Authorization is not implemented as part of service host. However, applications can implement their own authorization scheme using WS_SECURITY_DESCRIPTION and the WS_SERVICE_SECURITY_CALLBACK.
- It is the responsibility of the application to use secure bindings on its endpoint. Service host does not provide any security beyond what is configured on the endpoint.
The following API elements are used with the service host.
Changes to Service Host grouping in Windows 10
The Service Host (svchost.exe) is a shared-service process that serves as a shell for loading services from DLL files. Services are organized into related host groups, and each group runs inside a different instance of the Service Host process. In this way, a problem in one instance does not affect other instances. Service Host groups are determined by combining the services with matching security requirements. For example:
- Local Service
- Local Service No Network
- Local Service Network Restricted
- Local System
- Local System Network Restricted
- Network Service
Separating SvcHost services
Beginning with Windows 10 Creators Update (version 1703), services that were previously grouped will instead be separated — each will run in its own SvcHost process. This change is automatic for systems with more than 3.5 GB of RAM running the Client Desktop SKU. On systems with 3.5 GB or less RAM, we’ll continue to group services into a shared SvcHost process.
Benefits of this design change include:
- Increased reliability by insulating critical network services from the failure of another non-network service in the host, and adding the ability to restore networking connectivity seamlessly when networking components crash.
- Reduced support costs by eliminating the troubleshooting overhead associated with isolating misbehaving services in the shared host.
- Increased security by providing additional inter-service isolation
- Increased scalability by allowing per-service settings and privileges
- Improved resource management through per-service CPU, I/O and memory management and increase clear diagnostic data (report CPU, I/O and network usage per service).
To see the refactoring behavior, create a Windows 10 version 1703 VM and configure the memory settings as follows:
- To see grouped processes, set the RAM to 3484 MB or less. Restart the VM and then open Task Manager.
- To see separated processes, set the RAM to 3486 MB or greater. Restart the VM and then open Task Manager.
Refactoring also makes it easier to view running processes in Task Manager. You can look at Task Manager and know exactly which service is using what resources, without having to expand many separate host groups.
For example, here are the running processes displayed in Task Manager in Windows 10 version 1607:
Compare that to the same view of running processes in Windows 10 version 1703:
Exceptions
Some services will continue to be grouped on PCs running with 3.5GB or higher RAM. For example, the Base Filtering Engine (BFE) and the Windows Firewall (Mpssvc) will be grouped together in a single host group, as will the RPC Endpoint Mapper and Remote Procedure Call services.
If you need to identify services that will continue to be grouped, in addition to seeing them in Task Manager and using command line tools, you can look for the SvcHostSplitDisable value in their respective service keys under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services.
The default value of 1 prevents the service from being split.
For example, this is the registry key configuration for BFE:
Memory footprint
Be aware that separating services increases the total number of SvcHost instances, which increases memory utilization. (Service grouping provided a modest reduction to the overall resource footprint of the services involved.)
Что такое Service Host процесс (svchost.exe) и почему их так много?
Е сли Вы когда-нибудь просматривали Диспетчер задач, то, возможно, Вы задавались вопросом, почему запущенно так много Service Host процессов. Вы не можете убить их, и Вы точно не запускали их. Итак, что это?
Что такое Service Host процесс
Вот ответ, согласно Microsoft:
Svchost.exe — это общее имя хоста для служб, которые запускаются из библиотек динамической компоновки.
Но это не очень помогло нам понять что это. Некоторое время назад корпорация Майкрософт начала изменять большую часть функциональности Windows с использования внутренних служб Windows (которые запускались из EXE-файлов) на использование DLL-файлов. С точки зрения программирования это делает код более многоразовым и, возможно, легче поддерживать в актуальном состоянии. Проблема в том, что Вы не можете запускать DLL-файл непосредственно из Windows так же, как и исполняемый файл. Вместо этого оболочка, загружаемая из исполняемого файла, используется для размещения этих DLL-сервисов. Так появился процесс Service Host (svchost.exe).
Почему запущено так много Service Host процессов
Если Вы когда-нибудь просматривали раздел «Службы» в панели управления, то Вы, вероятно, заметили, что Windows требует много сервисов. Если каждая отдельная служба будет работать под одним Service Host процессом, то отказ в одной службе может привести к сбою всей Windows. Поэтому они отделены друг от друга.
Службы организованы в логические группы, которые все связаны друг с другом, а затем создается один экземпляр Service Host процесса для размещения каждой группы. Например, один Service Host процесс запускает три службы, связанные с брандмауэром. Другой Service Host процесс может запускать все службы, связанные с пользовательским интерфейсом, и так далее. На приведенном ниже изображении, например, Вы можете видеть, что один Service Host (узел службы) процесс запускает несколько связанных сетевых служб, а другой запускает службы, связанные с удаленными вызовами процедур.
Что мне делать со всей этой информацией?
Честно говоря, не так много. Во времена Windows XP (и предыдущих версий), когда на компьютерах было гораздо больше ограниченных ресурсов и операционные системы не были столь тонко настроены, часто рекомендовалось останавливать Windows от запуска ненужных служб. Теперь мы больше не рекомендуем отключать службы. Современные ПК, как правило, обладают большой памятью и мощными процессорами. Добавьте к этому тот факт, что способ обработки Windows-служб в современных версиях (в том числе и запущенных) был оптимизирован, и отключение служб, которые, по Вашему мнению, Вам не нужны, действительно не имеют большого влияния.
Тем не менее, если Вы заметили, что конкретный экземпляр Service Host или связанная с ним служба вызывает проблемы, такие как постоянное чрезмерное использование процессора или ОЗУ, то Вы можете проверить сервисы, которые задействованы. Это может по крайней мере дать Вам представление о том, где начать поиск и устранение неисправностей. Существует несколько способов узнать, какие службы содержатся в определенном экземпляре Service Host. Вы можете посмотреть это в диспетчере задач или использовать отличное стороннее приложение под названием Process Explorer.
Проверка связанных служб в диспетчере задач
Если вы используете Windows 8 или 10, процессы отображаются на вкладке «Процессы» диспетчера задач. Если процесс служит хостом для нескольких служб, то Вы можете увидеть эти службы, просто развернув процесс. Это позволит легко определить, какие службы относятся к каждому экземпляру Service Host процесса.
Вы можете щелкнуть правой кнопкой мыши по любой отдельной службе, чтобы остановить службу, просмотреть ее в приложении «Службы» или даже выполнить поиск в Интернете для получения информации о службе.
Если Вы используете Windows 7, то все немного по-другому. Диспетчер задач Windows 7 не группирует процессы таким же образом и не отображает обычные имена процессов — он показывает только все экземпляры «svchost.exe». Нужно немного больше действий, чтобы определить службы, связанные с конкретным экземпляром «svchost.exe».
На вкладке «Процессы» диспетчера задач в Windows 7 щелкните правой кнопкой мыши по определенному процессу «svchost.exe», а затем выберите вариант «Перейти к службам».
Это действие перенаправит Вас на вкладку «Службы», где все службы, запущенные под процессом «svchost.exe», будут выбраны.
Затем Вы можете увидеть полное имя каждой службы в столбце «Описание», чтобы можно было отключить эту службу, если Вы не хотите ее запускать или устранить неполадки, если они возникают.
Проверка связанных сервисов с помощью Process Explorer
Microsoft также предоставляет отличный инструмент для работы с процессами в составе линейки Sysinternals. Просто загрузите Process Explorer и запустите его — это портативное приложение, поэтому нет необходимости его устанавливать.
Для наших целей, однако, Process Explorer группирует связанные службы в каждом экземпляре «svchost.exe». Они перечислены по именам файлов, но их полные имена также отображаются в столбце «Описание». Вы также можете навести указатель мыши на любой из процессов «svchost.exe», чтобы увидеть всплывающее окно со всеми службами, связанными с этим процессом, — даже теми, которые в настоящее время не выполняются.
Может ли этот процесс быть вирусом?
Сам процесс является официальным компонентом Windows. Возможно, что вирус заменил реальный Service Host собственным исполняемым файлом, что очень маловероятно. Если Вы хотите быть уверенным, то можете проверить расположение файла процесса. В диспетчере задач щелкните правой кнопкой мыши на любом Service Host процессе и выберите опцию «Открыть расположение файла».
Если файл хранится в папке Windows\System32, то можете быть уверены, что это не вирус.
Тем не менее, если Вы хотите быть спокойным, то Вы всегда можете просканировать систему на вирусы с помощью антивирусного сканера.