Как найти пользователя по sid в ad

Given the SID of a user or a group, how can I find a LDAP object that belongs to it?
LDAP Server ist Active Directory (Windows Server 2008).

A LDAP query String would be useful.

asked Aug 17, 2011 at 8:03

mtm's user avatar

4

I wish it was as easy as:

dsget user "objectSID={thesid},CN=Users,DC=domain,DC=com" -samid

But it’s not; AD stores the objectSID as hexadecimal.

The folks on serverfault have written a few answers that may help, though:

Retrieve user details from Active Directory using SID

Jossef Harush Kadouri's user avatar

answered Aug 17, 2011 at 10:39

quux's user avatar

quuxquux

5,3681 gold badge24 silver badges36 bronze badges

1

Another way would be to forsake LDAP and use WMIC:

H:>wmic useraccount where (sid = "S-1-5-21-1698188384-1693678267-1543859470-6637") get * /format:list    

AccountType=512
Caption=MYDOMAINquux
Description=some guy's account
Disabled=FALSE
Domain=MYDOMAIN
FullName=Some Guy
InstallDate=
LocalAccount=FALSE
Lockout=FALSE
Name=quux
PasswordChangeable=TRUE
PasswordExpires=FALSE
PasswordRequired=TRUE
SID=S-1-5-21-1698188384-1693678267-1543859470-6637
SIDType=1
Status=OK

Now you have several attributes that should be easy to search via LDAP, if you still need to.

answered Aug 17, 2011 at 10:45

quux's user avatar

quuxquux

5,3681 gold badge24 silver badges36 bronze badges

2

I see this one is old, but you can do this in ADUC by going to Custom Search and clicking on the advanced tab.

LDAP query string is: (objectSID=SID)

Replace «SID» with the SID that you’re looking for.

I’ve had to do translations from SID to name and back to SID (for foreign security principals) in PowerShell using the following code:

function Find_By_SID($SID) {

    //Searches Active Directory by SID
    //Returns NetBios Name 
    // Example output: CONTOSOUser1

    $account = New-Object Security.Principal.SecurityIdentifier("$SID")
    $netbios = $account.Translate([Security.Principal.NTAccount])

    return $netbios.Value

}

answered Apr 26, 2013 at 22:42

Tim Wilde's user avatar

Tim WildeTim Wilde

331 silver badge5 bronze badges

It is to search by SID using an LDAP query. For example:

dsquery * domainroot -filter "(objectSid=S-1-5-21-blah-blah-blah-500)"

or, in PowerShell,

Get-ADuser -LDAPFilter '(objectSid=S-1-5-21-blah-blah-blah-500)'

will get the domain Administrator account, if you sub in your domain value for blah-blah-blah.

answered Mar 19, 2019 at 15:36

user2871239's user avatar

user2871239user2871239

1752 silver badges9 bronze badges

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_MACHINESAMSAM).

В 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).

There are a handful of tools and scripted solutions floating around for resolving SIDs to user accounts and the reverse, but here’s a handy way to do this by simply using Active Directory Users and Computers.

The first time you perform this for a domain it will be necessary to identify the RID and GUID portions of the domain’s SID, so that you can create an LDAP Query, and then any future lookups will only require some quick match to convert the GUID portion into a format suitable for searching AD with.  (The Additional Account Info tab makes it easy to double-check your work, so grab it from the Account Lockout and Management Tools page on Microsoft Download if you aren’t already using it; it’s a great plug-in for ADUC.)

The scenario is that we have a SID for an unknown user account in the domain and we need to figure out what user account it belongs to.  For example, maybe there is a large Recycle Bin (which displays the file owner’s SID) sitting on a terminal server with hundreds of local profiles and we need to know what user it belongs to.  Whatever the reason, having a Saved Query in ADUC is handy when you need to perform quick LDAP searches on AD.

So go ahead and create a new query and name it SID Search. Set the Find field to Custom Search and copy/paste this string into the Advanced tab:

(&(objectCategory=user)(objectSID=NULL))

This search will clearly not return anything, as NULL is just a place holder for the time being.  What needs to go in it’s place is an objectSid value in a particular format.  Let’s go ahead and pull the value from my own user account in my test lab to test this search query.

Using ADSI Edit I’ll copy the objectSid value as displayed in hexadecimal format:

image

And then paste it into a plain text file, replacing all the spaces with characters:

image

This -separated string should replace the NULL in our search query.  Hit refresh on the SID Search query and the results should appear:

image

Now we have a quick search that can be used by replacing the value of the objectSID in the query with the SID for an unknown user and ADUC will quickly return the matching user account (if it has not been deleted from AD.)

Where things get a little tricky is a SID is typically represented like this: S-1-5-21-1077035949-4083587494-3467333957-1607.  For the mechanics of converting a SID in this format into hexadecimal for the purposes of using our query, take a look at one of my old blog entries which explains the math behind this process.  I’ll quickly run through the steps here as once your understand the process it’s very easy to perform routinely.

  1. Record the unknown User’s SID: S-1-5-21-1077035949-4083587494-3467333957-1138
  2. Compare to another account in the same domain to isolate and verify the GUID portion (typically the value after the last hyphen): 1138
  3. Use calc.exe in Scientific Mode to convert 1140 decimal into hexadecimal: 472
  4. Rewrite that value in 8 digit format: 00000472
  5. Separate the value in pairs of digits: 00 00 04 72
  6. Re-order the pairs in reverse: 72 04 00 00
  7. Replace the last 4 hexadecimal values in the query string: 47600 becomes 72400

image

So I’ve discovered that the domain user account for S-1-5-21-1077035949-4083587494-3467333957-1138 is actually RTCService.  This simple query is just one example; you could change the query with (objectCategory=*) to broaden the search scope to include security groups and other non-user account objects if desired.

More LDAP Queries

In fact, here are some other custom queries I have made out of necessity which have proven to be quite handy.  Once you understand how a specific AD attribute is used it’s quite easy to create simple queries to identify subsets of objects for pretty much anything you can think of.

  • Displays any user accounts with Outlook Web Access disabled

(&(objectCategory=user)(protocolSettings=*HTTP*0*))

  • Searches for any mailbox-enabled account which are not using the Exchange Storage Quota defaults

((mailNickname=*)(mDBUseDefaults=FALSE))

  • Shows any user accounts with a Receiving message size limit set

(&(legacyExchangeDN=*)(mailNickname=*)(objectCategory=person)(objectClass=user)(delivContLength=*))

  • Shows any user accounts with a Sending message size limit set

(&(legacyExchangeDN=*)(mailNickname=*)(objectCategory=person)(objectClass=user)(submissionContlength=*))

  • Searches for X500 addresses that start with this specific org and ou

(&(objectCategory=group)(proxyAddresses=X500:/o=Schertz/ou=Lab*))

  • Looks for mail-enabled public folders which are visible in the Global Address List

(&(objectCategory=publicFolder)(msExchHideFromAddressLists=FALSE))(& (displayName=*))

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

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

Предлагаю Вашему вниманию мой метод работы с атрибутом Active Directory sIDHistory. А именно — будем производить поиск объекта по этому атрибуту.

Но вначале поговорим о самом атрибуте. sIDHistory служит для создания соответствия объектов в Active Directory, необходим он, например, при миграции учетных записей и групп из одного домена/леса в другой.

Что нам это дает? А дает это нам возможность не переназначать права на ресурсы, а оставить их «как есть».
Пример: в домене A.local есть группа A-G1, в нее входит пользователь A-U1.
Мы имеем файловый ресурс \server01share на который назначен доступ группе A-G1

Случилось так, что мы мигрировали в домен B.local, создали там пользователя B-U1 и прописали ему атрибут sIDHistory от пользователя AA-U1

Теперь пользователь BB-U1 без каких-либо дополнительных действий может входить на \server01share

Предположим, что пользователей у нас мигрировало 5000, некоторые из них могли полностью переименоваться, а sIDHistory выглядит как куча непонятных для администратора цифр. Найти какому пользователю в домене A соответствует пользователь из домена B просто становиться невозможно.

