Windows service local system local service

Как известно, службы Windows представляют собой одно из наиболее излюбленных мест для атак на операционную систему. В худшем (для нас, конечно) случае атакующий получает возможность действовать на атакованном компьютере в контексте учетной записи, от имени которой запущена взломанная служба. И если эта учетная запись обладает административными правами, то фактически злоумышленник получает полный контроль над компьютером. От версии к версии в Windows появляются новые механизмы, обеспечивающие дополнительную изоляцию служб и, как следствие, усиливающие безопасность системы в целом. Я хотел бы вкратце рассмотреть, что принципиально изменилось в этом направлении за последние несколько лет.

Первые существенные изменения в механизмах защиты служб появились в Windows XP Service Pack 2. Сейчас уже сложно себе это представить, но до выхода SP2 все службы самой операционной системы запускались в контексте встроенной учетной записи Local System, обладающей на компьютере максимально полными административными правами. SP2 добавил еще две записи: Local Service и Network Service. Принципиальные отличия трех перечисленных записей можно найти в табл. 1.

Учетная запись Локальные ресурсы Сетевые ресурсы
Local System Полный доступ ко всем ресурсам компьютера Подключение к сетевым ресурсам в контексте учетной записи компьютера, на котором запущена
Local Service Права стандартного пользователя + небольшой набор дополнительных привилегий Анонимное подключение к сетевым ресурсам
Network Service Права стандартного пользователя + небольшой набор дополнительных привилегий Подключение к сетевым ресурсам в контексте учетной записи компьютера, на котором запущена. Маркер доступа также содержит SID групп Everyone и Authenticated Users

Таблица 1

Соответственно, начиная с Windows XP SP2, администратор мог настраивать запуск службы в контексте одной из встроенных учетных записей, локальной или доменной учетной записи. Тем не менее, большая часть служб самой Windows по-прежнему запускается в контексте Local System. Но даже если абстрагироваться от этого, ситуация, когда несколько служб запускаются в контексте одной и той же учетной записи, приводит к тому, что успешный взлом одной службы, пусть даже без административных привилегий, потенциально открывает для атакующего любые другие ресурсы, к которым имеет доступ учетная запись взломанной службы.

В Windows Vista появилось несколько механизмов, повышающих изоляцию служб. Я остановлюсь на двух.
Первый механизм – это уникальный идентификатор безопасности службы (Service SID). Данный SID генерируется для каждой службы путем хеширования имени службы с помощью алгоритма SHA-1. К результату добавляется префикс S-1-5-80-. Просмотреть SID службы можно с помощью команды sc showsid, указав в качестве параметра имя службы (см. рис. 1).

image

Рис. 1

Вы можете поэкспериментировать, например, со службой W32Time. Для любой папки на NTFS в настройках разрешений (permissions) нужно лишь ввести имя пользователя в формате NT SERVICE\<имя службы>, в нашем случае NT SERVICE\w32time (см. рис 2).

image

Рис. 2

Нажимаете Check Names, затем ОК и видите пользователя (см. рис. 3), которому можно назначать права.

Рис. 3

Еще раз подчеркну, что w32time не является объектом-пользователем. Это – SID, но раз так, его можно использовать в списках ACL, причем как в графическом интерфейсе, так и в командной строке и программным путем. Более того, сервисные SID-ы можно использовать в настройках Windows Firewall, применяя те или иные правила к конкретной службе, точнее конкретному Service SID.

Второй изменение, появившееся в Vista, это идентификаторы безопасности нового типа – Write Restricted SID. Если служба помечена типом Write Restricted SID, то ее SID добавляется в ее же маркере доступа в специальный список – Restricted SID list. При попытке такой службы записать что-либо в какой-либо файл алгоритм проверки прав доступа несколько изменяется. А именно, служба сможет записать в файл только в том случае, если разрешение Write дано явным образом SID-у этой службы, либо группе Everyone.
Например, учетная запись ServiceAccount1 некоторой службы Service1 является членом группы Group1. Группа Group1 и только она имеет разрешение Write на папку Folder1. Что произойдет, если служба попытается что-то изменить в папке Folder1? В обычной ситуации ServiceAccount1 получит возможность записи в папку за счет членства в Group1. Но если служба Service1 помечена типом Write Restricted SID, то ее маркер доступа обрабатывается иначе, и она не сможет записать что-либо в папку, поскольку ей явным образом не дано разрешение Write, равно как не дано это право и Everyone.
Просмотреть тип идентификатора безопасности можно с помощью команды sc qsidtype (см. рис. 4).

