Click here to Skip to main content
Click here to Skip to main content

How to get user SID using DirectoryServices classes

By , 19 Feb 2003
 

Introduction

This article demonstrates how you can make use of DirectoryServices namespace classes to get a user's SID. This code does not make use of PInvoke to call into Win32 APIs to get the required information. We have extended the concepts of our previous article, How to get full name of logged in user, to show how every piece of information can be obtained by using DirectoryEntry object for a given user.

User's sid is returned by accessing objectSid property of DirectoryEntry obect. The value is returned as Byte [] array. This byte array can be parsed to get string representation of SID value. The binary representation of SID consists of following values.

PSID_IDENTIFIER_AUTHORITY    - First 6 bytes
SubAuthorityCount            - Next 1 Byte
SubAuthority0                - Next 4 bytes
SubAuthority1                - Next 4 bytes
SubAuthority2                - Next 4 bytes
SubAuthority3                - Next 4 bytes
SubAuthority4                - Next 4 bytes
SubAuthority5                - Next 4 bytes
SubAuthority6                - Next 4 bytes
SubAuthority7                - Next 4 bytes

Number of sub-authority values depend upon value of SubAuthorityCount. The max number of sub-authorities is 8.

private string GetSid(string strLogin)
{
    string str = "";
    // Parse the string to check if domain name is present.
    int idx = strLogin.IndexOf('\\');
    if (idx == -1)
    {
        idx = strLogin.IndexOf('@');
    }

    string strDomain;
    string strName;

    if (idx != -1)
    {
        strDomain = strLogin.Substring(0, idx);
        strName = strLogin.Substring(idx+1);
    }
    else
    {
        strDomain = Environment.MachineName;
        strName = strLogin;
    }

    
    DirectoryEntry obDirEntry = null;
    try
    {
        Int64 iBigVal = 5;
        Byte[] bigArr = BitConverter.GetBytes(iBigVal);
        obDirEntry = new DirectoryEntry("WinNT://" + 
                              strDomain + "/" + strName);
        System.DirectoryServices.PropertyCollection  
                           coll = obDirEntry.Properties;
        object obVal = coll["objectSid"].Value;
        if (null != obVal)
        {
            str = this.ConvertByteToStringSid((Byte[])obVal);
        }
        
    }
    catch (Exception ex)
    {
        str = "";
        Trace.Write(ex.Message);
    }
    return str;
}

private string ConvertByteToStringSid(Byte[] sidBytes)
{
    StringBuilder strSid = new StringBuilder();
    strSid.Append("S-");
    try
    {
        // Add SID revision.
        strSid.Append(sidBytes[0].ToString());
        // Next six bytes are SID authority value.
        if (sidBytes[6] != 0 || sidBytes[5] != 0)
        {
            string strAuth = String.Format
                ("0x{0:2x}{1:2x}{2:2x}{3:2x}{4:2x}{5:2x}",
                (Int16)sidBytes[1],
                (Int16)sidBytes[2],
                (Int16)sidBytes[3],
                (Int16)sidBytes[4],
                (Int16)sidBytes[5],
                (Int16)sidBytes[6]);
            strSid.Append("-");
            strSid.Append(strAuth);
        }
        else
        {
            Int64 iVal = (Int32)(sidBytes[1]) +
                (Int32)(sidBytes[2] << 8) +
                (Int32)(sidBytes[3] << 16) +
                (Int32)(sidBytes[4] << 24);
            strSid.Append("-");
            strSid.Append(iVal.ToString());
        }

        // Get sub authority count...
        int iSubCount = Convert.ToInt32(sidBytes[7]);
        int idxAuth = 0;
        for (int i = 0; i < iSubCount; i++)
        {
            idxAuth = 8 + i * 4;
            UInt32 iSubAuth = BitConverter.ToUInt32(sidBytes, idxAuth);
            strSid.Append("-");
            strSid.Append(iSubAuth.ToString());
        }
    }
    catch (Exception ex)
    {
        Trace.Warn(ex.Message);
        return "";
    }
    return strSid.ToString();
}

