-
Notifications
You must be signed in to change notification settings - Fork 0
/
PSLoginMonitor.ps1
798 lines (672 loc) · 26 KB
/
PSLoginMonitor.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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
<# Configuration variables #>
<#
Number of failed logins before an IP address is blocked. Values less than or
equal to 1 are treated as 1 (block on first failed login). Recommended value is
3-10. Note that some brute-force attacks can initiate several login attempts per second,
so some IPs will be able to attempt a handful of logins beyond the block threshold before
being stopped by the Windows firewall. From testing this is usually at most 3-4 beyond
the set block count.
#>
$BlockCount = 3
<#
Once an IP address is blocked, how many hours before it is unblocked. Values less than 0
are treated as infinite (never unblock). Recommended value is 24 hours to prevent Windows
firewall from filling up.
#>
$BlockTimeHours = 24
<#
After a failed login, how long before the failed login counter is "reset". Intended to
prevent one-off login failures from blocking an IP over a long period of time. From testing
1 - 3 hours appears to work best.
#>
$ResetCounterTimeHours = 3
<#
Use netsh command to manage firewall rules. Generally has better performance and less memory/CPU
overhead and will allow script to handle higher volumes of login attempts. May break if MS
changes output of netsh command since the script parses the command line output.
#>
[bool]$UseNetsh = 1
<#
List of IPs to ignore login failures. Ranges must be in CIDR notation. Default list is all
private IPv4 ranges.
#>
$WhiteList = @(
"127.0.0.0/8",
"192.168.0.0/16",
"172.16.0.0/12",
"10.0.0.0/8"
)
<# Configuration variables #>
<# Constants - DO NOT CHANGE#>
$dtFormat = "yyyy-MM-dd HH:mm:ss"
$ruleNameTemplate = "PS Login Monitor block for {0}"
$FirewallGroup = "PS Login Monitor"
[xml]$LoginData =
“<LoginData>
<IpAddress></IpAddress>
<FailedLoginCount></FailedLoginCount>
<LastLoginTime></LastLoginTime>
<LastLoginType></LastLoginType>
<CounterResetTime></CounterResetTime>
<UnblockTime></UnblockTime>
</LoginData>”
$EventIdsToProcess = @{
4625 = 'RDP/RDS' # Failed windows/RDP login
18456 = 'MSSQL' # Failed MSSQL login, but can also be triggered by other connection failures that are filtered out by $MssqlTextFilters array
17828 = 'MSSQL' # Usually the result of some kind of port scan on MSSQL port
17832 = 'MSSQL' # Usually the result of some kind of port scan on MSSQL port
17836 = 'MSSQL' # Usually the result of some kind of port scan on MSSQL port
}
#For MSSQL event 18456 there are some login failures that a block is not desired and are filtered out based on message text.
$MssqlTextFilters = @(
"Login is valid login, but server access failed.",
"Login is valid, but server access failed.",
"Password must be changed."
)
<# Constants #>
<#
IP address functions. Thanks to the author of this code here: http://www.gi-architects.co.uk/2016/02/powershell-check-if-ip-or-subnet-matchesfits/
#>
function Check-Subnet ([string]$addr1, [string]$addr2)
{
# Separate the network address and length
$network1, [int]$subnetlen1 = $addr1.Split('/')
$network2, [int]$subnetlen2 = $addr2.Split('/')
#Convert network address to binary
[uint32] $unetwork1 = NetworkToBinary $network1
[uint32] $unetwork2 = NetworkToBinary $network2
#Check if subnet length exists and is less then 32(/32 is host, single ip so no calculation needed) if so convert to binary
if($subnetlen1 -lt 32)
{
[uint32] $mask1 = SubToBinary $subnetlen1
}
if($subnetlen2 -lt 32)
{
[uint32] $mask2 = SubToBinary $subnetlen2
}
#Compare the results
if($mask1 -and $mask2)
{
# If both inputs are subnets check which is smaller and check if it belongs in the larger one
if($mask1 -lt $mask2)
{
return CheckSubnetToNetwork $unetwork1 $mask1 $unetwork2
}
else
{
return CheckNetworkToSubnet $unetwork2 $mask2 $unetwork1
}
}
ElseIf($mask1)
{
# If second input is address and first input is subnet check if it belongs
return CheckSubnetToNetwork $unetwork1 $mask1 $unetwork2
}
ElseIf($mask2)
{
# If first input is address and second input is subnet check if it belongs
return CheckNetworkToSubnet $unetwork2 $mask2 $unetwork1
}
Else
{
# If both inputs are ip check if they match
CheckNetworkToNetwork $unetwork1 $unetwork2
}
}
function CheckNetworkToSubnet ([uint32]$un2, [uint32]$ma2, [uint32]$un1)
{
$ReturnArray = "" | Select-Object -Property Condition,Direction
if($un2 -eq ($ma2 -band $un1))
{
$ReturnArray.Condition = $True
$ReturnArray.Direction = "Addr1ToAddr2"
return $ReturnArray
}
else
{
$ReturnArray.Condition = $False
$ReturnArray.Direction = "Addr1ToAddr2"
return $ReturnArray
}
}
function CheckSubnetToNetwork ([uint32]$un1, [uint32]$ma1, [uint32]$un2)
{
$ReturnArray = "" | Select-Object -Property Condition,Direction
if($un1 -eq ($ma1 -band $un2))
{
$ReturnArray.Condition = $True
$ReturnArray.Direction = "Addr2ToAddr1"
return $ReturnArray
}
else
{
$ReturnArray.Condition = $False
$ReturnArray.Direction = "Addr2ToAddr1"
return $ReturnArray
}
}
function CheckNetworkToNetwork ([uint32]$un1, [uint32]$un2)
{
$ReturnArray = "" | Select-Object -Property Condition,Direction
if($un1 -eq $un2)
{
$ReturnArray.Condition = $True
$ReturnArray.Direction = "Addr1ToAddr2"
return $ReturnArray
}
else
{
$ReturnArray.Condition = $False
$ReturnArray.Direction = "Addr1ToAddr2"
return $ReturnArray
}
}
function SubToBinary ([int]$sub)
{
return ((-bnot [uint32]0) -shl (32 - $sub))
}
function NetworkToBinary ($network)
{
$a = [uint32[]]$network.split('.')
return ($a[0] -shl 24) + ($a[1] -shl 16) + ($a[2] -shl 8) + $a[3]
}
function Get-UnblockTime
{
if($BlockTimeHours -lt 1)
{
$unblockTime = [DateTime]::ParseExact("9999-12-31 23:23:59", $dtFormat, $null)
}
else
{
$unblockTime = (Get-Date).AddHours($BlockTimeHours)
}
$unblockTime
}
<#Task Scheduler functions#>
function On-FailedRdpLogin
{
[cmdletbinding()]
Param
(
[parameter(position = 0, Mandatory=$true)]
[int]
$EventId,
[parameter(position = 1, Mandatory=$true)]
[AllowEmptyString()]
[string]
$SubjectUserSid,
[parameter(position = 2, Mandatory=$true)]
[AllowEmptyString()]
[string]
$SubjectUserName,
[parameter(position = 3, Mandatory=$true)]
[AllowEmptyString()]
[string]
$SubjectDomainName,
[parameter(position = 4, Mandatory=$true)]
[int]
$SubjectLogonId,
[parameter(position = 5, Mandatory=$true)]
[AllowEmptyString()]
[string]
$TargetUserSid,
[parameter(position = 6, Mandatory=$true)]
[AllowEmptyString()]
[string]
$TargetUserName,
[parameter(position = 7, Mandatory=$true)]
[AllowEmptyString()]
[string]
$TargetDomainName,
[parameter(position = 8, Mandatory=$true)]
[int]
$Status,
[parameter(position = 9, Mandatory=$true)]
[AllowEmptyString()]
[string]
$FailureReason,
[parameter(position = 10, Mandatory=$true)]
[int]
$SubStatus,
[parameter(position = 11, Mandatory=$true)]
[int]
$LogonType,
[parameter(position = 12, Mandatory=$true)]
[AllowEmptyString()]
[string]
$LogonProcessName,
[parameter(position = 13, Mandatory=$true)]
[AllowEmptyString()]
[string]
$AuthenticationPackageName,
[parameter(position = 14, Mandatory=$true)]
[AllowEmptyString()]
[string]
$WorkstationName,
[parameter(position = 15, Mandatory=$true)]
[AllowEmptyString()]
[string]
$TransmittedServices,
[parameter(position = 16, Mandatory=$true)]
[AllowEmptyString()]
[string]
$LmPackageName,
[parameter(position = 17, Mandatory=$true)]
[int]
$KeyLength,
[parameter(position = 18, Mandatory=$true)]
[int]
$ProcessId,
[parameter(position = 19, Mandatory=$true)]
[AllowEmptyString()]
[string]
$ProcessName,
[parameter(position = 20, Mandatory=$true)]
[AllowEmptyString()]
[string]
$IpAddress,
[parameter(position = 21, Mandatory=$true)]
[int]
$IpPort
)
# Only capture these login types (from https://docs.microsoft.com/en-us/windows/security/threat-protection/auditing/basic-audit-logon-events):
# 3 - Network - A user or computer logged on to this computer from the network.
# 10 - RemoteInteractive - A user logged on to this computer remotely using Terminal Services or Remote Desktop.
$loginTypesToProcess = @(3, 10);
if($loginTypesToProcess.Contains($LogonType))
{
if($UseNetsh)
{
ProcessFailedLoginNetsh $EventId $IpAddress
}
else
{
ProcessFailedlogin $EventId $IpAddress
}
}
}
function On-FailedMssqlLogin
{
[cmdletbinding()]
Param
(
[parameter(position = 0, Mandatory=$true)]
[int]
$EventId,
[parameter(position = 1, Mandatory=$true)]
[string]
$EventData
)
foreach($msg in $MssqlTextFilters)
{
if($EventData.Contains($msg) -eq $true)
{
return
}
}
$EventDataArray = $EventData.Split(',')
$IpAddress = ''
# Use Regex to extract client IP address
$Regex = [Regex]::new('(?<=\[CLIENT: )(.*)(?=\])')
foreach ($data in $EventDataArray)
{
$Match = $Regex.Match($data)
if ($Match.Success)
{
$IpAddress = $Match.Value.Trim()
break
}
}
if($UseNetsh)
{
ProcessFailedLoginNetsh $EventId $IpAddress
}
else
{
ProcessFailedlogin $EventId $IpAddress
}
}
function ProcessFailedLogin
{
[cmdletbinding()]
Param
(
[parameter(position = 0, Mandatory=$true)]
[int]
$EventID,
[parameter(position = 1, Mandatory=$true)]
[AllowEmptyString()]
[string]
$IpAddress
)
if($EventIdsToProcess.ContainsKey($EventId) -eq $false)
{
return
}
if($IpAddress -eq '' -or $IpAddress.Contains("localhost") -eq $true)
{
return
}
foreach($ip in $WhiteList)
{
if((Check-Subnet $IpAddress $ip).Condition -eq $true)
{
return
}
}
$RuleName = [string]::Format($ruleNameTemplate, $IpAddress)
$lastLoginType = $EventIdsToProcess[$EventID]
#Synchronize access by IP address
$mutex = [System.Threading.Mutex]::new($false, $ipAddress)
try
{
if($mutex.WaitOne(30000))
{
$FWRule = Get-NetFirewallRule -DisplayName $RuleName -ErrorAction SilentlyContinue | Select-Object -First 1
$counterResetTime = (Get-Date).AddHours([System.Math]::Max($ResetCounterTimeHours, 1))
$unblockTime = Get-UnblockTime
$executionTime = $counterResetTime
if($FWRule -eq $null) #First failed login
{
#Login data saved to rule description field
[xml]$description = $LoginData
$description.LoginData.FailedLoginCount = "1"
$description.LoginData.IpAddress = $IpAddress
$description.LoginData.CounterResetTime = $counterResetTime.ToString($dtFormat)
$description.LoginData.UnblockTime = $unblockTime.ToString($dtFormat)
$description.LoginData.LastLoginTime = (Get-Date).ToString($dtFormat)
$description.LoginData.LastLoginType = $lastLoginType
#Set placeholder rule that will be enabled when failed login threshold met
$enabled = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetSecurity.Enabled]::False
if($BlockCount -le 1) #Block on first failed attempt
{
$enabled = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetSecurity.Enabled]::True
}
$FWRule = New-NetFirewallRule -DisplayName $RuleName `
-Direction Inbound `
-Description $description.OuterXml `
-InterfaceType Any `
-Group $FirewallGroup `
-Action Block `
-RemoteAddress $IpAddress `
-Enable $enabled
if($enabled -eq [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetSecurity.Enabled]::True)
{
$executionTime = $unblockTime
}
if($BlockCount -gt 1)
{
CreateUnblockTask $RuleName $executionTime
}
}
else #Subsequent login failures
{
$instanceId = $FWRule.InstanceId
$description = [xml]($FWRule.Description) #Pull XML from rule description field
$description.PreserveWhitespace = $true
$loginCount = [int]$description.LoginData.FailedLoginCount
$loginCount = $loginCount + 1 #increment failed login count
$description.LoginData.CounterResetTime = $counterResetTime.ToString($dtFormat)
$description.LoginData.UnblockTime = $unblockTime.ToString($dtFormat)
$description.LoginData.FailedLoginCount = $loginCount.ToString()
$description.LoginData.LastLoginTime = (Get-Date).ToString($dtFormat)
$description.LoginData.LastLoginType = $lastLoginType
if($loginCount -ge $BlockCount)
{
Enable-NetFirewallRule -Name $instanceId
$executionTime = $unblockTime
}
Set-NetFirewallRule -Name $instanceId -Description $description.OuterXml #Update XML in description field
#Update the execution time of the delete task assigned to the firewall rule
$trigger = New-ScheduledTaskTrigger -At $executionTime -Once
Set-ScheduledTask -TaskName $RuleName -TaskPath $FirewallGroup -Trigger $trigger
}
}
}
finally
{
$mutex.ReleaseMutex()
}
}
function ProcessFailedLoginNetsh
{
[cmdletbinding()]
Param
(
[parameter(position = 0, Mandatory=$true)]
[int]
$EventID,
[parameter(position = 1, Mandatory=$true)]
[AllowEmptyString()]
[string]
$IpAddress
)
if($EventIdsToProcess.ContainsKey($EventId) -eq $false)
{
return
}
if($IpAddress -eq '' -or $IpAddress.Contains("localhost") -eq $true)
{
return
}
foreach($ip in $WhiteList)
{
if((Check-Subnet $IpAddress $ip).Condition -eq $true)
{
return
}
}
$ruleName = [string]::Format($ruleNameTemplate, $IpAddress)
$lastLoginType = $EventIdsToProcess[$EventID]
#Synchronize access by IP address
$mutex = [System.Threading.Mutex]::new($false, $ruleName)
try
{
if($mutex.WaitOne(30000))
{
$FWRule = netsh advfirewall firewall show rule name="$ruleName" verbose
$counterResetTime = (Get-Date).AddHours([System.Math]::Max($ResetCounterTimeHours, 1))
$unblockTime = Get-UnblockTime
$executionTime = $counterResetTime
if($FWRule -eq 'No rules match the specified criteria.') #First failed login
{
#Login data saved to rule description field
[xml]$description = $LoginData
$description.LoginData.FailedLoginCount = "1"
$description.LoginData.IpAddress = $IpAddress
$description.LoginData.CounterResetTime = $counterResetTime.ToString($dtFormat)
$description.LoginData.UnblockTime = $unblockTime.ToString($dtFormat)
$description.LoginData.LastLoginTime = (Get-Date).ToString($dtFormat)
$description.LoginData.LastLoginType = $lastLoginType
#Set placeholder rule that will be enabled when failed login threshold met
$enabled = (&{If($BlockCount -le 1) {"yes"} Else {"no"}})
$descriptionXml = $description.OuterXml;
netsh advfirewall firewall add rule name=$ruleName dir=in interface=any action=block remoteip=$IPAddress enable=$enabled description="$descriptionXml"
Get-NetFirewallRule -DisplayName $ruleName | ForEach { $_.Group = $FirewallGroup; Set-NetFirewallRule -InputObject $_ }
if($enabled -eq 'yes')
{
$executionTime = $unblockTime
}
if($BlockCount -gt 1)
{
CreateUnblockTask $RuleName $executionTime
}
}
else #Subsequent login failures
{
$description = [xml](($FWRule | Where-Object {$_.StartsWith('Description:') } | select -First 1).Replace('Description:', '').Trim()) #Pull XML from rule description field
$description.PreserveWhitespace = $true
$loginCount = [int]$description.LoginData.FailedLoginCount
$loginCount = $loginCount + 1 #increment failed login count
$description.LoginData.CounterResetTime = $counterResetTime.ToString($dtFormat)
$description.LoginData.UnblockTime = $unblockTime.ToString($dtFormat)
$description.LoginData.FailedLoginCount = $loginCount.ToString()
$description.LoginData.LastLoginTime = (Get-Date).ToString($dtFormat)
$description.LoginData.LastLoginType = $lastLoginType
if($loginCount -ge $BlockCount)
{
netsh advfirewall firewall set rule name=$RuleName new enable=yes
$executionTime = $unblockTime
}
$xmlText = $description.OuterXml
netsh advfirewall firewall set rule name=$ruleName new description="$xmlText" #Update XML in description field
#Update the execution time of the delete task assigned to the firewall rule
$trigger = New-ScheduledTaskTrigger -At $executionTime -Once
Set-ScheduledTask -TaskName $ruleName -TaskPath $FirewallGroup -Trigger $trigger
}
}
}
finally
{
$mutex.ReleaseMutex()
}
}
<#
Creates a task assigned to a firewall rule to eventually delete
when either the unblock time or counter reset time expires
#>
function CreateUnblockTask
{
[cmdletbinding()]
Param
(
[parameter(position = 0, Mandatory=$true)]
[string]
$RuleName,
[parameter(position = 1, Mandatory=$true)]
[DateTime]
$ExecutionTime
)
$taskPath = '\' + $FirewallGroup + '\'
$taskExists = (Get-ScheduledTask -TaskPath $taskPath -TaskName $RuleName -ErrorAction SilentlyContinue) -ne $null
if($taskExists)
{
Unregister-ScheduledTask -TaskPath $taskPath -TaskName $RuleName -Confirm:$false
}
# Create task assigned to firewall rule to eventually delete
# when either the unblock time or counter reset time expires
$trigger = New-ScheduledTaskTrigger -At $ExecutionTime -Once
# Command to remove firewall rule by unique instance ID
$firewallRuleDeleteCommand = '-command "Remove-NetFirewallRule -DisplayName ''' + $RuleName + '''"'
# Command to remove task after running
$taskDeleteCommand = '-command "Unregister-ScheduledTask -TaskName ''' + $RuleName + ''' -TaskPath ''\' + $FirewallGroup + '\'' -Confirm:$false"'
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries `
-DontStopIfGoingOnBatteries `
-ExecutionTimeLimit ([System.TimeSpan]::FromHours(1)) `
-Hidden `
-Priority 0
# Run under SYSTEM account
$principal = New-ScheduledTaskPrincipal -RunLevel Highest -UserId "SYSTEM"
$firewallRuleDeleteAction = New-ScheduledTaskAction -Execute powershell.exe -Argument $firewallRuleDeleteCommand
$taskDeleteAction = New-ScheduledTaskAction -Execute powershell.exe -Argument $taskDeleteCommand
$actions = @($firewallRuleDeleteAction, $taskDeleteAction)
$task = New-ScheduledTask -Action $actions -Trigger $trigger -Principal $principal -Settings $settings -Description $RuleName
Register-ScheduledTask -TaskName $RuleName -InputObject $task -TaskPath $FirewallGroup
}
<#
Displays data stored in firewall rules for recent failed login attempts by client IP address
#>
function Show-FirewallRuleStats
{
[cmdletbinding()]
Param
(
[Parameter()]
[switch]
$Descending
)
Get-NetFirewallRule -Group $FirewallGroup | ForEach-Object {
New-Object -Type PSObject -Property @{
'IPAddress' = ([xml]$_.Description).LoginData.IpAddress
'Failed Login Count' = ([xml]$_.Description).LoginData.FailedLoginCount -as [int]
'Last Login Attempt' = ([xml]$_.Description).LoginData.LastLoginTime -as [DateTime]
'Last Login Type' = ([xml]$_.Description).LoginData.LastLoginType
'Unblock Time' = ([xml]$_.Description).LoginData.UnblockTime -as [DateTime]
'Counter Reset Time' = ([xml]$_.Description).LoginData.CounterResetTime -as [DateTime]
'Blocked' = (&{If($_.Enabled -eq "True") {"Yes"} Else {"No"}})
}
} | Sort-Object -Descending:$Descending {$_."Last Login Attempt"
} | Format-Table -AutoSize -Property 'IPAddress', 'Failed Login Count', 'Last Login Attempt', 'Last Login Type', 'Unblock Time', 'Counter Reset Time', 'Blocked'
}
<#
Installs PS Login Monitor
#>
function Install-PSLoginMonitor
{
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$false)]
[string]
$ScriptPath = "$env:ProgramFiles\WindowsPowerShell\Modules\PS Login Monitor",
[Parameter()]
[switch]
$UninstallPrevious
)
if($UninstallPrevious)
{
Uninstall-PSLoginMonitor $ScriptPath
}
# Create new task scheduler folder
$scheduleObject = New-Object -ComObject schedule.service
$scheduleObject.connect()
$rootFolder = $scheduleObject.GetFolder("\")
$rootFolder.CreateFolder($FirewallGroup)
# Create folder for script and copy
New-Item -ItemType directory -Path $ScriptPath -Force
Copy-Item -Path $PSScriptRoot\PSLoginMonitor.ps1 -Destination $ScriptPath -Force
# Unblock file
Unblock-File -Path $ScriptPath\PSLoginMonitor.ps1 -Confirm:$false
do
{
$response = Read-Host -Prompt "Do you want to set up RDP/RDS login monitoring? [Y/N]"
if ($response -eq 'y')
{
#Enable logon auditing in local policy (note: does not override domain-level GPO)
auditpol /set /subcategory:Logon /success:enable /failure:enable
#Get task XML and edit working directory for task action
$taskXml = [xml](get-content "$PSScriptRoot\PS Login Monitor - RDP.xml" | out-string)
$taskXml.Task.Actions.Exec.WorkingDirectory = $ScriptPath
$task = Register-ScheduledTask -Xml $taskXml.OuterXml -TaskName "PS Login Monitor - RDP" -TaskPath $FirewallGroup
}
} until ($response -eq 'n' -or $response -eq 'y')
do
{
$response = Read-Host -Prompt "Do you want to set up MSSQL login monitoring? [Y/N]"
if ($response -eq 'y')
{
#Get task XML and edit working directory for task action
$taskXml = [xml](get-content "$PSScriptRoot\PS Login Monitor - MSSQL.xml" | out-string)
$taskXml.Task.Actions.Exec.WorkingDirectory = $ScriptPath
$task = Register-ScheduledTask -Xml $taskXml.OuterXml -TaskName "PS Login Monitor - MSSQL" -TaskPath $FirewallGroup
}
} until ($response -eq 'n' -or $response -eq 'y')
}
<#
Uninstalls PS Login Monitor by deleting the following:
- script directory
- all scheduled tasks and task folder
- all firewall rules
Can be run by the installer to provide a clean install as code is updated
#>
function Uninstall-PSLoginMonitor
{
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$true)]
[string]
$ScriptPath
)
#Remove script
Remove-Item -Path $ScriptPath -Force -Recurse
#Remove all firewall rules
Remove-NetFirewallRule -Group $FirewallGroup
#Remove all tasks and task folder
$TaskPath = '\' + $FirewallGroup + '\'
Unregister-ScheduledTask -TaskPath $TaskPath -Confirm:$false
$scheduleObject = New-Object -ComObject schedule.service
$scheduleObject.connect()
$rootFolder = $scheduleObject.GetFolder("\")
$rootFolder.DeleteFolder($FirewallGroup, 0)
}