【问题标题】:Using powershell to get the "Audit Policy" security setting value使用powershell获取“Audit Policy”安全设置值
【发布时间】:2021-08-30 14:22:03
【问题描述】:

我正在尝试使用 Powershell (auditpol) 来查询审核策略项的安全设置值。到目前为止,使用所有 auditpol 命令,我只能获取子类别值。

auditpol /get /category:*

到目前为止,我只能使用以下方法获取没有成功/失败/无审计值的 9 个项目的列表:

auditpol /list/category

是否有我可能为 auditpol 遗漏的命令/标志,或者是否有任何其他命令可供我检索策略及其相关的安全设置值?

Policy and values that I would like to query.

【问题讨论】:

    标签: powershell audit-logging


    【解决方案1】:

    如您所见,auditpol 仅管理启用“高级审核策略配置”功能时有效的设置。

    要查询“经典”审计策略,您需要使用LSA Policy Win32 API 来:

    1. 使用LsaOpenPolicy()打开本地安全策略
    2. 使用LsaQueryPolicyInformation()查询审核设置
    3. 将结果转换为可读的内容。

    以下示例使用 Add-Type 编译一个 C# 类型,然后执行上述所有操作:

    $AuditPolicyReader = Add-Type -TypeDefinition @'
    using System;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Linq;
    using System.Collections.Generic;
    
    public class AuditPolicyReader
    {
        [Flags()]
        public enum AuditPolicySetting
        {
            Unknown =  -1,
            None    = 0x0,
            Success = 0x1,
            Failure = 0x2
        }
    
        [StructLayout(LayoutKind.Sequential)]
        private struct LSA_UNICODE_STRING
        {
            public UInt16 Length;
            public UInt16 MaximumLength;
            public IntPtr Buffer;
        }
    
        [StructLayout(LayoutKind.Sequential)]
        private struct LSA_OBJECT_ATTRIBUTES
        {
            public int Length;
            public IntPtr RootDirectory;
            public LSA_UNICODE_STRING ObjectName;
            public UInt32 Attributes;
            public IntPtr SecurityDescriptor;
            public IntPtr SecurityQualityOfService;
        }
    
        public struct POLICY_AUDIT_EVENTS_INFO
        {
            public bool AuditingMode;
            public IntPtr EventAuditingOptions;
            public Int32 MaximumAuditEventCount;
        }
    
        [DllImport("advapi32.dll")]
        static extern uint LsaQueryInformationPolicy(IntPtr PolicyHandle, uint InformationClass, out IntPtr Buffer);
    
        [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
        static extern uint LsaOpenPolicy(ref LSA_UNICODE_STRING SystemName, ref LSA_OBJECT_ATTRIBUTES ObjectAttributes, uint DesiredAccess, out IntPtr PolicyHandle);
    
        [DllImport("advapi32.dll", SetLastError = true)]
        static extern uint LsaClose(IntPtr ObjectHandle);
    
        public static Dictionary<string, AuditPolicySetting> GetClassicAuditPolicy()
        {
            // Create dictionary to hold the audit policy settings (the key order here is important!!!)
            var settings = new Dictionary<string, AuditPolicySetting>
            {
                {"System", AuditPolicySetting.Unknown},
                {"Logon", AuditPolicySetting.Unknown},
                {"Object Access", AuditPolicySetting.Unknown},
                {"Privilige Use", AuditPolicySetting.Unknown},
                {"Detailed Tracking", AuditPolicySetting.Unknown},
                {"Policy Change", AuditPolicySetting.Unknown},
                {"Account Management", AuditPolicySetting.Unknown},
                {"Directory Service Access", AuditPolicySetting.Unknown},
                {"Account Logon", AuditPolicySetting.Unknown},
            };
    
            // Open local machine security policy
            IntPtr polHandle;
            LSA_OBJECT_ATTRIBUTES aObjectAttributes = new LSA_OBJECT_ATTRIBUTES();
            aObjectAttributes.Length = 0;
            aObjectAttributes.RootDirectory = IntPtr.Zero;
            aObjectAttributes.Attributes = 0;
            aObjectAttributes.SecurityDescriptor = IntPtr.Zero;
            aObjectAttributes.SecurityQualityOfService = IntPtr.Zero;
    
            var systemName = new LSA_UNICODE_STRING();
            uint desiredAccess = 2; // we only need the audit policy, no need to request anything else
            var res = LsaOpenPolicy(ref systemName, ref aObjectAttributes, desiredAccess, out polHandle);
            if (res != 0)
            {
                if(res == 0xC0000022)
                {
                    // Access denied, needs to run as admin
                    throw new UnauthorizedAccessException("Failed to open LSA policy because of insufficient access rights");
                }
                throw new Exception(string.Format("Failed to open LSA policy with return code '0x{0:X8}'", res));
            }
            try
            {
                // now that we have a valid policy handle, we can query the settings of the audit policy
                IntPtr outBuffer;
                uint policyType = 2; // this will return information about the audit settings
                res = LsaQueryInformationPolicy(polHandle, policyType, out outBuffer);
                if (res != 0)
                {
                    throw new Exception(string.Format("Failed to query LSA policy information with '0x{0:X8}'", res));
                }
    
                // copy the raw values returned by LsaQueryPolicyInformation() to a local array;
                var auditEventsInfo = Marshal.PtrToStructure<POLICY_AUDIT_EVENTS_INFO>(outBuffer);
                var values = new int[auditEventsInfo.MaximumAuditEventCount];                
                Marshal.Copy(auditEventsInfo.EventAuditingOptions, values, 0, auditEventsInfo.MaximumAuditEventCount);
    
                // now we just need to translate the provided values into our settings dictionary
                var categoryIndex = settings.Keys.ToArray();
                for (int i = 0; i < values.Length; i++)
                {
                    settings[categoryIndex[i]] = (AuditPolicySetting)values[i];
                }
    
                return settings;
            }
            finally
            {
                // remember to release policy handle
                LsaClose(polHandle);
            }
        }
    }
    '@ -PassThru |Where-Object Name -eq AuditPolicyReader
    

    现在我们可以调用GetClassicAuditPolicy()(记得在提升的提示符下运行它):

    PS ~> $AuditPolicyReader::GetClassicAuditPolicy()
    Key                                 Value
    ---                                 -----
    System                               None
    Logon                    Success, Failure
    Object Access                        None
    Privilige Use                        None
    Detailed Tracking                    None
    Policy Change                     Success
    Account Management       Success, Failure
    Directory Service Access             None
    Account Logon                        None
    

    【讨论】:

      【解决方案2】:

      auditpol 只返回Advanced audit policy configuration。这些设置可以在Security Settings &gt; Advanced Audit Policy Configuration &gt; System Audit Policies下的 UI 中找到

      您的屏幕截图显示的旧版审核策略在 Windows Server 2003/Windows Vista 之后大部分已被取消。请注意策略属性或 MS compatibility page 中的警告:

      对于高级策略,您可以使用/r 获取 csv 格式的表格:

      auditpol /get /category:'Account Logon' /r | ConvertFrom-Csv | 
      Format-Table 'Policy Target',Subcategory,'Inclusion Setting'
      
      Policy Target Subcategory                        Inclusion Setting
      ------------- -----------                        -----------------
      System        Kerberos Service Ticket Operations No Auditing      
      System        Other Account Logon Events         No Auditing      
      System        Kerberos Authentication Service    No Auditing      
      System        Credential Validation              No Auditing      
      
      

      对于旧版审计政策:

      secedit.exe /export /areas SECURITYPOLICY /cfg filename.txt
      
      [Event Audit]
      AuditSystemEvents = 0
      AuditLogonEvents = 0
      AuditObjectAccess = 0
      AuditPrivilegeUse = 0
      AuditPolicyChange = 0
      AuditAccountManage = 0
      AuditProcessTracking = 0
      AuditDSAccess = 0
      AuditAccountLogon = 0
      

      要求它没有被禁用。检查注册表:

      Get-ItemProperty HKLM:\System\CurrentControlSet\Control\Lsa -Name SCENoApplyLegacyAuditPolicy 
      

      【讨论】:

        猜你喜欢
        • 2012-07-06
        • 2019-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多