Managing Audit-Related Objects with Windows PowerShell Scripts

This chapter provides an overview of how you can use the cmdlets to access and manage audit information stored in Microsoft SQL Server databases and Active Directory using Windows PowerShell scripts. For more examples of how to perform common administrative and auditing analysis tasks using the cmdlets in PowerShell scripts, see the samples included with the software.

Using cmdlets to Manage Auditing

The Audit Module for PowerShell provides cmdlets that perform operations on objects that correspond to the core elements of Server Suite data. The core elements of Server Suite data for auditing are the following:

  • Audited computers with the Server Suite auditing services
  • Collectors that transfer audited activity from audited computers to the active audit store database
  • Active and attached audit store databases
  • Management database
  • Audit installation
  • User sessions
  • Audit trail events
  • Audit roles
  • Audit role assignments

You can use the cmdlets to create, access, modify, and remove information associated with these core elements of Server Suite data for auditing. Most of the cmdlets perform one of the following basic operations:

  • New-CdaXxx cmdlets create new Server Suite objects, such as a new audit role or a new audit store database.
  • Get-CdaXxx cmdlets get the properties of a specified object.
  • Set-CdaXxx cmdlets set or change the properties of a specified object.
  • Remove-CdaXxx cmdlets delete a specified object.

In addition to these basic operations, there are cmdlets for attaching or detaching an audit store database, exporting session activity to a file, and for publishing installation information to Active Directory.

For reference information describing the use and parameters for each cmdlet, you can use the get-help function within the PowerShell console. For example, if you want to see a description and syntax summary for the New-CdaAuditStore cmdlet, type the following command in the PowerShell console:

get-help New-CdaAuditStore

If you want to see more detailed information about a cmdlet’s parameters and code examples, you can use the -detailed or -full option. For example, type the following command in the PowerShell console:

get-help New-CdaAuditStore -detailed

Preparing the Environment to Run cmdlets

Because the Audit Module for PowerShell cmdlets run in the context of a domain account, you don’t need to make an explicit connection to an Active Directory domain.

Setting the Preferred Domain Controller

If there is more than one domain controller in the current domain, you can use the SetCdaConfiguration cmdlet to specify the preferred domain controller server to which you want to connect. The following example illustrates how to connect to the preferred domain controller for the finance.acme domain:

PS C:\> Set-CdaConfiguration -DomainController "win-2012r2dc.finance.acme"

You can also use the SetCdaConfiguration cmdlet to connect to an auditing installation in another trusted forest. In this case, specify the domain controller that is in the other trusted forest.

Setting the Logging Level

You can use the SetCdaConfiguration cmdlet to specify a logging level for running cmdlets. The following example illustrates how to use the Set-CdaConfiguration cmdlet to enable verbose logging:

PS C:\> Set-CdaConfiguration -LogLevel "Verbose"

The default path to the log file is C:\Program Files\Common Files\Centrify Shared\Logs\DirectAudit\_*date-time*.log.

Running cmdlets under Another Account

Some Audit Module for PowerShell cmdlets require permission to connect and update Microsoft SQL Server. If your login credentials do not have the required permissions, you can run cmdlets under another account. To run cmdlets as another user, you can use the standard PowerShell Start-Process -Credential to specify a different user name, then type the user’s password when prompted, or you can right-click the Audit Module for PowerShell menu item, then select Run As Administrator to run the cmdlets as the local administrator.

Organizing cmdlet Operations in a Sequence

There is no fixed sequence in which cmdlets must be called. There is, however, a logical sequence to follow to make information available from one to another. For example, to get all of the audit roles in an installation, you might first want to identify the installation object you want to work with before you call the Get-CdaAuditRole cmdlet, To accomplish this, you could organize the calls in the following sequence:

$site = Get-CdaInstallation -Name "production"
Get-CdaAuditRole $site

Similarly, before converting an active database into an attached database, you might organize the calls to create a new audit store database, then set the new database to be the active audit store database:

$install = Get-CdaInstallation -Name "site1"
 
