Одной из проблем в Active Directory является множество имен, которые можно использовать для обозначения или описания объекта. Большинство этих имен являются атрибутами (или свойствами) объекта. Путаница возникает из-за того, что один и тот же атрибут может иметь разное имя, в зависимости от используемого провайдера. Кроме того, имя одного атрибута может ссылаться на другой атрибут, что также не добавляет ясности. Ну и наконец, у атрибутов существуют методы (функции), которые вычисляют значение имени из других атрибутов.
Попробуем разобраться в этой ситуации на примере объекта пользователя. Для этого откроем оснастку Active Directory Users and Computers (ADUC) и создадим новую учетную запись. При создании мы указываем Имя (First name), Фамилию (Last name) и инициалы (Initials), из которых формируется полное имя (Full name). Ну и целых два имени для входа — User logon name и User logon name (pre-Windows 2000).
А теперь перейдем к редактору атрибутов и посмотрим что получилось. Для этого необходимо в оснастке ADUC в меню View отметить пункт Advanced Features.
Открываем редактор атрибутов и видим знакомые имена, но под совершенно разными названиями.
Полному имени здесь соответствуют целых три атрибута — name, displayName и cn. Можно подумать, что это одно и то же, но нет — это совершенно разные атрибуты пользователя.
Полное имя (name) и общее имя (Common name, cn) — это два разных атрибута, хотя возвращают они одно и то же значение. Это происходит потому, что атрибут name аналогичен относительному отличительному имени (Relative Distinguished Name, RDN), а RDN — это часть отличительного имени (Distinguished Name, DN). Так если DN равно ″CN=Иванов Иван Иванович,CN=Users,DC=Test,DC=local″, то RDN будет ″CN=Иванов Иван Иванович″. Отсюда получаем, что если cn = ″Иванов Иван Иванович″, то name = ″cn=Иванов Иван Иванович″.
Получается довольно запутанно. Но если посмотреть с практической точки зрения, то можно сказать так — изменить значение атрибута cn мы не можем, оно всегда будет равно значению атрибута name.
Отображаемое имя (displayName) по умолчанию формируется по такому же принципу, как полное (name) и общее (cn) имена, однако не зависит от их значений. Для проверки изменим полное имя нашего пользователя. Как видите, полное и отображаемое имена изменяются независимо друг от друга.
А в редакторе атрибутов видим, что вместе со значением атрибута name изменилось и значение cn, хотя его мы и не меняли.
Кстати, кроме отображаемого имени (displayName) у пользователя есть еще отображаемое имя для печати (displayNamePrintable). Это два разных, независимых друг от друга атрибута.
Примечание. Атрибут displayNamePrintable используется почтовым сервером Exchanhe при отправке сообщений вне организации. Его можно использовать в том случае, если необходимо в письме показывать имя пользователя, отличное от DisplayName (напр. англоязычный вариант).
Идем дальше. Имя соответствует атрибуту givenName, а фамилия — атрибуту sn (Surname). Может найдется и отчество? Давайте попробуем поискать его с помощью PowerShell, командой:
Get-ADUser ivanov_ii -Properties * | select *name
Нашелся атрибут с названием OtherName, возможно это оно и есть?
Зададим этому атрибуту значение:
Get-ADUser ivanov_ii -Properties * | Set-ADUser -OtherName "Иванович"
и проверим что получилось. А получилось сразу два новых атрибута — OtherName и MiddleName, оба с заданным значением.
На самом деле это просто два названия одного и того же атрибута:
cn: OtherName
ldapDisplayName: MiddleName
При этом если в PowerShell мы видим оба имени, то в оснастке ADUC отображается только одно MiddleName.
Переходим к именам входа (logon names), которых у пользователя тоже два.
Если посмотреть в редакторе атрибутов, то User logon name (pre-Windows 2000) скрывается под именем sAMAccountname, а User logon name соответствует атрибуту userPrincipalName.
Давайте немного углубимся в детали и посмотрим, чем же отличаются эти два имени.
sAMAccountName — имя учетной записи SAM. Предназначено для для совместимости со старыми (до Windows 2000) операционными системами. Впрочем это не означает, что sAMAccountName не используется в качестве имени для входа в современных системах Windows. sAMAccountname должно быть уникальным в рамках домена, имеет ограничение в 20 символов и работает в сочетании с NETBIOS именем домена, например TEST\ivanov_ii. sAMAccountName является обязательным атрибутом пользователя.
userPrincipalName (UPN) — имя участника-пользователя. Это новый формат указания имени пользователя для входа в систему, основанный на интернет-стандарте RFC 822. Для входа используется сочетание имени пользователя с доменным суффиксом, например ivanov_ii@test.local. Имя участника-пользователя должно быть уникальным среди всех объектов-участников безопасности в лесу доменов. Максимальная длина UPN составляет 1024 символа. UPN не является обязательным атрибутом, оно может быть не назначено при создании учетной записи пользователя.
И еще два важных имени, которые есть у пользователя. Это DistinguishedName (различающееся имя) и CanonicalName (каноническое имя). Оба эти атрибута однозначно определяют объект в Active Directory.
Различающееся имя включает в себя относительное отличительное имя объекта (RDN), а также полный путь к контейнеру, содержащему объект в Active Directory, например ″CN=Иванов Иван Иванович,CN=Users,DC=Test,DC=local″. Каноническое имя — это то же различающееся имя объекта, но в каноническом виде, например ″test.local/Users/Иван Иванович Иванов″.
Примечание. CanonicalName является конструируемым атрибутом (constructed attribute). Такие атрибуты не хранятся явным образом в AD, а вычисляются на лету при получении соответствующих запросов.
Как видите, у пользователя в Active Directory множество различных имен. Чтобы немного их упорядочить я составил небольшую табличку, в которую внес все атрибуты пользователя, так или иначе имеющие отношение к его имени.
Имя атрибута | Имя в оснастке ADUC | Описание | Значение (пример) |
givenName | First name | Имя | Иван |
sn (SurName) | Last name | Фамилия | Иванов |
OtherName (middleName) | Дополнительное имя (напр. отчество) | Иванович | |
Initials | Initials | Инициалы | И |
CommonName (cn) | Общее имя | Иванов Иван Иванович | |
name | Full name | Полное имя | Иванов Иван Иванович |
displayName | Display name | Отображаемое имя | Иванов Иван Иванович |
DisplayNamePrintable | Отображаемое имя для печати | Иванов Иван Иванович | |
DistinguishedName (DN) | Отличительное (уникальное) имя | CN=Иванов Иван Иванович,CN=Users,DC=Test,DC=local | |
sAMAccountName | User logon name (pre-Windows 2000) | Имя входа пользователя (пред-Windows 2000) | Ivanov_ii |
userPrincipalName | User logon name | Имя входа пользователя | Ivanov_ii@test.local |
CanonicalName | Canonical Name | Имя объекта в каноническом формате | test.local/Users/Иван Иванович Иванов |
Ну а теперь главное) Как вы думаете, нужны ли все эти имена для создания учетной записи пользователя. Чтобы выяснить это, откроем редактор атрибутов и отфильтруем все атрибуты кроме обязательных (Mandatory). И оказывается, что для пользователя обязательными являются всего два имени — CommonName (cn) и sAMAccountName. Безо всех остальных пользователь может легко обойтись.
На этом все. А все возможные атрибуты пользователя в схеме Active Directory можно посмотреть вот здесь : https://learn.microsoft.com/en-us/windows/win32/adschema/c-user?redirectedfrom=MSDN
This basic article is intended to provide a background in different Active Directory user name and domain name formats and how they are used by applications for basic and integrated authentication process within Windows Server.
The guidance provided throughout is targeted towards working with Microsoft Lync, Exchange, and third-party solutions or applications which support direct registration and authentication to these Microsoft UC platforms.
In most environments registration is as simple as typing in a SIP Address, username, and password which is the same information that native Lync and Outlook clients will leverage for connectivity and authentication. But in some more complex environments it may be necessary to known more specific information about the user accounts used to authenticate clients as these Active Directory deployments can often times use a variety of mismatched user name and domain name formats.
Thus it is beneficial to understand the following concepts in order to identify what is often simply a failure to register due to incorrect entering account credential information. The specifications and limitations of these formats are detailed in this TechNet article.
Domain Names
Active Directory supports two separate types of domain name formats since it’s introduction into Windows Server 2000.
Legacy Domain Name
The Legacy Domain Name parameter, which is also commonly referred to as the NetBIOS Domain Name, is a carryover from Windows NT and is limited to 15-characters. (NetBIOS names are 16-characters in length but the last character is hidden and is used to identify the name record type.) This is the value commonly used with the DOMAIN\username format when signing into various Microsoft applications and even though it is not case-sensitive this string is traditionally shown all in uppercase as a matter of good practice. Although it is considered a legacy format it is still the most prevalently used format today for user authentication.
DNS Domain Name
The DNS Domain Name parameter was added in Active Directory with the release of Windows 2000 and supports up to 24-characters for the hostname portion, but the Fully Qualified Domain Name can be much longer (e.g. subdomain1.subdomain2.domain.com).
As indicated in the screenshots above the sample environment is using a legacy domain name that is shorter than 15 characters so the same string can be used for both formats. This is ideal and is the general best practice used in the field; to select shorter domain names when designing an Active Directory forest so that authentication can be simplified across Microsoft and third-party applications which may use one or both formats. Unfortunately this is not always the case as mergers and divestitures over time can lead to more complicated Active Directory environments. Although newer versions of Windows Server does allow for these domain names to be changed post-deployment this is almost never actually attempted in the field due to the massive impact on the entire environment.
Alternatively the following screenshot shows an AD domain in which the two type use entirely different values (verylongdnsdomainname.com vs. SHORTNAME).
User Names
Just as with domain names there are two different formats in Active Directory for storing user names:
Legacy User Logon Name
The User Logon Name (Pre-Windows 2000) is the legacy format from Windows NT and is often referred to using the raw attribute name of sAMAccountName. This field is limited to a maximum of 20 characters and is used in conjunction with the legacy (or NetBIOS) domain name.
User Logon Name
The User Logon Name is a the newer username format which is often mistakenly referred to as the User Principal Name (UPN). That term is used to indicate the entire user name and domain name format.comprised of the User Logon Name and the UPN Suffix which is shown in the drop-down menu in the screenshot below.
Just as with domain name formats the user names can also be unique. Depending on the naming conventions used in the directory it is more common to have long user names truncated to 20 characters in the legacy user name field. In the complex example shown below a user name of 36 characters (e.g. abcdefghijklmnopqrstuvwxyz0123456789) is automatically truncated to only 20 characters in the legacy field.
Authentication Formats
Once the user name and domain name formats are clearly identified then they are assembled into pairs in specific formats to be used for authentication. The ubiquitous NTLM authentication used in Windows Server can support two different formats.
Legacy
The legacy format requires that the Legacy (NetBIOS) Domain Name value is used with the legacy User Logon Name (sAMAccountName).
Simple Example: SCHERTZ\jeff
Complex Example: SHORTNAME\abcdefghijklmnopqrst
User Principal Name
The newer User Principal Name format is comprised of the User Logon Name (not the legacy sAMAccountName) and the UPN Suffix assigned to the specific user account.
Simple Example: jeff@schertz.local
Complex Example: abcdefghijklmnopqrstuvwxyz0123456789@verylongdnsdomainname.com
It is important to understand that although the DNS Domain Name is the default assigned UPN Suffix for all user accounts created in the domain this value can be changed and customized in Active Directory. So in the event that the Active Directory namespace (e.g. schertz.local) does not match the Lync SIP Domain namespace (e.g. mslync.net) it is still possible to provide a simplified user sign-in experience by defining an additional UPN suffix which matches the SIP domain and then assigning that suffix to all desired user accounts.
- The following screenshot shows how an additional UPN suffix (e.g. mslync.net) can be added to the forest using the Active Directory Domains and Trusts application.
- Once this is defined then it will appear as a choice for all user accounts in the domain and can be selected in the Active Directory Users and Computer utility.
In the example above it would be possible to provide the same ‘string’ to users as both their SIP Address and User Principal Name even when separate namespaces are used between AD and Lync. This approach allows Lync users to enter the same information for both their Sign-In Address and their User Name. In fact in a recent Cumulative Update for the Lync client the sign-in behavior was changed to actually assume that the AD user name is the same as the SIP address during the first authentication attempt, and then if that fails (due to unique values being used for both) then the User Name field will be presented to the user to fill-out for a second attempt. This change in behavior makes the client more ‘cloud’ friendly as the default configuration for Office 365 and most hosted deployments of Lync will set these fields to the same values.
Hopefully this post has provided some clarity between the different user name formats and in turn help reduce confusion when signing. When the credentials are known to be accurate and in the proper format this make issues much easier to troubleshoot as it takes the uncertainty of out of equation.
After 2 month break (not that i have no idea!!), but since i’m busy with my Ethical Hacking & Pentest training, i have no time to deep dive to my server & write some blog..
anyway, today lets go through a simple step how we can change User Logon Name (pre-Windows 2000) using ADSI EDIT.
This actually happened to me in my few classes, where me & my students trying to change User Logon Name (pre-Windows 2000) in Server 2012 R2,
Why we need to change this? well, 1st, you might have VM with preloaded domain name, and you do not want to create a new domain infrastructure and to same a lot of time, we just need to rename our existing domain name to what ever name that we want.
for those who still wondering what am i talking about & how to rename domain name, please refer to my previous blog :
Simple Guide : How to Rename Domain Name in Windows Server 2012?
The issue here is simple, once you rename the domain, i notice that the User Logon Name (pre-Windows 2000) is not changing, it still remain with old NETBIOS name from previous domain, even my others domain member server & domain clients can log in to their profile.
its very annoying to me to see this issue, so to solve this issue, we need to so some minor changes in ADSI EDIT.
Lets get started :
1 – open your ADUC and check for the issue, in ADUC select any of the existing user and double click on it.
— click Account tab and notice that under User Logon name:, its stated my user connected to osi.com.my domain, but on the User Logon name (pre-Windows 2000), it still stated with my old domain name (Adatum) and this must go away…
2 – Next, open Server Manager, click Tools and then click ADSI EDIT…
3 – On the ADSI Edit console, right click ADSI Edit and then click Connect to….
4 – On the Connection Settings box, click Select a well known Naming Context: and then in the list click Configuration…
5 – On the ADSI Edit console, browse to CN=Partitions, and on the right side if you notice, under name, its stated CN=ADATUM (which is my old domain name), and my Directory Partition Name is DC=osi,DC=com,DC=my…
— you need to double click the CN=ADATUM..
6 – On the CN=ADATUM box, under Attributes:, browse to nETBIOSName, and the click Edit…
— on the String Attribute Editor, under Value change to your new domain name, which is in my case OSI, and then click OK..
— Reboot your Domain server for the changes to take effect.
7 – Once your domain server reboot, log in to any of your client PC, and click Other user…
8 – On the Other user interface, you can log in using our new domain successfully.
Подключал намедни линуксовый сервис для авторизации через AD, еле нашел описание соответствий атрибутов и их полей, да и те все на английском, что не очень удобно при русскоязычной системе, потому что хрен поймешь какие параметры за что отвечают. Чтобы каждый раз не выискивать их adexplorer’ом, решил составить таблицу основных атрибутов Active Directory.
Attribute \ Атрибут | Англоязычное название | Русскоязычное название | Value \ Значение |
OU (Organizational Unit) \ Подразделение | |||
distinguishedName | Distinguished Name | Отличительное (уникальное) имя | OU=Компания,DC=domain,DC=com |
name | Компания | ||
Group \ Группа | |||
distinguishedName | Distinguished Name | Отличительное (уникальное) имя | CN=Группа,OU=Компания,DC=domain,DC=com |
name | Группа | ||
member | Members | Члены группы (какие пользователи входят в данную группу) | CN=Сергей Петрович Иванов,OU=Компания,DC=domain,DC=com |
User \ Пользователь | |||
DN | Distinguished Name | Отличительное (уникальное) имя | CN=Сергей Петрович Иванов,OU=Компания,DC=domain,DC=com |
DC | Domain Component | Компонент(класс) доменного имени. | DC=domain,DC=com |
OU | Organizational Unit | Подразделение | Компания |
CN | Common Name | Общее имя | Сергей Петрович Иванов |
givenName | First name | Имя | Сергей Петрович |
name | Full name | Полное имя | Сергей Петрович Иванов |
sn (SurName) | Last name | Фамилия | Иванов |
displayName | Display Name | Выводимое имя | Сергей Петрович Иванов |
Электронная почта | mail@domain.com | ||
sAMAccountName | User logon name (pre-Windows 2000) | Имя входа пользователя (пред-Windows 2000) | IvanovSP |
userPrincipalName | User logon name | Имя входа пользователя | IvanovSP@domain.com |
memberOf | Member Of | Член групп (в какую группу входит данный пользователь) | CN=Группа,OU=Компания,DC=domain,DC=com |
Стоит отметить, что пользовательский displayName ≠ CN = Full name\Полное имя = namе
, что можно видеть на последнем скрине.
Для более наглядного понимая приложу скрины:
Атрибут userAccountControl
Иногда надо понять включена или отключена учетная запись в AD. Или что еще с ней вообще происходит. За это отвечает атрибут userAccountControl, который является суммой нескольких свойств атрибутов. При этом, значение 512 является значением по умолчанию при всех снятых флагах на вкладке «Учетная запись» и каждый дополнительный параметр прибавляется к нему. Например, значения атрибута userAccountControl для наиболее распространенных случаев:
512
— Включена (Enabled)
514 (512+2)
— Отключена (Disabled)
66048 (512+65536)
— Включена, срок действия пароля не ограничен (Enabled, password never expires)
66050 (512+65536+2)
— Отключена, срок действия пароля не ограничен (Disabled, password never expires)
Список основных значений атрибутов userAccountControl:
HEX | DEC | Описание |
0x00000002 | 2 | Учетная запись отключена |
0x00000010 | 16 | Учетная запись заблокирована |
0x00000020 | 32 | Пароль не требуется |
0x00000040 | 64 | Запретить смену пароля пользователем |
0x00000080 | 128 | Хранить пароль, используя обратимое шифрование |
0x00000200 | 512 | Учетная запись по умолчанию. Представляет собой типичного пользователя |
0x00010000 | 65536 | Срок действия пароля не ограничен |
0x00040000 | 262144 | Для интерактивного входа в сеть нужна смарт-карта |
0x00400000 | 4194304 | Без предварительной проверки подлинности Kerberos |
0x00800000 | 8388608 | Пароль пользователя истек |
Подробное описание всех атрибутов
The samAccountName is defined in MSDN.
LDAP Attribute Definition#
The SamAccountName AttributeTypes is defined as:
- OID of 1.2.840.113556.1.4.221
- NAME: SamAccountName
- DESC: User logon name (pre-Windows 2000)
- EQUALITY:
- ORDERING:
- SYNTAX: 1.3.6.1.4.1.1466.115.121.1.15
- SINGLE-VALUE
- Used as MUST in:
- securityPrincipal
- Used MAY in:
Interesting Aspects#
- SamAccountName attribute is a SINGLE-VALUE attribute that is the logon name used to support clients and servers from a previous version of Windows.
- SamAccountName MUST be less than 20 characters — with clients and servers running earlier versions of the Operating System, such as Windows NT 4.0, Windows 95, Windows 98, and LAN Manager
- The schema reports the size for {$pagename}] as a upper-range of 256.
- «pre-Windows 2000 logon name» is the label in MMC Account Tab
- SamAccountName value must be a Unique Identifier among all security principal objects within a AD DOMAIN.[7]
- SamAccountName is a Ambiguous Name Resolution value
Required?#
As far as we know, although the schema and MSDN states it is «required», Windows Server 2003 and later will create SamAccountName for you if you don’t specify it, but it is real ugly like: $9J2000-F2RTQRTA7C5F.
Windows Server 2000 Microsoft Active Directory does not create SamAccountName, you must specify a value.
Restricted Values#
There some value restrictions in regards to the characters but we can not find any «official» documentation to what the restrictions are.
When you apply a bad value SamAccountName in Windows Server 2003, you will receive an error:
Error while executing LDIF - [LDAP: error code 80 - 00000523: SysErr: DSID-031A0FB6, problem 22 (Invalid argument), data javax.naming.NamingException: [LDAP: error code 80 - 00000523: SysErr: DSID-031A0FB6, problem 22 (Invalid argument), data 0
We found a reference showing the following characters invalid in SamAccountName’s: (Windows Server 2003)
" [ ] : ; | = + * ? < > / \ ,
These appears to work:
! @ # $ % ^ & ~ `
We have seen it written[1] that the following are valid:
- unicode characters, but accented characters generate collisions. So you can provision jmüller today and if tomorrow you try to provision jmuller, you will get a collision. So better normalize your SamAccountNames.
- The SamAccountName cannot end with . (period).
- Blanks (space) are allowed.
RegEx For Verification[2]#
We have used this and it appears to work:
^(?:(?:[^. \"\/\\\[\]\:\|\\+\=\;\?\*\<\>\,][^\"\/\\\[\]\:\|\\+\=\;\?\*\<\>\,]{0,62}[^. \"\/\\\[\]\:\|\\+\=\;\?\*\<\>\,])|[^.\"\/\\\[\]\:\|\\+\=\;\?\*\<\>\,])$
This translates to:
- Not Starting with a period (.) or a space ( ). — This, by design, excludes strings consisting solely of all periods (.) or spaces ( ).
- Between 1 and 64 characters (inclusive) long.
- Not including any of these characters: » [ ] : ; | = + * ? < > / \ ,
- Not ending in a period (.).
- I realize the page says 63 characters, but my testing shows 64 to be valid (Windows Server 2008) yet schema page [1] says 256!!! Adding or Modifying SamAccountName
Adding or modifying a user, from LDAP, with a samAccountName value that is the same value of an existing user entry will result in the following error:
Error while executing LDIF - [LDAP: error code 68 - 00000524: UpdErr: DSID-031A0F4F, problem 6005 (ENTRY_EXISTS), data javax.naming.NameAlreadyBoundException: [LDAP: error code 68 - 00000524: UpdErr: DSID-031A0F4F, problem 6005 (ENTRY_EXISTS), data 0
More Information#
There might be more information for this subject on one of the following:
- 1.2.840.113556.1.4.221
- ANR attribute set
- Active Directory Computer Related LDAP Query
- Ambiguous Name Resolution
- LDIF Generator
- MAD Naming Attributes
- MMC Account Tab
- MsDS-AdditionalSamAccountName
- Password Character Composition
- Password Flow From Active Directory to eDirectory
- SamAccountName
- SecurityPrincipal