Что такое sid в ос windows

Время на прочтение6 мин

Количество просмотров104K

Привет, Хабр! Упомянутая в заголовке тема всё ещё порождает множественные дискуссии и недопонимание между системными администраторами. В своей статье я постараюсь ответить на следующие вопросы:

  1. Что такое SID и каких он бывает типов?
  2. Когда наличие двух и более машин с одинаковыми Machine SID будет порождать проблемы? Или, другими словами, когда всё-таки (не)нужно менять Machine SID?
  3. Что такое Sysprep и нужен ли Sysprep для клонирования/развёртывания?

Эти вопросы будут рассмотрены в первую очередь в контексте задачи развёртывания/клонирования множества рабочих станций/серверов из одного мастер-образа в пределах одной компании.

В основу рассуждений была взята популярная статья Марка Руссиновича (доступна также на русском языке), которую довольно часто неправильно интерпретируют (судя по комментариям и «статьям-ответам»), что приводит к неприятным последствиям. Добро пожаловать под кат.

TL;DR

  1. Менять SID машины само по себе бессмысленно и даже вредно для современных ОСей (пример последствий смены SID на Windows 10 ниже).
  2. Для подготовки машины к клонированию/развёртыванию образа стоит использовать sysprep.
  3. SID машины будет иметь значение, только если одну из склонированных машин промоутить до домен контроллера. Так делать не стоит.
  4. Не стоит клонировать/развёртывать образ машины, которая УЖЕ добавлена в домен; добавление в домен нужно делать после клонирования/развертывания.

Что такое SID, его типы и чем отличается Machine SID от Domain SID?

Ликбез

SID (Security Identifier), или Идентификатор безопасности – Это структура данных переменной длины, которая идентифицирует учетную запись пользователя, группы, домена или компьютера (в Windows на базе технологии NT (NT4, 2000, XP, 2003,Vista,7,8)). SID ставится в соответствие с каждой учетной записью в момент её создания. Система оперирует с SID’ами учетных записей, а не их именами. В контроле доступа пользователей к защищаемым объектам (файлам, ключам реестра и т.п.) участвуют также только SID’ы.

В первую очередь, важно различать SID компьютера (Machine SID) и SID домена (Domain SID), которые являются независимыми и используются в разных операциях.

Machine SID и Domain SID состоят из базового SID’а (base SID) и относительного SID’а (Relative SID = RID), который «приклеивается» в конец к базовому. Базовый SID можно рассматривать как сущность, в рамках которой можно определить группы и аккаунты. Машина (компьютер) является сущностью, в рамках которой определяются локальные группы и аккаунты. Каждой машине присваивается machine SID, и SID’ы всех локальных групп и аккаунтов включают в себя этот Machine SID с добавлением RID в конце. Для примера:

Machine SID для машины с именем DEMOSYSTEM S-1-5-21-3419697060-3810377854-678604692
DEMOSYSTEM\Administrator S-1-5-21-3419697060-3810377854-678604692-500
DEMOSYSTEM\Guest S-1-5-21-3419697060-3810377854-678604692-501
DEMOSYSTEM\CustomAccount1 S-1-5-21-3419697060-3810377854-678604692-1000
DEMOSYSTEM\CustomAccount2 S-1-5-21-3419697060-3810377854-678604692-1001

Именно SID’ы (а не имена) хранятся в токенах доступа (access tokens) и дескрипторах безопасности (security descriptors), и именно SID’ы используются при проверке возможности доступа к объектам системы Windows (в том числе, например, к файлам).

На машине вне домена используются локальные SID’ы, описанные выше. Соответственно, при соединении с машиной удалённо используется локальная аутентификация, поэтому даже имея 2 или более машин с одинаковым machine SID в одной сети вне домена, проблем с логином и работой внутри системы не будет, т.к. SID’ы в операциях удалённой аутентификации попросту не используются. Единственный случай, в котором возможны проблемы, это полное совпадение имени пользователя и пароля на двух машинах – тогда, например, RDP между ними может глючить.

Когда машина добавляется в домен, в игру вступает новый SID, который генерируется на этапе добавления. Machine SID никуда не девается, так же как и локальные группы, и пользователи. Этот новый SID используется для представления аккаунта машины в рамках домена. Для примера:

Domain SID для домена BIGDOMAIN S-1-5-21-124525095-708259637-1543119021
BIGDOMAIN\DEMOSYSTEM$ (аккаунт машины (computer account)) S-1-5-21-124525095-708259637-1543119021-937822
BIGDOMAIN\JOHNSMITH (аккаунт пользователя (user account)) S-1-5-21-124525095-708259637-1543119021-20937

Таким образом, машина DEMOSYSTEM теперь имеет два независимых SID’а:

• Machine SID, определяющая машину как сущность, в рамках которой заданы группы и аккаунты (первая строчка в первой таблице).

• SID аккаунта машины (computer account SID) в рамках домена BIGDOMAIN (вторая строчка во второй таблице).

Увидеть точное значение machine SID можно с помощью утилиты PsGetSid, запустив её без параметров. Второй SID, относящийся к домену, можно увидеть, запустив PsGetSid со следующими параметрами: psgetsid %COMPUTERNAME%$. Соответственно, для примера из таблиц это будет “psgetsid DEMOSYSTEM$«.

Основная суть в том, что SID’ы должны быть уникальны в пределах окружения (authority), к которому они применимы. Другими словами, если машине DEMOSYSTEM присвоен machine SID S-1-5-21-3419697060-3810377854-678604692-1000, то неважно, что у другой машины в той же сети будет идентичный machine SID, т.к. этот SID используется только локально (в пределах машины DEMOSYSTEM). Но в пределах домена BIGDOMAIN computer SID у обоих машин должен быть уникальным для корректной работы в этом домене.

Смена SID при клонировании или развёртывании

В применении к продукту Acronis Snap Deploy 5 (основное предназначение — массовое развёртывание систем из мастер-образа), в котором функциональность смены SID-а присутствовала с самой первой версии, это означает, что мы, как и многие пользователи, ошибочно пошли на поводу у устоявшегося мнения, что менять SID нужно.

Однако исходя из вышесказанного, ничего страшного в развёртывании (или клонировании) машины без изменения Machine SID вовсе нет, в случае если это развёртывание происходит до добавления машины в домен. В противном случае — возникнут проблемы.

Из этого правила есть одно исключение: нельзя клонировать машину, если в дальнейшем роль этого клона планируется повышать (promote) до уровня домена контроллера. В этом случае Machine SID домен контроллера будет совпадать с computer SID в созданном домене, что вызовет проблемы при попытке добавления оригинальной машины (из которой производилось клонирование) в этот домен. Это, очевидно, относится только к серверному семейству Windows.

Проблемы, связанные со сменой SID

Пересмотреть точку зрения на функциональность смены SID нас подтолкнул выпуск новой версии Windows. При первом тестовом развёртывании образа Windows 10 со сменой SID на получившейся машине обнаружилось, что кнопка Start перестала нажиматься (и это оказалось только вершиной «айсберга»). Если же развёртывать тот же образ без смены SID, то такой проблемы не возникает.

Основная причина в том, что эта опция вносит изменения практически во всю файловую систему развёртываемой машины. Изменения вносятся в реестр Windows, в разрешения NTFS (NTFS permissions) для каждого файла, в SID’ы локальных пользователей (так как SID пользователя включает в себя в том числе и machine SID; подробнее тут) и т.д.

В случае с Windows 10 большая часть ключей реестра не могла быть модифицирована («Error code = C0000005. Access violation» и другие ошибки) и, как следствие, наша функция смены SID’а отрабатывала не до конца, что и приводило к

трагической гибели

практически нерабочей копии Windows 10.

Было принято решение убрать эту опцию в случае, если в мастер-образе мы находим Windows 10 (или Windows Server 2016). Решение было принято на основе теоретических выкладок описанных выше плюс, естественно, было подтверждено практикой при тестировании недавно вышедшего обновления Acronis Snap Deploy 5 во множестве комбинаций: с и без переименования машин после развёртывания, с добавлением в домен и рабочую группу, развёртывание из мастер-образов снятых от разных состояний мастер-машины (она была добавлена в домен или рабочую группу в разных тестах) и т.д.

Использование Sysprep

Начиная с Windows NT клонирование (развертывание) ОСи с использованием только NewSID никогда не рекомендовалось самим Microsoft. Вместо этого рекомендуется использовать родную утилиту Sysprep (см. KB314828), которая, помимо смены SID’а, также вносит большое число других изменений, и с каждой новой версией Windows их становится только больше. Вот небольшой (неполный) список основных вносимых изменений:

  • Удаляется имя машины
  • Машина выводится из домена: это нужно для последующего успешного добавления в домен с новым именем
  • Удаляются plug-and-play драйвера, что уменьшает риск возникновения проблем с совместимостью на новом «железе»
  • Опционально удаляются Windows Event Logs (параметр ‘reseal’)
  • Удаляются точки восстановления
  • Удаляется профиль локального администратора и этот аккаунт отключается
  • Обеспечивается загрузка целевой машины в режим аудита, позволяющий устанавливать дополнительные приложения и драйверы
  • Обеспечивается запуск mini-setup при первом запуске для смены имени машины и другой дополнительной конфигурации
  • Сбрасывается период активации Windows (сброс возможен до 3 раз)

Таким образом, клонирование/развертывание без использования Sysprep может повлиять (читай «скорее всего, сломает») на функциональность Windows Update, Network Load Balancing, MSDTC, Vista и выше Key Manager Activation (KMS), который завязан на CMID (не путать с Machine SID), также изменяемый Sysprep’ом, и т.д.

Итого

Повторяя TL;DR из начала статьи, основной вывод можно сделать такой: для подготовки образа машины к клонированию/развёртыванию следует использовать sysprep в подавляющем большинстве случаев.

Линки

— Как изменить SID в Windows 7 и Windows Server 2008 R2 с помощью sysprep
— How to View Full Details of All User Accounts in Windows 10
— Миф о дублировании SID компьютера
— Sysprep, Machine SIDs and Other Myths
— The Machine SID Duplication Myth (and Why Sysprep Matters)
— Yes you do need to worry about SIDs when you clone virtual machines – reasserting the ‘myth’
— Why Sysprep is a necessary Windows deployment tool