$auditStore = Get-CdaAuditStore -Installation $install -Name "auditstore1"
 
// Use New-CdaDatabase to create and attach the new database
$newDB = New-CdaDatabase -AuditStore $auditStore -Name "audit-us-Oct2014" -Server "sql_server1.domain.com\da" -Database "audit-us-Oct2014"
 
// Set the newly created database as the active database for this audit store
Set-CdaActiveDatabase -AuditStore $auditStore -Database $newDB
 
// Create another new database
$newDB2 = New-CdaDatabase -AuditStore $auditStore -Name "audit-us-Nov2014" -Server "sql_server1.domain.com\da" -Database "audit-us-Nov2014"
 
// Set the second database as active database
Set-CdaActiveDatabase -AuditStore $auditStore -Database $newDB2
 
// Detach the first database if it is no longer needed
Detach-CdaDatabase -Database $newDB

In most cases, you can determine from the parameters of a cmdlet whether you need to call another cmdlet first. For example, most Set-Cda*Xxx* or Remove-Cda*Xxx* cmdlets, you must call the corresponding GetCda*Xxx* cmdlet to obtain the object first. For example, to delete the "forensics" audit role from the "production" audit installation, you could call the cmdlets as follows:

Get-CdaAuditRole -Installation "production" -Name "forensics" | RemoveCdaAuditRole

In this example, the Get-CdaAuditRole cmdlet retrieves “forensics” from the specified installation and passes it to the Remove-CdaAuditRole cmdlet.

Checking for Valid Licenses

All of the cmdlets check for a valid license before performing the requested action. The license check succeeds only if one of the following conditions is true:

  • There is at least one evaluation license that has not expired.
  • There is at least one workstation license.
  • There is at least one server license.

If the license check fails, the cmdlet displays an error and stops running. If the license check succeeds, the result is cached. The next time a cmdlet tries to access the same forest, it uses the cached result rather than performing the license check again. Note that the cache is only effective in one PowerShell console. If another PowerShell console runs a cmdlet accessing the same forest, the cmdlet in that console performs a separate license check.

Specifying Parameters using Different Formats

For certain types of parameters, you can specify a value using any one of several different supported formats. For example, you can specify a user principal for a CdaAdPrincipal object type by providing the information that identifies the user in any of the following formats:

  • distinguished name (DN) for the user.
  • security identifier for the user (SID).
  • sAMAccountName attribute for the user in either the sAMAccountName@domain format or domain\sAMAccountName format.
  • in a stored user object.

The following formats are all valid for specifying an Active Directory user principal:

New-CdaRoleAssignment -AuditRole $role -Assignee "cn=ben,cn=Users,dc=acme,dc=com"

New-CdaRoleAssignment -AuditRole $role -Assignee "S-1-5-21-12345678-98765432-500"

New-CdaRoleAssignment -AuditRole $role -Assignee "ben@acme.com"

New-CdaRoleAssignment -AuditRole $role -Assignee "acme\ben"

New-CdaRoleAssignment -AuditRole $role -Assignee $userObject

The following table lists the supported formats for each type of parameter.

Type Supported parameter formats
CdaInstallation You can specify an installation name as string, for example, “DefaultInstallation,” or using a CdaInstallation object.
CdaAdPrincipal You can specify Active Directory users, groups, or computers using any of the following formats:

- Distinguished name string
- SID string
- sAMAccountName@domain
- domain\sAMAccountName

You can specify Active Directory users, groups, or computers using a CdaAdPrincipal object.
CdaAccessAccount You can specify a Windows account name or a SQL Server login account name and password, for example.

For a Windows user account, all of the same formats listed for a CdaAdPrincipal object are supported.

For SQL Server login accounts, the format is “sql:sql_name:sql_password”. The password can be empty.
CdaAuditScope You can specify the audit scope using the Active Directory site name as a string, for example, “default-first-site” or by specifying a network subnet definition as a string, for example, “192.168.100.0/24”.