Скрипт на Powershell, с использованием QUESTовских коммандлетов, который выведет все объекты указанному атрибуту.

#Указываем пользователя, у которого будем искать sIDHistory
$user="B-U1"

#Выбираем нужные нам атрибуты из AD
$obj=(Get-qADObject -Identity $user -service "B.local" -includedproperties sIDHistory | select name,dn,sIDHistory)

#Формируем LDAP запрос
$ldap="LDAP://{0}" -f $obj.dn

#Создаем объект .NET, преобразуем цифры в SID
$indents=([ADSI]$ldap).getex(“sidhistory”) | % { (new-object System.Security.Principal.SecurityIdentifier $_ ,0).value }

# По скольку sIDHistory может содержать много строк соответствий, то ищем все
foreach ($indent in $indents) {
     get-qadobject -identity $indent -service "A.local"
}

Условия для работы скрипта:

  • Точно знаем домен пользователя

На вход можно подавать и CSV и выгрузку из групп:

users.txt:
name
B-U1

import-csv -delimiter "`t" -path "users.txt" | % {

#Указываем пользователя, у которого будем искать sIDHistory
$user=$_.name

#Выбираем нужные нам атрибуты из AD
$obj=(Get-qADObject -Identity $user -service "B.local" -includedproperties sIDHistory | select name,dn,sIDHistory)

#Формируем LDAP запрос
$ldap="LDAP://{0}" -f $obj.dn

#Создаем объект .NET, преобразуем цифры в SID
$indents=([ADSI]$ldap).getex(“sidhistory”) | % { (new-object System.Security.Principal.SecurityIdentifier $_ ,0).value }

# По скольку sIDHistory может содержать много строк соответствий, то ищем все
foreach ($indent in $indents) {
      get-qadobject -identity $indent -service "A.local"
}
}

Performing LDAP queries to find objects in your directory by SID or GUID aren’t always straightforward.  It’s not as easy in Active Directory, for example, to perform a query like:

“objectSID={theSID},CN=Users,DC=domain,DC=com” since Active Directory stores values in hex.

A Lot of Solutions Exist

There are some nice write-ups out there that give an example using PowerShell for a GUID (but not an SID).  The same write-up explains that you can do queries of the form:  [ADSI]“LDAP://<SID=$theSID>” to make it work.  When I tried this technique with system.directoryservices.protocols (S.DS.P), however, I wasn’t able to get it going since you don’t write queries of the form “LDAP://” or “GC://” but instead work with port numbers to specify your protocol.  It might be possible (I didn’t spend a lot of time), but the application that I’m writing builds LDAP query strings dynamically and this technique would make SIDs or GUIDs special cases in my code.  Avoiding these kinds of special cases is important to me for easier code maintenance.

I also didn’t want to use PowerShell’s Active Directory commandlets because they aren’t generic to LDAP but are instead specific to Active Directory.  I wanted to stick with S.DS.P.  S.DS.P is also faster than abstractions that have been written on top of LDAP to simplify it.

There are a lot of old algorithms to convert the SID or GUID into a string representation of a byte array.  I have my own C# algorithm that does it, and there are plenty out there in VBScript.  It’s not that clean to me.  What came to my rescue (in either PowerShell or .NET) was System.Security.Principal.SecurityIdentifier and the method GetBinaryForm.

System.Security.Principal.SecurityIdentifier and GetBinaryForm Helped

The following in PowerShell (easily adaptable to C#) is what I used:

$ot = New-Object System.Security.Principal.SecurityIdentifier($theSID)
$c = New-Object 'byte[]' $ot.BinaryLength
$ot.GetBinaryForm($c,0)
$c | %{ $out += $("{0:x2}" -f $_) }

“$out” gets the converted result.  This was much more preferable to me then including yet another conversion function in my script and I was happy to find it.

Login

Понравилась статья? Поделить с друзьями:
  • Утечка электроэнергии в квартире как найти
  • Как вы нашли свой цвет волос
  • Как найти вес руки
  • Посоветуйте как найти хорошего невролога
  • Как исправить неровность губ