Спасибо за внимание!

From Wikipedia, the free encyclopedia

Security Identifier (SID) is a unique, immutable identifier of a user account, user group, or other security principal in the Windows NT family of operating systems. A security principal has a single SID for life (in a given Windows domain), and all properties of the principal, including its name, are associated with the SID. This design allows a principal to be renamed (for example, from «Jane Smith» to «Jane Jones») without affecting the security attributes of objects that refer to the principal.

Windows grants privileges and access to resources based on access control lists (ACLs). Each entry on the list defines one SID and a set of permissions for that SID. When a user logs into a PC, Windows generates an access token that contains the user SID, the group SIDs to which the user account belongs, and the user privilege level. When a user requests access to a resource, its ACL is checked against the user’s access token to permit or deny particular action on a particular object.

The human-readable representation of a SID is a string that starts with «S-» and consists of several dash-separated numbers. For example, «S-1-5-21-3623811015-3361044348-30300820-1013» could be a user account’s SID. The following table explains the components of this example SID.

Anatomy of a SID

Component Example Explanation
Header S Identifies the string as a SID
Revision level 1 The version number of the SID specification. As of 2025, «1» is the only valid number.
Authority 5 See below
Subauthorities 21-3623811015-3361044348-30300820 In this example, «21» indicates a «domain» subauthority. The following 96-bit ID is a domain identifier.
Relative ID (RID) 1013 Uniquely identifies the principal within its subauthority group. In the context of domain accounts (which is the focus of our example), RIDs greater than 1000 indicate an admin-defined principal (as opposed to a predefined, built-in, or special-purpose generic principal).

Originally, SIDs were supposed to allow arbitrarily deep nesting, with each level allowed to create sub-authorities underneath itself. However, that goal was abandoned early in Windows NT development, when it was decided that it would be too unmanageable in practice; by then, however, the SID format had already been finalized and was in heavy use in the Windows code.[1]

Identifier authority

[edit]

Identifier authorities are formally defined as six-byte (48-bit) quantities. The identifier authority is expressed in decimal if its value is less than 232, otherwise in hexadecimal.[2][3] However, while this is the behavior formally defined by Microsoft, and implemented by the relevant Windows APIs (e.g. RtlConvertSidToUnicodeString),[3] hexadecimal identifier authorities appear to have never been used in practice. All known values fit in the least significant byte, and the other 5 bytes are always zero. Identifier authorities are stored in big-endian format, even on little-endian CPU architectures.

Valid identifier authority values[4][5]

Authority Formal name First introduced Notes
0 Null Authority e.g., «Nobody» (S-1-0-0)
1 World Authority e.g., well-known groups such as «Everyone». (S-1-1-0)
2 Local Authority e.g., flag SIDs like «CONSOLE LOGON»
3 Creator Authority
4 Non-unique Authority
5 NT Authority Managed by the NT security subsystem. There are many sub-authorities such as «BUILTIN» and every Active Directory Domain
6[6][7] Site Server Authority Windows XP
7[6][7] Internet Site Authority Windows XP
8[6][7][8] Exchange Authority Windows XP
9[7][9][10] Resource Manager Authority Windows Server 2003
10[6] Passport Authority
11[11] Microsoft Account Authority Windows 8
12 Azure Active Directory Windows 10
15[12][13][14] App Package Authority (Capability SIDs) Windows Server 2012 All capability SIDs begin at S-1-15-3. By design, a capability SID does not resolve to a friendly name. The most commonly used capability SID is S-1-15-3-1024-1065365936-1281604716-3511738428-1654721687-432734479-3232135806-4053264122-3456934681
16[15] Mandatory Label Authority Windows Vista Used as part of Mandatory Integrity Control
17[16] Scoped Policy ID Authority
18[16] Authentication Authority
19[17] Process Trust Authority

S-1-5 subauthority values[12][18][5]

Decimal Name First introduced Format and purpose
8[5] Proxy Windows Server 2003 S-1-5-8 is the SID of the «SECURITY_NT_AUTHORITY» proxy.[5]
18 LocalSystem Windows NT 3.1 S-1-5-18 is the SID of the LocalSystem account on all Windows machines.
19 LocalService S-1-5-19 is the SID of the LocalService account on all Windows machines.
20 NetworkService S-1-5-20 is the SID of the NetworkService account on all Windows machines.
21 Domain S-1-5-21-<Domain ID>-<RID>, where <Domain ID> is in the form of <32-bit>-<32-bit>-<32-bit>. See below for details.
32 Users Windows 7 S-1-5-32-<RID>. Example: S-1-5-32-544 (the built-in Administrators group).

The resulting SID pertains a predefined, special-purpose user group, and is valid on all Windows machines. RID could only be one the predefined ones.

64 Authentication S-1-5-64-<RID>, where <RID> is one of the following:

  • 10: NTLM
  • 14: SChannel
  • 21: Digest