If a parameter is not listed in the table, you must specify the object instance returned by a previously cmdlet. For example, you can use the Get-CdaAuditStore cmdlet to return an object instance of the audit store then use that object instance for parameters in other cmdlets that require it.

# Get the audit store object instance and store it in $cdaAuditStoreObject

$cdaAduitStoreObject = Get-CdaAuditStore -Installation “DefaultInstallation” -Name “Default-First-Site”

# Use the audit store object instance to specify a parameter value

Attach-CdaDatabase -AuditStore $cdaAduitStoreObject -Name “audit-store-db” ‑Server “win2012\instance1” -Database “audit-store-database”

Working with Sample Scripts

The Audit Module for PowerShell includes some sample scripts that you can use to do database rotation; rotating a database involves creating a new audit store database and making the new database the active database for the installation. You can copy and modify the sample scripts to use the code directly in your environment or study the syntax used in the script to serve as an example for writing your own custom scripts.

  • db_rotation.ps1

    This PowerShell script demonstrates how to use the following cmdlets to do database rotation:

    • New-CdaDatabase
    • Set-CdaDatabase
    • Detach-CdaDatabase
  • db_rotation_sql_script.ps1

    This PowerShell script demonstrates how to do database rotation using the SQL scripts and PowerShell cmdlets.

  • SetupDatabase.sql, SetupServer.sql

    You can modify the file path settings in these SQL scripts to create a new audit store database using the New-CdaDatabase cmdlet with the DatabaseScriptFile and ServerScriptFile parameters. This case is useful if you want to create a new audit store database with a customized database file folder path, database log file folder path, or database full-text catalog root path.

    If you want to use these SQL scripts and you also want to customize the StoredProcedureAccount, IsAwsRds, and IntegrityCheckEnabled settings, you also need to customize the settings in the SQL scripts instead of using the StoredProcedureAccount, IsAwsRds, and IntegrityCheckEnabled parameters. These three parameters can't be used along with the DatabaseScriptFile and ServerScriptFile parameters.

To run the sample script:

  1. Open the Audit Module for PowerShell.

  2. Verify you have permission to execute scripts.

    Get-ExecutionPolicy

    In most cases, the permission to execute scripts is restricted. You can use the SetExecutionPolicy to allow execution. For example:

    Set-ExecutionPolicy Unrestricted

    For more information about execution policies and the options available, use the gethelp function.

  3. Verify you are in the directory where the db_rotation.ps1 script is located.

  4. Execute the sample script.

Writing Your Own Scripts

You can combine Audit Module for PowerShell cmdlets with native Windows PowerShell cmdlets to perform many common administrative tasks. The following examples illustrate how you can combine the Audit Module for PowerShell cmdlets and native cmdlets to accomplish a simple but specific goal.

Exporting Specific Session Fields For A Report

By default, the cmdlet for getting session information might return more information than you want for a simple report. If you want to narrow down the fields returned, you can use a native cmdlet, such as Select-Object, to specify the fields of interest, then another native cmdlet, such as Out-File, to export the results to a text file. For example, to limit the results to a few key fields, you might specify a command similar to this:

Get-CdaAuditSession -Installation "installation-name" 
| Select‑Object ‑Property User, Machine, StartTime, EndTime, 
State, | Out‑File c:\samplesession.txt

This example pipes the results from the Audit Module for PowerShell GetCdaAuditSession cmdlet to the Select-Object cmdlet, then uses another pipe to send the resulting output to a file.

Checking the status of agents and collectors

You can use Server Suite cmdlets to get status information for agents and collectors and combine those cmdlets with native or custom cmdlets to schedule checking for connectivity to run on a regular basis and to trigger an email notification if the status returned for the agent or collector in any interval is Disconnected. For example, to check for disconnected agents, you might specify a command similar to this:

Get-CdaAgent -i "*installation-name*" | Where { $_.Status -eq "Disconnected" }

To check for agents that haven’t connected to the collector since a specific time, you might specify a command similar to this:

Get-CdaAgent -i "*installation-name*" | where { $_.LastUpdateTime -lt ([DateTime]"12:00:00 AM, 12/29/2014") }