image

Рис. 4

В частности, на рис. 4 вы видите, что служба Windows Firewall относится как раз к упомянутому типу. Естественно, что введен этот тип был для того, чтобы дополнительно ограничить возможности службы (возможности стереть или перезаписать что-либо) в случае ее успешного взлома. Надо также добавить, что данный механизм предназначен в первую очередь не для администраторов систем, а для разработчиков служб. Только бы пользовались.

В Windows 7 и Windows Server 2008 R2 работа над изоляцией служб была продолжена. Появились виртуальные учетные записи (virtual accounts) и управляемые учетные записи служб (managed service accounts). А собственно в чем проблема? Нужно изолировать службы – давайте создадим нужное количество локальных (или доменных) учетных записей пользователей. Для каждой критически важной службы свой account. Да, это решение. Но для локальных служб, которым не нужен сетевой доступ к ресурсам, необходимо вручную задавать пароли, длинные и сложные. И также вручную их периодически обновлять. Ну, раз уж мы за безопасность. Для служб, которые должны по сети обращаться к ресурсам в контексте доменных учетных записей, плюс к этому еще нужно регистрировать Service Principal Name (SPN), свой для каждой службы. Это неудобно. Но неудобство становится реальной проблемой, когда служба из-за просроченного пароля не может стартовать. А админ просто забыл сменить для нее пароль.

Так вот для локальных служб вы можете использовать virtual accounts. Виртуальная учетная запись используется только для запуска конкретной службы, точнее для создания контекста безопасности конкретной службы. Вы не найдете эту запись среди пользователей в Computer Management. И, тем не менее, это – account, со своим уникальным SID-ом, со своим пользовательским профилем. А стало быть, вы можете назначать ему разрешения и, тем самым, разграничивать права доступа и четко их контролировать. Но также как и в случае с Local System, Local Service и Network Service операционная система берет на себя задачи управления паролями для virtual accounts. Мы изолируем нужные службы, и у нас не болит голова о паролях.

Чтобы создать виртуальную учетную запись, нужно в настройках службы указать в качестве учетной записи: NT SERVICE\<имя службы> (см. рис 5)

image

Рис. 5

После запуска службы virtual account отобразится в консоли Services (рис. 6), а в папке Users вы заметите появление нового пользовательского профиля.

image

Рис. 6

По формату это очень напоминает сервисный SID. Но подчеркну, это не просто дополнительный уникальный SID для службы как в Vista, это отдельная учетная запись и, соответственно, другой уровень изоляции. По умолчанию виртуальные учетные записи используются, например, для пулов приложений (application pool) в IIS 7.5 в Windows Server 2008 R2. Надо иметь в виду, что virtual accounts предназначены для локального использования. Если служба, запущенная в контексте virtual account, обращается по сети, то это обращение происходит от имени учетной записи компьютера, на котором служба запущена. Если же необходимо, чтобы служба, например SQL Server, работала по сети от имени доменной учетной записи, то здесь как раз помогут managed service accounts. С ними, однако, связано больше тонкостей, и их рассмотрение выходит за рамки данного поста. Более подробно с MSA можно познакомиться здесь.

Перечисленные мною механизмы изоляции служб на этом не заканчиваются. Можно еще упомянуть об изоляции нулевого сеанса, уровнях целостности, механизме DEP. Я сосредоточился на тех, которые, как мне кажется, в меньшей степени известны, но при этом имеют вполне практический смысл для администратора. Ну и конечно, работа по усилению защищенности служб в последующих версиях Windows будет продолжена.

codeling 1602 — 6666
@2017-05-04 13:41:17

In earlier versions of Windows, most system services run under the powerful SYSTEM (aka Local System) account. Because most services don’t need SYSTEM-level authority, Microsoft created the two new principals with less authority than SYSTEM and reconfigured many of the services on Windows 2003 and XP to run as either Local Service or Network Service.

  • Local System is a very high-privileged built-in account. It has extensive privileges on the local system and acts as the computer on the network. The actual name of the account is «NT AUTHORITY\SYSTEM«.
  • The Local Service account is a built-in account that has the same level of access to resources and objects as members of the Users group. This limited access helps safeguard the system if individual services or processes are compromised. Services that run as the Local Service account access network resources as a null session without credentials. Be aware that the Local Service account is not supported for the SQL Server or SQL Server Agent services. The actual name of the account is «NT AUTHORITY\LOCAL SERVICE«.
  • The Network Service account is a built-in account that has more access to resources and objects than members of the Users group. Services that run as the Network Service account access network resources by using the credentials of the computer account. The actual name of the account is «NT AUTHORITY\NETWORK SERVICE«

Most services do not need such a high privilege level. If your service does not need these privileges, and it is not an interactive service, consider using the LocalService account or the NetworkService account.

Comments

You must Sign In to comment on this topic.

© 2025 Digcode.com


 15 June 2012
|
 Edit Post

 LocalService, LocalSystem, NetworkService, Access is denied, TopShelf, WCF, Your process does not have access rights to this namespace





Overview

Recently I experienced a bit of confusion over the users you can run a TopShelf service as, in particular, one which started a WCF endpoint.

I would get an error, with a nice stack trace, but research on the Internet didn’t yield me an answer. — Once I had a solution, I thought I would share, so others don’t have to spend as long as I did try to resolve the issue.

So, the error I got was this:

System.ServiceModel.AddressAccessDeniedException: HTTP could not register URL http://+:8082/MyWCFService/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details). ---> System.Net.HttpListenerException: Access is denied
at System.Net.HttpListener.AddAllPrefixes()
at System.Net.HttpListener.Start()
at System.ServiceModel.Channels.SharedHttpTransportManager.OnOpen()

With a pretty long stack trace after!

Now, this does look like a useful error, with a link to a Microsoft post (http://go.microsoft.com/fwlink/?LinkId=70353).  Brilliant I thought until I found clicking the link resulted in this…

This was far from helpful

The first thing that confused me was the URL, which changed from “http://localhost:8082/MyWCFService” changed to “http://+:8082/MyWCFService/”. When looking at URLs, it would seem that the “+” symbol means “Generic host”, therefore it could be anything, as long as it is on this PC. The config could state “http://127.0.0.1:8082/MyWCFService/” whereby localhost and 127.0.0.1 are the same. The log file only shows the 1 value, a “+”.

A little scout around and I was able to understand that the user I was running my service under didn’t have sufficient permissions, and I should run as a more elevated “Administrator” user, sure enough, setting my windows service to run as the system admin did the trick, though, TopShelf doesn’t offer this as a default install address, you can just have:

  • LocalService
  • NetworkService
  • LocalSystem

I eventually decided to work my way through the users to find out which one had sufficient permission to start the service, and it turns out “LocalSystem” does. – Which at the time, I thought was least likely to work!

Sure enough, I could change my TopShelf setup to be:

hc.Service<MyWCFService>(sc =>
{
sc.SetServiceName(Name);
sc.ConstructUsing(() => new MyWCFService());
sc.WhenStarted(cs => cs.OnStart());
sc.WhenStopped(cs => cs.OnStop());
});
hc.RunAsLocalSystem();
hc.SetDescription(Description);
hc.SetDisplayName(DisplayName);
hc.SetServiceName(Name);

And this worked like a charm!

This got me thinking about the 3 “RunAs” I had to choose between, and what purpose I would use each of them for, so lifted from a TechNet post  (http://technet.microsoft.com/en-us/library/cc782435(v=ws.10).aspx).

LocalService

The Local Service account is a special, built-in account that is similar to an authenticated user account. The Local Service account has the same level of access to resources and objects as members of the Users group. This limited access helps safeguard your system if individual services or processes are compromised. Services that run as the Local Service account access network resources as a null session with no credentials.

NetworkService

The Network Service account is a special, built-in account that is similar to an authenticated user account. The Network Service account has the same level of access to resources and objects as members of the Users group. This limited access helps safeguard your system if individual services or processes are compromised. Services that run as the Network Service account access network resources using the credentials of the computer account.

LocalSystem

The Local System account is a powerful account that has full access to the system, including the directory service on domain controllers. If a service logs on to the Local System account on a domain controller, that service has access to the entire domain. Some services are configured by default to log on to the Local System account. Do not change the default service setting.

I hope that this post will help other to overcome the user problem I encountered faster than I did!




A, Windows Services Overview

Service and process

Windows service is a system automatically, and the process does not require user interaction, it can be long-running executable application. These services can be started automatically when the computer starts, you can pause and restart and does not display any user interface. This service is ideal for use on the server, or at any time, in order not to affect other users working on the same computer, in case you need to run the function for a long time. Also can be different from the specific user account logged-on user or the default security context of the computer account to run the service.

Examples of processes are running, the system will run in the process allocates CPU, memory and other resources.

Whether or not a service is running, all in your hard disk only when it is actually running, the operating system will allocate real memory, CPU time and other resources to slice it, this corresponds to a run on a «process.»

Service Control Manager

Windows Service Control Manager (SCM) is responsible for configuring the service, start and stop them.

SCM control panel via the Control Panel | System and Security | Administrative Tools | Services Access. It displays the names of all configuration services, description, listing status, startup type, and user names.

service status

Services in a variety of states. Some states are required, others are optional. Stop all services are running and must support two basic states. The status display in the SCM.

The third alternative is to suspend the state. No installation is another implicit state.

Services can convert between these states, as shown below.

Second, the operation of the service

Configuration Service

Double-click a service in the SCM can be configured for the service.

Content can be configured Startup type, login identities and recovery operations.

You can also view the service relies on dependencies in the system set up and who else is dependent on the current service.

Start Service

A status bar is not displayed, right-click in the SCM, the startup type to Manual or automatic service, you can select the start menu to start the service.

Out of service

In SCM, right-click the status bar as a service is running, you can select the start menu to stop the service. You can also select to restart the menu, stop, and then start the service.

Third, introduce common services

Local System (Local System)

The account has a very high authority.

First of all, the account also belongs to the local Administrators group user, so all users to the local Administrators

The operation of the account be performed can be performed. Secondly, the account can also control the file permissions (NTFS file system)

And registry permissions, and even occupy the owner permission to get access qualifications. If the machine is in a domain, then run

Service under the Local System account can also use the account to get the machine to other machines in the same forest in automatic identification

certificate. The last point in the process is to run under the Local System can use a null session (null session) to access network resources. Moreover, the core components in a number of other Windows user mode also runs under the account, for example system32 / Smss. Exe and so on.

It should be noted that the process running under this account using HKEY_USERS /. Default account configuration, so it

Configuration can not access other accounts.

For example, a service running in Local System account are:

Windows Update (Windows Update)

Com + (Component Object Model Management (COM +) configuration and trace components)

Messenger Service (SMS support and related functions)

Task Scheduler (on this computer to configure and schedule automated tasks)

Server (support the computer network file, print, and named pipe sharing)

Windows Installer (add, modify and delete a Windows Installer package (*. Msi, *. Msp) provided by the application)

Network Service (network service)

Network Service account is the default owner of the machine part of local authority accounts that can access network resources in the name of the computer. But he did not so much Local System privileges, services running in this account will be submitted to the credentials to access the remote computer based on the actual environment.

Network Service account usually has access Network Service, Everyone group, as well as authenticated users have access to resources.

Process running under this account using a network account profile HKEY_USERS / S-1-5-20 and Documents and

Settings/NetworkService

For example, the Network Service account to run the service are:

Distr ibuted Transact ion Coordinator (coordination across multiple databases, message queues, file systems, etc. The transaction manager resource)

DNS Client (DNS Client service)

Performance Logs and Alerts (Performance Logs and Alerts)

Remote Procedure Call (service control manager COM and DCOM servers. It performs and COM

Object DCOM server activation requests, object exporter parsing and distributed garbage collection)

Workstation (using the SMB protocol to create and maintain a connection between the client and the remote network server)

IPsec Policy Agent (Internet Protocol security (IPsec) supports network-level peer authentication, data origin authentication, data integrity, data confidentiality (encryption), and replay protection. This service is enforced by the IP Security Policy snap-in or command IPsec policy line tool «netsh ipsec» created.)

Local Service (local service)

Local Service account is the default local accounts have minimum rights and anonymity of identity in the network credential.

The difference between process and operation running under this account to process under the Network Service account is that the process runs under the Local Service account can only access network resources that allow anonymous access.

Run the configuration file using the account under the Local Service is HKU / S-1-5-19 and Documents and

Settings/LocaI Service

For example, a service run as Local Service account are:

Remote Registry (so that remote users to modify registry settings on this computer)

Smart Card (management take this computer access to read smart cards)

SSDP (SSDP discovery using the equipment and service agreements)

DHCP Client (registered for this computer and update the IP address)

Base Filtering Engine (managed firewalls and Internet Protocol security (IPsec) policies and implements user mode filtering)

Network List Service (attribute identifies the computer is connected to the network, collects and stores these networks, and notifies applications when these properties change)

Fourth, the relevant PowerShell command

Query Management Services Directive

Query service status

Start the Automatic Updates service

Check in service

Command View

Filtering Service

Out of service

Obtain the content of a file

Search win32_service WmiObject this class of machine

Часто в Windows 10 пользователям приходится сталкиваться с ситуацией, что процесс «Узел службы: локальная система» / «Service Host: Local System» потребляет много ресурсов. Процесс может сильно использовать память, процессор или диск. Проблема может возникать после установки обновления, во время выполнения задач обслуживания системы, после выхода из режима сна или гибернации, или сама по себе.

Service Host: Local System (Узел службы: локальная система) – это набор системных процессов и полностью приостановить или завершить процесс целиком через «Диспетчер задач» нельзя. В состав процесса Service Host: Local System может входить несколько различных служб (в зависимости от настроек компьютера и версии Windows 10).

Узел службы: локальная система грузит компьютер

Чаще всего, чтобы исправить проблему, достаточно просто перезагрузить компьютер, поскольку ошибка вызвана единичным случаем сбоя одной из служб, входящих в группу. Однако если перезагрузки оказалось недостаточно и сразу после запуска компьютера узел службы грузит диск, попробуйте временно отключите антивирус и проверьте, сохраняется ли нагрузка на компьютер. Также стоит попробовать в настройках антивируса отключить его автоматический запуск при загрузке Windows.
Чтобы уменьшить нагрузку на систему можно попробовать перезапустить или отключить одну из служб, входящих в этот процесс. Но из диспетчера задач нельзя определить какая именно из служб, входящих в Service Host: Local System, сильно нагружает систему (обратите внимание, что в диспетчере задач может быть несколько процессов с именем Service Host: Local System).

Service Host: Local System в Windows 10

Чтобы понять какая именно из служб, входящих в состав «Узел службы: локальная система» вызывает большую нагрузку на систему можно воспользоваться бесплатной утилитой от Microsoft – Process Explorer (https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer). Скачайте архив с утилитой и распакуйте его. Запустите программу procexp64.exe (на Windows 10 x64) с правами администратора.

Отсортируйте процессы по использованию памяти или CPU, щелкнув по заголовку столбца в Process Explorer. Найдите среди процессов процесс svchost.exe, который потребляет больше всего ресурсов системы. Наведите курсор на процесс svchost.exe и вы увидите, какие системные службы работают внутри данного процесса.

svchost.exe анализ в Process Explorer

Теперь щелкните правой кнопкой по процессу и выберите свойства. В окне свойств процесса перейдите на вкладку Services. Здесь также будет отображен список служб, которые работают под этим процессом. Обратите внимание, что для каждой службы указана файл библиотеки, которая используется данной службой (например, wuaueng.dll или usocore.dll).

службы в svchost.exe

Теперь перейдите на вкладку Threads. Здесь содержатся все потоки, выполняемые в рамках данной службы. Отсортируйте потоки по использованию CPU и Cycles Delta, и найдите имя службы и/или библиотеки, которая вызывает высокую загрузку.

Попробуйте временно приостановить или отключить данный процесс с помощью кнопок Kill и Suspend. Подождите некоторое время и проверьте, не снизилась ли ненормальная загрузка системы. Таким образом вы можете найди и приостановить все службы, которые могут вызывают высокое использование памяти и диска.

Вы можете сопоставить имена библиотек с именами и служб и временно отключить из в консоли управления службами (services.msc).

отключить/приостановить службы

Если вы обнаружили проблемную службу, чтобы исправить проблему попробуйте:

  1. Выполнить проверку образа системы и системных файлов с помощью команд:DISM.exe /Online /Cleanup-image /Restorehealth
    sfc /scannow
  2. Очистите папку обновлений SoftwareDistribution командами:net stop wuauserv
    net stop bits
    cd %systemroot%
    Ren SoftwareDistribution SoftwareDistribution.old
    rd SoftwareDistribution.old /s /q
    net start bits
    net start wuauserv
  3. Если проблема возникла недавно и в системе включена функция автоматического создания точек восстановления, можно воспользоваться одной из последних точек, чтобы вернуть настройки системы к прежнему состоянию;
  4. Обновите ваш билд Windows 10 и установите все последние кумулятивные обновления.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Rtf для windows 10
  • Обзор windows 7 ultimate
  • Приложения для windows home server
  • Как открыть диск линукс на windows
  • Intel extreme tuning utility windows 7 x64