Managed service accounts в windows server 2016

Управляемые учётные записи сервисов - Group Managed Service Accounts в Windows Server 2016

Привет.

Ранее я написал обзорную статью про MSA в Windows Server 2008 R2. Теперь, так как вышли новые версии платформы Windows Server, надо добавлять. Ведь есть что, и очень даже интересное. Это – обновлённая версия статьи; оригинальная была написана по Windows Server 2012 RTM, данная уже учитывает существование и Windows Server 2012 R2, и Windows Server 2016.

Работаем с Managed Service Accounts

  • Зачем нужны MSA
  • Функционал MSA – обычных MSA и современных gMSA
  • Подготавливаем лес Active Directory к работе с MSA и gMSA
  • Включаем и настраиваем Key Distribution Services
  • Создаём gMSA на Windows Server 2012 и выше
  • Дополнительные возможности

Приступим.

Зачем нужны MSA

Изначально в Windows NT такого понятия, как “специальный вид учётной записи для приложения-сервиса” не существовало. Была системная учётка SYSTEM, которая олицетворяла собой Одина, Будду, Ктулху и прочих интересных личностей в одном флаконе. Эта учётная запись была неявно включена в BUILTINAdministrators и обладала всеми правами на системе, которые могут быть – ну а если чем-то не обладала, так от её лица можно было сделать take ownership на любом объекте, имеющем ACL, и в результате всё ж обладать всеми правами. От этой учётки работали все системные процессы, а также запускались сервисы – но подчеркну, сделана она была не именно для запуска сервисов, а чтобы олицетворять “всю систему”.

Вы могли запускать сервисы как от неё, так и от обычной учётной записи пользователя – это менялось в настройках примерно так же, как меняется сейчас:

Да и сервисы свои вы тоже могли создавать, для этого была специальная утилитка srvany, входившая в состав Resource Kit.

Вроде как всё хорошо, но на самом деле – проблемы.

Первая и очевидная состояла в небезопасности выдачи всех-всех-всех прав в системе любому приложению, которому надо было запускаться на фоне. Допустим, берём сервис DHCP Client. Что ему нужно от системы? Возможность доступа к сети, притом небольшую совсем, да возможность записи конфигурации в некоторые ветки реестра (где хранятся настройки сетевых интерфейсов). Всё, что он делает – обменивается несколькими видами ethernet-кадров, да пишет Надо ли ему доступ ко всем данным на всех дисках? К созданию пользователей и смене прав? К раздаче системных привилегий типа “shut down from remote system”? Нет конечно, зачем. Но всё это выдаётся, если работаешь от SYSTEM.

Вторая состояла в том, что даже если заводишь специальную учётную запись пользователя, от имени которой запускаешь этот сервис, то возникает новая пачка проблем, в том числе:

  • Надо старательно выдать этой учётной записи только минимально нужные для этой операции права и запретить изначально разрешаемые ей, но не нужные в данном сценарии использования (например, запретить сетевой вход);
  • Надо периодически менять у этой учётной записи пароль, а также сделать его стойким;
  • Пароль к этой учётной записи будет храниться в системе в виде открытого текста (надо ж при запуске сервиса сымитировать log on as a service, поэтому надо предоставить связку логин-пароль в исходном варианте);
  • Пароль может использоваться в нескольких местах (например, когда данная служба на нескольких серверах работает), и доступ к нему возможен на любом из этих серверов от любой учётной записи с правами локального администратора;

Всё это неудобно, небезопасно, заставляет тратить лишнее время, и зачастую сводится к “разово сделаем пароль, поставим галочку, чтобы мозг не конопатил, выдадим права локального админа этой учётке и забудем”.

Managed Service Accounts – MSA (я буду говорить уже именно про новые, gMSA, появившиеся в Windows Server 2012, новая буква g – это Group) – позволяют решить все эти проблемы.

Функционал MSA – обычных MSA и современных gMSA

Managed Service Accounts будут различаться – самый первый вариант, появившийся в Windows Server 2008 R2 (про него предыдущая статья про MSA), будет уметь работать только с одним сервером, и, так как в следующей же операционной системе, Windows Server 2012, появились gMSA, лишённые этого ограничения, речь пойдёт сразу же про них. Называть я их буду MSA, без буквы g, так проще.

Итак, как MSA решают все вышеперечисленные вопросы?

  • Проблема с минимизацией прав упростилась – MSA – это не пользовательская учётка, выкорчёвывать лишние полномочия не нужно, изначально на локальной системе никаких прав у MSA нет, громоздкий профиль, как пользователь, при логине, она тоже не создаёт. Вы просто добавляете её в нужные группы, чтобы предоставить соответствующие задаче права и полномочия.
  • Периодичность смены пароля у MSA задаётся через групповые политики и проводится автоматически.
  • Пароль у MSA генерится очень стойкий – 240 символов, половина латинские буквы, половина – цифры. Такой пароль нет смысла подбирать bruteforce’ом, потому что это займёт времени больше, чем линейный перебор всех значений хэша.
  • При использовании MSA на нескольких серверах проблемы со сменой пароля также нет – всё делается автоматически.

Из дополнительных преимуществ – MSA использует только Kerberos, поэтому хоть NTLM дополнительно обезопасить можно, в случае с MSA это просто не нужно – проблем с безопасностью LM, NTLMv1 и NTLMv2 у этих учёток нет.

В результате получается очень удобный вид учётных записей для упрощения обслуживания и улучшения ситуации с безопасностью.

Давайте внедрять.

Подготавливаем лес Active Directory к работе с MSA и gMSA

Домиком для всех видов MSA – обычных, которые msDS-ManagedServiceAccount, и новых, которые msDS-GroupManagedServiceAccount – будет контейнер CN=Managed Service Accounts,DC=контекст домена, находящийся в корне domain partition вашего домена:

Для работы MSA надо будет также включить специальный сервис на выбранном хосте, который будет отвечать за централизованное управление паролями. Этот сервис будет называться KDS – Key Distribution Services.

Необходимые для работы этого сервиса объекты в Active Directory будут создаваться либо сразу, когда поднимается новый лес, либо когда идёт /forestprep при установке первого DC на базе Windows Server 2012. Проверить, что данные операции на уровне леса прошли удачно, можно отследить по трекеру Forest Updates – зайдите в ADSI-редактор и откройте вот такой контейнер:

В нём должны (если всё хорошо) быть GUID’ы выполненных операций, 4 штуки:

  • {defc28cd-6cb6-4479-8bcb-aabfb41e9713}
  • {d6bd96d4-e66b-4a38-9c6b-e976ff58c56d}
  • {bb8efc40-3090-4fa2-8a3f-7cd1d380e695}
  • {2d6abe1b-4326-489e-920c-76d5337d2dc5}

Там, конечно, много всяких других, благо с 2000го Windows Server в Active Directory изменения есть, но нам надо, чтобы были все эти 4 – это будет обозначать, что дефолтные объекты для работы Key Distribution Services были созданы.

Дополнительно можно глянуть рядом расположенный объект, CN=ActiveDirectoryUpdate,CN=ForestUpdates,CN=Configuration,DC=atraining,DC=z. Он будет содержать атрибут revision – нам надо, чтобы этот атрибут был как минимум 11.

Если всё ОК, то продолжаем.

Включаем и настраиваем Key Distribution Services

Начиная с Windows Server 2012, в Active Directory появляется новый контейнер для хранения данных, находящийся в лесном разделе Configuration:

Обращающиеся к нему сервисы работают на всех DC под управлением Windows Server 2012 и старше, технически выглядят как вызываемые из библиотеки kdssvc.dll функции по управлению ключевой информацией. Эти функции и будут составлять собой Microsoft Key Distribution Services.

Внутри контейнера CN=Group Key Distribution Service есть два других – один для общих настроек Microsoft Key Distribution Services, называется Server Configuration:

а второй – для самих ключей, он будет называться Master Root Keys:

Что в них?

Server Configuration

Здесь будет находиться единственный объект с названием Group Key Distribution Service Server Configuration, класса msKds-ProvServerConfiguration. Из интересного в нём разве что атрибут msKds-Version, равный единице со времён Windows Server 2012 – двойка пока нигде, включая Windows Server 2016 TP5, не обнаружена.

Master Root Keys

Здесь будут находиться сами ключи. Идентифицироваться они будут по CN, равному GUID ключа, класс объекта у них будет msKds-ProvRootKey, а интересных атрибутов у них будет много:

Два параметра msKds-CreateTime и msKds-UseStartTime будут содержать время создания объекта и время начала возможности его использования. Логика такова, что после создания объекта ему даётся время на то, чтобы среплицироваться на все DC в лесу. Это время стандартно и составляет 10 часов. До наступления msKds-UseStartTime данный ключ не будет использоваться, DC просто не будут находить его по запросам со стороны функций, работающих с gMSA.

Криптографические параметры будут задавать длины закрытого (msKds-PrivateKeyLength) и открытого (msKds-PublicKeyLength) ключа RSA, алгоритм совместной генерации общего секретного ключа (msKds-SecretAgreementAlgorithmID, в нашем случае DH) и сами блобы этих криптографических параметров. В атрибуте msKds-Version будет версия – такая же, как и в предыдущем объекте, а в msKds-KDFAlgorithmID будет название KDF-функции – сейчас там значение SP800_108_CTR_HMAC, пока оно стандартное, но API допускает и возможность других значений из подмножества поддерживаемых CNG KDF-функций (например, SP80056A_CONCAT, или PBKDF2). Посмотреть фактическую поддержку KDF на хосте (контроллере домена Active Directory или просто Windows-машине – неважно), можно командой show crypto algo:

KDF, если что – это аббревиатура от Key Derivation Function, т.е. способа генерации ключа нужной длины из не-криптографического материала (например, из пароля).

Эти параметры можно также просмотреть через командлет Get-KdsConfiguration:

Он, в общем-то, эти же атрибуты и выводит. Парный к нему командлет, Set-KdsConfiguration, позволит изменять параметры – алгоритмы, длины ключей, и всё остальное. Например, можно сменить стандартную KFD-функцию на другую:

Set-KdsConfiguration -KdfAlgorithm "PBKDF2"

По идее, можно ещё сменить сам алгоритм генерации ключевого материала со старого DH на ECDH, или хотя бы увеличить количество бит у DH с 2048 до 4096, но только вот это сейчас (в Windows Server 2016 TP5) не работает по неизвестной причине – надеюсь, к RTM доделают. Меняется т.е. пока только KDF-функция – список доступных вы можете просмотреть через ATcmd, пример есть выше.

Давайте теперь создадим ключ.

Создание нового Root Key

Это несложно – используется командлет Add-KdsRootKey, из параметров у которого только разве что время начала действия ключа. Самый простой способ – создать так:

Add-KdsRootKey -EffectiveImmediately

Тогда ключ создастся и начнётся отсчёт 10 часов – для подстраховки, чтобы среплицировалось во всём лесу Active Directory. Если не хотите ждать – не вопрос. Можно сделать хитро – сгенерить ключ с “минус десятью часами начала работы”:

Add-KdsRootKey –EffectiveTime ((get-date).addhours(-10))

В этом случае ключ будет работоспособен сразу же. После создания Вы увидите GUID ключа:

Можно зайти в контейнер с ключами и посмотреть его параметры – опять же, из интересного там пока что будет разве что сервер, на котором Вы создали этот ключ – в атрибуте msKds-DomainID.

Теперь можно и gMSA создать.

Создаём gMSA

Для начала, выберем хост, на котором мы создадим gMSA. Хост должен быть строго на Windows Server 2012 и выше и обладать установленным .NET Framework 4.5 (это будет само собой, если там развёрнуты службы AD DS).

Создание будет несложным – используется тот же командлет, что и раньше:

New-ADServiceAccount

В качестве обязательных параметров будет имя, которое можно указать сразу после командлета (например, msa1):

New-ADServiceAccount msa1

И надо выбрать – создаём ли “обычный” MSA, привязанный к одному серверу – тогда это выглядит так:

New-ADServiceAccount msa2 -RestrictToSingleComputer

Или создаём именно gMSA, пригодную для использования в кластерах, и тогда надо указать FQDN хоста, на котором мы заводили KDS-ключ (например, server-a.atraining.z):

New-ADServiceAccount msa1 -DNSHostName server-a.atraining.z

А после – указать все те учётки computer’ов, которые смогут получать доступ к security-информации (паролю, например) новорожденной gMSA, задав их перечень в параметре -PrincipalsAllowedToRetrieveManagedPassword (например, разрешим учётке DC1):

New-ADServiceAccount msa1 -DNSHostName server-a.atraining.z -PrincipalsAllowedToRetrieveManagedPassword DC1$

Можно ещё добавить в конец -Enabled $true, и тогда будет полный вариант.

Вот так выглядят созданные учётки (я сделал msa1 нормальной, gMSA, а msa2 – ‘устаревшей’ MSA, чтобы было видно, что в зависимости от параметров командлета New-ADServiceAccount создаются разные типы объектов Active Directory):

Дальнейшее использование простое – надо пойти на хосты, на которых планируется использование этой gMSA, и выполнить на них Install-ADServiceAccount. Всё идентично обычному MSA, только можно установить больше чем на 1 хост.

Дополнительные возможности

Вы можете задать криптоалгоритмы, используемые для тикетов Kerberos, выдаваемых этой MSA. Это делается, используя параметр -KerberosEncryptionTypes. Задавать можно несколько, выбор есть из DES, RC4, AES128 и AES256. Например, так:

New-ADServiceAccount msa1 -KerberosEncryptionType AES128|AES256

Можно (и нужно) явно задать промежуток смены пароля для gMSA – теперь же нет явного “хоста-монопольного-владельца-MSA”, от настроек которого это было зависимо:

New-ADServiceAccount msa1 -ManagedPasswordIntervalInDays 60

60, как понятно – это в днях.

Интересный момент – Вы не сможете получить полный доступ к вкладке Attributes у gMSA, если подключаетесь по обычному LDAP. Только если по LDAPS. Ну, это тема отдельного разговора о безопасности Active Directory. Намекну, что сможете через ATcmd.exe :).

В качестве заключения

Очередная технология, ощутимо поднимающая безопасность и упрощающая управление сервисами стала только лучше. Категорически рекомендуется к использованию – более того, ранее заведённые MSA проще переделать как gMSA – чтобы был единый тип объектов, а не два разных. Конечно, это потребует, чтобы в лесу Active Directory были как минимум NT 6.2-системы, но плюсы очевидны – проще делать gMSA, привязанные к 1й машине, чем специальный устаревший тип объектов с неполным функционалом.

Удач!

In this article, I’ll show you how to deploy and configure Managed Service Accounts with Windows Server 2016 and Active Directory.

Managed Service Account (MSA) Is a new type of Active Directory Account type where AD responsible for changing the account password every 30 days.

With MSA no one needs to set up the account password or even know it, the entire password management process Is managed by Active Directory.

In my example, I’ll use the Managed Service Account to run my IIS Application Pool.

Requirements

To use MSA, Active Directory forest level will have to be set to Windows Server 2012 at a minimum.

You will need Active Directory Management Tools to run the cmdlets In this post

Before we start

I have to say that before I wrote this article I visited a few blogs and most of them overcomplicated the process, This post will show you how to deploy MSA In 10 minutes.

Just make sure to test it in the lab before deploying Into production.

Master Root key

The first step In the MSA deployment process Is to create a Master root Key using the cmdlet below.

Add-KdsRootKey -EffectiveTime ((get-date).addhours(-10)) -Verbose

Create a Service Account

To create and configure the service. I’ll use 4 cmdlets.

The first cmdlet will create the account and also create a DNS name for the account.

New-ADServiceAccount sms -DisplayName "WDS Service" -DNSHostName sms.test.local

Once the account has been created, I will grant the Server (WDS) access to it, which mean the Server (WDS) will have permission to request a password reset every 30 days from Active Directory.

I could add multiple server names If needed.

Set-ADServiceAccount sms -PrincipalsAllowedToRetrieveManagedPassword wds$

With the cmdlet below, I can test the account (return result should be true).

Test-ADServiceAccount sms |fl

And the final cmdlet will Install the Service Account on the WDS Server.

install-ADServiceAccount sms

Set Windows Service

To setup Windows Server service to use the managed Service account, I’ll open the service and use the format below

Testsms$ without typing the password.

If the account needs the log in as a service right you will see the prompt below.

Once configured, I can start the service

Just remember that If the service account needs to be part of the Domain Admins group or any other group you will need to add the service to the group as well.

SET IIS Application Pool

Next, I’ll configure the IIS Application Pool to use the Service Account.

Using the Application Pools menu and right-click on the DefaultAppPool

Select Advanced Settings

In the Advanced Setting -> Process Model -> Identity I’ll change the account

No need to type the password

As you can see below, The Application Pool started and Is using the Service Account.

Get-ADServiceAccount -Filter *

Rollback

To remove the Service Account from Active Directory, I’ll use the cmdlet below:

Remove-adservcieaccount sms

To remove the account from a Windows service, I’ll run the line below (from the command line) with the service name

sc config audiosvr obj= testAdmin password=Password123

By clicking submit, you agree to share your email address with the site owner and Mailchimp to receive marketing, updates, and other emails from the site owner. Use the unsubscribe link in those emails to opt out at any time.

Processing…

Success! You’re on the list.

Управляемые учетные записи (Managed Service Accounts – MSA) это специальный тип учетных записей Active Directory, которые можно использовать для безопасного запуска служб, приложений и заданий планировщика. Основная их идея в том, что паролем таких учетных записей полностью управляет Active Directory. Для них автоматически генерируется сложный пароль длиной 240 символов, который меняется автоматически (по умолчанию каждые 30 дней). Для аутентификации используется только Kerberos (нет проблем с безопасностью NTLM), интерактивный вход не возможен, пароль не известен никому и не хранится в локальной системе (нельзя извлечь пароль из системного процесса LSASS с помощью mimikatz или аналогичных утилит). Таким образом для запуска службы или автоматических заданий, вам не нужно создавать отдельных сервисных пользователей в AD и управлять их паролями.

Managed Service Accounts появились в Windows Server 2008 R2 (тип объекта msDS-ManagedServiceAccount). Основное их ограничение – такую учетную запись можно использовать только на одном сервере (т.е. их нельзя использовать с кластерными и NLB службами). Поэтому в Windows Server появились групповые учетные записи служб, gMSA — Group Managed Service Accounts (тип msDS-GroupManagedServiceAccount). gMSA аккаунты могут одновременно использоваться на нескольких серверах.

Рассмотрим особенности использования MSA и gMSA для запуска служб и заданий на серверах в Active Directory.

Содержание:

  • Требования для использования сервисных аккаунтов MSA/gMSA
  • Создаем корневой ключа KDS службы распространения ключей
  • Создаем управляемую учётную запись MSA в Active Directory
  • Создаем групповую учетную запись gMSA
  • Настройка учетных записей MSA/gMSA на серверах
  • Запуск служб Windows от имени Managed Service Account
  • Запуск задания планировщика от имени сервисной учетной записи /gMSA

Требования для использования сервисных аккаунтов MSA/gMSA

Managed Service Account Group Managed Service Accoun
Уровень домена и леса AD Не ниже Windows Server 2008 R2 Не ниже Windows Server 2012
KDC Контроллер домена с включенной службой распространения ключей Microsoft Key Distribution Service (KdsSvc)
PowerShell Для создания и управления сервисными аккаунтами нужно установить модуль Active Directory module for Windows PowerShell
.Net Framework На сервере нужно установить .NET Framework 3.5 или выше
Поддерживаемые клиенты Windows 7/Windows Server 2008 R2 и выше Windows Server 2012/Windows 8 и выше

Создаем корневой ключа KDS службы распространения ключей

Прежде, чем приступить к созданию учетной записи MSA/gMSA, нужно выполнить разовую операцию по созданию корневого ключа KDS (KDS root key). Для этого на контроллере домена с правами администратора выполните команду (служба Microsoft Key Distribution Services должна быть установлена и включена):

Add-KdsRootKey –EffectiveImmediately

В этом случае ключ будет создан и доступен для использования через 10 часов, после окончания репликации между контролерами домена.

Совет. В тестовой среде для немедленного использования KDS ключа можно воспользоваться командой:

Add-KdsRootKey –EffectiveTime ((get-date).addhours(-10))

Проверим, что корневой ключ KDS создался успешно:

Get-KdsRootKey

Add-KdsRootKey создать корневой ключ KDS в active directory

Для проверки ключа используется команда:

Test-KdsRootKey -KeyId (Get-KdsRootKey).KeyId

Test-KdsRootKey

Создаем управляемую учётную запись MSA в Active Directory

Чтобы создать новую управляемую учетную запись MSA в AD воспользуйтесь командой:

New-ADServiceAccount -Name msaMskSrv1Tasks –RestrictToSingleComputer

По умолчанию MSA и gMSA создаются в корневом контейнере CN=Managed Service Accounts, но вы можете изменить OU с помощью параметра Path.

Привяжите сервисную учетную запись MSA к нужному компьютеру:

$Identity = Get-ADComputer -identity msk-srv01

Add-ADComputerServiceAccount -Identity $identity -ServiceAccount msaMskSrv1Tasks

Напоминаю, что вы можете использовать MSA аккаунт только на одном сервере.

Откройте консоль
dsa.msc
(ADUC, Active Directory Users and Computers) и проверьте, что в контейнере (OU) Managed Service Accounts появилась новая учетная запись типа msDS-ManagedServiceAccount.

контейнер Managed Service Accounts в active directory

по умолчанию этот контейнер не отображается. Чтобы его увидеть, нужно в консоли ADUC выбрать View -> Advanced Features.

Информацию об MSA аккаунте можно получить с помощью команды:

Get-ADServiceAccount msaMskSrv1Tasks

информация об аккаунте MSA - Get-ADServiceAccount

Создаем групповую учетную запись gMSA

Прежде чем создавать учетную запись gMSA, создайте доменную группу и поместите в нее сервера, которым будет разрешено использовать пароль этой групповой сервисной учетной записи. Проще всего создать и наполнить группу с помощью PowerShell:
New-ADGroup MskSQL1 -path 'OU=Groups,OU=MSK,OU=RU,dc=winitpro,DC=ru' -GroupScope Global -PassThru –Verbose
Add-AdGroupMember -Identity MskSQL1 -Members msk-sql01$, msk-sql02$, msk-sql03$

создать группу в active directory

Чтобы создать групповую учетную запись Group Managed Service Account (gMSA), используйте команду:

New-ADServiceAccount -name gmsaMskSQL1 -DNSHostName gmsaMskSQL1.winitpro.ru -PrincipalsAllowedToRetrieveManagedPassword MskSQL1 –verbose

New-ADServiceAccount создать Group Managed Service Account (gMSA) с помощью powershell

Учётная запись gMSA также по умолчанию создается в OU Managed Service Accounts.

объект msDS-GroupManagedServiceAccount в acttive directory

Настройка учетных записей MSA/gMSA на серверах

Для использования сервисных аккаунтов MSA/gMSA на целевых серверах или рабочих станциях сначала нужно установить модуль PowerShell для Active Directory:

Add-WindowsFeature RSAT-AD-PowerShell

Установите учетную запись MSA/gMSA на сервере:

Install-ADServiceAccount -Identity gmsaMskSQL1

Проверьте, сервисная учетная запись установлена корректно:

Test-ADServiceAccount gmsaMskSQL1

Если команда вернет True – все настроено правильно.

установка Install-ADServiceAccount на сервере

Если команда вернула False, скорее всего учетная запись MSA не установлена на сервере или у данного компьютера нет прав на нее:

this computer does not have permission to use the group MSA

WARNING: Test failed for Managed Service Account gmsaMskSQL1. If standalone Managed Service Account, the account is linked to another computer object in the Active Directory. If group Managed Service Account, either this computer does not have permission to use the group MSA or this computer does not support all the Kerberos encryption types required for the gMSA.

Можно изменить периодичность смены пароля (по умолчанию 30 дней):

Set-ADServiceAccount gmsaMskSQL1 -ManagedPasswordIntervalInDays 60

Получить время последней смены пароля можно так:

Get-ADServiceAccount -Identity gmsaMskSQL1 -Properties passwordlastset

Get-ADServiceAccount passwordlastset

Для проверки работы служб и скриптов от имени сервисной учетной записи MAS не получится использовать стандартный RunAs. Вместо этого воспользуйтесь утилитой PsExec (ранее мы показывали, как использовать psexec для запуска командной строки от имени System).

  1. Откройте командную строку с правами администратора;
  2. Выполните команду:
    PsExec64.exe -i -u winitprogmsaMskSQL1$ -p ~ cmd.exe

    Вместо пароля указа знак
    ~
    , это значит что пароль нужно получить из AD.

  3. В открывшемся окне cmd выполните команду
    whoami
    , чтобы убедиться, что консоль запущена от имени аккаунта gMSA. PsExec64 запуск командной строки от имени gmsa аккаунта в windows server
  4. Проверьте запуск скриптов, программ или служб от имени учетной записи Managed Service Account.

Теперь осталось настроить запуск из-под MSA/gMSA нужных вам служб Windows, заданий Task Scheduler, пулов IIS и т.д.

Запуск служб Windows от имени Managed Service Account

Теперь можно настроить запуск нужной службы Windows из-под сервисной записи MSA/gMSA.

  1. Откройте консоль
    services.msc
    ;
  2. Откройте свойства нужной службы и перейдите на вкладку Log on;
  3. Выберите опцию This account и укажите имя MSA аккаунта. В конце имени обязательно указывается символ $ (пароль указывать не нужно);
  4. Сервисной учетной записи MSA будут автоматически предоставлены права Log On As a Service; запуск службы windows от имени gMSA учетной записи
  5. После сохранения изменений службу нужно перезапустить.

Для запуска сложных сервисов с помощью gMSA, проверьте в документации, что это поддерживается. На данный момент gMSA поддерживаются в SQL Server, IIS, AD LDS, Exchange Server.

Запуск задания планировщика от имени сервисной учетной записи /gMSA

Вы можете настроить запуск заданий планировщика Windows Task Scheduler от имени сервисной учетной записи gMSA. Это удобно, так как пароли учетной записи gMSA не хранятся в скриптах в явном виде, вам не нужно их шифровать или защищать. При изменении пароля не нужно перенастраивать задание.

Для предоставления прав учетной записи MSA/gMSA достаточно включить ее в нужные группы доступа. Например, в локальные администраторы сервера, Domain Admins, DNS admins и т.д.

Настроить задание для запуска от имени MSA/gMSA можно только с помощью PowerShell. Например, следующий скрипт создаст новое задание планировщика, которое ежедневно в 21:00 запускает PowerShell скрипт для резервного копирования базы данных:

$action = New-ScheduledTaskAction -Execute powershell.exe  -Argument "-file C:PSDBBackupDB.ps1 -executionpolicy bypass -NoProfile"
$trigger = New-ScheduledTaskTrigger -At 21:00 -Daily
$principal = New-ScheduledTaskPrincipal -UserID winitprogmsaMskSQL1$ -LogonType Password
Register-ScheduledTask BackupDB –Action $action –Trigger $trigger –Principal $principal

powershell создать задание планировщика для запуска от аккаунта Group Managed Service Accounts (gMSA)

Примечание. Для запуска заданий планировщика нужно предоставить учетной записи gMSA права “Log on as a batch job”.

Аргумент “
-LogonType Password
” означает, что пароль для этой gMSA учетной записи будет получен с контроллера домена.

Также вы можете создать задание планировщика с нужными настройками из графической консоли. Затем с помощью утилиты schtasks.exe можно настроить, чтобы оно запускалось от имени Managed Service Account:

schtasks /Change /TN BackupDB /RU "winitprogmsaMskSQL1$" /RP ""

В комментариях к статье есть PowerShell скрипт от Tony, который позволяет перенастроить любое имеющееся задание на запуск от имени gMSA аккаунта.

title description ms.topic ms.assetid ms.author author manager ms.date

Group Managed Service Accounts Overview