80 NT Service Windows Vista S-1-5-80-<RID>, where <RID> is a service identifier. «0» (zero) is reserved for the ALL SERVICES group (hence, S-1-5-80-0’s fully qualified name is NT SERVICE\ALL SERVICES).
82 IIS AppPool Windows 7
83-0 Virtual Machines Windows 7 S-1-5-83-0 is the SID of the «NT VIRTUAL MACHINE\Virtual Machines» group, which maintains a list of all Hyper-V virtual machines.
83-1 Virtual machine Windows 7 S-1-5-83-1-<ID1>-<ID2>-<ID3>-<ID4>.

The resulting SID pertains a Hyper-V virtual machine.

90[5] Windows Manager Windows 7 S-1-5-90-0 is the SID of the «Windows Manager Group», a built-in group that maintains all virtual accounts of the Desktop Windows Manager (DWM).

S-1-5-90-0-<RID>, where <RID> is a number, is the SID format of a DWM virtual account. For example, S-1-5-90-0-1 pertains DWM-1.

96 User-Mode Driver Framework Windows 7 S-1-5-96-0-<RID>, where <RID> is a number, is the SID format of a User-Mode Driver Framework (UMDF) virtual account. For example, S-1-5-96-0-1 pertains UMDF-1. The User-mode Font Driver Host (fontdrvhost.exe) runs in the context of a UMDF account.

SIDs that start with «S-1-5-21» are noticeably longer than most other SIDs (with the notable exception of service SIDs). Their general format is: S-1-5-21-<Domain ID>-<RID>, where <Domain ID> is in the form of <32-bit>-<32-bit>-<32-bit>.

The Domain ID uniquely identifies a Windows domain. The RID specifies a principal (user account, group account, or computer account) within that domain.

If the RID portion is greater than 1000, the resulting SID pertains an admin-defined user account, user group, or computer account, e.g., S-1-5-21-3361044348-303008203623811015-1001. The name of this account could be anything, e.g., Domain.local\JaneDoe.

If the RID portion is smaller than 1000, the resulting SID pertains a predefined (built-in) user account or user group. For example, RID 500 identifies the controversial «Administrator» user account while RID 512 pertains the «Domain Admins» group.

Machine SIDs are variety of domain SIDs (S-1-5-21) with a 96-bit domain ID (a machine is considered its own local domain) but no RID. Their general format is: S-1-5-21-<Machine ID>, where <Machine ID> is in the form of <32-bit>-<32-bit>-<32-bit>.

The machine SID is stored in the SECURITY hive of the Windows Registry, more specifically at HKEY_LOCAL_MACHINE\SECURITY\SAM\Domains\Account. This key has two values: F and V. The latter is a raw binary value that has the machine SID embedded within it at the end of its data (last 96 bits).[19] (Some sources[example needed] state that it is stored in the SAM hive instead.) A backup is located at SECURITY\Policy\PolAcDmS\@.[citation needed]

NewSID ensures that this SID is in a standard NT 4.0 format (3 32-bit subauthorities preceded by three 32-bit authority fields). Next, NewSID generates a new random SID for the computer. NewSID’s generation takes great pains to create a truly random 96-bit value, which replaces the 96-bits of the 3 subauthority values that make up a computer SID.

— NewSID readme[20]

The machine SID is stored in a raw-bytes form in the registry. To convert it into the more common numeric form, one interprets it as three, little endian, 32-bit integers, converts them to decimal, and add hyphens between them.

Service SIDs are a feature of service isolation, introduced in Windows Vista and Windows Server 2008.[21] Any service with the «unrestricted» SID-type property will have a service-specific SID added to the access token of the service host process, allowing permissions for a single service to be managed without necessitating the creation of service accounts.

Each service SID is a local, machine-level SID that has the general form of S-1-5-80-<Service ID>. To generate <Service ID>, Windows copies the service name (in UTF-16 encoding), converts all characters to uppercase, and calculates the SHA-1 digest of said uppercase name. This digest becomes the <Service ID>. The sc.exe command can be used to generate this special SID value; for example, given the «dnscache» service:

C:\>sc query

NAME: dnscache
SERVICE SID: S-1-5-80-859482183-879914841-863379149-1145462774-2388618682

Therefore, the «dnscache» service can be referred to as either NT SERVICE\dnscache or S-1-5-80-859482183-879914841-863379149-1145462774-2388618682. Since a Service SID is determined exclusively by the service name, the value of the SID for a given service is always the same across all machines wherever the service runs.

A common method of mass-producing Windows PCs is to install Windows on a template machine, and duplicate its disk sector by sector to other identical machines. As a result, these mass-produced machines are identical in every respect, including their SIDs.[20]

Microsoft engineer Mark Russinovich is the creator of a utility called NewSID, the purpose of which is to solve «The SID Duplication Problem.»[20] Microsoft has retired the utility on November 2, 2009, because, Mark and the Windows security team have concluded that duplicate SIDs do not pose any problem whatsoever.[22]

  • Access control
  • Access Control Matrix
  • Discretionary Access Control (DAC)
  • Globally Unique Identifier (GUID)
  • Mandatory Access Control (MAC)
  • Role-Based Access Control (RBAC)
  • Capability-based security
  • Post-cloning operations
  1. ^ «[MS-AZOD]: Security Identifiers (SIDs)». learn.microsoft.com. 2022-06-14. Retrieved 2024-12-29.
  2. ^ «[MS-DTYP]: SID String Format Syntax». learn.microsoft.com. 2023-12-12. Retrieved 2024-12-29.
  3. ^ a b «RtlConvertSidToUnicodeString function (ntifs.h) — Windows drivers». learn.microsoft.com. 2022-11-04. Retrieved 2024-12-29.
  4. ^ «Well-known security identifiers in Windows operating systems». support.microsoft.com. Retrieved 12 December 2019.
  5. ^ a b c d e openspecs-office. «[MS-DTYP]: Well-Known SID Structures». docs.microsoft.com. Retrieved 2020-09-03.
  6. ^ a b c d «[MS-PAC]: SID Filtering and Claims Transformation». learn.microsoft.com. 2023-06-28. Retrieved 2024-12-29.
  7. ^ a b c d Honeycutt, Jerry (2005). Microsoft Windows Registry Guide. Microsoft Press. p. 11. ISBN 978-0-7356-2218-0.
  8. ^ «Outlook2007CodeSamples/SampleWrappedPSTStoreProvider/WrapPST/EdkMdb.h at 10edfa1ce7e6895a4788ad7c766b9120bec0128d · microsoft/Outlook2007CodeSamples». GitHub. Retrieved 2024-12-29.
  9. ^ See «Custom Principals» section on https://msdn.microsoft.com/en-us/library/aa480244.aspx
  10. ^ «Larry Osterman’s WebLog». 17 July 2020.
  11. ^ «Example impact of Microsoft Accounts on Windows APIs in Windows 8/8.1 – Windows SDK Support Team Blog». blogs.msdn.microsoft.com. 12 December 2014.
  12. ^ a b «Security identifiers». support.microsoft.com. 28 August 2021. Retrieved 2020-09-02.
  13. ^ «Some SIDs do not resolve into friendly names». support.microsoft.com. 24 September 2021. Retrieved 2020-09-02.
  14. ^ «Capability SID Constants (Winnt.h) — Win32 apps». docs.microsoft.com. Retrieved 2020-09-02.
  15. ^ «SYSTEM_MANDATORY_LABEL_ACE (winnt.h) — Win32 apps». learn.microsoft.com. 2024-02-22. Retrieved 2024-12-29.
  16. ^ a b «[MS-DTYP]: SID_IDENTIFIER_AUTHORITY». learn.microsoft.com. 2020-10-30. Retrieved 2024-12-29.
  17. ^ «Sandboxing Antimalware Products for Fun and Profit — Elastic Security Labs». www.elastic.co. 2023-02-21. Retrieved 2024-12-29.
  18. ^ «IIS AppPool Identity SIDs». winterdom. 2020-09-02.
  19. ^ «MS TechNet NewSID Utility — How It Works». Knowledge Base. Microsoft. November 1, 2006. Retrieved 2008-08-05.
  20. ^ a b c «NewSID v4.10». Windows Sysinternals. Microsoft. 2006-11-01.
  21. ^ «Windows Service Isolation Feature». Article. Windows IT Pro. June 6, 2012. Retrieved December 7, 2012.
  22. ^ Russinovich, Mark (2009-11-03). «The Machine SID Duplication Myth». Mark’s Blog. Microsoft – via Microsoft Learn’s blog archive.
  • Official
    • ObjectSID and Active Directory
    • Microsoft TechNet: Server 2003: Security Identifiers Technical Reference
    • MSKB154599: How to Associate a Username with a Security Identifier
    • MSKB243330: Well-known security identifiers in Windows operating systems
    • Support tools for Windows Server 2003 and Windows XP
    • Security Identifiers — Windows Security docs
  • Other
    • Why Understanding SIDs is Important
    • Microsoft Security Descriptor (SID) Attributes : Tutorial Article about SID handling / converting in scripts

SID (Security IDentifier) – это уникальный идентификатор, который присваивается пользователям, группам, компьютерам или другим объектам безопасности при их создании в Windows или Active Directory. Windows использует SID, а не имя пользователя для контроля доступа к различным ресурсам: сетевым папкам, ключам реестра, объектам файловой системы (NTFS разрешения), принтерам и т.д. В этой статье мы покажем несколько простых способов получить SID пользователя, группы или компьютера, и обратную процедуру – получить объект по известному SID.

Содержание:

  • Что такое SID объекта в Windows?
  • Как получить SID локального пользователя?
  • Узнать SID пользователя или группы в домене Active Directory
  • Получить SID компьютера
  • Как узнать имя пользователя или группы по известному SID?
  • Поиск объектов в Active Directory по SID

Что такое SID объекта в Windows?

Как мы уже сказали, SID (security identifier) позволяет уникально идентифицировать пользовали, группу или компьютер в пределах определенной области (домена или локального компьютера). SID представляет собой строку вида:

S-1-5-21-2927053466-1818515551-28245911311103.
В данном примере:

  • 2927053466-1818515551-2824591131 – это уникальный идентификатор домена, выдавшего SID (у всего объекта в одном домене эта часть будет одинакова)
  • 1103 – относительный идентификатор безопасности объекта (RID). Начинается с 1000 и увеличивается на 1 для каждого нового объекта. Выдается контроллером домена с FSMO ролью RID Master)

