Example #1
0
 public static extern NtStatus LsaOpenPolicy
 (
     ref LsaUnicodeString systemName,
     ref LsaObjectAttributes objectAttributes,
     Kernel32.Kernel32.AccessMask.PolicySpecificRights accessMask,
     out LsaPolicyHandle policyHandle
 );
Example #2
0
        private static string Lsaus2String(LsaUnicodeString lsaus)
        {
            var cvt = new char[lsaus.Length / UnicodeEncoding.CharSize];

            Marshal.Copy(lsaus.Buffer, cvt, 0, lsaus.Length / UnicodeEncoding.CharSize);
            return(new string(cvt));
        }
Example #3
0
        private static LsaUnicodeString String2Lsaus(string myString)
        {
            var retStr = new LsaUnicodeString();

            retStr.Buffer        = Marshal.StringToHGlobalUni(myString);
            retStr.Length        = (ushort)(myString.Length * UnicodeEncoding.CharSize);
            retStr.MaximumLength = (ushort)((myString.Length + 1) * UnicodeEncoding.CharSize);
            return(retStr);
        }
Example #4
0
        static LsaUnicodeString[] StringsToLsaStrings(string[] privileges)
        {
            var lsaPrivileges = new LsaUnicodeString[privileges.Length];

            for (var idx = 0; idx < privileges.Length; ++idx)
            {
                lsaPrivileges[idx] = new LsaUnicodeString(privileges[idx]);
            }
            return(lsaPrivileges);
        }
Example #5
0
 public LsaNamesResult LookupNames2(string name, LsaLookupNamesFlags flags = LsaLookupNamesFlags.None)
 {
     using (var lsaString = new LsaUnicodeString(name))
     {
         var names = new[] { lsaString };
         LsaReferencedDomainsHandle referencedDomainsHandle = null;
         LsaTranslatedSidHandle translatedSidHandle = null;
         LsaChecked(() => NativeMethods.LsaLookupNames2(this, flags, 1, names, out referencedDomainsHandle, out translatedSidHandle));
         return new LsaNamesResult(referencedDomainsHandle, translatedSidHandle);
     }
 }
 public LsaNamesResult LookupNames2(string name, LsaLookupNamesFlags flags = LsaLookupNamesFlags.None)
 {
     using (var lsaString = new LsaUnicodeString(name))
     {
         var names = new[] { lsaString };
         LsaReferencedDomainsHandle referencedDomainsHandle = null;
         LsaTranslatedSidHandle     translatedSidHandle     = null;
         LsaChecked(() => NativeMethods.LsaLookupNames2(this, flags, 1, names, out referencedDomainsHandle, out translatedSidHandle));
         return(new LsaNamesResult(referencedDomainsHandle, translatedSidHandle));
     }
 }
Example #7
0
        /// <summary>
        /// Converts a string to an LSA_UNICODE_STRING.
        /// </summary>
        /// <param name="s">The string that should be converted.</param>
        /// <returns>The converted string</returns>
        /// <exception cref="ArgumentException">String too long to create a LSA_UNICODE_STRING. - s</exception>
        public static LsaUnicodeString ToLsaString(this string s)
        {
            // Unicode strings max. 32KB
            if (s.Length > 0x7FFE)
            {
                throw new ArgumentException("String too long to create a LSA_UNICODE_STRING.", nameof(s));
            }

            LsaUnicodeString lus = new LsaUnicodeString();

            lus.Buffer        = s;
            lus.Length        = (ushort)(s.Length * UnicodeEncoding.CharSize);
            lus.MaximumLength = (ushort)(lus.Length + UnicodeEncoding.CharSize);

            return(lus);
        }
Example #8
0
        public static LsaPolicyHandle Open(LsaAccessPolicy accessPolicy)
        {
            var systemName = new LsaUnicodeString();
            var objectAttributes = new LsaObjectAttributes
            {
                Length = 0,
                RootDirectory = IntPtr.Zero,
                Attributes = 0,
                SecurityDescriptor = IntPtr.Zero,
                SecurityQualityOfService = IntPtr.Zero,
            };

            LsaPolicyHandle handle = null;
            LsaChecked(() => NativeMethods.LsaOpenPolicy(ref systemName, ref objectAttributes, (int)accessPolicy, out handle));
            return handle;
        }
