简体   繁体   English

使用 powershell 获取“审计策略”安全设置值

[英]Using powershell to get the "Audit Policy" security setting value

I am trying to use Powershell (auditpol) to query the security setting values of the Audit Policy items.我正在尝试使用 Powershell (auditpol) 来查询审计策略项的安全设置值。 So far with all the auditpol commands, I only able to get the subcategories value instead.到目前为止,对于所有 auditpol 命令,我只能获取子类别值。

auditpol /get /category:*

So far I could only get the list of the 9 items without the success/failure/no auditing values using:到目前为止,我只能使用以下方法获取没有成功/失败/无审核值的 9 项列表:

auditpol /list/category

Could there be a command/flag that I might have left out for auditpol or is there any other command for me to retrieve the policies and its relevant security setting values?是否有我可能为 auditpol 遗漏的命令/标志,或者是否有任何其他命令可供我检索策略及其相关安全设置值?

Policy and values that I would like to query.我想查询的策略和值。

As you've found, auditpol only manages the settings that are in effect when the "Advanced Audit Policy Configuration" feature is enabled.如您所见, auditpol仅管理启用“高级审核策略配置”功能时生效的设置。

To query the "classic" audit policy, you will need to use the LSA Policy Win32 API to:要查询“经典”审核策略,您需要使用LSA Policy Win32 API来:

  1. Open the local security policy using LsaOpenPolicy()使用LsaOpenPolicy()打开本地安全策略
  2. Query the audit settings using LsaQueryPolicyInformation()使用LsaQueryPolicyInformation()查询审核设置
  3. Translate the results to something readable.将结果翻译成可读的东西。

The following example uses Add-Type to compile a C# type that in turn does all of the above:以下示例使用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

Now we can call GetClassicAuditPolicy() (remember to run this from an elevated prompt):现在我们可以调用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

auditpol only returns the Advanced audit policy configuration . auditpol只返回高级审计策略配置 These settings can be found in the UI under Security Settings > Advanced Audit Policy Configuration > System Audit Policies这些设置可以在Security Settings > Advanced Audit Policy Configuration > System Audit Policies下的 UI 中找到

The legacy audit policy your screenshot shows were mostly done away with after Windows Server 2003/Windows Vista.您的屏幕截图显示的旧审计策略在 Windows Server 2003/Windows Vista 之后大部分被取消了。 Note the warnings in the policy properties or on the MS compatibility page :请注意策略属性或 MS 兼容性页面上的警告:

For advanced policies, you can use /r to get a csv-formatted table:对于高级策略,您可以使用/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      

For legacy audit policies:对于遗留审计政策:

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

Requires that it hasn't been disabled.要求它没有被禁用。 Check in the registry:检查注册表:

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

Here is a code that gives you a list of all categories and subcategories with their current audit-status.这是一个代码,可以为您提供所有类别和子类别及其当前审核状态的列表。 I made it a bit longer than really needed to add the local names of each object. Also see some usage-samples at the end of the code.我让它比添加每个 object 的本地名称实际需要的时间长了一点。另请参阅代码末尾的一些用法示例。

# getting the audit policy settings for each subcategory
# works for any OS language

cls
Remove-Variable * -ea 0
$ErrorActionPreference = 'stop'
#requires -runasadmin

$dll = [string]::Join("`r`n", '[DllImport("advapi32.dll")]', 'public static extern bool') 
$auditpol = Add-Type -Name 'AuditPol' -Namespace 'Win32' -PassThru -MemberDefinition "
$dll AuditEnumerateCategories(out IntPtr catList, out uint count);
$dll AuditLookupCategoryName(Guid catGuid, out string catName);
$dll AuditEnumerateSubCategories(Guid catGuid, bool all, out IntPtr subList, out uint count);
$dll AuditLookupSubCategoryName(Guid subGuid, out String subName);
$dll AuditQuerySystemPolicy(Guid subGuid, uint count, out IntPtr policy);
$dll AuditFree(IntPtr buffer);"

Add-Type -TypeDefinition "
using System;
public struct AUDIT_POLICY_INFORMATION {
    public Guid AuditSubCategoryGuid;
    public UInt32 AuditingInformation;
    public Guid AuditCategoryGuid;
}"

function getPolicyInfo($sub) {
    # get policy info for one subcategory:
    $pol = new-object AUDIT_POLICY_INFORMATION
    $size = $ms::SizeOf($pol)
    $ptr  = $ms::AllocHGlobal($size)
    $null = $ms::StructureToPtr($pol, $ptr, $false)
    $null = $auditpol::AuditQuerySystemPolicy($sub, 1, [ref]$ptr)
    $pol  = $ms::PtrToStructure($ptr, [type][AUDIT_POLICY_INFORMATION])
    $null = $ms::FreeHGlobal($ptr)
    [PsCustomObject]@{
        category = $pol.AuditCategoryGuid
        success  = [bool]($pol.AuditingInformation -band 1)
        failure  = [bool]($pol.AuditingInformation -band 2)
    }
}

# (optional) get GUID and local name of all categories:
$ms = [System.Runtime.InteropServices.Marshal]
$count = [uint32]0
$buffer = [IntPtr]::Zero
$size = $ms::SizeOf([type][guid])
$null = $auditpol::AuditEnumerateCategories([ref]$buffer,[ref]$count)
$ptr = [int64]$buffer
$name = [System.Text.StringBuilder]::new()
$catList = @{}
foreach($id in 1..$count) {
    $guid = $ms::PtrToStructure([IntPtr]$ptr,[type][guid])
    $null = $auditpol::AuditLookupCategoryName($guid,[ref]$name)
    $catList[$guid] = $name
    $ptr += $size
}
$null = $auditpol::AuditFree($buffer)

# get all subcategories (with optional name):
$guid = [guid]::Empty
$null = $auditpol::AuditEnumerateSubCategories($guid, $true, [ref]$buffer, [ref]$count)
$ptr = [int64]$buffer
$subList = @{}
foreach($id in 1..$count) {
    $guid = $ms::PtrToStructure([IntPtr]$ptr,[type][guid])
    $null = $auditpol::AuditLookupSubCategoryName($guid,[ref]$name)
    $pol  = getPolicyInfo $guid
    $data = [psCustomObject]@{
        category = $catList[$pol.category]
        subcategory = $name
        success = $pol.success
        failure = $pol.failure
    }
    $subList[$guid.guid] = $data
    $ptr += $size
}
$null = $auditpol::AuditFree($buffer)

# listing all subCategories and their audit settings:
$subList.Values | sort category, subcategory | ft -AutoSize

# gettings the audit-settings for a given subcategory-GUID (without '{}'):
$process_creation_guid = '0CCE922B-69AE-11D9-BED3-505054503030'
$subList[$process_creation_guid]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM