Example #1
0
        /****************************************************************************++
         *
         * Description :
         *
         * This function creates a well known sid using User domain. CreateWellKnownSid requires
         * domain sid to be provided to generate such sids. This function first gets the domain sid
         * out of the user information in the token and then generate a well known sid.
         *
         * Arguments:
         *
         * hToken - [supplies] The token for which sid has to be generated
         * sidType - [supplies] The type of well known sid
         * pSid - [receives] The newly create sid
         * pdwSidSize - [Supplies/Receives] The size of the memory allocated for ppSid
         *
         * Returns:
         *
         * Errors returned by GetTokenInformation
         * Errors returned by CreateWellKnownSid
         * E_OUTOFMEMORY In case there is not enough memory
         * Errors returned by GetWindowsAccountDomainSid
         * --***************************************************************************/
        static SafePSID CreateWellKnownSidForAccount(HTOKEN hToken, WELL_KNOWN_SID_TYPE sidType)
        {
            var hTok = new SafeHTOKEN((IntPtr)hToken, false);

            using var pUserToken = hTok.GetInfo(TOKEN_INFORMATION_CLASS.TokenUser);

            //
            // Now get the domain sid from the TokenUser
            //
            Win32Error.ThrowLastErrorIfFalse(GetWindowsAccountDomainSid(pUserToken.ToStructure <TOKEN_USER>().User.Sid, out var pDomainSid));

            return(SafePSID.CreateWellKnown(sidType, pDomainSid));
        }
        /// <summary>
        /// Get the specified "well known" SID. Note that not all well known SIDs are available on all OSes.
        /// </summary>
        public unsafe static SID CreateWellKnownSid(WELL_KNOWN_SID_TYPE sidType)
        {
            SID sid = new SID();

            uint size = (uint)sizeof(SID);

            if (!Imports.CreateWellKnownSid(sidType, null, &sid, ref size))
            {
                throw Errors.GetIoExceptionForLastError();
            }

            return(sid);
        }
Example #3
0
            /// <summary>Creates a SID for predefined aliases.</summary>
            /// <param name="WellKnownSidType">Member of the WELL_KNOWN_SID_TYPE enumeration that specifies what the SID will identify.</param>
            /// <param name="DomainSid">
            /// A pointer to a SID that identifies the domain to use when creating the SID. Pass <c>PSID.NULL</c> to use the local computer.
            /// </param>
            /// <returns>A <see cref="SafePSID"/> instance.</returns>
            public static SafePSID CreateWellKnown(WELL_KNOWN_SID_TYPE sidType, PSID domainSid = default)
            {
                var sz = 0U;

                CreateWellKnownSid(sidType, domainSid, Null, ref sz);
                if (sz == 0)
                {
                    Win32Error.ThrowLastError();
                }
                var newSid = new SafePSID((int)sz);

                if (!CreateWellKnownSid(sidType, domainSid, newSid, ref sz))
                {
                    Win32Error.ThrowLastError();
                }
                return(newSid);
            }
Example #4
0
        public static bool CreateWellKnownSid(WELL_KNOWN_SID_TYPE WellKnownSidType, System.IntPtr DomainSid, ref PInvokePointer pSid)
        {
            PInvokePointer varpSid     = null;
            bool           retVar_     = false;
            uint           sizeVar     = 2056;
            uint           oldSizeVar_ = 0;

PerformCall:
            oldSizeVar_ = sizeVar;
            varpSid     = new PInvokePointer(Convert.ToInt32(sizeVar));
            retVar_     = NativeMethods.CreateWellKnownSid(WellKnownSidType, DomainSid, varpSid.IntPtr, ref sizeVar);
            if ((sizeVar <= oldSizeVar_))
            {
                varpSid.Free();
                sizeVar = (sizeVar * Convert.ToUInt32(2));
                goto PerformCall;
            }
            pSid = varpSid;
            return(retVar_);
        }
Example #5
0
        /// <summary>
        /// Creates a Security Identity for a well known SID (such as LOCAL SYSTEM)
        /// </summary>
        /// <param name="sidType">The type of well known SID</param>
        /// <returns>A populated Security Identity</returns>
        public static SecurityIdentity SecurityIdentityFromWellKnownSid(WELL_KNOWN_SID_TYPE sidType)
        {
            if (sidType == WELL_KNOWN_SID_TYPE.None)
            {
                throw new ExternalException("Unable to Get Well Known SID");
            }

            var secId = new SecurityIdentity
            {
                wellKnownSidType = sidType
            };

            // Get the size required for the SID
            var size = GetSidLengthRequired(SID_MAX_SUB_AUTHORITIES);;

            var sidStruct = Marshal.AllocHGlobal((IntPtr)size);

            try
            {
                // Get the SID struct from the well known SID type
                if (!CreateWellKnownSid(sidType, IntPtr.Zero, sidStruct, ref size))
                {
                    throw new ExternalException("Unable to Get Well Known SID");
                }

                var sidString = IntPtr.Zero;

                // Convert the SID structure to a SID string
                ConvertSidToStringSid(sidStruct, out sidString);

                try
                {
                    // Marshal and store the SID string
                    secId.sid = Marshal.PtrToStringAnsi(sidString);
                }
                finally
                {
                    if (sidString != IntPtr.Zero)
                    {
                        Util.LocalFree(sidString);
                    }
                }

                uint nameLen   = 0;
                uint domainLen = 0;


                // Get the lengths of the object and domain names
                LookupAccountSid(null, sidStruct, IntPtr.Zero, ref nameLen, IntPtr.Zero, ref domainLen, out var nameUse);

                if (nameLen == 0)
                {
                    throw new ExternalException("Unable to Find SID");
                }

                var accountName = Marshal.AllocHGlobal((IntPtr)nameLen);
                var domainName  = domainLen > 0 ? Marshal.AllocHGlobal((IntPtr)domainLen) : IntPtr.Zero;

                try
                {
                    // Get the object and domain names
                    if (!LookupAccountSid(null, sidStruct, accountName, ref nameLen, domainName, ref domainLen, out nameUse))
                    {
                        throw new ExternalException("Unable to Find SID");
                    }

                    // Marshal and store the object name
                    secId.name = string.Format("{0}{1}{2}", domainLen > 1 ? Marshal.PtrToStringAnsi(domainName) : "", domainLen > 1 ? "\\" : "", Marshal.PtrToStringAnsi(accountName));
                }
                finally
                {
                    if (accountName != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(accountName);
                    }
                    if (domainName != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(domainName);
                    }
                }
            }
            finally
            {
                if (sidStruct != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(sidStruct);
                }
            }

            return(secId);
        }
Example #6
0
 private static extern bool CreateWellKnownSid(WELL_KNOWN_SID_TYPE WellKnownSidType, IntPtr DomainSid, IntPtr pSid, ref uint cbSid);
Example #7
0
 public static extern bool CreateWellKnownSid(
     WELL_KNOWN_SID_TYPE wellKnownSidType,
     IntPtr domainSid,
     SafeHGlobalBuffer pSid,
     ref Int32 cbSid);
Example #8
0
 public static extern bool CreateWellKnownSid(
     [In] WELL_KNOWN_SID_TYPE WellKnownSidType,
     [In] IntPtr DomainSid,
     [In] IntPtr pSid,
     ref uint cbSid);
 public unsafe static extern BOOL IsWellKnownSid(
     ref SID pSid,
     WELL_KNOWN_SID_TYPE WellKnownSidType);
Example #10
0
 public static extern bool CreateWellKnownSid(
     WELL_KNOWN_SID_TYPE WellKnownSidType,
     IntPtr DomainSid,
     IntPtr pSid,
     ref uint cbSid);
 /// <summary>
 /// Returns true if the given SID is the specified "well known" SID type.
 /// </summary>
 public static bool IsWellKnownSid(ref SID sid, WELL_KNOWN_SID_TYPE sidType)
 {
     return(Imports.IsWellKnownSid(ref sid, sidType));
 }
 public unsafe static extern BOOL CreateWellKnownSid(
     WELL_KNOWN_SID_TYPE WellKnownSidType,
     SID *DomainSid,
     SID *pSid,
     ref uint cbSid);
Example #13
0
 public static extern bool IsWellKnownSid(PSID pSid, WELL_KNOWN_SID_TYPE WellKnownSidType);
Example #14
0
 public static extern bool CreateWellKnownSid(WELL_KNOWN_SID_TYPE WellKnownSidType, [System.Runtime.InteropServices.InAttribute()]
                                              System.IntPtr DomainSid, System.IntPtr pSid, ref uint cbSid);
Example #15
0
 public static extern int IsWellKnownSid([NativeTypeName("PSID")] void *pSid, WELL_KNOWN_SID_TYPE WellKnownSidType);
Example #16
0
 public static extern int CreateWellKnownSid(WELL_KNOWN_SID_TYPE WellKnownSidType, [NativeTypeName("PSID")] void *DomainSid, [NativeTypeName("PSID")] void *pSid, [NativeTypeName("DWORD *")] uint *cbSid);