Please feel free to send your suggestions directly to me at softomatix@pardesiservices.com.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Softomatix
Web Developer
United States United States
Member
To learn more about us, Please visit us at http://www.netomatix.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralSystem.Security.Principal.SecurityIdentifier is the bestmemberwebmoon19 Jan '09 - 17:32 
DirectoryEntry ude = ....;
SecurityIdentifier sid = new SecurityIdentifier((byte[])ude.Properties["objectSid"].Value, 0);
GeneralTry this!memberMohammad Reza Jooyandeh12 Jul '07 - 5:57 

[DllImport("advapi32", CharSet=CharSet.Auto, SetLastError=true)]
static extern bool ConvertSidToStringSid(
[MarshalAs(UnmanagedType.LPArray)] byte []pSID,
out IntPtr ptrSid);
 

public static string GetSidString(byte[] sid)
{
IntPtr ptrSid;
string sidString;
if (!ConvertSidToStringSid(sid,out ptrSid))
throw new System.ComponentModel.Win32Exception();
try
{
sidString = Marshal.PtrToStringAuto(ptrSid);
}
finally
{
LocalFree(ptrSid);
}
return sidString;
}
 
// or you can see this example for DirectoryEntry
 
private string GetTextualSID(DirectoryEntry objGroup)
{
string sSID = string.Empty;
byte []SID = (byte[])objGroup.Properties["objectSID"].Value;
IntPtr sidPtr = Marshal.AllocHGlobal(SID.Length);
sSID = "";
System.Runtime.InteropServices.Marshal.Copy(SID, 0, sidPtr, SID.Length);
ConvertSidToStringSid((IntPtr)sidPtr, ref sSID);
System.Runtime.InteropServices.Marshal.FreeHGlobal(sidPtr);
return sSID;
}

GeneralWinNT Provider not supported on 2003sussXileh15 Sep '05 - 8:39 
This is a good article, but remember that it will not work on a 2003 machine. Sniff | :^)
 
Because you have relied on getting the SID using the WinNT provider, this code will not run on any platform that uses 2003 or later.
 
Unfortunately this solution will not work if you simply switch to the LDAP provider.
 
If anyone has a solution using directory services that does not involve using the WinNt provider please post it. Until then I'll be stuck using p/invoke for Win32 code Frown | :(
GeneralRelated: Get SIDs from GC cachememberLehi6 Jan '05 - 14:31 
Get SIDs from AD's global catalog
 
I am cool.
GeneralJust one safe methodmembermaher.tebourbi22 Nov '04 - 2:56 
Try to use the function that are offred in the win32 SDK and dont worry about the SID format Wink | ;)
 
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool ConvertStringSidToSid(string StringSid, out IntPtr ptrSid);
 
[DllImport("advapi32", CharSet=CharSet.Auto, SetLastError=true)]
static extern bool ConvertSidToStringSid( [MarshalAs(UnmanagedType.LPArray)] byte [] pSID, out IntPtr ptrSid);
GeneralSID decoding is wrongmemberSidhe27 Apr '04 - 1:58 
Hi there,
I think your SID decoding is wrong. The number of sub authorities is the 2nd byte in the SID byte array, not the 8th, and the main authority has its bytes stored in the other order from the one you're reading in.
 
What you have will work on most SIDs because many SIDs start S-1-5-..., but it fails spectacularly on SIDs for built-in users. e.g. here's a valid set of SID bytes from a built-in: 1,2,0,0,0,0,0,5,32,0,0,0,39,2,0,0
 

Here's another piece of code that correctly *encodes* a SID, so you can see how the decode would need to work...
 
http://www.scriptlogic.com/Kixtart/FunctionLibrary_ViewFunction.aspx?ID=StrSidToHexSid
 

But, why bother with any of that when you can use the real ConvertSidToStringSid function in the advapi32.dll library via P/Invoke?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.1 | Last Updated 20 Feb 2003
Article Copyright 2003 by Softomatix
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid