Beispiel #1
0
        public static void SetValue(string key, string?value)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (key.Length == 0)
            {
                throw new ArgumentException($"{nameof(key)} must not be empty", nameof(key));
            }

            var objectAttributes = new LSA_OBJECT_ATTRIBUTES();
            var localsystem      = new LSA_UNICODE_STRING();
            var secretName       = new LSA_UNICODE_STRING(key);

            var lusSecretData = !string.IsNullOrEmpty(value) ? new LSA_UNICODE_STRING(value) : default;

            var lsaPolicyHandle = GetLsaPolicy(ref objectAttributes, ref localsystem);

            var result = LsaStorePrivateData(lsaPolicyHandle, ref secretName, ref lusSecretData);

            ReleaseLsaPolicy(lsaPolicyHandle);

            var winErrorCode = LsaNtStatusToWinError(result);

            if (winErrorCode != 0)
            {
                throw new Win32Exception(winErrorCode, "StorePrivateData failed: " + winErrorCode.ToString(CultureInfo.InvariantCulture));
            }
        }
Beispiel #2
0
            public static List <String> getAccessTokens(String sidString)
            {
                List <String> tokens = new List <String>();
                IntPtr        sid    = IntPtr.Zero;

                if (!ConvertStringSidToSid(sidString, out sid))
                {
                    int errorCode = GetLastError();
                    switch (errorCode)
                    {
                    case ERROR_FILE_NOT_FOUND:   // no such user?
                        return(tokens);

                    default:
                        throw new System.ComponentModel.Win32Exception(errorCode);
                    }
                }

                IntPtr policyHandle            = IntPtr.Zero;
                LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();
                int  mode   = POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION;
                uint result = LsaNtStatusToWinError(LsaOpenPolicy(null, ref objAttrs, mode, out policyHandle));

                if (result != 0)
                {
                    Marshal.FreeHGlobal(sid);
                    throw new System.ComponentModel.Win32Exception((int)result);
                }

                IntPtr rightsArray = IntPtr.Zero;
                UInt32 rightsLen   = 0;

                result = LsaNtStatusToWinError(LsaEnumerateAccountRights(policyHandle, sid, out rightsArray, out rightsLen));
                Marshal.FreeHGlobal(sid);
                switch ((int)result)
                {
                case ERROR_SUCCESS:
                    LSA_UNICODE_STRING myLsaus = new LSA_UNICODE_STRING();
                    for (ulong i = 0; i < rightsLen; i++)
                    {
                        IntPtr itemAddr = new IntPtr(rightsArray.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus)));
                        myLsaus = (LSA_UNICODE_STRING)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
                        String thisRight = LSAUS2string(myLsaus);
                        tokens.Add(thisRight);
                    }
                    break;

                case ERROR_FILE_NOT_FOUND:
                    // no account rights were found for the user
                    break;

                default:
                    LsaClose(policyHandle);
                    throw new System.ComponentModel.Win32Exception((int)result);
                }

                LsaClose(policyHandle);
                return(tokens);
            }
Beispiel #3
0
        // Adds a privilege to an account
        public void SetRight(string accountName, string privilegeName)
        {
            long   winErrorCode = 0;
            string errorMessage = string.Empty;

            IntPtr        sid         = IntPtr.Zero;
            int           sidSize     = 0;
            StringBuilder domainName  = new StringBuilder();
            int           nameSize    = 0;
            int           accountType = 0;

            LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

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

            if (!LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType))
            {
                winErrorCode = GetLastError();
                errorMessage = string.Format("LookupAccountName failed: {0}", winErrorCode);
            }
            else
            {
                LSA_UNICODE_STRING    systemName       = new LSA_UNICODE_STRING();
                IntPtr                policyHandle     = IntPtr.Zero;
                LSA_OBJECT_ATTRIBUTES objectAttributes = CreateLSAObject();

                uint resultPolicy = LsaOpenPolicy(ref systemName, ref objectAttributes, Access, out policyHandle);
                winErrorCode = LsaNtStatusToWinError(Convert.ToInt32(resultPolicy));

                if (winErrorCode != 0)
                {
                    errorMessage = string.Format("OpenPolicy failed: {0} ", winErrorCode);
                }
                else
                {
                    LSA_UNICODE_STRING[] userRights = new LSA_UNICODE_STRING[1];
                    userRights[0]               = new LSA_UNICODE_STRING();
                    userRights[0].Buffer        = Marshal.StringToHGlobalUni(privilegeName);
                    userRights[0].Length        = (UInt16)(privilegeName.Length * UnicodeEncoding.CharSize);
                    userRights[0].MaximumLength = (UInt16)((privilegeName.Length + 1) * UnicodeEncoding.CharSize);

                    int res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
                    winErrorCode = LsaNtStatusToWinError(Convert.ToInt32(res));
                    if (winErrorCode != 0)
                    {
                        errorMessage = string.Format("LsaAddAccountRights failed: {0}", winErrorCode);
                    }

                    LsaClose(policyHandle);
                }
                FreeSid(sid);
            }

            if (winErrorCode > 0)
            {
                throw new ApplicationException(string.Format("Failed to add right {0} to {1}. Error detail:{2}", accountName, privilegeName, errorMessage));
            }
        }
        /// <summary>Initializes a new instance of the <see cref="LocalSecurity"/> class.</summary>
        /// <param name="server">The server. Use <c>null</c> for the local server.</param>
        /// <param name="accessRights">The access rights mask for the actions to be taken.</param>
        /// <exception cref="System.ComponentModel.Win32Exception"></exception>
        public LocalSecurity(string server = null, LsaPolicyAccessRights accessRights = LsaPolicyAccessRights.AllAccess)
        {
            LSA_UNICODE_STRING    systemName       = server;
            LSA_OBJECT_ATTRIBUTES objectAttributes = LSA_OBJECT_ATTRIBUTES.Empty;

            ThrowIfLsaError(LsaOpenPolicy(systemName, ref objectAttributes, 0x000F0000 | (int)accessRights, out handle));             // Add in STANDARD_RIGHTS_REQUIRED
            svr = server;
        }
Beispiel #5
0
        private static System.Collections.Specialized.StringCollection GetRights(System.Security.Principal.WindowsIdentity identity)
        {
            System.Collections.Specialized.StringCollection rights = new System.Collections.Specialized.StringCollection();

            LSA_OBJECT_ATTRIBUTES objectAttributes = CreateLSAObjectAttributes();
            IntPtr policyHandle = IntPtr.Zero;

            LSA_UNICODE_STRING SystemName = new LSA_UNICODE_STRING();

            /*
             * SystemName.Length = (ushort)(System.Environment.MachineName.Length * System.Text.UnicodeEncoding.CharSize);
             * SystemName.MaximumLength = (ushort)((System.Environment.MachineName.Length + 1) * System.Text.UnicodeEncoding.CharSize);
             * SystemName.Buffer = System.Environment.MachineName; // Marshal.StringToHGlobalUni(System.Environment.MachineName);
             */


            // Open a policy handle on the remote PC.
            uint ret = LsaOpenPolicy(ref SystemName, ref objectAttributes, (int)POLICY_ALL_ACCESS, out policyHandle);

            if (ret == 0)
            {
                //long winErrorCode = 0;
                //IntPtr sid = IntPtr.Zero;
                //int sidSize = 0;
                //System.Text.StringBuilder domainName = new System.Text.StringBuilder();
                //int nameSize = 0;
                //int accountType = 0;
                long winErrorCode = 0;

                IntPtr userRightsPtr = IntPtr.Zero;
                int    countOfRights = 0;

                byte[] accountSidBytes = new byte[identity.User.BinaryLength];
                identity.User.GetBinaryForm(accountSidBytes, 0);
                int result = LsaEnumerateAccountRights(policyHandle, accountSidBytes, out userRightsPtr, out countOfRights);

                winErrorCode = LsaNtStatusToWinError(result);
                if (winErrorCode == 0)
                {
                    long current = userRightsPtr.ToInt64();
                    LSA_UNICODE_STRING userRight;

                    for (int i = 0; i < countOfRights; i++)
                    {
                        userRight = (LSA_UNICODE_STRING)Marshal.PtrToStructure(new IntPtr(current), typeof(LSA_UNICODE_STRING));
                        string userRightStr = Marshal.PtrToStringAuto(userRight.Buffer);
                        rights.Add(userRightStr);
                        current += Marshal.SizeOf(userRight);
                    }
                }

                LsaClose(policyHandle);
            }

            return(rights);
        }
 private unsafe static extern int LsaOpenPolicy(
     [In]
     ref LSA_UNICODE_STRING SystemName,
     [In, MarshalAs(UnmanagedType.LPStruct)]
     LSA_OBJECT_ATTRIBUTES Attributes,
     [In]
     System.UInt32 DesiredAccess,
     [Out]
     out System.IntPtr PolicyHandle
     );
        private static LSA_OBJECT_ATTRIBUTES CreateLSAObject()
        {
            var newInstance = new LSA_OBJECT_ATTRIBUTES();

            newInstance.Length                   = 0;
            newInstance.RootDirectory            = IntPtr.Zero;
            newInstance.Attributes               = 0;
            newInstance.SecurityDescriptor       = IntPtr.Zero;
            newInstance.SecurityQualityOfService = IntPtr.Zero;
            return(newInstance);
        }
Beispiel #8
0
        /// <summary>
        /// Constructor for <see cref="LocalSecurityPolicy"/>
        /// </summary>
        /// <param name="systemName">local system if systemName is null</param>
        public LocalSecurityPolicy(string systemName)
        {
            lsaHandle = IntPtr.Zero;
            LSA_UNICODE_STRING system = InitLsaString(systemName);


            //combine all policies
            int access = (int)(
                LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
                LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
                LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
                LSA_AccessPolicy.POLICY_CREATE_SECRET |
                LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
                LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
                LSA_AccessPolicy.POLICY_NOTIFICATION |
                LSA_AccessPolicy.POLICY_SERVER_ADMIN |
                LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
                LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
                LSA_AccessPolicy.POLICY_TRUST_ADMIN |
                LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
                LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
                );
            //initialize a pointer for the policy handle
            IntPtr policyHandle = IntPtr.Zero;

            //these attributes are not used, but LsaOpenPolicy wants them to exists
            LSA_OBJECT_ATTRIBUTES ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();

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

            //get a policy handle
            uint ret = LsaOpenPolicy(ref system, ref ObjectAttributes, access, out lsaHandle);

            if (ret == 0)
            {
                return;
            }
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }

            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }

            throw new Win32Exception((int)LsaNtStatusToWinError(ret));
        }
        private static IntPtr GetLsaPolicy(ref LSA_OBJECT_ATTRIBUTES objectAttributes, ref LSA_UNICODE_STRING localsystem)
        {
            var ntsResult    = LsaOpenPolicy(ref localsystem, ref objectAttributes, (uint)LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION, out var lsaPolicyHandle);
            var winErrorCode = LsaNtStatusToWinError(ntsResult);

            if (winErrorCode != 0)
            {
                throw new Win32Exception(winErrorCode, "LsaOpenPolicy failed: " + winErrorCode);
            }

            return(lsaPolicyHandle);
        }
Beispiel #10
0
        /*
         * // Returns the Local Security Authority rights granted to the account
         * public static System.Collections.Generic.IList<string> GetRights(string accountName)
         * {
         *  System.Collections.Generic.IList<string> rights = new System.Collections.Generic.List<string>();
         *  string errorMessage = string.Empty;
         *
         *  long winErrorCode = 0;
         *  IntPtr sid = IntPtr.Zero;
         *  int sidSize = 0;
         *  System.Text.StringBuilder domainName = new System.Text.StringBuilder();
         *  int nameSize = 0;
         *  int accountType = 0;
         *
         *  LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);
         *
         *  domainName = new System.Text.StringBuilder(nameSize);
         *  sid = Marshal.AllocHGlobal(sidSize);
         *
         *  if (!LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType))
         *  {
         *      winErrorCode = GetLastError();
         *      errorMessage = ("LookupAccountName failed: " + winErrorCode);
         *  }
         *  else
         *  {
         *      LSA_UNICODE_STRING systemName = new LSA_UNICODE_STRING();
         *
         *      IntPtr policyHandle = IntPtr.Zero;
         *      IntPtr userRightsPtr = IntPtr.Zero;
         *      int countOfRights = 0;
         *
         *      LSA_OBJECT_ATTRIBUTES objectAttributes = CreateLSAObject();
         *
         *      uint policyStatus = LsaOpenPolicy(ref systemName, ref objectAttributes, (int)POLICY_ALL_ACCESS, out policyHandle);
         *      winErrorCode = LsaNtStatusToWinError(Convert.ToInt32(policyStatus));
         *
         *      if (winErrorCode != 0)
         *      {
         *          errorMessage = string.Format("OpenPolicy failed: {0}.", winErrorCode);
         *      }
         *      else
         *      {
         *          int result = LsaEnumerateAccountRights(policyHandle, sid, out userRightsPtr, out countOfRights);
         *          winErrorCode = LsaNtStatusToWinError(result);
         *          if (winErrorCode != 0)
         *          {
         *              errorMessage = string.Format("LsaEnumerateAccountRights failed: {0}", winErrorCode);
         *          }
         *
         *          Int32 ptr = userRightsPtr.ToInt32();
         *          LSA_UNICODE_STRING userRight;
         *
         *          for (int i = 0; i < countOfRights; i++)
         *          {
         *              userRight = (LSA_UNICODE_STRING)Marshal.PtrToStructure(new IntPtr(ptr), typeof(LSA_UNICODE_STRING));
         *              string userRightStr = Marshal.PtrToStringAuto(userRight.Buffer);
         *              rights.Add(userRightStr);
         *              ptr += Marshal.SizeOf(userRight);
         *          }
         *          LsaClose(policyHandle);
         *      }
         *      FreeSid(sid);
         *  }
         *  if (winErrorCode > 0)
         *  {
         *      throw new ApplicationException(string.Format("Error occured in LSA, error code {0}, detail: {1}", winErrorCode, errorMessage));
         *  }
         *  return rights;
         * }
         */
        private static LSA_OBJECT_ATTRIBUTES CreateLSAObjectAttributes()
        {
            LSA_OBJECT_ATTRIBUTES objectAttributes = new LSA_OBJECT_ATTRIBUTES();

            objectAttributes.Length                   = (uint)Marshal.SizeOf(objectAttributes);
            objectAttributes.RootDirectory            = IntPtr.Zero;
            objectAttributes.ObjectName               = new LSA_UNICODE_STRING();
            objectAttributes.Attributes               = 0;
            objectAttributes.SecurityDescriptor       = IntPtr.Zero;
            objectAttributes.SecurityQualityOfService = IntPtr.Zero;

            return(objectAttributes);
        }
Beispiel #11
0
            public static List<String> getAccessTokens(String sidString)
            {
                List<String> tokens = new List<String>();
                IntPtr sid = IntPtr.Zero;
                if (!ConvertStringSidToSid(sidString, out sid)) {
                int errorCode = GetLastError();
                switch(errorCode) {
                  case ERROR_FILE_NOT_FOUND: // no such user?
                return tokens;
                  default:
                throw new System.ComponentModel.Win32Exception(errorCode);
                }
                }

                IntPtr policyHandle = IntPtr.Zero;
                LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();
                int mode = POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION;
                uint result = LsaNtStatusToWinError(LsaOpenPolicy(null, ref objAttrs, mode, out policyHandle));
                if (result != 0) {
                Marshal.FreeHGlobal(sid);
                throw new System.ComponentModel.Win32Exception((int)result);
                }

                IntPtr rightsArray = IntPtr.Zero;
                UInt32 rightsLen = 0;
                result = LsaNtStatusToWinError(LsaEnumerateAccountRights(policyHandle, sid, out rightsArray, out rightsLen));
                Marshal.FreeHGlobal(sid);
                switch((int)result) {
                  case ERROR_SUCCESS:
                LSA_UNICODE_STRING myLsaus = new LSA_UNICODE_STRING();
                for (ulong i=0; i < rightsLen; i++) {
                IntPtr itemAddr = new IntPtr(rightsArray.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus)));
                myLsaus = (LSA_UNICODE_STRING)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
                String thisRight = LSAUS2string(myLsaus);
                tokens.Add(thisRight);
                }
                break;
                  case ERROR_FILE_NOT_FOUND:
                // no account rights were found for the user
                break;
                  default:
                LsaClose(policyHandle);
                throw new System.ComponentModel.Win32Exception((int)result);
                }

                LsaClose(policyHandle);
                return tokens;
            }
        public static string GetValue(string key)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (key.Length == 0)
            {
                throw new ArgumentException($"{nameof(key)} must not be empty", nameof(key));
            }

            var objectAttributes = new LSA_OBJECT_ATTRIBUTES();
            var localsystem      = new LSA_UNICODE_STRING();
            var secretName       = new LSA_UNICODE_STRING(key);

            // Get LSA policy
            var lsaPolicyHandle = GetLsaPolicy(ref objectAttributes, ref localsystem);

            var result = LsaRetrievePrivateData(lsaPolicyHandle, ref secretName, out var privateData);

            ReleaseLsaPolicy(lsaPolicyHandle);

            if (result == STATUS_OBJECT_NAME_NOT_FOUND)
            {
                return(null);
            }

            var winErrorCode = LsaNtStatusToWinError(result);

            if (winErrorCode != 0)
            {
                throw new Win32Exception(winErrorCode, "LsaRetrievePrivateData failed: " + winErrorCode);
            }

            if (privateData == IntPtr.Zero)
            {
                return(null);
            }

            var lusSecretData = Marshal.PtrToStructure <LSA_UNICODE_STRING>(privateData);
            var value         = Marshal.PtrToStringAuto(lusSecretData.Buffer).Substring(0, lusSecretData.Length / UnicodeEncoding.CharSize);

            FreeMemory(privateData);

            return(value);
        }
        public static LsaHandle LsaOpenLocalPolicy(PolicyAccessRights access)
        {
            LSA_OBJECT_ATTRIBUTES attributes = new LSA_OBJECT_ATTRIBUTES();
            LsaHandle             handle;
            NTSTATUS status;

            unsafe
            {
                status = Imports.LsaOpenPolicy(null, &attributes, access, out handle);
            }

            if (status != NTSTATUS.STATUS_SUCCESS)
            {
                throw ErrorMethods.GetIoExceptionForNTStatus(status);
            }

            return(handle);
        }
Beispiel #14
0
        static void Main(string[] args)
        {
            // LsaOpenPolicy function opens a handle to the Policy object on a local or remote system.
            //initialize an empty unicode-string
            LSA_UNICODE_STRING aSystemName = new LSA_UNICODE_STRING();

            //these attributes are not used, but LsaOpenPolicy wants them to exists
            LSA_OBJECT_ATTRIBUTES aObjectAttributes = new LSA_OBJECT_ATTRIBUTES();


            //these attributes are not used, but LsaOpenPolicy wants them to exist
            // (MSDN: "the structure members are not used, initalize them to NULL or zero")
            LSA_OBJECT_ATTRIBUTES ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();

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

            // This was hard coded in keithga's binary - https://docs.microsoft.com/en-us/windows/win32/secauthz/access-mask
            uint access = 1;

            // A pointer to an LSA_HANDLE variable that receives a handle to the Policy object.
            IntPtr policy = IntPtr.Zero;

            //get a policy handle
            UInt32 resultPolicy = LsaOpenPolicy(ref aSystemName, ref ObjectAttributes, access, out policy);
            UInt32 winErrorCode = LsaNtStatusToWinError(resultPolicy);

            if (resultPolicy != 0)
            {
                Console.WriteLine("OpenPolicy failed: " + resultPolicy);
            }

            if (winErrorCode != 0)
            {
                Console.WriteLine("OpenPolicy Error: " + winErrorCode);
            }

            string result = RetrievePrivateData("DefaultPassword", policy);

            Console.WriteLine("AutoLogon Password: " + result);
        }
Beispiel #15
0
        private static IntPtr GetLsaPolicyHandle()
        {
            string computerName = Environment.MachineName;
            IntPtr hPolicy;
            LSA_OBJECT_ATTRIBUTES objectAttributes = new LSA_OBJECT_ATTRIBUTES();

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

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

            HandleLsaResult(result);
            return(hPolicy);
        }
        public bool GrantUserLogonAsServicePrivilage(string domain, string userName)
        {
            Trace.Entering();
            IntPtr lsaPolicyHandle = IntPtr.Zero;

            ArgUtil.NotNullOrEmpty(userName, nameof(userName));

            try
            {
                LSA_UNICODE_STRING    system = new LSA_UNICODE_STRING();
                LSA_OBJECT_ATTRIBUTES attrib = new LSA_OBJECT_ATTRIBUTES()
                {
                    Length                   = 0,
                    RootDirectory            = IntPtr.Zero,
                    Attributes               = 0,
                    SecurityDescriptor       = IntPtr.Zero,
                    SecurityQualityOfService = IntPtr.Zero,
                };

                uint result = LsaOpenPolicy(ref system, ref attrib, LSA_POLICY_ALL_ACCESS, out lsaPolicyHandle);
                if (result != 0 || lsaPolicyHandle == IntPtr.Zero)
                {
                    if (result == ReturnCode.STATUS_ACCESS_DENIED)
                    {
                        throw new Exception(StringUtil.Loc("ShouldBeAdmin"));
                    }
                    throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaOpenPolicy), result));
                }

                result = LsaAddAccountRights(lsaPolicyHandle, GetSidBinaryFromWindows(domain, userName), LogonAsServiceRights, 1);
                Trace.Info("LsaAddAccountRights return with error code {0} ", result);

                return(result == 0);
            }
            finally
            {
                int result = LsaClose(lsaPolicyHandle);
                if (result != 0)
                {
                    Trace.Error(StringUtil.Format("Can not close LasPolicy handler. LsaClose failed with error code {0}", result));
                }
            }
        }
Beispiel #17
0
        private static IntPtr GetLsaPolicyHandle()
        {
            var    computerName = Environment.MachineName;
            IntPtr hPolicy;
            var    objectAttributes = new LSA_OBJECT_ATTRIBUTES
            {
                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 LSA_UNICODE_STRING(computerName);
            var        result         = LsaOpenPolicy(ref machineNameLsa, ref objectAttributes, accessMask, out hPolicy);

            HandleLsaResult(result);
            return(hPolicy);
        }
Beispiel #18
0
        public LSAPolicy(LSA_AccessPolicy access)
        {
            //initialize an empty unicode-string
            string systemName = null;

            //these attributes are not used, but LsaOpenPolicy wants them to exist
            // (MSDN: "the structure members are not used, initalize them to NULL or zero")
            var objectAttributes = new LSA_OBJECT_ATTRIBUTES();
            //				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, (int)access, out _policy);
            var winErrorCode = LsaNtStatusToWinError(resultPolicy);

            if (winErrorCode != 0)
            {
                throw new Win32Exception(winErrorCode, "OpenPolicy failed: " + winErrorCode);
            }
        }
Beispiel #19
0
            public LsaPolicy()
            {
                LSA_UNICODE_STRING system = new LSA_UNICODE_STRING();

                LSA_OBJECT_ATTRIBUTES attrib = new LSA_OBJECT_ATTRIBUTES()
                {
                    Length                   = 0,
                    RootDirectory            = IntPtr.Zero,
                    Attributes               = 0,
                    SecurityDescriptor       = IntPtr.Zero,
                    SecurityQualityOfService = IntPtr.Zero,
                };

                IntPtr handle = IntPtr.Zero;
                uint   result = LsaOpenPolicy(ref system, ref attrib, LSA_POLICY_ALL_ACCESS, out handle);

                if (result != 0 || handle == IntPtr.Zero)
                {
                    throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaOpenPolicy), result));
                }

                Handle = handle;
            }
        public LSAutil(string key)
        {
            if (key.Length == 0)
            {
                throw new Exception("Key length zero");
            }

            objectAttributes                          = new LSA_OBJECT_ATTRIBUTES();
            objectAttributes.Length                   = 0;
            objectAttributes.RootDirectory            = IntPtr.Zero;
            objectAttributes.Attributes               = 0;
            objectAttributes.SecurityDescriptor       = IntPtr.Zero;
            objectAttributes.SecurityQualityOfService = IntPtr.Zero;

            localsystem               = new LSA_UNICODE_STRING();
            localsystem.Buffer        = IntPtr.Zero;
            localsystem.Length        = 0;
            localsystem.MaximumLength = 0;

            secretName               = new LSA_UNICODE_STRING();
            secretName.Buffer        = Marshal.StringToHGlobalUni(key);
            secretName.Length        = (UInt16)(key.Length * UnicodeEncoding.CharSize);
            secretName.MaximumLength = (UInt16)((key.Length + 1) * UnicodeEncoding.CharSize);
        }
 private static extern UInt32 LsaOpenPolicy(
     ref LSA_UNICODE_STRING SystemName,
     ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
     Int32 DesiredAccess,
     out IntPtr PolicyHandle
 );
        /// <summary>
        /// Constructor for <see cref="LocalSecurityPolicy"/>
        /// </summary>
        /// <param name="systemName">local system if systemName is null</param>
        public LocalSecurityPolicy(string systemName)
        {
            lsaHandle = IntPtr.Zero;
            LSA_UNICODE_STRING system = InitLsaString(systemName);
            

            //combine all policies
            int access = (int)(
                LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
                LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
                LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
                LSA_AccessPolicy.POLICY_CREATE_SECRET |
                LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
                LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
                LSA_AccessPolicy.POLICY_NOTIFICATION |
                LSA_AccessPolicy.POLICY_SERVER_ADMIN |
                LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
                LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
                LSA_AccessPolicy.POLICY_TRUST_ADMIN |
                LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
                LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
                );
            //initialize a pointer for the policy handle
            IntPtr policyHandle = IntPtr.Zero;

            //these attributes are not used, but LsaOpenPolicy wants them to exists
            LSA_OBJECT_ATTRIBUTES ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();
            ObjectAttributes.Length = 0;
            ObjectAttributes.RootDirectory = IntPtr.Zero;
            ObjectAttributes.Attributes = 0;
            ObjectAttributes.SecurityDescriptor = IntPtr.Zero;
            ObjectAttributes.SecurityQualityOfService = IntPtr.Zero;

            //get a policy handle
            uint ret = LsaOpenPolicy(ref system, ref ObjectAttributes, access, out lsaHandle);
            if (ret == 0)
                return;
            if (ret == STATUS_ACCESS_DENIED)
            {
                throw new UnauthorizedAccessException();
            }
            if ((ret == STATUS_INSUFFICIENT_RESOURCES) || (ret == STATUS_NO_MEMORY))
            {
                throw new OutOfMemoryException();
            }
            throw new Win32Exception((int)LsaNtStatusToWinError(ret));
        }
Beispiel #23
0
 internal static extern uint LsaOpenPolicy(
    ref LSA_UNICODE_STRING systemName,
    ref LSA_OBJECT_ATTRIBUTES objectAttributes,
    uint desiredAccess,
    out IntPtr policyHandle);
Beispiel #24
0
        public static Dictionary <AuditEventPolicy, Dictionary <String, AuditEventStatus> > GetSubcategoryPolicies()
        {
            Dictionary <AuditEventPolicy, Dictionary <String, AuditEventStatus> > result = new Dictionary <AuditEventPolicy, Dictionary <String, AuditEventStatus> >();

            LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();
            IntPtr hPolicy        = IntPtr.Zero;
            IntPtr pInfo          = IntPtr.Zero;
            IntPtr pGuid          = IntPtr.Zero;
            IntPtr pAuditPolicies = IntPtr.Zero;
            IntPtr pSubcategories = IntPtr.Zero;

            UInt32 lrc  = LsaOpenPolicy(null, ref objAttrs, POLICY_VIEW_AUDIT_INFORMATION, out hPolicy);
            uint   code = LsaNtStatusToWinError(lrc);

            if (code != 0)
            {
                throw new System.ComponentModel.Win32Exception((int)code);
            }
            try {
                //
                // Query the policy
                //
                lrc  = LsaQueryInformationPolicy(hPolicy, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pInfo);
                code = LsaNtStatusToWinError(lrc);
                if (code != 0)
                {
                    throw new System.ComponentModel.Win32Exception((int)code);
                }
                POLICY_AUDIT_EVENTS_INFO info = new POLICY_AUDIT_EVENTS_INFO();
                info = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pInfo, info.GetType());

                //
                // Iterate through the event types
                //
                for (UInt32 eventType = 0; eventType < info.MaximumAuditEventCount; eventType++)
                {
                    pGuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GUID)));
                    if (!AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)eventType, pGuid))
                    {
                        throw new System.ComponentModel.Win32Exception(GetLastError());
                    }
                    UInt32 subcategoryCount = 0;
                    if (!AuditEnumerateSubCategories(pGuid, false, ref pSubcategories, out subcategoryCount))
                    {
                        throw new System.ComponentModel.Win32Exception(GetLastError());
                    }
                    if (!AuditQuerySystemPolicy(pSubcategories, subcategoryCount, out pAuditPolicies))
                    {
                        throw new System.ComponentModel.Win32Exception(GetLastError());
                    }

                    Dictionary <String, AuditEventStatus> dict = new Dictionary <String, AuditEventStatus>();
                    AUDIT_POLICY_INFORMATION policyInfo        = new AUDIT_POLICY_INFORMATION();
                    for (UInt32 subcategoryIndex = 0; subcategoryIndex < subcategoryCount; subcategoryIndex++)
                    {
                        IntPtr itemPtr = new IntPtr(pAuditPolicies.ToInt64() +
                                                    (long)subcategoryIndex * (Int64)Marshal.SizeOf(policyInfo));
                        policyInfo = (AUDIT_POLICY_INFORMATION)Marshal.PtrToStructure(itemPtr, policyInfo.GetType());
                        dict.Add(AuditPolicySubcategories[policyInfo.AuditSubCategoryGuid.ToString()],
                                 (AuditEventStatus)policyInfo.AuditingInformation);
                    }
                    result.Add((AuditEventPolicy)eventType, dict);

                    AuditFree(pAuditPolicies);
                    pAuditPolicies = IntPtr.Zero;
                    AuditFree(pSubcategories);
                    pSubcategories = IntPtr.Zero;
                    Marshal.FreeHGlobal(pGuid);
                    pGuid = IntPtr.Zero;
                }
            } finally {
                //
                // Cleanup
                //
                if (pInfo != IntPtr.Zero)
                {
                    LsaFreeMemory(pInfo);
                }
                if (pGuid != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pGuid);
                }
                if (pAuditPolicies != IntPtr.Zero)
                {
                    AuditFree(pAuditPolicies);
                }
                if (pSubcategories != IntPtr.Zero)
                {
                    AuditFree(pSubcategories);
                }
                LsaClose(hPolicy);
            }
            return(result);
        }
Beispiel #25
0
 public static extern UInt32 LsaOpenPolicy(String SystemName,
                                           ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, Int32 DesiredAccess, out IntPtr PolicyHandle);
        public bool GrantUserLogonAsServicePrivilage(string domain, string userName)
        {
            Trace.Entering();
            IntPtr lsaPolicyHandle = IntPtr.Zero;

            ArgUtil.NotNullOrEmpty(userName, nameof(userName));

            try
            {
                LSA_UNICODE_STRING system = new LSA_UNICODE_STRING();
                LSA_OBJECT_ATTRIBUTES attrib = new LSA_OBJECT_ATTRIBUTES()
                {
                    Length = 0,
                    RootDirectory = IntPtr.Zero,
                    Attributes = 0,
                    SecurityDescriptor = IntPtr.Zero,
                    SecurityQualityOfService = IntPtr.Zero,
                };

                uint result = LsaOpenPolicy(ref system, ref attrib, LSA_POLICY_ALL_ACCESS, out lsaPolicyHandle);
                if (result != 0 || lsaPolicyHandle == IntPtr.Zero)
                {
                    if (result == ReturnCode.STATUS_ACCESS_DENIED)
                    {
                        throw new Exception(StringUtil.Loc("ShouldBeAdmin"));
                    }
                    throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaOpenPolicy), result));
                }

                result = LsaAddAccountRights(lsaPolicyHandle, GetSidBinaryFromWindows(domain, userName), LogonAsServiceRights, 1);
                Trace.Info("LsaAddAccountRights return with error code {0} ", result);

                return result == 0;
            }
            finally
            {
                int result = LsaClose(lsaPolicyHandle);
                if (result != 0)
                {
                    Trace.Error(StringUtil.Format("Can not close LasPolicy handler. LsaClose failed with error code {0}", result));
                }
            }
        }
Beispiel #27
0
 internal static extern uint LsaOpenPolicy(
     ref UNICODE_STRING SystemName,
     ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
     uint DesiredAccess,
     out IntPtr PolicyHandle
     );
Beispiel #28
0
 public static extern uint LsaOpenPolicy(
     LSA_UNICODE_STRING[]?SystemName,
     ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
     int AccessMask,
     out IntPtr PolicyHandle
     );
Beispiel #29
0
        public static Dictionary<AuditEventPolicy, AuditEventStatus> GetPolicies()
        {
            Dictionary<AuditEventPolicy, AuditEventStatus> result = new Dictionary<AuditEventPolicy, AuditEventStatus>();

            LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();
            IntPtr hPolicy = IntPtr.Zero;
            IntPtr pInfo = IntPtr.Zero;
            IntPtr pGuid = IntPtr.Zero;

            UInt32 lrc = LsaOpenPolicy(null, ref objAttrs, POLICY_VIEW_AUDIT_INFORMATION, out hPolicy);
            uint code = LsaNtStatusToWinError(lrc);
            if (code != 0) {
            throw new System.ComponentModel.Win32Exception((int)code);
            }
            try {
            //
            // Query the policy
            //
            lrc = LsaQueryInformationPolicy(hPolicy, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pInfo);
            code = LsaNtStatusToWinError(lrc);
            if (code != 0) {
            throw new System.ComponentModel.Win32Exception((int)code);
            }
            POLICY_AUDIT_EVENTS_INFO info = new POLICY_AUDIT_EVENTS_INFO();
            info = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pInfo, info.GetType());

            //
            // Iterate through the event types
            //
            for (UInt32 eventType = 0; eventType < info.MaximumAuditEventCount; eventType++) {
            pGuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GUID)));
            if (AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)eventType, pGuid)) {
            IntPtr itemPtr = new IntPtr(info.EventAuditingOptions.ToInt64() +
                (Int64)eventType * (Int64)Marshal.SizeOf(typeof(UInt32)));
            UInt32 status = 0;
            status = (UInt32)Marshal.PtrToStructure(itemPtr, status.GetType());
            result.Add((AuditEventPolicy)eventType, (AuditEventStatus)(status & 0x3));
            Marshal.FreeHGlobal(pGuid);
            pGuid = IntPtr.Zero;
            } else {
            throw new System.ComponentModel.Win32Exception(GetLastError());
            }
            }
            } finally {
            //
            // Cleanup
            //
            if (pInfo != IntPtr.Zero) {
            LsaFreeMemory(pInfo);
            }
            if (pGuid != IntPtr.Zero) {
            Marshal.FreeHGlobal(pGuid);
            }
            LsaClose(hPolicy);
            }
            return result;
        }
            public LsaPolicy()
            {
                LSA_UNICODE_STRING system = new LSA_UNICODE_STRING();

                LSA_OBJECT_ATTRIBUTES attrib = new LSA_OBJECT_ATTRIBUTES()
                {
                    Length = 0,
                    RootDirectory = IntPtr.Zero,
                    Attributes = 0,
                    SecurityDescriptor = IntPtr.Zero,
                    SecurityQualityOfService = IntPtr.Zero,
                };

                IntPtr handle = IntPtr.Zero;
                uint result = LsaOpenPolicy(ref system, ref attrib, LSA_POLICY_ALL_ACCESS, out handle);
                if (result != 0 || handle == IntPtr.Zero)
                {
                    if (result == ReturnCode.STATUS_ACCESS_DENIED)
                    {
                        throw new Exception(StringUtil.Loc("ShouldBeAdmin"));
                    }
                    throw new Exception(StringUtil.Loc("OperationFailed", nameof(LsaOpenPolicy), result));
                }

                Handle = handle;
            }
Beispiel #31
0
        public static List<string> getAccessTokens(string targetHost, string entityName)
        {
            List<string> retList = new List<string>();

            IntPtr sid = IntPtr.Zero;
            int sidSize = 0;
            StringBuilder domainName = new StringBuilder();
            int nameSize = 0;
            int accountType = 0;
            UInt32 lretVal;
            uint retVal;

            LookupAccountName("\\\\" + targetHost, entityName, sid, ref sidSize,
                domainName, ref nameSize, ref accountType);
            domainName = new StringBuilder(nameSize);
            sid = Marshal.AllocHGlobal(sidSize);

            bool result = LookupAccountName("\\\\" + targetHost, entityName, sid, ref sidSize,
                domainName, ref nameSize, ref accountType);

            if (!result)
            {
                Marshal.FreeHGlobal(sid);
                throw new System.ComponentModel.Win32Exception(GetLastError());
            }

            LSA_UNICODE_STRING systemName = string2LSAUS("\\\\" + targetHost);
            IntPtr policyHandle = IntPtr.Zero;
            LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();
            lretVal = LsaOpenPolicy(ref systemName, ref objAttrs,
                                POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION, out policyHandle);
            retVal = LsaNtStatusToWinError(lretVal);

            if (retVal != 0)
            {
                Marshal.FreeHGlobal(sid);
                throw new System.ComponentModel.Win32Exception((int)retVal);
            }

            IntPtr rightsArray = IntPtr.Zero;
            UInt32 rightsCount = 0;
            lretVal = LsaEnumerateAccountRights(policyHandle, sid, out rightsArray, out rightsCount);
            retVal = LsaNtStatusToWinError(lretVal);
            Marshal.FreeHGlobal(sid);

            if (retVal == 2)
            {
                LsaClose(policyHandle);
                return retList;
            }
            if (retVal != 0)
            {
                LsaClose(policyHandle);
                throw new System.ComponentModel.Win32Exception((int)retVal);
            }

            LSA_UNICODE_STRING myLsaus = new LSA_UNICODE_STRING();
            for (ulong i = 0; i < rightsCount; i++)
            {
                IntPtr itemAddr = new IntPtr(rightsArray.ToInt64() + (long)(i * (ulong)Marshal.SizeOf(myLsaus)));
                myLsaus = (LSA_UNICODE_STRING)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
                string thisRight = LSAUS2string(myLsaus);
                retList.Add(thisRight);
            }

            lretVal = LsaClose(policyHandle);
            retVal = LsaNtStatusToWinError(lretVal);
            if (retVal != 0)
                throw new System.ComponentModel.Win32Exception((int)retVal);

            return retList;
        }
Beispiel #32
0
        // Returns the Local Security Authority rights granted to the account
        public IList <string> GetRights(string accountName)
        {
            IList <string> rights       = new List <string>();
            string         errorMessage = string.Empty;

            long          winErrorCode = 0;
            IntPtr        sid          = IntPtr.Zero;
            int           sidSize      = 0;
            StringBuilder domainName   = new StringBuilder();
            int           nameSize     = 0;
            int           accountType  = 0;

            LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

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

            if (!LookupAccountName(string.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType))
            {
                winErrorCode = GetLastError();
                errorMessage = ("LookupAccountName failed: " + winErrorCode);
                throw new Win32Exception((int)winErrorCode, errorMessage);
            }
            else
            {
                LSA_UNICODE_STRING systemName = new LSA_UNICODE_STRING();

                IntPtr policyHandle  = IntPtr.Zero;
                IntPtr userRightsPtr = IntPtr.Zero;
                int    countOfRights = 0;

                LSA_OBJECT_ATTRIBUTES objectAttributes = CreateLSAObject();

                uint policyStatus = LsaOpenPolicy(ref systemName, ref objectAttributes, Access, out policyHandle);
                winErrorCode = LsaNtStatusToWinError(Convert.ToInt32(policyStatus));

                if (winErrorCode != 0)
                {
                    errorMessage = string.Format("OpenPolicy failed: {0}.", winErrorCode);
                    throw new Win32Exception((int)winErrorCode, errorMessage);
                }
                else
                {
                    try
                    {
                        int result = LsaEnumerateAccountRights(policyHandle, sid, out userRightsPtr, out countOfRights);
                        winErrorCode = LsaNtStatusToWinError(result);
                        if (winErrorCode != 0)
                        {
                            if (winErrorCode == 2)
                            {
                                return(new List <string>());
                            }
                            errorMessage = string.Format("LsaEnumerateAccountRights failed: {0}", winErrorCode);
                            throw new Win32Exception((int)winErrorCode, errorMessage);
                        }

                        Int32 ptr = userRightsPtr.ToInt32();
                        LSA_UNICODE_STRING userRight;

                        for (int i = 0; i < countOfRights; i++)
                        {
                            userRight = (LSA_UNICODE_STRING)Marshal.PtrToStructure(new IntPtr(ptr), typeof(LSA_UNICODE_STRING));
                            string userRightStr = Marshal.PtrToStringAuto(userRight.Buffer);
                            rights.Add(userRightStr);
                            ptr += Marshal.SizeOf(userRight);
                        }
                    }
                    finally
                    {
                        LsaClose(policyHandle);
                    }
                }
                FreeSid(sid);
            }
            return(rights);
        }
Beispiel #33
0
 public extern static uint LsaOpenPolicy(ref string SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint AccessMask, out IntPtr PolicyHandle);
Beispiel #34
0
        private static IntPtr GetLsaPolicyHandle()
        {
            string computerName = Environment.MachineName;
            IntPtr hPolicy;
            LSA_OBJECT_ATTRIBUTES objectAttributes = new LSA_OBJECT_ATTRIBUTES();
            objectAttributes.Length = 0;
            objectAttributes.RootDirectory = IntPtr.Zero;
            objectAttributes.Attributes = 0;
            objectAttributes.SecurityDescriptor = IntPtr.Zero;
            objectAttributes.SecurityQualityOfService = IntPtr.Zero;

            const uint ACCESS_MASK = POLICY_CREATE_SECRET | POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION;
            LSA_UNICODE_STRING machineNameLsa = new LSA_UNICODE_STRING(computerName);
            uint result = LsaOpenPolicy(ref machineNameLsa, ref objectAttributes, ACCESS_MASK, out hPolicy);
            HandleLsaResult(result);
            return hPolicy;
        }
Beispiel #35
0
        public static Dictionary<AuditEventPolicy, Dictionary<String, AuditEventStatus>> GetSubcategoryPolicies()
        {
            Dictionary<AuditEventPolicy, Dictionary<String, AuditEventStatus>> result = new Dictionary<AuditEventPolicy, Dictionary<String, AuditEventStatus>>();

            LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();
            IntPtr hPolicy = IntPtr.Zero;
            IntPtr pInfo = IntPtr.Zero;
            IntPtr pGuid = IntPtr.Zero;
            IntPtr pAuditPolicies = IntPtr.Zero;
            IntPtr pSubcategories = IntPtr.Zero;

            UInt32 lrc = LsaOpenPolicy(null, ref objAttrs, POLICY_VIEW_AUDIT_INFORMATION, out hPolicy);
            uint code = LsaNtStatusToWinError(lrc);
            if (code != 0) {
            throw new System.ComponentModel.Win32Exception((int)code);
            }
            try {
            //
            // Query the policy
            //
            lrc = LsaQueryInformationPolicy(hPolicy, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pInfo);
            code = LsaNtStatusToWinError(lrc);
            if (code != 0) {
            throw new System.ComponentModel.Win32Exception((int)code);
            }
            POLICY_AUDIT_EVENTS_INFO info = new POLICY_AUDIT_EVENTS_INFO();
            info = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pInfo, info.GetType());

            //
            // Iterate through the event types
            //
            for (UInt32 eventType = 0; eventType < info.MaximumAuditEventCount; eventType++) {
            pGuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GUID)));
            if (!AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)eventType, pGuid)) {
            throw new System.ComponentModel.Win32Exception(GetLastError());
            }
            UInt32 subcategoryCount = 0;
            if (!AuditEnumerateSubCategories(pGuid, false, ref pSubcategories, out subcategoryCount)) {
            throw new System.ComponentModel.Win32Exception(GetLastError());
            }
            if (!AuditQuerySystemPolicy(pSubcategories, subcategoryCount, out pAuditPolicies)) {
            throw new System.ComponentModel.Win32Exception(GetLastError());
            }

            Dictionary<String, AuditEventStatus> dict = new Dictionary<String, AuditEventStatus>();
            AUDIT_POLICY_INFORMATION policyInfo = new AUDIT_POLICY_INFORMATION();
            for (UInt32 subcategoryIndex = 0; subcategoryIndex < subcategoryCount; subcategoryIndex++) {
            IntPtr itemPtr = new IntPtr(pAuditPolicies.ToInt64() +
                (long)subcategoryIndex * (Int64)Marshal.SizeOf(policyInfo));
            policyInfo = (AUDIT_POLICY_INFORMATION)Marshal.PtrToStructure(itemPtr, policyInfo.GetType());
            dict.Add(AuditPolicySubcategories[policyInfo.AuditSubCategoryGuid.ToString()],
                (AuditEventStatus)policyInfo.AuditingInformation);
            }
            result.Add((AuditEventPolicy)eventType, dict);

            AuditFree(pAuditPolicies);
            pAuditPolicies = IntPtr.Zero;
            AuditFree(pSubcategories);
            pSubcategories = IntPtr.Zero;
            Marshal.FreeHGlobal(pGuid);
            pGuid = IntPtr.Zero;
            }
            } finally {
            //
            // Cleanup
            //
            if (pInfo != IntPtr.Zero) {
            LsaFreeMemory(pInfo);
            }
            if (pGuid != IntPtr.Zero) {
            Marshal.FreeHGlobal(pGuid);
            }
            if (pAuditPolicies != IntPtr.Zero) {
            AuditFree(pAuditPolicies);
            }
            if (pSubcategories != IntPtr.Zero) {
            AuditFree(pSubcategories);
            }
            LsaClose(hPolicy);
            }
            return result;
        }
Beispiel #36
0
        public static void SetRight(string user, string machine, string right, bool Add)
        {
            int winerror = 0; 
            IntPtr sid = IntPtr.Zero;
            int sidsize = 0;
            StringBuilder domainname = new StringBuilder();
            int namesize = 0;
            int accounttype = 0;
            
            LookupAccountName(string.Empty, user, sid, ref sidsize, domainname, ref namesize, ref accounttype);

            domainname = new StringBuilder(namesize);
            sid = Marshal.AllocHGlobal(sidsize);

            bool result = LookupAccountName(string.Empty, user, sid, ref sidsize, domainname, ref namesize, ref accounttype);

            if (!result)
            {
                winerror = GetLastError();
                throw new Exception("LookupAccountName failure #" + winerror);
            }
            else
            {
                LSA_UNICODE_STRING systemname = new LSA_UNICODE_STRING();
                systemname.Buffer = Marshal.StringToHGlobalUni(machine);
                systemname.Length = (UInt16)(machine.Length * UnicodeEncoding.CharSize);
                systemname.MaximumLength = (UInt16)((machine.Length + 1) * UnicodeEncoding.CharSize);
                
                int access = (int)(
                    LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
                    LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
                    LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
                    LSA_AccessPolicy.POLICY_CREATE_SECRET |
                    LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
                    LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
                    LSA_AccessPolicy.POLICY_NOTIFICATION |
                    LSA_AccessPolicy.POLICY_SERVER_ADMIN |
                    LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
                    LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
                    LSA_AccessPolicy.POLICY_TRUST_ADMIN |
                    LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
                    LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
                    );
                
                IntPtr hpolicy = IntPtr.Zero;

                LSA_OBJECT_ATTRIBUTES objattribs = new LSA_OBJECT_ATTRIBUTES();
                objattribs.Length = 0;
                objattribs.RootDirectory = IntPtr.Zero;
                objattribs.Attributes = 0;
                objattribs.SecurityDescriptor = IntPtr.Zero;
                objattribs.SecurityQualityOfService = IntPtr.Zero;

                uint policyresult = LsaOpenPolicy(ref systemname, ref objattribs, access, out hpolicy);
                winerror = LsaNtStatusToWinError(policyresult);

                if (winerror != 0)
                {
                    throw new Exception("OpenPolicy failure #" + winerror);
                }
                else
                {
                    LSA_UNICODE_STRING[] userrights = new LSA_UNICODE_STRING[1];
                    userrights[0] = new LSA_UNICODE_STRING();
                    userrights[0].Buffer = Marshal.StringToHGlobalUni(right);
                    userrights[0].Length = (UInt16)(right.Length * UnicodeEncoding.CharSize);
                    userrights[0].MaximumLength = (UInt16)((right.Length + 1) * UnicodeEncoding.CharSize);

                    if (Add)
                    {
                        uint res = LsaAddAccountRights(hpolicy, sid, userrights, 1);
                        winerror = LsaNtStatusToWinError(res);
                        if (winerror != 0)
                        {
                            throw new Exception("LsaAddAccountRights failure #" + winerror);
                        }
                    }
                    else
                    {
                        uint res = LsaRemoveAccountRights(hpolicy, sid, false, userrights, 1);
                        winerror = LsaNtStatusToWinError(res);
                        if (winerror != 0)
                        {
                            throw new Exception("LsaRemoveAccountRights failure #" + winerror);
                        }
                    }

                    LsaClose(hpolicy);
                }
                FreeSid(sid);
            }
        }
Beispiel #37
0
        public static int SetRight(string accountName, string privilegeName)
        {
            int winErrorCode = 0;             //contains the last error

            //pointer an size for the SID
            IntPtr sid     = IntPtr.Zero;
            int    sidSize = 0;
            //StringBuilder and size for the domain name
            StringBuilder domainName = new StringBuilder();
            int           nameSize   = 0;
            //account-type variable for lookup
            int 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
            bool result = LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

            //say what you're doing
            Trace.WriteLine("LookupAccountName result = " + result);
            Trace.WriteLine("IsValidSid: " + IsValidSid(sid));
            Trace.WriteLine("LookupAccountName domainName: " + domainName.ToString());

            if (!result)
            {
                winErrorCode = GetLastError();
                Trace.WriteLine("LookupAccountName failed: " + winErrorCode);
            }
            else
            {
                //initialize an empty unicode-string
                LSA_UNICODE_STRING systemName = new LSA_UNICODE_STRING();
                //combine all policies
                int access = (int)(
                    LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
                    LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
                    LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
                    LSA_AccessPolicy.POLICY_CREATE_SECRET |
                    LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
                    LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
                    LSA_AccessPolicy.POLICY_NOTIFICATION |
                    LSA_AccessPolicy.POLICY_SERVER_ADMIN |
                    LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
                    LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
                    LSA_AccessPolicy.POLICY_TRUST_ADMIN |
                    LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
                    LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
                    );
                //initialize a pointer for the policy handle
                IntPtr policyHandle = IntPtr.Zero;

                //these attributes are not used, but LsaOpenPolicy wants them to exists
                LSA_OBJECT_ATTRIBUTES ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();
                ObjectAttributes.Length                   = 0;
                ObjectAttributes.RootDirectory            = IntPtr.Zero;
                ObjectAttributes.Attributes               = 0;
                ObjectAttributes.SecurityDescriptor       = IntPtr.Zero;
                ObjectAttributes.SecurityQualityOfService = IntPtr.Zero;

                //get a policy handle
                uint resultPolicy = LsaOpenPolicy(ref systemName, ref ObjectAttributes, access, out policyHandle);
                winErrorCode = (int)LsaNtStatusToWinError(resultPolicy);

                if (winErrorCode != 0)
                {
                    Trace.WriteLine("OpenPolicy failed: " + winErrorCode);
                }
                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
                    LSA_UNICODE_STRING[] userRights = new LSA_UNICODE_STRING[1];
                    userRights[0]               = new LSA_UNICODE_STRING();
                    userRights[0].Buffer        = Marshal.StringToHGlobalUni(privilegeName);
                    userRights[0].Length        = (UInt16)(privilegeName.Length * UnicodeEncoding.CharSize);
                    userRights[0].MaximumLength = (UInt16)((privilegeName.Length + 1) * UnicodeEncoding.CharSize);

                    //add the right to the account
                    uint res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
                    winErrorCode = (int)LsaNtStatusToWinError(res);
                    if (winErrorCode != 0)
                    {
                        Trace.WriteLine("LsaAddAccountRights failed: " + winErrorCode);
                    }

                    LsaClose(policyHandle);
                }
                FreeSid(sid);
            }

            return(winErrorCode);
        }
Beispiel #38
0
 public static extern UInt32 LsaOpenPolicy(String SystemName,
     ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, Int32 DesiredAccess, out IntPtr PolicyHandle);
 private static extern int LsaOpenPolicy(LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, int DesiredAccess, out SafeLsaHandle PolicyHandle);
Beispiel #40
0
        public virtual Dictionary<AuditEventSubcategories, AuditEventStatus> GetAuditEventSubcategoriesPolicy(TargetInfo targetInfo)
        {
            Dictionary<AuditEventSubcategories, AuditEventStatus> retList = new Dictionary<AuditEventSubcategories, AuditEventStatus>();

            string target = @"\\" + targetInfo.GetAddress();
            LSA_UNICODE_STRING systemName = string2LSAUS(target);
            LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();

            IntPtr policyHandle = IntPtr.Zero;
            IntPtr pAuditEventsInfo = IntPtr.Zero;
            IntPtr pAuditCategoryId = IntPtr.Zero;
            IntPtr pAuditSubCategoryGuids = IntPtr.Zero;
            IntPtr pAuditPolicies = IntPtr.Zero;

            UInt32 lretVal = LsaOpenPolicy(ref systemName, ref objAttrs, POLICY_VIEW_AUDIT_INFORMATION, out policyHandle);
            UInt32 retVal = LsaNtStatusToWinError(lretVal);

            if (retVal == (UInt32)0)
            {
                try
                {
                    lretVal = LsaQueryInformationPolicy(policyHandle, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pAuditEventsInfo);
                    retVal = LsaNtStatusToWinError(lretVal);

                    if (retVal == 0)
                    {
                        POLICY_AUDIT_EVENTS_INFO myAuditEventsInfo = new POLICY_AUDIT_EVENTS_INFO();
                        myAuditEventsInfo = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pAuditEventsInfo, myAuditEventsInfo.GetType());

                        for (var policyAuditEventType = 0; policyAuditEventType < myAuditEventsInfo.MaximumAuditEventCount; policyAuditEventType++)
                        {
                            pAuditCategoryId = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GUID)));
                            if (!AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)policyAuditEventType, pAuditCategoryId))
                            {
                                int causingError = GetLastError();
                                throw new System.ComponentModel.Win32Exception(causingError);
                            }

                            UInt32 nSubCats = 0;
                            pAuditSubCategoryGuids = IntPtr.Zero;
                            if (!AuditEnumerateSubCategories(pAuditCategoryId, false, ref pAuditSubCategoryGuids, out nSubCats))
                            {
                                int causingError = GetLastError();
                                throw new System.ComponentModel.Win32Exception(causingError);
                            }

                            Marshal.FreeHGlobal(pAuditCategoryId);
                            pAuditCategoryId = IntPtr.Zero;

                            pAuditPolicies = IntPtr.Zero;
                            if (nSubCats > 0)
                            {

                                if (!AuditQuerySystemPolicy(pAuditSubCategoryGuids, nSubCats, out pAuditPolicies))
                                {
                                    int causingError = GetLastError();
                                    throw new System.ComponentModel.Win32Exception(causingError);
                                }

                                for (var subcategoryIndex = 0; subcategoryIndex < nSubCats; subcategoryIndex++)
                                {
                                    AUDIT_POLICY_INFORMATION currentPolicy = new AUDIT_POLICY_INFORMATION();

                                    IntPtr itemPtr = new IntPtr(pAuditPolicies.ToInt64() + (Int64)subcategoryIndex * (Int64)Marshal.SizeOf(currentPolicy));
                                    currentPolicy = (AUDIT_POLICY_INFORMATION)Marshal.PtrToStructure(itemPtr, currentPolicy.GetType());

                                    String subCategoryName = String.Empty;
                                    Marshal.StructureToPtr(currentPolicy, itemPtr, true);
                                    AuditLookupSubCategoryName(itemPtr, ref subCategoryName);

                                    AuditEventSubcategories value;
                                    if (subcategoriesDictionary.TryGetValue(subCategoryName, out value))
                                    {
                                        retList.Add(value, (AuditEventStatus)(currentPolicy.AuditingInformation & 0x3));
                                    }
                                }

                                if (pAuditPolicies != IntPtr.Zero)
                                {
                                    AuditFree(pAuditPolicies);
                                    pAuditPolicies = IntPtr.Zero;
                                }
                            }

                            if (pAuditSubCategoryGuids != IntPtr.Zero)
                            {
                                AuditFree(pAuditSubCategoryGuids);
                                pAuditSubCategoryGuids = IntPtr.Zero;
                            }

                            nSubCats = 0;
                        }
                    }
                    else
                    {
                        throw new System.ComponentModel.Win32Exception((int)retVal);
                    }
                }
                finally
                {
                    if (pAuditPolicies != IntPtr.Zero)
                    {
                        AuditFree(pAuditPolicies);
                        pAuditPolicies = IntPtr.Zero;
                    }

                    if (pAuditSubCategoryGuids != IntPtr.Zero)
                    {
                        AuditFree(pAuditSubCategoryGuids);
                        pAuditSubCategoryGuids = IntPtr.Zero;
                    }

                    if (pAuditEventsInfo != IntPtr.Zero)
                    {
                        LsaFreeMemory(pAuditEventsInfo);
                    }

                    if (pAuditCategoryId != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(pAuditCategoryId);
                    }

                    LsaClose(policyHandle);
                }
            }
            else
            {
                throw new System.ComponentModel.Win32Exception((int)retVal);
            }

            return retList;
        }
Beispiel #41
0
 internal static extern /*DWORD*/ uint LsaOpenPolicy(
     string systemName,
     ref LSA_OBJECT_ATTRIBUTES attributes,
     int accessMask,
     out SafeLsaPolicyHandle handle
     );
Beispiel #42
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 static long SetRight(String accountName, String privilegeName)
        {
            long winErrorCode = 0; //contains the last error

            //pointer an size for the SID
            IntPtr sid = IntPtr.Zero;
            int sidSize = 0;
            //StringBuilder and size for the domain name
            StringBuilder domainName = new StringBuilder();
            int nameSize = 0;
            //account-type variable for lookup
            int 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
            bool result = LookupAccountName(String.Empty, accountName, sid, ref sidSize, domainName, ref nameSize, ref accountType);

            //say what you're doing
            Console.WriteLine("LookupAccountName result = "+result);
            Console.WriteLine("IsValidSid: "+IsValidSid(sid));
            Console.WriteLine("LookupAccountName domainName: "+domainName.ToString());

            if( ! result ){
                winErrorCode = GetLastError();
                Console.WriteLine("LookupAccountName failed: "+ winErrorCode);
            }else{

                //initialize an empty unicode-string
                LSA_UNICODE_STRING systemName = new LSA_UNICODE_STRING();
                //combine all policies
                int access = (int)(
                    LSA_AccessPolicy.POLICY_AUDIT_LOG_ADMIN |
                    LSA_AccessPolicy.POLICY_CREATE_ACCOUNT |
                    LSA_AccessPolicy.POLICY_CREATE_PRIVILEGE |
                    LSA_AccessPolicy.POLICY_CREATE_SECRET |
                    LSA_AccessPolicy.POLICY_GET_PRIVATE_INFORMATION |
                    LSA_AccessPolicy.POLICY_LOOKUP_NAMES |
                    LSA_AccessPolicy.POLICY_NOTIFICATION |
                    LSA_AccessPolicy.POLICY_SERVER_ADMIN |
                    LSA_AccessPolicy.POLICY_SET_AUDIT_REQUIREMENTS |
                    LSA_AccessPolicy.POLICY_SET_DEFAULT_QUOTA_LIMITS |
                    LSA_AccessPolicy.POLICY_TRUST_ADMIN |
                    LSA_AccessPolicy.POLICY_VIEW_AUDIT_INFORMATION |
                    LSA_AccessPolicy.POLICY_VIEW_LOCAL_INFORMATION
                    );
                //initialize a pointer for the policy handle
                IntPtr policyHandle = IntPtr.Zero;

                //these attributes are not used, but LsaOpenPolicy wants them to exists
                LSA_OBJECT_ATTRIBUTES ObjectAttributes = new LSA_OBJECT_ATTRIBUTES();
                ObjectAttributes.Length = 0;
                ObjectAttributes.RootDirectory = IntPtr.Zero;
                ObjectAttributes.Attributes = 0;
                ObjectAttributes.SecurityDescriptor = IntPtr.Zero;
                ObjectAttributes.SecurityQualityOfService = IntPtr.Zero;

                //get a policy handle
                uint resultPolicy = LsaOpenPolicy(ref systemName, ref ObjectAttributes, access, out policyHandle);
                winErrorCode = LsaNtStatusToWinError(resultPolicy);

                if(winErrorCode != 0){
                    Console.WriteLine("OpenPolicy failed: "+ winErrorCode);
                }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
                    LSA_UNICODE_STRING[] userRights = new LSA_UNICODE_STRING[1];
                    userRights[0] = new LSA_UNICODE_STRING();
                    userRights[0].Buffer = Marshal.StringToHGlobalUni(privilegeName);
                    userRights[0].Length = (UInt16)( privilegeName.Length * UnicodeEncoding.CharSize );
                    userRights[0].MaximumLength = (UInt16)( (privilegeName.Length+1) * UnicodeEncoding.CharSize );

                    //add the right to the account
                    long res = LsaAddAccountRights(policyHandle, sid, userRights, 1);
                    winErrorCode = LsaNtStatusToWinError(res);
                    if(winErrorCode != 0){
                        Console.WriteLine("LsaAddAccountRights failed: "+ winErrorCode);
                    }

                    LsaClose(policyHandle);
                }
                FreeSid(sid);
            }

            return winErrorCode;
        }
Beispiel #43
0
        public static Dictionary <AuditEventPolicy, AuditEventStatus> GetPolicies()
        {
            Dictionary <AuditEventPolicy, AuditEventStatus> result = new Dictionary <AuditEventPolicy, AuditEventStatus>();

            LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();
            IntPtr hPolicy = IntPtr.Zero;
            IntPtr pInfo   = IntPtr.Zero;
            IntPtr pGuid   = IntPtr.Zero;

            UInt32 lrc  = LsaOpenPolicy(null, ref objAttrs, POLICY_VIEW_AUDIT_INFORMATION, out hPolicy);
            uint   code = LsaNtStatusToWinError(lrc);

            if (code != 0)
            {
                throw new System.ComponentModel.Win32Exception((int)code);
            }
            try {
                //
                // Query the policy
                //
                lrc  = LsaQueryInformationPolicy(hPolicy, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pInfo);
                code = LsaNtStatusToWinError(lrc);
                if (code != 0)
                {
                    throw new System.ComponentModel.Win32Exception((int)code);
                }
                POLICY_AUDIT_EVENTS_INFO info = new POLICY_AUDIT_EVENTS_INFO();
                info = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pInfo, info.GetType());

                //
                // Iterate through the event types
                //
                for (UInt32 eventType = 0; eventType < info.MaximumAuditEventCount; eventType++)
                {
                    pGuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GUID)));
                    if (AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)eventType, pGuid))
                    {
                        IntPtr itemPtr = new IntPtr(info.EventAuditingOptions.ToInt64() +
                                                    (Int64)eventType * (Int64)Marshal.SizeOf(typeof(UInt32)));
                        UInt32 status = 0;
                        status = (UInt32)Marshal.PtrToStructure(itemPtr, status.GetType());
                        result.Add((AuditEventPolicy)eventType, (AuditEventStatus)(status & 0x3));
                        Marshal.FreeHGlobal(pGuid);
                        pGuid = IntPtr.Zero;
                    }
                    else
                    {
                        throw new System.ComponentModel.Win32Exception(GetLastError());
                    }
                }
            } finally {
                //
                // Cleanup
                //
                if (pInfo != IntPtr.Zero)
                {
                    LsaFreeMemory(pInfo);
                }
                if (pGuid != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pGuid);
                }
                LsaClose(hPolicy);
            }
            return(result);
        }
Beispiel #44
0
 internal static extern uint LsaOpenPolicy(
     LSA_UNICODE_STRING[] SystemName,
     ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
     int AccessMask,
     out LSA_HANDLE PolicyHandle
     );
Beispiel #45
0
 internal static extern uint LsaOpenPolicy(
     LSA_UNICODE_STRING[] SystemName,
     ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
     int AccessMask,
     out LSA_HANDLE PolicyHandle
     );
        public virtual Dictionary<AuditEventPolicies, AuditEventStatus> GetAuditEventPolicies(TargetInfo targetInfo)
        {
            Dictionary<AuditEventPolicies, AuditEventStatus> retList = new Dictionary<AuditEventPolicies, AuditEventStatus>();

            LSA_UNICODE_STRING systemName = string2LSAUS(targetInfo.GetAddress());
            LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();

            IntPtr policyHandle = IntPtr.Zero;
            IntPtr pAuditEventsInfo = IntPtr.Zero;
            IntPtr pAuditCategoryGuid = IntPtr.Zero;
            IntPtr pAuditSubCategoryGuids = IntPtr.Zero;
            IntPtr pAuditPolicies = IntPtr.Zero;

            UInt32 lretVal = LsaOpenPolicy(ref systemName, ref objAttrs, POLICY_VIEW_AUDIT_INFORMATION, out policyHandle);
            uint retVal = LsaNtStatusToWinError(lretVal);
            if (retVal != 0)
            {
                throw new System.ComponentModel.Win32Exception((int)retVal);
            }

            try
            {
                lretVal = LsaQueryInformationPolicy(policyHandle, POLICY_INFORMATION_CLASS.PolicyAuditEventsInformation, out pAuditEventsInfo);
                retVal = LsaNtStatusToWinError(lretVal);
                if (retVal != 0)
                {
                    throw new System.ComponentModel.Win32Exception((int)retVal);
                }

                //  EventAuditingOptions: The index of each array element corresponds to an audit event type value in the POLICY_AUDIT_EVENT_TYPE enumeration type.
                //  Each POLICY_AUDIT_EVENT_OPTIONS variable in the array can specify the following auditing options.
                //  POLICY_AUDIT_EVENT_UNCHANGED, POLICY_AUDIT_EVENT_SUCCESS, POLICY_AUDIT_EVENT_FAILURE, POLICY_AUDIT_EVENT_NONE
                POLICY_AUDIT_EVENTS_INFO myAuditEventsInfo = new POLICY_AUDIT_EVENTS_INFO();
                myAuditEventsInfo = (POLICY_AUDIT_EVENTS_INFO)Marshal.PtrToStructure(pAuditEventsInfo, myAuditEventsInfo.GetType());

                for (UInt32 policyAuditEventType = 0; policyAuditEventType < myAuditEventsInfo.MaximumAuditEventCount; policyAuditEventType++)
                {

                    pAuditCategoryGuid = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(GUID)));
                    if (!AuditLookupCategoryGuidFromCategoryId((POLICY_AUDIT_EVENT_TYPE)policyAuditEventType, pAuditCategoryGuid))
                    {
                        int causingError = GetLastError();
                        throw new System.ComponentModel.Win32Exception(causingError);
                    }

                    String categoryName = String.Empty;
                    AuditLookupCategoryName(pAuditCategoryGuid, ref categoryName);

                    UInt32 status = 0;
                    IntPtr itemPtr = new IntPtr(myAuditEventsInfo.EventAuditingOptions.ToInt64() + (Int64)policyAuditEventType * (Int64)Marshal.SizeOf(typeof(UInt32)));
                    status = (UInt32)Marshal.PtrToStructure(itemPtr, status.GetType());
                    retList.Add((AuditEventPolicies)policyAuditEventType, (AuditEventStatus)(status & 0x3));

                    Marshal.FreeHGlobal(pAuditCategoryGuid);
                    pAuditCategoryGuid = IntPtr.Zero;
                }
            }
            finally
            {
                if (pAuditEventsInfo != IntPtr.Zero)
                {
                    LsaFreeMemory(pAuditEventsInfo);
                }

                if (pAuditCategoryGuid != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pAuditCategoryGuid);
                }

                LsaClose(policyHandle);
            }

            return retList;
        }
Beispiel #47
0
 private static extern UInt32 LsaOpenPolicy(ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, Int32 DesiredAccess, out IntPtr PolicyHandle);
 public static extern uint LsaOpenPolicy(ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, int DesiredAccess, out IntPtr PolicyHandle);