Example #9
0
        public void AddRights(LsaTranslatedSidHandle translatedSidHandle, params string[] userRights)
        {
            var rights = new LsaUnicodeString[userRights.Length];
            for (int i = 0; i < userRights.Length; i++)
            {
                rights[i] = new LsaUnicodeString(userRights[i]);
            }

            try
            {
                LsaChecked(() => NativeMethods.LsaAddAccountRights(this, translatedSidHandle.Sid, rights, (uint)rights.Length));
            }
            finally
            {
                rights.DisposeAll();
            }
        }
        public static LsaPolicyHandle Open(LsaAccessPolicy accessPolicy)
        {
            var systemName       = new LsaUnicodeString();
            var objectAttributes = new LsaObjectAttributes
            {
                Length                   = 0,
                RootDirectory            = IntPtr.Zero,
                Attributes               = 0,
                SecurityDescriptor       = IntPtr.Zero,
                SecurityQualityOfService = IntPtr.Zero,
            };

            LsaPolicyHandle handle = null;

            LsaChecked(() => NativeMethods.LsaOpenPolicy(ref systemName, ref objectAttributes, (int)accessPolicy, out handle));
            return(handle);
        }
Example #11
0
        public static LsaUnicodeString ToLsaString(this string s)
        {
            // Unicode strings max. 32KB
            if (s.Length > 0x7ffe)
            {
                throw new ArgumentException("String to long for converting into a LSA_UNICODE_STRING.");
            }

            var lus = new LsaUnicodeString
            {
                //Buffer = s, //TODO
                Length        = (ushort)(s.Length * UnicodeEncoding.CharSize),
                MaximumLength = (ushort)((s.Length + 1) * UnicodeEncoding.CharSize)
            };

            return(lus);
        }
        public void AddRights(LsaTranslatedSidHandle translatedSidHandle, params string[] userRights)
        {
            var rights = new LsaUnicodeString[userRights.Length];

            for (int i = 0; i < userRights.Length; i++)
            {
                rights[i] = new LsaUnicodeString(userRights[i]);
            }

            try
            {
                LsaChecked(() => NativeMethods.LsaAddAccountRights(this, translatedSidHandle.Sid, rights, (uint)rights.Length));
            }
            finally
            {
                rights.DisposeAll();
            }
        }
Example #13
0
        static IntPtr GetLsaPolicyHandle()
        {
            var computerName     = Environment.MachineName;
            var objectAttributes = new LsaObjectAttributes
            {
                Length                   = 0,
                RootDirectory            = IntPtr.Zero,
                Attributes               = 0,
                SecurityDescriptor       = IntPtr.Zero,
                SecurityQualityOfService = IntPtr.Zero
            };

            const uint accessMask     = POLICY_CREATE_SECRET | POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION;
            var        machineNameLsa = new LsaUnicodeString(computerName);
            var        result         = LsaOpenPolicy(ref machineNameLsa, ref objectAttributes, accessMask, out var hPolicy);

            HandleLsaResult(result);
            return(hPolicy);
        }
Example #14
0
        public static string[] GetPrivileges(string identity)
        {
            var sidPtr    = GetIdentitySid(identity);
            var hPolicy   = GetLsaPolicyHandle();
            var rightsPtr = IntPtr.Zero;

            try
            {
                var privileges = new List <string>();

                var result         = LsaEnumerateAccountRights(hPolicy, sidPtr, out rightsPtr, out var rightsCount);
                var win32ErrorCode = LsaNtStatusToWinError(result);
                // the user has no privileges
                if (win32ErrorCode == StatusObjectNameNotFound)
                {
                    return(new string[0]);
                }

                HandleLsaResult(result);

                var myLsaus = new LsaUnicodeString();
                for (ulong i = 0; i < rightsCount; i++)
                {
                    var itemAddr = new IntPtr(rightsPtr.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus)));
                    myLsaus = (LsaUnicodeString)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
                    var cvt = new char[myLsaus.Length / UnicodeEncoding.CharSize];
                    Marshal.Copy(myLsaus.Buffer, cvt, 0, myLsaus.Length / UnicodeEncoding.CharSize);
                    var thisRight = new string(cvt);
                    privileges.Add(thisRight);
                }

                return(privileges.ToArray());
            }
            finally
            {
                Marshal.FreeHGlobal(sidPtr);
                var result = LsaClose(hPolicy);
                HandleLsaResult(result);
                result = LsaFreeMemory(rightsPtr);
                HandleLsaResult(result);
            }
        }
