Windows service account user

Service User Accounts

Each service executes in the security context of a user account. The user name and password of an account are specified by the CreateService function at the time the service is installed. The user name and password can be changed by using the ChangeServiceConfig function. You can use the QueryServiceConfig function to get the user name (but not the password) associated with a service object. The service control manager (SCM) automatically loads the user profile.

When starting a service, the SCM logs on to the account associated with the service. If the log on is successful, the system produces an access token and attaches it to the new service process. This token identifies the service process in all subsequent interactions with securable objects (objects that have a security descriptor associated with them). For example, if the service tries to open a handle to a pipe, the system compares the service’s access token to the pipe’s security descriptor before granting access.

The SCM does not maintain the passwords of service user accounts. If a password is expired, the logon fails and the service fails to start. The system administrator who assigns accounts to services can create accounts with passwords that never expire. The administrator can also manage accounts with passwords that expire by using a service configuration program to periodically change the passwords.

If a service needs to recognize another service before sharing its information, the second service can either use the same account as the first service, or it can run in an account belonging to an alias that is recognized by the first service. Services that need to run in a distributed manner across the network should run in domain-wide accounts.

You can specify one of the following special accounts instead of specifying a user account for the service:

Service Accounts

Applies to

  • Windows 10
  • Windows Server 2016

This topic for the IT professional explains group and standalone managed service accounts, and the computer-specific virtual computer account, and it points to resources about these service accounts.

Overview

A service account is a user account that is created explicitly to provide a security context for services running on Windows Server operating systems. The security context determines the service’s ability to access local and network resources. The Windows operating systems rely on services to run various features. These services can be configured through the applications, the Services snap-in, or Task Manager, or by using Windows PowerShell.

This topic contains information about the following types of service accounts:

Standalone managed service accounts

A managed service account is designed to isolate domain accounts in crucial applications, such as Internet Information Services (IIS), and eliminate the need for an administrator to manually administer the service principal name (SPN) and credentials for the accounts.

To use managed service accounts, the server on which the application or service is installed must be running at least Windows ServerВ 2008В R2. One managed service account can be used for services on a single computer. Managed service accounts cannot be shared between multiple computers, and they cannot be used in server clusters where a service is replicated on multiple cluster nodes. For this scenario, you must use a group managed service account. For more information, see Group Managed Service Accounts Overview.

In addition to the enhanced security that is provided by having individual accounts for critical services, there are four important administrative benefits associated with managed service accounts:

You can create a class of domain accounts that can be used to manage and maintain services on local computers.

Unlike domain accounts in which administrators must reset manually passwords, the network passwords for these accounts are automatically reset.

You do not have to complete complex SPN management tasks to use managed service accounts.

Читайте также:  Установка линукс manjaro рядом с виндовс 10

Administrative tasks for managed service accounts can be delegated to non-administrators.

Software requirements

Managed service accounts apply to the Windows operating systems that are designated in the Applies To list at the beginning of this topic.

Group managed service accounts

Group managed service accounts are an extension of the standalone managed service accounts, which were introduced in Windows ServerВ 2008В R2. These are managed domain accounts that provide automatic password management and simplified service principal name (SPN) management, including delegation of management to other administrators.

The group managed service account provides the same functionality as a standalone managed service account within the domain, but it extends that functionality over multiple servers. When connecting to a service that is hosted on a server farm, such as Network Load Balancing, the authentication protocols that support mutual authentication require all instances of the services to use the same principal. When group managed service accounts are used as service principals, the Windows Server operating system manages the password for the account instead of relying on the administrator to manage the password.

The Microsoft Key Distribution Service (kdssvc.dll) provides the mechanism to securely obtain the latest key or a specific key with a key identifier for an Active Directory account. This service was introduced in Windows Server 2012, and it does not run on previous versions of the Windows Server operating system. The Key Distribution Service shares a secret, which is used to create keys for the account. These keys are periodically changed. For a group managed service account, the domain controller computes the password on the key that is provided by the Key Distribution Services, in addition to other attributes of the group managed service account.

Practical applications

Group managed service accounts provide a single identity solution for services running on a server farm, or on systems that use Network Load Balancing. By providing a group managed service account solution, services can be configured for the group managed service account principal, and the password management is handled by the operating system.

By using a group managed service account, services or service administrators do not need to manage password synchronization between service instances. The group managed service account supports hosts that are kept offline for an extended time period and the management of member hosts for all instances of a service. This means that you can deploy a server farm that supports a single identity to which existing client computers can authenticate without knowing the instance of the service to which they are connecting.

Failover clusters do not support group managed service account s. However, services that run on top of the Cluster service can use a group managed service account or a standalone managed service account if they are a Windows service, an App pool, a scheduled task, or if they natively support group managed service account or standalone managed service accounts.

Software requirements

Group managed service accounts can only be configured and administered on computers running at least Windows Server 2012, but they can be deployed as a single service identity solution in domains that still have domain controllers running operating systems earlier than Windows Server 2012. There are no domain or forest functional level requirements.

A 64-bit architecture is required to run the Windows PowerShell commands that are used to administer group managed service accounts.

A managed service account is dependent on encryption types supported by Kerberos. When a client computer authenticates to a server by using Kerberos protocol, the domain controller creates a Kerberos service ticket that is protected with encryption that the domain controller and the server support. The domain controller uses the account’s msDS-SupportedEncryptionTypes attribute to determine what encryption the server supports, and if there is no attribute, it assumes that the client computer does not support stronger encryption types. The Advanced Encryption Standard (AES) should always be explicitly configured for managed service accounts. If computers that host the managed service account are configured to not support RC4, authentication will always fail.

Читайте также:  Стадии установки windows 10

NoteВ В Introduced in WindowsВ ServerВ 2008В R2, the Data Encryption Standard (DES) is disabled by default. For more information about supported encryption types, see Changes in Kerberos Authentication.

Group managed service accounts are not applicable in Windows operating systems prior to Windows Server 2012.

Virtual accounts

Virtual accounts were introduced in Windows ServerВ 2008В R2 and WindowsВ 7, and are managed local accounts that provide the following features to simplify service administration:

The virtual account is automatically managed.

The virtual account can access the network in a domain environment.

No password management is required. For example, if the default value is used for the service accounts during SQL Server setup on Windows ServerВ 2008В R2, a virtual account that uses the instance name as the service name is established in the format NT SERVICE\ .

Services that run as virtual accounts access network resources by using the credentials of the computer account in the format \ $.

For information about how to configure and use virtual service accounts, see Service Accounts Step-by-Step Guide.

Software requirements

Virtual accounts apply to the Windows operating systems that are designated in the Applies To list at the beginning of this topic.

See also

The following table provides links to additional resources that are related to standalone managed service accounts, group managed service accounts, and virtual accounts.

Управляемые учётные записи служб (Managed Service Accounts)

Есть способ, который позволяет узнать пароль администратора в случае, если какая-либо служба запускается от его имени.
Пароли учетных записей, от которых запускаются службы Windows, хранятся в зашифрованном виде в реестре (LSA Secrets) по пути:

Существуют способы, которые позволяют извлечь пароли из LSA Secrets:

  • Скопировать путь реестра во временный путь, а затем расшифровать зашифрованные пароли
  • Использовать теневые копии
  • Использовать специальные утилиты для работы с процессом lsass.exe

Попробуем получить пароль от учетной записи под которой запускается служба SQL Server.
Имеется:
Контроллер домена на Windows Server 2012 R2
SQL Server Express 2012
При установке SQL Server, для запуска службы, специально укажем существующую доменную учётную запись (пароль меньше 14 символов).

Воспользуемся утилитой gsecdump для извлечения паролей.
Запустим PowerShell от имени администратора и выполним команду: gsecdump-v2b5.exe -l
Результат:

Чтобы защититься от такого рода атак в Windows Server 2008 R2 был придуман механизм Managed Service Accounts.
Managed Service Accounts являются управляемыми учетными записями в домене, которые обеспечивают автоматическое управление паролями и упрощенное управление именами служб-участников, включая делегирование управления другим администраторам.
Преимущества управляемых учетных записей служб:

  • Автоматическая смена паролей. По умолчанию смена пароля – раз в 30 дней
  • Сложный пароль. Используется комплексный автоматически генерируемый пароль из 240 символов в случайном порядке (первая половина — буквы английского алфавита, вторая половина — цифры и другие символы)
  • Отсутствие избыточных прав
  • Возможность использования одного MSA на нескольких серверах (gMSA). В случае, когда требуется, чтобы все экземпляры служб использовали один и тот же субъект, например для использования в службе NLB
  • Управление SPN

Автоматическое обновление SPN при переименовании
— учетной записи сервера
— свойства dnshostname учетной записи сервера
— изменении свойства addition¬aldnshostname учетной записи сервера
— изменении свойства additionalsam¬accountname учетной записи сервера

Сервисы и службы, которые поддерживают MSA:

  • IIS
  • AD LDS
  • SQL Server 2008 R2 SP1, 2012
  • MS Exchange 2010, 2013

Требования MSA:

  • Уровень домена и леса – Windows Server 2008 R2
  • Windows Server 2008 R2, Windows 7 (Professional, Enterprise, Ultimate)
  • .Net Framework 3.5x
  • Модуль администрирования Active Directory для PowerShell
  • Установленный патч 2494158

Если лес и домен не имеют уровень 2008 R2 (MSA) и 2012 (gMSA) нужно поднять уровень леса командой:
adprep /forestprep
И уровень домена, командой:
adprep /domainprep в каждом домене, в котором необходимо создать и использовать управляемые учетные записи службы.

Включение MSA в PowerShell
1) Выполнить командлет: Import-Module ActiveDirectory
2) Чтобы создать учётную запись MSA нужно выполнить командлет:
New-ADServiceAccount serviceaccount –RestrictToSingleComputer
где serviceaccount – имя учетной записи MSA
RestrictToSingleComputer – параметр означает, что MSA будет привязан только к одному серверу.
Можно зайти в Active Directory Users and Computers и убедиться, что MSA был создан (чтобы появился раздел Managed Service Accounts, нужно включить в оснастке View — Advanced Features).

Читайте также:  Кнопки закрытия как у mac os

3) Чтобы привязать MSA к серверу нужно выполнить командлет:
Add-ADComputerServiceAccount -Identity server -ServiceAccount serviceaccount
где server – имя сервера, который будет соотнесён с MSA
serviceaccount – имя учетной записи MSA
Чтобы проверить, что операция выполнена успешно, нужно зайти в оснастку Active Directory Users and Computers, перейти в свойства сервера и посмотреть атрибут msDS-HostServiceAccount

4) Установка управляемой учетной записи службы на локальном компьютере
Нужно выполнить командлет:
Install-ADServiceAccount -Identity serviceaccount
где serviceaccount – имя учетной записи MSA
5) Тестирование MSA (Windows 8.1, Windows PowerShell 4.0, Windows Server 2012 R2)
Нужно выполнить командлет:
Test-ADServiceAccount serviceaccount
где serviceaccount – имя учетной записи MSA
Вернёт значение True или False
6) Установить для службы Windows запуск от имени MSA и перезапустить службу.
В конце имени MSA не забудьте указать знак $
Поле пароль нужно оставить пустым.

Проверим с помощью утилиты gsecdump пароль для учётной записи службы

В Windows Server 2012 появились Групповые управляемые учетные записи служб (Group Managed Service Accounts).
Они позволяют привязывать управляемую учетную запись не к одному серверу, а к нескольким.
Это может потребоваться, например, для использования в службе балансировки сетевой нагрузки.

Требования:

  • Уровень схемы – Windows Server 2012
  • Контроллер домена Windows Server 2012 (R2) на котором запущена служба Microsoft Key Distribution Service
  • Windows Server 2012, 2012 R2, 8, 8.1
  • Модуль администрирования Active Directory для PowerShell

Включение gMSA в PowerShell
1) Проверить, что включена служба Microsoft Key Distribution Services
“Служба распространения ключей использует общий секрет для создания ключей учетной записи. Эти ключи периодически изменяются. В дополнение к прочим атрибутам групповых управляемых учетных записей служб контроллер домена Windows Server 2012 вычисляет пароль для ключа, предоставленного службами распространения ключей. Обратившись к контроллеру домена Windows Server 2012, узлы Windows Server 2012 и Windows 8 могут получить текущий и предыдущий пароль.”
2) Создать Root Key
За создание Root Key отвечает командлет:
Add-KdsRootKey
Чтобы создать новый Root Key нужно выполнить командлет:
Add-KdsRootKey –EffectiveImmediately
В таком случае ключ будет доступен через 10 часов, пока не среплицируется.
Можно выполнить командлет:
Add-KdsRootKey –EffectiveTime ((get-date).addhours(-10))
В таком случае, ключ будет доступен сразу (-10 часов начала работы)
3) Создать gMSA
Выполнить командлет:
New-ADServiceAccount serviceaccount -DNSHostName test.test.com –PrincipalsAllowedToRetrieveManagedPassword $test
где serviceaccount – имя учетной записи gMSA
test.test.com – имя сервера, на котором был создан Root Key
$test – имя сервера, который может обращаться к KDS для получения информации

Можно зайти в Active Directory Users and Computers и убедиться, что gMSA был создан (чтобы появился раздел Managed Service Accounts, нужно включить в оснастке View — Advanced Features).

4) Установка управляемой учетной записи службы на локальном компьютере
Нужно выполнить командлет:
Install-ADServiceAccount -Identity serviceaccount
где serviceaccount – имя учетной записи gMSA
5) Тестирование MSA (Windows 8.1, Windows PowerShell 4.0, Windows Server 2012 R2)
Нужно выполнить командлет:
Test-ADServiceAccount serviceaccount
где serviceaccount – имя учетной записи MSA
Вернёт значение True или False
6) Установить для службы Windows запуск от имени gMSA и перезапустить службу.
В конце имени gMSA не забудьте указать знак $
Поле пароль нужно оставить пустым.

Проверим с помощью утилиты gsecdump пароль для учётной записи службы

Удалить MSA/gMSA можно с помощью командлета Uninstall-ADServiceAccount

Задавать параметры MSA/gMSA можно с помощью командлета Set-ADServiceAccount
Задание периода смены пароля:
Set-ADServiceAccount serviceaccount -ManagedPasswordIntervalInDays 60
где serviceaccount – имя учетной записи gMSA
60 – период, через который сменится пароль
Задание криптоалгоритмов Kerberos для использования MSA
Варианты: RC4, AES128, AES256
Set-ADServiceAccount serviceaccount -KerberosEncryptionType RC4, AES128, AES256
Задание SPN
Set-ADServiceAccount serviceaccount -ServicePrincipalNames @

Задание NetBIOS имени для сервиса (SAMAccountName)
Если не задано, используется идентификатор Name
Если задано, имя отображения в AD будет из Name, а идентификатор для логина из SAMAccountName
Set-ADServiceAccount serviceaccount –SamAccountName test

MSA – это ещё один способ, который позволяет повысить безопасность.

Оцените статью