Similarly, you can use the Get-CdaCollector cmdlet to check for connectivity between a collector and the Microsoft SQL Server database you are using as the active audit store database.

Get-CdaCollector -i "*installation_name*" | where { $_.LastUpdateTime –lt "10:00:00 AM, 12/17/2014"}

You can include these cmdlets in scripts that run automatically using a task scheduler to check for connectivity issues at the interval you specify, such as once a day or once a week, and to send the results to specified channels, such as an email message or SNMP trap, using a cmdlet such as Send-MailMessage.

Recommendations for Writing Custom Scripts

Most cmdlets and scripts return information efficiently without any special handling or any noticeable effect on performance. If you plan to write custom scripts that could potentially return large data sets, however, you should consider ways to improve performance. For example, if you are writing a script that exports a large number of sessions or reports on activity for a large audit installation, you might want to use the following recommendations as guidelines.

  • When testing the performance of the script, use the standard Measure-Command cmdlet to accurately measure cmdlet and script performance.

    The Measure-Command cmdlet ignores the time it takes to print all of the results returned to the PowerShell console. In many cases, the execution of a query or script is efficient, but rendering the results in the PowerShell console might make the cmdlet or script performance seem unacceptable.

  • Avoid using the PowerShell pipeline if your cmdlet or script returns large data collections.

    For example, you might use foreach in a script instead of using the pipeline to improve performance.

    Use syntax similar to this:

    foreach ($cmd in Get-CdaUnixCommand -Session $s) { *action_on_each_cmd* }

    Instead of:

    Get-CdaUnixCommand -Session $s | *action_on_each_cmd*

  • Cache the data, if possible, by writing the results to a file.

    For example, use syntax similar to this:

    $cmds = Get-CdaUnixCommand -Session $s
    

    Out-File -InputObject $cmds -FilePath file

    Instead of:

    Get-CdaUnixCommand -Session $s | Out-File -FilePath file
    
  • Use Export-Csv instead of Out-File if possible. The Export-Csv cmdlet writes results to a file faster than the Out-File cmdlet.

  • If you are writing a script that generates a very large data set—for example, reporting information for a global audit installation—you might want to use the native .NET FileStream function. The FileStream function is the fastest way to write content to a file.

    For example, you might use a code snipper like this:

    $fs = New-Object IO.FileStream <file>, 'Append','Write','Read'
    

    $fw = New-Object System.IO.StreamWriter $fs

    $cmds = Get-CdaUnixCommand -Session $s

    foreach ($cmd in $cmds) {$fw.WriteLine("{0} {1} {2}",

    $cmd.Sequence, $cmd.Time, $cmd.Command)}

    $fw.Close()

$fs.Dispose() ```

Executing Custom Scripts

In most cases, the permission to execute scripts is restricted. You can use the native PowerShell cmdlet Get-ExecutionPolicy to check whether you have permission to execute scripts using your current account credentials and the native Set-ExecutionPolicy cmdlet to specify an execution policy.

To check and update the execution policy for scripts

  1. Open the Audit Module for PowerShell.

  2. Verify you have permission to execute scripts.

    Get-ExecutionPolicy

  3. Run the SetExecutionPolicy cmdlet to change the execution policy. For example:

    Set-ExecutionPolicy Unrestricted

    For more information about execution policies and the options available, use the gethelp function.

  4. Verify you are in the directory where your scripts are located.

  5. Execute the sample script.

Getting Information about the cmdlet Available

You can use the get-help command with different options to get summary or detailed information about the cmdlets available in the Audit Module for PowerShell or about the specific cmdlets you want to use. For example, you can use get-help with the full command-line option to see complete reference information for a specified cmdlet or get-help -example to display only the examples for a specified cmdlet.

To see the current list of cmdlets available open the Audit Module for PowerShell, then run the following command:

get-help *-cda*

This command displays a summary of the Audit Module for PowerShell cmdlets similar to the following partial list of commands:

alt