Learn about the group Managed Service Account; specifically practical applications, changes in Microsoft’s implementation, and hardware and software requirements.

article

cef0693c-f861-48a7-a1c0-8d1bc06143ce

jgerend

JasonGerend

mtillman

10/12/2016

Group Managed Service Accounts Overview

Applies to: Windows Server 2022, Windows Server 2019, Windows Server 2016

This topic for the IT professional introduces the group Managed Service Account by describing practical applications, changes in Microsoft’s implementation, and hardware and software requirements.

Feature description

A standalone Managed Service Account (sMSA) is a managed domain account that provides automatic password management, simplified service principal name (SPN) management and the ability to delegate the management to other administrators. This type of managed service account (MSA) was introduced in Windows Server 2008 R2 and Windows 7.

The group Managed Service Account (gMSA) provides the same functionality within the domain but also extends that functionality over multiple servers. When connecting to a service hosted on a server farm, such as Network Load Balanced solution, the authentication protocols supporting mutual authentication require that all instances of the services use the same principal. When a gMSA is used as service principals, the Windows 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. The Key Distribution Service shares a secret which is used to create keys for the account. These keys are periodically changed. For a gMSA the domain controller computes the password on the key provided by the Key Distribution Services, in addition to other attributes of the gMSA. Member hosts can obtain the current and preceding password values by contacting a domain controller.

Practical applications

gMSAs provide a single identity solution for services running on a server farm, or on systems behind Network Load Balancer. By providing a gMSA solution, services can be configured for the new gMSA principal and the password management is handled by Windows.

Using a gMSA, services or service administrators do not need to manage password synchronization between service instances. The gMSA supports hosts that are kept offline for an extended time period, and management of member hosts for all instances of a service. This means 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 gMSAs. However, services that run on top of the Cluster service can use a gMSA or a sMSA if they are a Windows service, an App pool, a scheduled task, or natively support gMSA or sMSA.

Software requirements

A 64-bit architecture is required to run the Windows PowerShell commands which are used to administer gMSAs.

A managed service account is dependent upon Kerberos supported encryption types.When a client computer authenticates to a server using Kerberos the DC creates a Kerberos service ticket protected with encryption both the DC and server supports. The DC uses the account’s msDS-SupportedEncryptionTypes attribute to determine what encryption the server supports and, if there is no attribute, it assumes the client computer does not support stronger encryption types. If the host is configured to not support RC4, then authentication will always fail. For this reason, AES should always be explicitly configured for MSAs.

[!NOTE]
Beginning with Windows Server 2008 R2, DES is disabled by default. For more information about supported encryption types, see Changes in Kerberos Authentication.

gMSAs are not applicable to Windows operating systems prior to Windows Server 2012.

Server Manager information

There are no configuration steps necessary to implement MSA and gMSA using Server Manager or the Install-WindowsFeature cmdlet.

See also

The following table provides links to additional resources related to Managed Service Accounts and group Managed Service Accounts.

Content type References
Product evaluation What’s New for Managed Service Accounts

Managed Service Accounts Documentation for Windows 7 and Windows Server 2008 R2

Service Accounts Step-by-Step Guide

Planning Not yet available
Deployment Not yet available
Operations Managed Service Accounts in Active Directory
Troubleshooting Not yet available
Evaluation Getting Started with Group Managed Service Accounts
Tools and settings Managed Service Accounts in Active Directory Domain Services
Community resources Managed Service Accounts: Understanding, Implementing, Best Practices, and Troubleshooting
Related technologies Active Directory Domain Services Overview

Credentials are the keys to an account. By harvesting credentials, attackers can enter your network, move laterally and escalate their privileges to steal your data. Windows Server 2016 has several features for minimizing the chance that attackers will be able to harvest credentials.

Using the Protected Users group

Putting users, especially highly privileged users, in the “Protected Users” group helps you protect against compromise of their credentials by disabling authentication options that are less secure. For example, Windows does not cache the credentials of members of this group locally, so they are never left on workstations for attackers to harvest. In addition, user accounts that are members of this group cannot:

  • Use default credentials delegation
  • Use Windows Digest
  • Use NTLM
  • Use Kerberos long-term keys
  • Sign on offline
  • Use NT LAN Manager (NTLM) for authentication
  • Use DES for Kerberos pre-authentication
  • Use RC4 cipher suites for Kerberos pre-authentication
  • Be delegated privileges using constrained delegation
  • Be delegated privileges using unconstrained delegation
  • Renew user ticket-granting tickets (TGTs) past the initial 240-minute lifetime

Using account preferences

  • User Accounts

For user accounts that need less stringent protection, you can use the following security options, which are available for any AD account:

  • Logon Hours — Enables you to specify when users can use an account.
  • Logon Workstations — Enables you to limit the computers the account can sign in to.
  • Password Never Expires — Absolves the account from the “Maximum password age” policy setting; don’t configure this option for privileged accounts.
  • Smart card is required for interactive logon — Requires a smart card to be presented for the account to sign in.
  • Account is sensitive and cannot be delegated — Ensures that trusted applications cannot forward the account’s credentials to other services or computers on the network.
  • This account supports Kerberos AES 128-bit encryption — Allows Kerberos AES 128-bit encryption.
  • This account supports Kerberos AES 256-bit encryption — Allows Kerberos AES 256-bit encryption. Use this option for privileged accounts.
  • Account expires — Enables you to specify an end date for the account.
  • Computer Accounts

In addition to controlling user accounts, you also need to understand and manage the reach of computer and service accounts. When you join a computer to the domain for the first time, Windows creates a computer account in Active Directory in the “Computers” container and automatically assigns it a password. AD manages these passwords and updates them automatically every 30 days.