SIDы объектов Active Directory хранятся в базе ntds.dit, а SIDы локальных пользователей и групп в локальной базе диспетчера учетных записей Windows (SAM, Security Account Manager в ветке реестра HKEY_LOCAL_MACHINE\SAM\SAM).

В Windows есть так называемые известные идентификаторы безопасности (Well-known SID). Это SID встроенных (BuiltIn) пользователей и групп, которые есть на любых компьютерах Windows. Например:

  • S-1-5-32-544
    – встроенная группу Administrators
  • S-1-5-32-545
    – локальные пользователи
  • S-1-5-32-555
    – группа Remote Desktop Users, которым разрешен вход по RDP
  • S-1-5-domainID-500
    – учетная запись встроенного администратора Windows
  • И т.д.

В Windows можно использовать различные средства для преобразования SID -> Name и Username -> SID: утилиту whoami, wmic, WMI, классы PowerShell или сторонние утилиты.

Как получить SID локального пользователя?

Чтобы получить SID локальной учетной записи, можно воспользоваться утилитой wmic, которая позволяет обратится к пространству имен WMI (Windows Management Instrumentation) компьютера.

wmic useraccount where name='test_user' get sid

Узнать SID пользователя через WMI

Команда может вернуть ошибку, если репозиторий WMI поврежден. Воспользуйтесь этой инструкцией для восстановления WMI репозитория.

Команда вернула SID указанного пользователя —
S-1-5-21-1175651296-1316126944-203051354-1005
.

Чтобы вывести список SID всех локальных пользователей Windows, выполните:

wmic useraccount get name,sid.

Если нужно узнать SID текущего пользователя (под которым выполняется команда), используйте такую команду:

wmic useraccount where name='%username%' get sid

Можно обратится к WMI напрямую из PowerShell:

(Get-CimInstance -Class win32_userAccount -Filter "name='test_user' and domain='$env:computername'").SID

В новых версиях PowerShell Core 7.x вместо команды Get-WmiObject нужно использовать Get-CimInstance.

Но еще проще получить SID локального пользователя с помощью встроенного PowerShell модуля управления локальными пользователями и группами (Microsoft.PowerShell.LocalAccounts).

Get-LocalUser -Name 'test_user' | Select-Object Name, SID

powershell получить sid локалього пользователя в Windows

По аналогии можно получить SID локальной группы:

Get-LocalGroup -Name tstGroup1 | Select-Object Name, SID

Также вы можете использовать.NET классы System.Security.Principal.SecurityIdentifier и System.Security.Principal.NTAccount для получения SID пользователя с помощью PowerShell:

$objUser = New-Object System.Security.Principal.NTAccount("LOCAL_USER_NAME")
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value

Узнать SID пользователя или группы в домене Active Directory

Вы можете узнать SID своей доменной учетной записи командой:

whoami /user

whoami user getsid

Получить SID пользователя домена Active Directory можно с помощью WMIC. В этом случае в команде нужно указать имя домена:

wmic useraccount where (name='jjsmith' and domain=′corp.winitpro.ru′) get sid

Для получения SID доменного пользователя можно воспользоваться командлетом Get-ADUser, входящего в состав модуля Active Directory Module для Windows PowerShell. Получим SID для доменного пользователя jjsmith:

Get-ADUser -Identity 'jjsmith' | select SID

get-aduser select sid

Вы можете получить SID группы AD с помощью командлета Get-ADGroup:

Get-ADGroup -Filter {Name -like "msk-admin*"} | Select SID

Get-ADGroup получить sid доменной группы

Если на вашем компьютере не установлен модуль AD для PowerShell, вы можете получить SID пользователя с помощью классов .Net:

$objUser = New-Object System.Security.Principal.NTAccount("corp.wintpro.ru","jjsmith")

$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value

PowerShell - get SID via SecurityIdentifier and NTAccount

Эта же команда PowerShell в одну строку:

(new-object security.principal.ntaccount “jjsmith").translate([security.principal.securityidentifier])

Получить SID компьютера

Если компьютер с Windows добавлен в домен Active Directory, у него будет два разных SID. Первый SID – идентификатор локального компьютера (Machine SID), а второе – уникальный идентификатор компьютера в AD.

SID компьютера в домене Active Directory можно получить с помощью команды:

Get-ADComputer srv-rds1 -properties sid|select name,sid

get-adcomputer команда для получения SID компьютера в домене Active Directory

SID локального компьютера (Machine SID) можно получить с помощью бесплатной утилиты PsGetsid (https://docs.microsoft.com/en-us/sysinternals/downloads/psgetsid): Но ее придется скачивать и устанавливать на каждый компьютер вручную.

.\PsGetsid64.exe

Или просто, обрезав последние 4 символа RID и SID любого локального пользователя:

$user=(Get-LocalUser Administrator).sid
$user -replace ".{4}$"

PsGetsid6 вывести machine sid локального компьютера

Важно, чтобы у каждого компьютера в домене был уникальный локальный SID. Если вы клонируете компьютеры или виртуальные машины, или создаете их из одного шаблона, то перед тем как добавить их в домен нужно выполнить команду sysprep. Эта утилита сбрасывает локальный Machine SID. Это избавит вас от частых ошибок “Не удалось восстановить доверительные отношения между рабочей станцией и доменом”.

Как узнать имя пользователя или группы по известному SID?

Чтобы узнать имя учетной записи пользователя по SID (обратная процедура), можно воспользоваться одной из следующих команд:

wmic useraccount where sid='S-1-3-12-12452343106-3544442455-30354867-1434' get name

Для поиска имени доменного пользователя по SID используйте командлеты из модуля
RSAT-AD-PowerShell
:

Get-ADUser -Identity S-1-5-21-247647651-3952524288-2944781117-23711116

Чтобы определить имя группы по известному SID, используйте команду:

Get-ADGroup -Identity S-1-5-21-247647651-3952524288-2944781117-23711116

Get-ADGroup найти группу по SID

Также можно узнать получить SID группы и пользователя с помощью встроенных классов PowerShell (без использования дополнительных модулей):

$objSID = New-Object System.Security.Principal.SecurityIdentifier ("S-1-5-21-2470456651-3958312488-29145117-23345716")
$objUser = $objSID.Translate( [System.Security.Principal.NTAccount])
$objUser.Value

Поиск объектов в Active Directory по SID

Если вы не знаете к какому типу объекта AD относится SID и какой точно командлет нужно использовать для его поиска (Get-AdUser, Get-ADComputer или Get-ADGroup), вы можете использовать универсальный метод поиска объектов в Active Directory по SID с помощью командлета Get-ADObject

$sid = ‘S-1-5-21-2470146651-3951111111-2989411117-11119501’
Get-ADObject –IncludeDeletedObjects -Filter "objectSid -eq '$sid'" | Select-Object name, objectClass

Get-ADObject поиск объектов в AD по известному SID

В нашем случае объект AD, который имеет данный SID, является компьютером (objectClass=computer).

The Security Identifier (SID) plays a pivotal role in maintaining the integrity and accessibility of system resources. Unique to each user, group, and security entity within the system, the SID is a fundamental component that dictates access rights and permissions.

This article aims to demystify the concept of the SID in Windows Security, offering an in-depth exploration of its functionality, significance, and operational mechanics.

In this article:

  1. What is the Security Identifier (SID)?
  2. Understanding SID Structure and Composition
  3. Management of SIDs in Windows
  4. SIDs and Access Control
  5. SIDs in System Administration
  6. Troubleshooting SID-Related Issues
  7. Advanced Topics in SID
  8. References
Security Identifier (SID) conceptual representation

1. What is the Security Identifier (SID)?

A Security Identifier (SID) in Windows Security is a unique string of characters assigned to each user, group, or other security principal. It serves as the primary token in determining access rights and permissions within the Windows operating system. The SID is critical in the security infrastructure, as it is used to control access to objects like files, directories, and printers, ensuring secure and appropriate access for users and groups.

The structure of a SID includes a series of numerical values separated by hyphens. These values contain information about the security entity’s creation and origin, such as the issuing authority and a unique identifier for the user or group. The SID is assigned at the creation of the account or group and remains constant throughout the lifecycle of the account, even if the user or group’s name is altered.

2. Understanding SID Structure and Composition

Breakdown of SID Format

A Security Identifier (SID) in Windows Security is structured as a string of alphanumeric characters, uniquely representing each security principal (like a user or group). The format of an SID can be dissected into several components:

  1. Identifier Authority. This segment indicates the entity that issued the SID, typically representing the Windows OS or a domain controller.
  2. Subauthority Values. Following the identifier authority are subauthority values, which include the domain identifier and a unique identifier for the user or group within that domain.
  3. Revision Level. The SID begins with a revision level, indicating the version of the SID structure. This is usually a single digit.

An example of an SID is “S-1-5-21-1180699209-877415012-3182924384-1004”. Here, ‘S’ represents the string as an SID, ‘1’ is the revision level, ‘5’ is the identifier authority, and the subsequent numbers are the subauthority values.

How SIDs are Generated

SIDs are generated when a new user account or security group is created. The process involves:

  1. Assignment by the System. The SID is automatically generated by the operating system or the domain controller, ensuring its uniqueness within the domain or local machine.
  2. Combination of Domain SID and Unique RID. For domain accounts, the SID combines the domain’s unique SID with a relative identifier (RID) unique to the account within that domain.

3. Management of SIDs in Windows

Creating and Assigning SIDs

In Windows, SIDs are created and assigned as follows:

  1. Automatic Creation During Account Setup. When a new user or group is created, Windows automatically generates a unique SID for that entity.
  2. System-Level Assignment. The SID is assigned at the system level and is integral to the entity’s security profile within the Windows environment.

Managing SID Changes

  1. Renaming Users or Groups. When a user or group is renamed, the SID remains unchanged. This design ensures that the security permissions and access rights associated with the account are maintained despite the name change.
  2. Handling Duplicate SIDs. In scenarios like system cloning, duplicate SIDs can occur. Windows provides tools like Sysprep with a security ID reset option to handle such situations, ensuring that each entity has a unique SID.
  3. SID History. In domain environments, when user accounts are migrated between domains, the SID history attribute maintains a record of the user’s previous SIDs, preserving access to resources across domain boundaries.

In summary, the structure, composition, and management of SIDs are critical to the security and operational integrity of Windows environments. Their unique and immutable nature ensures consistent and secure access control, while the system’s ability to manage SID changes underpins the flexibility and robustness of Windows security.

4. SIDs and Access Control

Role of SIDs in Access Control Lists (ACLs)

Security Identifiers (SIDs) play a crucial role in implementing access control mechanisms within Windows environments. Their primary function is manifested in Access Control Lists (ACLs), which are pivotal in defining permissions for users and groups.

  1. Defining Access Rights: Each ACL contains a series of Access Control Entries (ACEs), each of which associates a user or group’s SID with specific access rights to a resource, such as a file or directory.
  2. Unique Identification: The unique nature of SIDs allows ACLs to accurately identify which permissions apply to which user or group, regardless of name changes or other alterations.
  3. Granular Control: By leveraging SIDs, ACLs can provide granular control over resources, specifying exactly what type of access each user or group has, ranging from read-only to full control.

How SIDs Facilitate Security Permissions

SIDs facilitate security permissions by ensuring that each access request is authenticated and authorized based on the SID attached to the user or group. When a user attempts to access a resource:

  1. Authentication Check: The system first verifies the user’s identity through their SID.
  2. Permission Verification: It then checks the ACL of the requested resource to see if an ACE exists that matches the user’s SID, and what level of access is permitted.
  3. Access Decision: Based on this information, the system allows or denies access, ensuring that users can only access resources for which they have explicit permissions.

5. SIDs in System Administration

SID Usage in User and Group Management

In system administration, SIDs are integral in the management of users and groups:

  1. Consistent Identity. SIDs provide a consistent way to identify accounts, even if their names change, ensuring that permissions and policies remain correctly associated with users and groups.
  2. Security Policy Enforcement. Administrators use SIDs to enforce security policies across the network, ensuring the correct application of security settings based on user or group identities.

Tools and Commands for SID Management

Several tools and commands assist in managing SIDs in a Windows environment:

  1. Security Policy Editor. This tool allows administrators to assign and modify user and group permissions, utilizing SIDs to identify the correct accounts.
  2. Windows PowerShell Commands. PowerShell provides commands like Get-ADUser and Get-ADGroup for retrieving the SID of users and groups in Active Directory environments.
  3. Sysinternals Suite. Tools like PsGetSid from the Sysinternals Suite can be used to display the SID of a computer or a user.
  4. Active Directory Administrative Center. For domain environments, this tool allows for the management of user accounts and groups, where SIDs are a key part of the account properties.

In summary, SIDs are indispensable in access control and system administration within Windows environments. They provide a robust mechanism for identity verification, permission allocation, and security policy enforcement, underpinning the security architecture of Windows systems. The tools and commands available for SID management enable administrators to maintain and oversee these critical security identifiers effectively.

Common Problems Associated with SIDs

In managing Windows environments, several issues can arise related to SIDs:

  1. Duplicate SIDs. This usually occurs in environments where systems are cloned without properly resetting SIDs, leading to security and access issues.
  2. Orphaned SIDs. When user accounts are deleted but their SIDs remain in ACLs, it can lead to confusion and clutter in access control settings.
  3. SID Misalignment. This happens when SIDs in ACLs do not correspond to any existing user or group, often due to domain migrations or restructuring.

Best Practices for Resolving SID Conflicts

To effectively handle SID-related issues, the following best practices are recommended:

  1. Use of Sysprep Tool. For system cloning, use the Sysprep tool with the option to reset SIDs, ensuring each system has a unique SID.
  2. Regular Audit of ACLs. Periodically audit ACLs to identify and remove orphaned SIDs, maintaining clarity in access controls.
  3. Proper Domain Migration Tools. When migrating users between domains, use tools that manage SID history and translation to ensure continuity of access rights.

7. Advanced Topics in SID

SID History and SID Filtering in Trusts

SID history is a feature that retains a user’s old SID when they are moved to a new domain, allowing continued access to resources that were permitted under the old SID. In trust relationships between domains, SID filtering is crucial to prevent malicious use of SID history, ensuring that only appropriate SIDs from trusted domains are honored.

The Impact of SID on Network Security and Domain Environments

In network security and domain management, SIDs are fundamental in defining and enforcing security boundaries:

  1. Security Boundary Definition. SIDs help in defining security boundaries by uniquely identifying users and groups, crucial for implementing security policies.
  2. Access Control in Domains. SIDs are vital in managing access controls in domain environments, ensuring that rights and permissions are accurately assigned and enforced.

8. References

Technical Documentation from Microsoft

  1. Microsoft’s official documentation on SID structure and management.
  2. Security guidelines and best practices for SID management.

Key Resources and Further Readings

  1. “Windows Security Essentials” by Darril Gibson.
  2. “Windows Internals” by Mark Russinovich and David Solomon, particularly sections discussing security and user management.

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как добавить приложение в карантин windows 10
  • How to install windows on dosbox
  • Путь сбойного модуля c windows system32 cdp dll
  • Выполнить команду от другого пользователя windows
  • Автоматический вход в windows 10 после спящего режима