Example #17
0
        /****************************************************************************++
         *
         * Routine Description:
         *
         * Verifies whether specified well-known SID is in the current user token
         *
         * Arguments:
         *
         * sid - one of the WELL_KNOWN_SID_TYPE consts
         * hToken - Optional the token for which we want to test membership
         * pfMember - [Receives] TRUE if specified sid is a member of the user token, false otherwise
         *
         * Notes:
         *
         * -
         *
         * Return Value:
         *
         * Errors returned by CreateWellKnownSid
         * Errors returned by CheckTokenMembership
         * --*****************************************************************************/
        static HRESULT IsMemberOf(WELL_KNOWN_SID_TYPE sid, HTOKEN hToken, out bool pfMember)
        {
            pfMember = false;

            try
            {
                var hTok = new SafeHTOKEN((IntPtr)hToken, false);
                using var pUserToken = hTok.GetInfo(TOKEN_INFORMATION_CLASS.TokenUser);

                SafePSID pSID = null;
                try
                {
                    //
                    // create SID for the authenticated users
                    //
                    pSID = SafePSID.CreateWellKnown(sid);
                }
                catch
                {
                    //
                    // In case of invalid-arg we might need to provide the domain, so create well known sid for domain
                    //
                    pSID = CreateWellKnownSidForAccount(hToken, sid);
                }

                //
                // check whether token has this sid
                //
                if (!CheckTokenMembership(hToken, pSID, out pfMember))
                {
                    var hr = Win32Error.GetLastError().ToHRESULT();

                    // just to be on the safe side (as we don't know that CheckTokenMembership
                    // does not modify fAuthenticated in case of error)
                    pfMember = false;
                    if (hr == HRESULT.E_ACCESSDENIED && hToken.IsNull)
                    {
                        // unable to query the thread token. Open as self and try again
                        using var ttok = SafeHTOKEN.FromThread(GetCurrentThread(), TokenAccess.TOKEN_QUERY);
                        {
                            if (CheckTokenMembership(ttok, pSID, out pfMember))
                            {
                                return(HRESULT.S_OK);
                            }
                            else
                            {
                                // stick with the original error code, but ensure that fMember is correct
                                pfMember = false;
                            }
                        }
                    }
                }

                return(HRESULT.S_OK);
            }
            catch (Exception ex)
            {
                var hr = HRESULT.FromException(ex);
                if (hr == (HRESULT)Win32Error.ERROR_NON_ACCOUNT_SID)
                {
                    return(HRESULT.S_OK);
                }
                return(hr);
            }
        }
Example #18
0
 public static extern bool CreateWellKnownSid(WELL_KNOWN_SID_TYPE WellKnownSidType, PSID DomainSid, SafePSID pSid, ref uint cbSid);
Example #19
0
        /// <summary>
        /// Creates a Security Identity for a well known SID (such as LOCAL SYSTEM)
        /// </summary>
        /// <param name="sidType">The type of well known SID</param>
        /// <returns>A populated Security Identity</returns>
        public static SecurityIdentity SecurityIdentityFromWellKnownSid(WELL_KNOWN_SID_TYPE sidType)
        {
            if (sidType == WELL_KNOWN_SID_TYPE.None)
            {
                throw new ExternalException("Unable to Get Well Known SID");
            }

            SecurityIdentity secId = new SecurityIdentity();

            secId.wellKnownSidType = sidType;

            // Get the size required for the SID
            uint size = SecurityIdentity.GetSidLengthRequired(SecurityIdentity.SID_MAX_SUB_AUTHORITIES); ;

            IntPtr sidStruct = Marshal.AllocHGlobal((IntPtr)size);

            try
            {
                // Get the SID struct from the well known SID type
                if (!SecurityIdentity.CreateWellKnownSid(sidType, IntPtr.Zero, sidStruct, ref size))
                {
                    throw new ExternalException("Unable to Get Well Known SID");
                }

                IntPtr sidString = IntPtr.Zero;

                // Convert the SID structure to a SID string
                SecurityIdentity.ConvertSidToStringSid(sidStruct, out sidString);

                try
                {
                    // Marshal and store the SID string
                    secId.sid = Marshal.PtrToStringAnsi(sidString);
                }
                finally
                {
                    if (sidString != IntPtr.Zero) Util.LocalFree(sidString);
                }

                uint nameLen = 0;
                uint domainLen = 0;

                SID_NAME_USE nameUse;

                // Get the lengths of the object and domain names
                SecurityIdentity.LookupAccountSid(null, sidStruct, IntPtr.Zero, ref nameLen, IntPtr.Zero, ref domainLen, out nameUse);

                if (nameLen == 0)
                {
                    throw new ExternalException("Unable to Find SID");
                }

                IntPtr accountName = Marshal.AllocHGlobal((IntPtr)nameLen);
                IntPtr domainName = domainLen > 0 ? Marshal.AllocHGlobal((IntPtr)domainLen) : IntPtr.Zero;

                try
                {
                    // Get the object and domain names
                    if (!SecurityIdentity.LookupAccountSid(null, sidStruct, accountName, ref nameLen, domainName, ref domainLen, out nameUse))
                    {
                        throw new ExternalException("Unable to Find SID");
                    }

                    // Marshal and store the object name
                    secId.name = String.Format("{0}{1}{2}", domainLen > 1 ? Marshal.PtrToStringAnsi(domainName) : "", domainLen > 1 ? "\\" : "", Marshal.PtrToStringAnsi(accountName));
                }
                finally
                {
                    if (accountName != IntPtr.Zero) Marshal.FreeHGlobal(accountName);
                    if (domainName != IntPtr.Zero) Marshal.FreeHGlobal(domainName);
                }
            }
            finally
            {
                if (sidStruct != IntPtr.Zero) Marshal.FreeHGlobal(sidStruct);
            }

            return secId;
        }