Example #15
0
        public bool CheckRight(string accountName, string privilegeName)
        {
            accountName = GetSanitizedAccountName(accountName);

            // contains the last error
            long winErrorCode = 0;

            // pointer an size for the SID
            var sid     = IntPtr.Zero;
            var sidSize = 0;

            // StringBuilder and size for the domain name
            var domainName = new StringBuilder();
            var nameSize   = 0;

            // account-type variable for lookup
            var accountType = 0;

            // get required buffer size
            LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

            // allocate buffers
            domainName = new StringBuilder(nameSize);
            sid        = Marshal.AllocHGlobal(sidSize);

            // lookup the SID for the account
            var result = LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

            // log info
            ////Console.WriteLine("LookupAccountName result = " + result);
            ////Console.WriteLine("IsValidSid: " + IsValidSid(sid));
            ////Console.WriteLine("LookupAccountName domainName: " + domainName.ToString());

            if (!result)
            {
                winErrorCode = GetLastError();
                throw new Exception("LookupAccountName failed.  Win32 Error Code: " +
                                    Marshal.GetLastWin32Error() + "|| Message: " +
                                    new Win32Exception(Marshal.GetLastWin32Error()).Message);
            }

            // initialize an empty unicode-string
            var systemName = new LsaUnicodeString();

            // combine all policies
            const uint access = (uint)(
                LsaAccessPolicy.PolicyAuditLogAdmin |
                LsaAccessPolicy.PolicyCreateAccount |
                LsaAccessPolicy.PolicyCreatePrivilege |
                LsaAccessPolicy.PolicyCreateSecret |
                LsaAccessPolicy.PolicyGetPrivateInformation |
                LsaAccessPolicy.PolicyLookupNames |
                LsaAccessPolicy.PolicyNotification |
                LsaAccessPolicy.PolicyServerAdmin |
                LsaAccessPolicy.PolicySetAuditRequirements |
                LsaAccessPolicy.PolicySetDefaultQuotaLimits |
                LsaAccessPolicy.PolicyTrustAdmin |
                LsaAccessPolicy.PolicyViewAuditInformation |
                LsaAccessPolicy.PolicyViewLocalInformation);

            // initialize a pointer for the policy handle
            IntPtr policyHandle;

            // these attributes are not used, but LsaOpenPolicy wants them to exists
            var objectAttributes = new LsaObjectAttributes();

            objectAttributes.Length                   = 0;
            objectAttributes.RootDirectory            = IntPtr.Zero;
            objectAttributes.Attributes               = 0;
            objectAttributes.SecurityDescriptor       = IntPtr.Zero;
            objectAttributes.SecurityQualityOfService = IntPtr.Zero;

            // get a policy handle
            var resultPolicy = LsaOpenPolicy(ref systemName, ref objectAttributes, access, out policyHandle);

            winErrorCode = LsaNtStatusToWinError(resultPolicy);

            if (winErrorCode != 0)
            {
                var errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
                throw new Exception("OpenPolicy failed. Error code: " + winErrorCode + "|| ErrorMessage: " + errorMessage);
            }
            else
            {
                var   rightsArray = IntPtr.Zero;
                ulong rightsCount = 0;
                LsaEnumerateAccountRights(policyHandle, sid, out rightsArray, out rightsCount);
                winErrorCode = LsaNtStatusToWinError(resultPolicy);

                if (winErrorCode != 0)
                {
                    var errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
                    throw new Exception("EnumerateAccountRights failed. Error code: " + winErrorCode + "|| ErrorMessage: " + errorMessage);
                }
                else
                {
                    var myLsaus = new LsaUnicodeString();
                    for (ulong i = 0; i < rightsCount; i++)
                    {
                        var itemAddr = new IntPtr(rightsArray.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus)));
                        myLsaus = (LsaUnicodeString)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
                        var thisRight = Lsaus2String(myLsaus);

                        if (string.Compare(thisRight, privilegeName, StringComparison.OrdinalIgnoreCase) != 0)
                        {
                            continue;
                        }
                        LsaClose(policyHandle);
                        FreeSid(sid);
                        return(true);
                    }
                }

                LsaClose(policyHandle);
            }

            FreeSid(sid);
            return(false);
        }
Example #16
0
 static extern uint LsaOpenPolicy(ref LsaUnicodeString SystemName, ref LsaObjectAttributes ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle);
 public static extern LsaStatus LsaOpenPolicy(ref LsaUnicodeString systemName, ref LsaObjectAttributes objectAttributes, int desiredAccess, out LsaPolicyHandle policyHandle);
Example #18
0
        /// <summary>
        /// Adds a privilege to an account
        /// </summary>
        /// <param name="accountName">Name of an account - "domain\account" or only "account"</param>
        /// <param name="privilegeName">Name ofthe privilege</param>
        /// <returns>The windows error code returned by LsaAddAccountRights</returns>
        public long SetRight(string accountName, string privilegeName)
        {
            accountName = GetSanitizedAccountName(accountName);

            // contains the last error
            long winErrorCode = 0;

            // pointer an size for the SID
            var sid     = IntPtr.Zero;
            var sidSize = 0;

            // StringBuilder and size for the domain name
            var domainName = new StringBuilder();
            var nameSize   = 0;

            // account-type variable for lookup
            var accountType = 0;

            // get required buffer size
            LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

            // allocate buffers
            domainName = new StringBuilder(nameSize);
            sid        = Marshal.AllocHGlobal(sidSize);

            // lookup the SID for the account
            var result = LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

            // log info
            ////Console.WriteLine("LookupAccountName result = " + result);
            ////Console.WriteLine("IsValidSid: " + IsValidSid(sid));
            ////Console.WriteLine("LookupAccountName domainName: " + domainName.ToString());

            if (!result)
            {
                winErrorCode = GetLastError();
                throw new Exception("LookupAccountName failed: " + winErrorCode);
            }
            // initialize an empty unicode-string
            var systemName = new LsaUnicodeString();

            // combine all policies
            const uint access = (uint)(
                LsaAccessPolicy.PolicyAuditLogAdmin |
                LsaAccessPolicy.PolicyCreateAccount |
                LsaAccessPolicy.PolicyCreatePrivilege |
                LsaAccessPolicy.PolicyCreateSecret |
                LsaAccessPolicy.PolicyGetPrivateInformation |
                LsaAccessPolicy.PolicyLookupNames |
                LsaAccessPolicy.PolicyNotification |
                LsaAccessPolicy.PolicyServerAdmin |
                LsaAccessPolicy.PolicySetAuditRequirements |
                LsaAccessPolicy.PolicySetDefaultQuotaLimits |
                LsaAccessPolicy.PolicyTrustAdmin |
                LsaAccessPolicy.PolicyViewAuditInformation |
                LsaAccessPolicy.PolicyViewLocalInformation);

            // initialize a pointer for the policy handle
            var policyHandle = IntPtr.Zero;

            // these attributes are not used, but LsaOpenPolicy wants them to exists
            var objectAttributes = new LsaObjectAttributes();

            objectAttributes.Length                   = 0;
            objectAttributes.RootDirectory            = IntPtr.Zero;
            objectAttributes.Attributes               = 0;
            objectAttributes.SecurityDescriptor       = IntPtr.Zero;
            objectAttributes.SecurityQualityOfService = IntPtr.Zero;

            // get a policy handle
            var resultPolicy = LsaOpenPolicy(ref systemName, ref objectAttributes, access, out policyHandle);

            winErrorCode = LsaNtStatusToWinError(resultPolicy);

            if (winErrorCode != 0)
            {
                var errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
                throw new Exception("OpenPolicy failed: " + winErrorCode + " ErrorMessage: " + errorMessage);
            }
            else
            {
                // Now that we have the SID an the policy, we can add rights to the account.

                // initialize an unicode-string for the privilege name
                var userRights = new LsaUnicodeString[1];
                userRights[0]               = new LsaUnicodeString();
                userRights[0].Buffer        = Marshal.StringToHGlobalUni(privilegeName);
                userRights[0].Length        = (ushort)(privilegeName.Length * UnicodeEncoding.CharSize);
                userRights[0].MaximumLength = (ushort)((privilegeName.Length + 1) * UnicodeEncoding.CharSize);

                // add the right to the account
                var res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
                winErrorCode = LsaNtStatusToWinError(res);
                if (winErrorCode != 0)
                {
                    var errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
                    throw new Exception("LsaAddAccountRights failed: " + winErrorCode + " Error Message: " + errorMessage);
                }

                LsaClose(policyHandle);
            }

            FreeSid(sid);

            return(winErrorCode);
        }
Example #19
0
 public static extern UInt32 LsaOpenPolicy(ref LsaUnicodeString systemName, ref LsaObjectAttributes objectAttributes, Int32 desiredAccess, out IntPtr policyHandle);
Example #20
0
 public static extern uint LsaRemoveAccountRights(
     IntPtr hPolicy,
     byte[] lpAccountSid,
     [MarshalAs(UnmanagedType.U1)] bool bAllRights,
     LsaUnicodeString lpUserRights,
     uint dwCountOfRights);
Example #21
0
 internal static extern LsaStatus LsaLookupNames2(LsaPolicyHandle policyHandle, LsaLookupNamesFlags flags, uint count, LsaUnicodeString[] names, out LsaReferencedDomainsHandle referencedReferencedDomains, out LsaTranslatedSidHandle translatedSid);
Example #22
0
 public static extern LsaStatus LsaOpenPolicy(ref LsaUnicodeString systemName, ref LsaObjectAttributes objectAttributes, int desiredAccess, out LsaPolicyHandle policyHandle);
Example #23
0
 public static extern LsaStatus LsaAddAccountRights(LsaPolicyHandle policyHandle, IntPtr accountSid, LsaUnicodeString[] userRights, uint countOfRights);
Example #24
0
 private static extern uint LsaOpenPolicy(
     ref LsaUnicodeString systemName,
     ref LsaObjectAttributes objectAttributes,
     uint desiredAccess,
     out IntPtr policyHandle);
Example #25
0
 public static extern uint LsaAddAccountRights(
     IntPtr hPolicy,
     byte[] lpAccountSid,
     LsaUnicodeString lpUserRights,
     uint dwCountOfRights);