-
Notifications
You must be signed in to change notification settings - Fork 225
/
020.SqlAudit.ps1
596 lines (501 loc) · 21.8 KB
/
020.SqlAudit.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
<#
.SYNOPSIS
The `SqlAudit` DSC resource is used to create, modify, or remove
server audits.
.DESCRIPTION
The `SqlAudit` DSC resource is used to create, modify, or remove
server audits.
The built-in parameter **PSDscRunAsCredential** can be used to run the resource
as another user. The resource will then authenticate to the SQL Server
instance as that user. It also possible to instead use impersonation by the
parameter **Credential**.
## Requirements
* Target machine must be running Windows Server 2012 or later.
* Target machine must be running SQL Server Database Engine 2012 or later.
* Target machine must have access to the SQLPS PowerShell module or the SqlServer
PowerShell module.
## Known issues
All issues are not listed here, see [here for all open issues](https://github.com/dsccommunity/SqlServerDsc/issues?q=is%3Aissue+is%3Aopen+in%3Atitle+SqlAudit).
### Property **Reasons** does not work with **PSDscRunAsCredential**
When using the built-in parameter **PSDscRunAsCredential** the read-only
property **Reasons** will return empty values for the properties **Code**
and **Phrase. The built-in property **PSDscRunAsCredential** does not work
together with class-based resources that using advanced type like the parameter
**Reasons** have.
### Using **Credential** property
SQL Authentication and Group Managed Service Accounts is not supported as
impersonation credentials. Currently only Windows Integrated Security is
supported to use as credentials.
For Windows Authentication the username must either be provided with the User
Principal Name (UPN), e.g. `username@domain.local` or if using non-domain
(for example a local Windows Server account) account the username must be
provided without the NetBIOS name, e.g. `username`. Using the NetBIOS name, e.g
using the format `DOMAIN\username` will not work.
See more information in [Credential Overview](https://github.com/dsccommunity/SqlServerDsc/wiki/CredentialOverview).
.PARAMETER Name
The name of the audit.
.PARAMETER LogType
Specifies the to which log an audit logs to. Mutually exclusive to parameter
**Path**.
.PARAMETER Path
Specifies the destination path for a file audit. Mutually exclusive to parameter
**LogType**.
.PARAMETER Filter
Specifies the filter that should be used on the audit.
.PARAMETER MaximumFiles
Specifies the number of files on disk. Mutually exclusive to parameter
**MaximumRolloverFiles**. Mutually exclusive to parameter **LogType**.
.PARAMETER MaximumFileSize
Specifies the maximum file size in units by parameter **MaximumFileSizeUnit**.
If this is specified the parameter **MaximumFileSizeUnit** must also be
specified. Mutually exclusive to parameter **LogType**. Minimum allowed value
is 2 (MB). It also allowed to set the value to 0 which mean unlimited file
size.
.PARAMETER MaximumFileSizeUnit
Specifies the unit that is used for the file size.
If this is specified the parameter **MaximumFileSize** must also be
specified. Mutually exclusive to parameter **LogType**.
.PARAMETER MaximumRolloverFiles
Specifies the amount of files on disk before SQL Server starts reusing
the files. Mutually exclusive to parameter **MaximumFiles** and **LogType**.
.PARAMETER OnFailure
Specifies what should happen when writing events to the store fails.
This can be `Continue`, `FailOperation`, or `Shutdown`.
.PARAMETER QueueDelay
Specifies the maximum delay before a event is written to the store.
When set to low this could impact server performance.
When set to high events could be missing when a server crashes.
.PARAMETER ReserveDiskSpace
Specifies if the needed file space should be reserved. only needed
when writing to a file log. Mutually exclusive to parameter **LogType**.
.PARAMETER Enabled
Specifies if the audit should be enabled. Defaults to `$false`.
.PARAMETER Ensure
Specifies if the server audit should be present or absent. If set to `Present`
the audit will be added if it does not exist, or updated if the audit exist.
If `Absent` then the audit will be removed from the server. Defaults to
`Present`.
.PARAMETER Force
Specifies if it is allowed to re-create the server audit if a current audit
exist with the same name but of a different audit type. Defaults to `$false`
not allowing server audits to be re-created.
.EXAMPLE
Invoke-DscResource -ModuleName SqlServerDsc -Name SqlAudit -Method Get -Property @{
ServerName = 'localhost'
InstanceName = 'SQL2017'
Credential = (Get-Credential -UserName 'myuser@company.local' -Message 'Password:')
Name = 'Log1'
}
This example shows how to call the resource using Invoke-DscResource.
#>
[DscResource(RunAsCredential = 'Optional')]
class SqlAudit : SqlResourceBase
{
[DscProperty(Key)]
[System.String]
$Name
[DscProperty()]
[ValidateSet('SecurityLog', 'ApplicationLog')]
[System.String]
$LogType
# The Path is evaluated if exist in AssertProperties().
[DscProperty()]
[System.String]
$Path
[DscProperty()]
[System.String]
$AuditFilter
[DscProperty()]
[Nullable[System.UInt32]]
$MaximumFiles
[DscProperty()]
# There is an extra evaluation in AssertProperties() for this range.
[ValidateRange(0, 2147483647)]
[Nullable[System.UInt32]]
$MaximumFileSize
[DscProperty()]
[ValidateSet('Megabyte', 'Gigabyte', 'Terabyte')]
[System.String]
$MaximumFileSizeUnit
[DscProperty()]
[ValidateRange(0, 2147483647)]
[Nullable[System.UInt32]]
$MaximumRolloverFiles
[DscProperty()]
[ValidateSet('Continue', 'FailOperation', 'Shutdown')]
[System.String]
$OnFailure
[DscProperty()]
# There is an extra evaluation in AssertProperties() for this range.
[ValidateRange(0, 2147483647)]
[Nullable[System.UInt32]]
$QueueDelay
[DscProperty()]
[ValidatePattern('^[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$')]
[System.String]
$AuditGuid
[DscProperty()]
[Nullable[System.Boolean]]
$ReserveDiskSpace
[DscProperty()]
[Nullable[System.Boolean]]
$Enabled
[DscProperty()]
[Ensure]
$Ensure = [Ensure]::Present
[DscProperty()]
[Nullable[System.Boolean]]
$Force
SqlAudit () : base ()
{
# These properties will not be enforced.
$this.ExcludeDscProperties = @(
'ServerName'
'InstanceName'
'Name'
'Credential'
'Force'
)
}
[SqlAudit] Get()
{
# Call the base method to return the properties.
return ([ResourceBase] $this).Get()
}
[System.Boolean] Test()
{
# Call the base method to test all of the properties that should be enforced.
return ([ResourceBase] $this).Test()
}
[void] Set()
{
# Call the base method to enforce the properties.
([ResourceBase] $this).Set()
}
<#
Base method Get() call this method to get the current state as a hashtable.
The parameter properties will contain the key properties.
#>
hidden [System.Collections.Hashtable] GetCurrentState([System.Collections.Hashtable] $properties)
{
Write-Verbose -Message (
$this.localizedData.EvaluateServerAudit -f @(
$properties.Name,
$properties.InstanceName
)
)
$currentStateCredential = $null
if ($this.Credential)
{
<#
This does not work, even if username is set, the method Get() will
return an empty PSCredential-object. Kept it here so it at least
return a Credential object.
#>
$currentStateCredential = [PSCredential]::new(
$this.Credential.UserName,
[SecureString]::new()
)
}
<#
Only set key property Name if the audit exist. Base class will set it
and handle Ensure.
#>
$currentState = @{
Credential = $currentStateCredential
InstanceName = $properties.InstanceName
ServerName = $this.ServerName
Force = $this.Force
}
$serverObject = $this.GetServerObject()
$auditObject = $serverObject |
Get-SqlDscAudit -Name $properties.Name -ErrorAction 'SilentlyContinue' |
Select-Object -First 1
if ($auditObject)
{
$currentState.Name = $properties.Name
if ($auditObject.DestinationType -in @('ApplicationLog', 'SecurityLog'))
{
$currentState.LogType = $auditObject.DestinationType.ToString()
}
if ($auditObject.FilePath)
{
# Remove trailing slash or backslash.
$currentState.Path = $auditObject.FilePath -replace '[\\|/]*$'
}
$currentState.AuditFilter = $auditObject.Filter
$currentState.MaximumFiles = [System.UInt32] $auditObject.MaximumFiles
$currentState.MaximumFileSize = [System.UInt32] $auditObject.MaximumFileSize
# The value of MaximumFileSizeUnit can be zero, so have to check against $null
if ($null -ne $auditObject.MaximumFileSizeUnit)
{
$convertedMaximumFileSizeUnit = (
@{
0 = 'Megabyte'
1 = 'Gigabyte'
2 = 'Terabyte'
}
).($auditObject.MaximumFileSizeUnit.value__)
$currentState.MaximumFileSizeUnit = $convertedMaximumFileSizeUnit
}
$currentState.MaximumRolloverFiles = [System.UInt32] $auditObject.MaximumRolloverFiles
$currentState.OnFailure = $auditObject.OnFailure
$currentState.QueueDelay = [System.UInt32] $auditObject.QueueDelay
$currentState.AuditGuid = $auditObject.Guid
$currentState.ReserveDiskSpace = $auditObject.ReserveDiskSpace
$currentState.Enabled = $auditObject.Enabled
}
return $currentState
}
<#
Base method Set() call this method with the properties that should be
enforced are not in desired state. It is not called if all properties
are in desired state. The variable $properties contain the properties
that are not in desired state.
#>
hidden [void] Modify([System.Collections.Hashtable] $properties)
{
$serverObject = $this.GetServerObject()
$auditObject = $null
if ($properties.Keys -contains 'Ensure')
{
# Evaluate the desired state for property Ensure.
switch ($properties.Ensure)
{
'Present'
{
# Create the audit since it was missing. Always created disabled.
$auditObject = $this.CreateAudit()
}
'Absent'
{
# Remove the audit since it was present
$serverObject | Remove-SqlDscAudit -Name $this.Name -Force
}
}
}
else
{
<#
Update any properties not in desired state if the audit should be present.
At this point it is assumed the audit exist since Ensure property was
in desired state.
If the desired state happens to be Absent then ignore any properties not
in desired state (user have in that case wrongly added properties to an
"absent configuration").
#>
if ($this.Ensure -eq [Ensure]::Present)
{
$auditObject = $serverObject |
Get-SqlDscAudit -Name $this.Name -ErrorAction 'Stop' |
Select-Object -First 1
if ($auditObject)
{
$auditIsWrongType = (
# If $auditObject.DestinationType is not null.
$null -ne $auditObject.DestinationType -and (
# Path is not in desired state but the audit is not of type File.
$properties.ContainsKey('Path') -and $auditObject.DestinationType -ne 'File'
) -or (
# LogType is not in desired state but the audit is of type File.
$properties.ContainsKey('LogType') -and $auditObject.DestinationType -eq 'File'
)
)
# Does the audit need to be re-created?
if ($auditIsWrongType)
{
if ($this.Force -eq $true)
{
$auditObject | Remove-SqlDscAudit -Force
$auditObject = $this.CreateAudit()
}
else
{
New-InvalidOperationException -Message $this.localizedData.AuditIsWrongType
}
}
else
{
<#
Should evaluate DestinationType so that is does not try to set a
File audit property when audit type is of a Log-type.
#>
if ($null -ne $auditObject.DestinationType -and $auditObject.DestinationType -ne 'File')
{
# Look for file audit properties not in desired state
$fileAuditProperty = $properties.Keys.Where({
$_ -in @(
'Path'
'MaximumFiles'
'MaximumFileSize'
'MaximumFileSizeUnit'
'MaximumRolloverFiles'
'ReserveDiskSpace'
)
})
# If a property was found, throw an exception.
if ($fileAuditProperty.Count -gt 0)
{
New-InvalidOperationException -Message ($this.localizedData.AuditOfWrongTypeForUseWithProperty -f $auditObject.DestinationType)
}
}
# Get all optional properties that has an assigned value.
$assignedOptionalDscProperties = $this | Get-DscProperty -HasValue -Attribute 'Optional' -ExcludeName @(
# Remove optional properties that is not an audit property.
'ServerName'
'Ensure'
'Force'
'Credential'
# Remove this audit property since it must be handled later.
'Enabled'
)
<#
Only call Set when there is a property to Set. The property
Enabled was ignored, so it could be the only one that was
not in desired state (Enabled is handled later).
#>
if ($assignedOptionalDscProperties.Count -gt 0)
{
<#
This calls Set-SqlDscAudit to set all the desired value
even if they were in desired state. Then the no logic is
needed to make sure we call using the correct parameter
set that Set-SqlDscAudit requires.
#>
$auditObject | Set-SqlDscAudit @assignedOptionalDscProperties -Force
}
}
}
}
}
<#
If there is an audit object either from a newly created or fetched from
current state, and if the desired state is Present, evaluate if the
audit should be enable or disable.
#>
if ($auditObject -and $this.Ensure -eq [Ensure]::Present -and $properties.Keys -contains 'Enabled')
{
switch ($properties.Enabled)
{
$true
{
$serverObject | Enable-SqlDscAudit -Name $this.Name -Force
}
$false
{
$serverObject | Disable-SqlDscAudit -Name $this.Name -Force
}
}
}
}
<#
Base method Assert() call this method with the properties that was assigned
a value.
#>
hidden [void] AssertProperties([System.Collections.Hashtable] $properties)
{
# The properties MaximumFiles and MaximumRolloverFiles are mutually exclusive.
$assertBoundParameterParameters = @{
BoundParameterList = $properties
MutuallyExclusiveList1 = @(
'MaximumFiles'
)
MutuallyExclusiveList2 = @(
'MaximumRolloverFiles'
)
}
Assert-BoundParameter @assertBoundParameterParameters
# LogType is mutually exclusive from any of the File audit properties.
$assertBoundParameterParameters = @{
BoundParameterList = $properties
MutuallyExclusiveList1 = @(
'LogType'
)
MutuallyExclusiveList2 = @(
'Path'
'MaximumFiles'
'MaximumFileSize'
'MaximumFileSizeUnit'
'MaximumRolloverFiles'
'ReserveDiskSpace'
)
}
Assert-BoundParameter @assertBoundParameterParameters
# Get all assigned *FileSize properties.
$assignedSizeProperty = $properties.Keys.Where({
$_ -in @(
'MaximumFileSize',
'MaximumFileSizeUnit'
)
})
<#
Neither or both of the properties MaximumFileSize and MaximumFileSizeUnit
must be assigned.
#>
if ($assignedSizeProperty.Count -eq 1)
{
$errorMessage = $this.localizedData.BothFileSizePropertiesMustBeSet
New-InvalidArgumentException -ArgumentName 'MaximumFileSize, MaximumFileSizeUnit' -Message $errorMessage
}
<#
Since we cannot use [ValidateScript()], and it is no possible to exclude
a value in the [ValidateRange()], evaluate so 1 is not assigned.
#>
if ($properties.Keys -contains 'MaximumFileSize' -and $properties.MaximumFileSize -eq 1)
{
$errorMessage = $this.localizedData.MaximumFileSizeValueInvalid
New-InvalidArgumentException -ArgumentName 'MaximumFileSize' -Message $errorMessage
}
<#
Since we cannot use [ValidateScript()], and it is no possible to exclude
a value in the [ValidateRange()], evaluate so 1-999 is not assigned.
#>
if ($properties.Keys -contains 'QueueDelay' -and $properties.QueueDelay -in 1..999)
{
$errorMessage = $this.localizedData.QueueDelayValueInvalid
New-InvalidArgumentException -ArgumentName 'QueueDelay' -Message $errorMessage
}
# ReserveDiskSpace can only be used with MaximumFiles.
if ($properties.Keys -contains 'ReserveDiskSpace' -and $properties.Keys -notcontains 'MaximumFiles')
{
$errorMessage = $this.localizedData.BothFileSizePropertiesMustBeSet
New-InvalidArgumentException -ArgumentName 'ReserveDiskSpace' -Message $errorMessage
}
# Test so that the path exist.
if ($properties.Keys -contains 'Path' -and -not (Test-Path -Path $properties.Path))
{
$errorMessage = $this.localizedData.PathInvalid -f $properties.Path
New-InvalidArgumentException -ArgumentName 'Path' -Message $errorMessage
}
}
<#
Create and returns the desired audit object. Always created disabled.
This should return an object of type [Microsoft.SqlServer.Management.Smo.Audit]
but using that type fails the build process currently.
See issue https://github.com/dsccommunity/DscResource.DocGenerator/issues/121.
#>
hidden [System.Object] CreateAudit()
{
# Get all properties that has an assigned value.
$assignedDscProperties = $this | Get-DscProperty -HasValue -Attribute @(
'Key'
'Optional'
) -ExcludeName @(
# Remove properties that is not an audit property.
'InstanceName'
'ServerName'
'Ensure'
'Force'
'Credential'
# Remove this audit property since it must be handled later.
'Enabled'
)
if ($assignedDscProperties.Keys -notcontains 'LogType' -and $assignedDscProperties.Keys -notcontains 'Path')
{
New-InvalidOperationException -Message $this.localizedData.CannotCreateNewAudit
}
$serverObject = $this.GetServerObject()
$auditObject = $serverObject | New-SqlDscAudit @assignedDscProperties -Force -PassThru
return $auditObject
}
}