- Windows user sid format
- Сколько у компьютера SID-ов?
- Существует два типа SID у компьютера:
- Нюансы идентификаторов безопасности на рабочих станциях
- Методы определения сида компьютера
- SID пользователя в Windows: Что это такое и как его узнать
- Что такое SID пользователя в Windows?
- Как узнать SID пользователя в Windows с помощью cmd
- Get SID of user
Windows user sid format
Добрый день! Уважаемые читатели и гости IT блога Pyatilistnik.org. В прошлый раз мы с вами установили домен Active Directory на Windows Server 2019. Одним из краеугольных понятий в AD является идентификатор безопасности компьютера SID, о нем и пойдет речь. Мы разберем, какие они бывают у сервера и рабочей станции, а так же научимся определять SID компьютера, буквально за минуту.
Сколько у компьютера SID-ов?
О том, что такое SID у пользователя, я уже рассказывал. SID — это уникальное имя (буквенно-цифровая символьная строка), которое используется для идентификации объекта, такого как пользователь или компьютер в сети систем NT. Windows предоставляет или запрещает доступ и права доступа к ресурсам на основе ACL, которые используют SID для уникальной идентификации компьютеров и их членства в группах. Когда компьютер запрашивает доступ к ресурсу, его ACL проверяет SID компьютера, чтобы определить, разрешено ли этому компьютеру выполнять это действие или нет. Схематично выглядит вот так.
Существует два типа SID у компьютера:
- Первый тип, это когда рабочая станция или сервер не являются членом домена Active Directory
- Второй тип, это когда компьютер входит в домен Active Directory
В обоих случаях у вас будет два абсолютно разных SID. Первый дескриптор безопасности у вас генерируется при установке системы, второй если вы вводите его в домен AD. И так, у меня есть тестовый домен root.pyatilistnik.org. Есть клиентская станция с Windows 10 1803. Для того, чтобы вам показать разницу и оба SID идентификатора на моей тестовой Windows 10, мы воспользуемся утилитой Марка Русиновича PsGetSid из инструментария Sysinternals (Скачать PsGetSid можно по ссылке https://docs.microsoft.com/en-us/sysinternals/downloads/psgetsid). Распаковываете архив с утилитой, открываете командную строку от имени администратора и переходите с помощью cd в каталог с утилитой PsGetSid.
Первым делом я выведу имя компьютера, через команду hostname. В моем примере, это W10-CL01.
Далее я выведу локальный SID компьютера, через утилиту PsGetSid:
В итоге я получил SID for W10-CL01\w10-cl01:S-1-5-21-7706586-876249769-275126362. Обратите внимание, что перед идентификатором безопасности идет имя компьютера, это сразу говорит, что он локальный.
И команда указанная выше, показывает вам доменный SID рабочей станции. SID for ROOT\w10-cl01$:S-1-5-21-233550040-578987154-4094747311-1602. Обратите внимание, что перед идентификаторам идет имя домена ROOT\.
Нюансы идентификаторов безопасности на рабочих станциях
Некоторое время назад, Марк Руссинович, очень известный человек в мире Microsoft, написал замечательную статью, про мифы дублирования SID, где показал на практике свои мысли, но после прочтения статьи у некоторых людей оставалась в голове путаница или вопросы, \ бы хотел немного уточнить по статье (Ссылка на нее https://blogs.technet.microsoft.com/mark_russinovich/2009/11/15/sid/).
Предположим, что вы клонируете нужную вам виртуальную машину или хост. Если вы не обезличиваете систему, с помощью Sysprep, то у вас все полученные клоны систем, будут иметь один локальный SID компьютера. Если мы говорим про окружение в виде рабочей группы в локальной сети, то ни каких проблем с доступом или конфликтом с доступом к ресурсам вы не увидите. Но вот в случае с доменным SID, такое не получится, он должен быть уникальным в пределах Active Directory, в противном случае, у вас будут конфликты между двумя объектами. Убедитесь, что после клонирования и обезличивания у вас разные SID, полученные от мастера RID.
Например, если вы попытаетесь восстановить безопасный канал между контроллером домена и клонированной машиной у которой дублирующий идентификатор безопасности, то она в домен попадет, но выкинет из него первую рабочую станцию и еще кучу различного и разного, глючного поведения.
Методы определения сида компьютера
- Первый метод я вам уже показал. он заключается в использовании утилиты PsGetSid
- Второй метод, это использование командной строки, с помощью утилиты dsquery. Получать мы таким методом будем доменный SID у сервера или рабочей станции:
dsquery computer — name «Имя компьютер» | dsget computer — SID
Хочу отметить, что данную команду вы должны выполнять либо на контроллере домена или же на рабочей станции, где установлены консоли администрирования и утилиты из пакета RSAT.
- Через скриптик VBS. Вы копируете код представленный ниже или скачиваете уже готовый файл у меня, только лишь потом отредактировав его и изменив имя на свое. После чего у вас будет запрошен локальный SID компьютера. Напоминаю, что у всех встроенных групп или учетных записей, начало их идентификатора безопасности состоит из полного SID компьютера с добавлением своего дополнительного номера.
- Куда же без PowerShell в нем можно делать, что угодно. Вот пример кода дающего локальный идентификатор безопасности у рабочей станции:
тут так же будет запрошен SID учетной записи «Администратор». Если компьютер доменный, то нам поможет командлет Get-ADComputer. Запускаем оснастку PowerShell и вводим команду:
Get-ADComputer W10-CL01 -prop sid
Как видите методов очень много. Видел я метод и получения сида из реестра Windows, в ветке
SID пользователя в Windows: Что это такое и как его узнать
Вы наверняка пытались управлять разрешениями определенных файлов, папок или часто просматриваете реестр Windows, то может показаться, что вы видели некоторые строковые значения типа S-1-5-21-281723897-98365329832-7382047462- 600. Эти значения известны как идентификаторы безопасности или SID. Давайте разберем, что такое SID пользователя в Windows 10 и какие способы его узнать.
Что такое SID пользователя в Windows?
Идентификатор безопасности или SID пользователя в Windows 10 является единственным значащим значением, которое служит для идентификации принципа безопасности или группы безопасности в Windows. Поэтому можно сказать, что SID пользователя в Windows 10 похож на паспорт, который присваивается каждому компьютеру во время установки операционной системы. Кроме того, этот идентификатор может быть полезен во время выполнения определенных команд, связанных с безопасностью нашего компьютера, поэтому давайте разберем, как узнать SID пользователя в Windows 10.
Как узнать SID пользователя в Windows с помощью cmd
Одним из самых быстрых способов узнать идентификатор пользователя SID в Windows 10, — это воспользоваться командной строкой. Откройте командную строку и введите ниже команды, которые соответствуют вашим требованиям.
- Имя SID используемое в настоящее время: введите команду whoami /user и нажмите Enter.
- Имя SID определенного пользователя: введите в командую строку wmic useraccount where name=»хомячок» get name,sid . Где «хомячок» — это фактическое имя пользователя.
- Все SID пользователей в Windows: введите wmic useraccount get name,sid .
Get SID of user
In Windows environment, each user is assigned a unique identifier called Security ID or SID, which is used to control access to various resources like Files, Registry keys, network shares etc. We can obtain SID of a user through WMIC USERACCOUNT command. Below you can find syntax and examples for the same.
Get SID of a local user
For example, to get the SID for a local user with the login name ‘John’, the command would be as below
Get SID for current logged in user
To retrieve the SID for current logged in user we can run the below command. This does not require you to specify the user name in the command. This can be used in batch files which may be executed from different user accounts.
Get SID for current logged in domain user
Run the command ‘whoami /user’ from command line to get the SID for the logged in user.
Example:
Get SID for the local administrator of the computer
Get SID for the domain administrator
Find username from a SID
Now this is tip is to find the user account when you have a SID. One of the readers of this post had this usecase and he figured out the command himself with the help of the commands given above. Adding the same here.
very good explanation,it’s just great
Hi, Very good post!
Can you tell me how to get the SID of AD Group?
to get the SID of a ADGroup you can simply use the PowerShell CmdLet Get-ADGroup:
Get-ADGroup -Identity “Group Name”
DistinguishedName : CN=Administratoren,CN=Builtin,DC=domain,DC=com
GroupCategory : Security
GroupScope : DomainLocal
Name : Administratoren
ObjectClass : group
ObjectGUID : 7d6471ab-9ea3-4cc4-8652-be3345623291
SamAccountName : Administratoren
SID : S-1-5-32-544
With the exact same Cmdlet you can get the Groupname from a given SID:
PS C:\Windows> Get-ADGroup -Identity S-1-5-32-544
DistinguishedName : CN=Administratoren,CN=Builtin,DC=horaios,DC=local
GroupCategory : Security
GroupScope : DomainLocal
Name : Administratoren
ObjectClass : group
ObjectGUID : 7d6471ab-9ea3-4cc4-8652-be3345623291
SamAccountName : Administratoren
SID : S-1-5-32-544
Hi Guy, nice post.
Could you tell me how to get Admin SID from cmd using another user but administrator?
How to delete SID in admin group.
Very good post. Thanks for sharing the information.
How to get sid of ad user id, I am not able to get the user id from whoami command.
How to get sid of computer object for all user on AD ?
Thank you.
You would do that with Powershell:
get-adcomputer -filter * | select Name, SID
This will give you a list with computernames and corresponding SID.
to output to text:
get-adcomputer -filter * | select Name, SID >> C:\temp\computersandSID.txt
to output to csv:
get-adcomputer -filter * | select Name, SID | output-csv C:\temp\computersandSID.csv
this should be done from a Domain controller or from a domain client with RSAT tools.
I needed it the other way round, I had an SID and wanted to know what user it was, so I turned the wmic command around an it worked fine:
wmic useraccount where sid=’S-1-5-21-….’ get name
Thank you for this tip!
Hello Rofel, glad that this article helped you figure out the command for your reverse usecase. I am including this in the post for the benefit of others.
Hi .. is there a way to set the SID into a var?
Meanwhile i get this via wmic useraccount get name,sid | findstr %userprofile:
9% or woami /user is nice. 😉
and set it manually .. :/
Hi and thank you for this tip!
I have to create a little script to automatically copy some registry files.
First it has to get the sid of the user and then it has to navigate to the registry – HKEY_USERS\%sid% and copy the files there.
Can anyone help me out with that please?
Thank you in advance!
Thank you for this command line page.
B/G: OS 7 Home Premium SP1 in Dual Boot environment with Win 10
When checking file security of multiple files, I discovered two Unknown Account SIDs:
Account Unknown(S-1-5-21- … -1001)
Account Unknown(S-1-5-21- … -1007)
I was unable to delete these accounts and they did not show up under UAC. These accounts have inherited properties for EACH file. If I removed the inheritance, I couldn’t any access the file at all. I bumped up UAC to default, which had been turned off.
Turns out the dual boot scenario generated at least one of the unknown SIDs. I found that the SIDs does belong to my Win 10. So when I access files on the Win7 partition from a Win 10 logon, as I have done, the ‘unknown SID’ really belongs to the user there in 10 (moi).
Here are the command lines that I used:
WhoAmI ‘determines current user; works in Win 7, 10 and also as a Linux command as I understand.
wmic useraccount where name=’%username%’ get sid ;returns the SID
Running the latter on Win 10, gave me exactly one of the unknown SIDs. Bingo!
I also have Virtual Machines on my Win 7 machine with a shared folder and wondering if they created the second SID. Finally, my dual boot is really a tri-boot with Vista on a second drive and I will check its SID. I don’t recall accessing data from Vista in any other partition but I have copied files from Vista into 7.
At least the mystery is solved in that I do not have a virus, a keylogger, or some rogue user with full access to my machine.
Again the command that helped resolve this issue was: wmic useraccount where name=’%username%’ get sid
Thank you so much,
Wonder if there any option or wmic useraccount command to provide all the users that belong to a group
Something like wmic useraccount get domain,name,sid where SID=S-1-5-32-544 (this SID is from the Group command)
Looks good, thanks to all who have put this info out.
Now I need to put this in to a .bat file such that I can end up with a variable that has the user’s SID which I can then use to navigate to places that are based on the user sid such as in Win 10 there is a folder “c:\users\public\publicaccountpictures\usersSID”
or I could user it to go to the “Actual” user reg settings etc.
Is there a way to use a wildcard in this command? This is kinda what I was looking to do…
wmic useraccount where sid=”S-1-5-21*” get name
But that is not working.
thanks a lot. How can i delete “SID” word. Example:
wmic useraccount where name=’%username%’ get sid > C:\sid.txt
and sid.txt
SID
S-1-5-21-2416115148-63416681-3240496290-1000
I only need the number (delete SID)
Thanks
@acg
you can use my script
—
wmic useraccount where name=’user’ get sid >usersid.txt
MORE /E +1 usersid.txt > usersidno.txt
set /p usersid= Bryan
Hi!
Nice work!
How to get the list of (all) registered users?
wmic useraccount get name /all
Half way there. Is there a way to turn off the headers in the response? If not this is only good for you as an individual looking at it and if that’s the case, there’s not really value in this command. I need to be able to use the response as a value in a subsequent command and I don’t want to have to parse the results.
if you need the number (delete SID)
wmic useraccount where name=’user’ get sid >usersid.txt
MORE /E +1 usersid.txt > usersidno.txt
“name=” with a capital letter “Name=”
wmic useraccount where Name=’user’ get sid >usersid.txt
MORE /E +1 usersid.txt > usersidno.txt
Sir,
i want to disable the WMIC useraccount get name,sid from the domain ( for security purpose). because locally I enter this command from the local machine its showing all the users list so actually i dont want see this things to others users workshop.
Kindly suggest me how to disable
How to get the SID`s of administrator groups using powershell for single system and group of systems
How can I recover an accidentally delete Administrator account
None of the above works while running it as a normal user. (without admin rights)
Use the Whoami command and convert its output of use in powershell:
This works with restricted or domain users.