To manage the permissions of computer accounts and control which Group Policies are applied to them, you can add them to groups and move them to different OUs. You can also disable and reset computer accounts:

  • Disabling a computer account means that the computer cannot connect to the domain anymore. If you delete a computer account and the computer is still operational, you’ll need to rejoin the computer to the domain if you want it to regain domain membership.
  • Resetting a computer account removes the connection between the computer and the domain.
  • Service Accounts

Service accounts are a special type of account that Windows services use to interact with the operating system and resources on the network. (It’s also possible to create user accounts and configure them to run as service accounts, but that is not convenient.)

There are three types of built-in service accounts:

  • Local system — The NT AUTHORITYSYSTEM account has privileges equivalent to the local Administrators group on the computer.
  • Local service — The NT AUTHORITYLocalService account has privileges equivalent to the local Users group on the computer.
  • Network service — The NT AUTHORITYNetworkService account has privileges equivalent to the local Users group on the computer.

To protect these accounts, ensure a sysadmin updates their passwords on a regular basis. This is a manual process if you use native tools.

  • Group Managed Service Accounts and Virtual Accounts

A Group Managed Service Account is a special type of service account; AD automatically updates the passwords of these accounts. A virtual account is the computer-specific local equivalent of a Group Managed Service Account.

Using Windows Defender Credential Guard

Windows Defender Credential Guard is a new technology in Windows 10 and Windows Server 2016 that helps to protect credentials from attackers who try to harvest them by using malware. Windows Defender Credential Guard uses virtualization-based security that allows you to isolate secrets, such as cached credentials, so that only privileged software can access them.

In virtualization-based security, the specific processes that use credentials or data, and the memory associated with those processes, run in a separate operating system parallel with, but independent of, the host operating system. This virtual operating system protects processes from attempts by any external software to read the data that those processes store and use. Windows Defender Credential Guard takes advantage of hardware security, including secure boot and virtualization.

You can manage Windows Defender Credential Guard using Group Policy, Windows Management Instrumentation (WMI), or Windows PowerShell.

Windows Defender Credential Guard does not allow the use of:

  • Unconstrained Kerberos delegation
  • NT LAN Manager version 1 (NTLMv1)
  • Microsoft Challenge Handshake Authentication Protocol (MS-CHAPv2)
  • Digest
  • Credential Security Support Provider (CredSSP)
  • Kerberos DES encryption

Using the Local Administrator Password Solution

Microsoft’s Local Administrator Password Solution (LAPS) provides a secure central repository for the passwords all built-in local Administrator accounts and automates proper management of those passwords. In particular, LAPS:

  • Ensures that local administrator passwords are unique on each computer
  • Automatically changes all local administrator passwords every 30 days
  • Provides configurable permissions to control access to passwords
  • Transmits passwords to the client in a secure, encrypted manner

Using the Active Directory Administrative Center

The Active Directory Administrative Center enables you to search your Active Directory for accounts that are ripe for takeover by attackers. In particular, you should regularly look for the following types of accounts:

  • User accounts whose passwords never expire — You should avoid configuring accounts with fixed passwords because they are less secure than accounts with passwords that users have to update periodically.
  • Inactive user accounts — Inactive user accounts usually belong to a person who has left the organization. The Active Directory Administrative Center console enables you to find accounts that haven’t signed in for a specified number of days.

Deleting or disabling these user accounts prevents them from being misused by outside attackers or malicious insiders.

Summary

As you can see, Windows Server 2016 offers a lot of to help you protect credentials in your environment. You can use some or all of them. In particular, it’s smart to take advantage of Group Managed Service Accounts, Windows Defender Credential Guard and LAPS because they can improve IT security dramatically with relatively little effort.

Jeff is a former Director of Global Solutions Engineering at Netwrix. He is a long-time Netwrix blogger, speaker, and presenter. In the Netwrix blog, Jeff shares lifehacks, tips and tricks that can dramatically improve your system administration experience.

Hey everyone,

I have never created one but it seems straight forward, at least from the looks of this technet blog

https://blogs.technet.microsoft.com/askds/2009/09/10/managed-service-accounts-understanding-implemen… Opens a new window 

That blog applies for Server 2008r2, but when I search for 2016 I come up with others similar to https://www.ntweekly.com/2018/02/07/configure-managed-service-accounts-windows-server-2016/ Opens a new window

It seems like there are more steps and values in 2016.  And the above article mentions creating a root key:
Add-KdsRootKey -EffectiveTime ((get-date).addhours(-10)) -Verbose

An MSA account already exists on the domain (it’s been there before my time), so I dont know if a rootkey is also required when creating a new MSA account.

Can someone with more experience guide as to where to look and what is needed to create an MSA in 2016

Thanks!

more info: I run the following command and it seems like there’s no kdsrootkey

Powershell

PS C:WINDOWSsystem32> test-kdsrootkey -keyid (get-kdsrootkey).keyid
Test-KdsRootKey : Cannot convert 'System.Object[]' to the type 'System.Guid' required by parameter 'KeyId'. Specified
method is not supported.
At line:1 char:24
+ test-kdsrootkey -keyid (get-kdsrootkey).keyid
+                        ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Test-KdsRootKey], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.KeyDistributionService.Cmdlets.TestKdsRootKeyCommand

When I run get-kdsrootkey I only get the output for our parent and child DC’s

Powershell

PS C:Usersme> Get-KdsRootKey


AttributeOfWrongFormat :
KeyValue               : {123, 194, 53, 246...}
EffectiveTime          : 12/8/2017 12:37:31 PM
CreationTime           : 12/8/2017 12:37:31 PM
IsFormatValid          : True
DomainController       : CN=DC2,OU=Domain Controllers,DC=child,DC=domain,DC=local
ServerConfiguration    : Microsoft.KeyDistributionService.Cmdlets.KdsServerConfiguration
KeyId                  : c5761ee0-4837-673a-8241-8xxxxxxxxx
VersionNumber          : 1

AttributeOfWrongFormat :
KeyValue               : {202, 74, 117, 201...}
EffectiveTime          : 4/25/2018 3:35:34 AM
CreationTime           : 4/25/2018 1:35:36 PM
IsFormatValid          : True
DomainController       : CN=DC1,OU=Domain Controllers,DC=domain,DC=local
ServerConfiguration    : Microsoft.KeyDistributionService.Cmdlets.KdsServerConfiguration
KeyId                  : 291a072b-e65b-c1b1-3aff-cxxxxxxxxxx
VersionNumber          : 1

So with that being said I guess I do need to create this rootkey after all?

Using NetworkService powered application pools does have the nice effect, that there is no password needed, because the pool will be running with the credential of the webserver machine account, which is a domain account, where no password management is needed.

To access resources on the network, the webserver machine account must be enabled on the network destination and everything is fine and secure using windows authentication or Kerberos

This approach is good enough, if the scenario is limited to one application per server, because the minute you need another application, which does have different requirements in terms of security, then this approach will fail.

Lets assume, there are 2 web apps on the machine, which each does have its own SQL Server DB and which should not be allowed to access the other ones data.

image

This scenario can only be used with custom domain accounts, if windows authentication should be used.

Only with 2 different accounts and 2 application pools, the security on each database can be limited to the one matching application pool.

But then someone has to manage this domain passwords and make sure, that they are not expiring, but still changed from time to time. A tedious task and the passwords are probably distributed across the company, hopefully in a secure way and not inside XLS or Textfiles…

Another way with Server 2016 is to use Group Managed Service accounts.

This requires, that Active Directory scheme is on level 2012 R2, only then, the feature “Group Managed Service Accounts” can be used.

Setup a Group Managed Service Account

Login to DC:

Enable gMSA globally on Domain

— for Lab environments we use the switch –EffectiveTime, so that we don’t have to wait for 10 hours, which usually should make sure, that AD sync is ready.

Add-KdsRootKey –EffectiveTime ((get-date).addhours(-10));

This will usually be done from the Active Directory team in your environment

Open ServerManager => Tools => Active Directory Administrative Center

Add new global SecurityGroup named gMSAGroup

clip_image002

clip_image004

Go to AD Admin Center and search for the newly created group (gMSAGroup)

clip_image005

OR: Use Powershell and first install the Powershell AD-modules

Install-WindowsFeature -Name RSAT-AD-PowerShell

Then create the global security group using

NEW-ADGroup –name “gMSAGroup”  –path “OU=XYZ,DC=mydomain,DC=com” -GroupCategory Security -groupscope Global

Right click the gMSAGroup entry and add all the memberserver, which should be able to use the Group Service Managed Account IIS1Svc

or use Powershell:

Add-ADGroupMember «gMSAGroup” -Members «Server1$», «Server2$» 

clip_image007

clip_image008

After adding all the memberservers to the Group Managed Service Group, they must be rebooted!

Create first gMSA Account on the DC: (max 15 chars)

New-ADServiceAccount IIS1SvC -DNSHostName IIS1Svc.corp.litware.com -PrincipalsAllowedToRetrieveManagedPassword gMSAGroup

optionally use –path to define, whe the account should be placed into the domain structure, eg:
-Path «OU=OUXy,DC=mydomain,DC=com»

Check in AD Admin Center, that the account is visible
clip_image010S

Switch to MemberServer (HSW2K12R2Web1)

Install on MemberServers: Remote Server Administration Tools via Server Manager to get Active Directory Module for Windows Powershell

OR with Powershell: Install-WindowsFeature -Name RSAT-AD-PowerShell

clip_image011

Open Powershell Admin Console and

Install-ADServiceAccount IIS1Svc

If error is “access denied”, make sure, that the memberserver was added to the allow list of the group service group and the server was rebooted afterwards!

clip_image012

clip_image013

Create new AppPool in InetMgr:

clip_image014

Use this GroupServiceManaged Account and append “$” to the name and leave password empty

Use this Account for a web application.

When this web application will access a resource on another computer, it will then use this GMSA

clip_image015

More infos:

https://blogs.technet.microsoft.com/askpfeplat/2012/12/16/windows-server-2012-group-managed-service-accounts/

  • Remove From My Forums

 locked

Managed Service Accounts in Windows Server 2016 — Which Windows services would you assign Managed Service Accounts with?

  • Question

  • Hi all,

    As the title of this post is self explanatory, please could you give me examples of Windows services where you would assign Managed Service Accounts with and why, I can understand the concept of this with SQL Server as well as third party products but not with
    Windows i.e. Windows Server. Your help would be much appreciated.

    Kind regards,

    RocknRollTim 

Answers

  • Hi,

    The managed service account is designed to provide applications with:

    • Automatic password management, which can better isolate these services from other services on the computer.
    • Simplified service principal name (SPN) management, which allows service administrators to set SPNs on these accounts. In addition, SPN management can be delegated to other administrators.

    So for the service that you want it to work in  long-term stability,you could use MSA.Such as Exchange,IIS.


    Best Regards
    Cartman
    Please remember to mark the replies as an answers if they help. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com

    • Proposed as answer by

      Wednesday, March 15, 2017 12:34 PM

    • Marked as answer by
      RocknRollTim
      Wednesday, March 29, 2017 10:57 AM

Понравилась статья? Поделить с друзьями:
  • Malwarebytes не устанавливается windows 7 требует обновления
  • Map mas ios driver windows 10
  • Map keyboard for windows 10 скачать
  • Malwarebytes не устанавливается windows 10 недопустимый путь
  • Map keyboard for windows 10 как настроить