-
Notifications
You must be signed in to change notification settings - Fork 3
/
CyberArkStationSuspendedTool.ps1
1511 lines (1182 loc) · 230 KB
/
CyberArkStationSuspendedTool.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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Set-StrictMode -Version Latest
# This utility requires PowerShell major version 4 or above
If ($PSVersionTable.PSVersion.Major -ilt 4)
{
# Display error dialog popup
$message = "ERROR: THIS SERVER IS RUNNING POWERSHELL VERSION " + $PSVersionTable.PSVersion.Major + ".`r`n`r`nTHIS UTILITY REQUIRES POWERSHELL VERSION 5 OR HIGHER.`r`n`r`nCLICK OK TO EXIT."
$caption = "ERROR"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
$msgbox0 = [System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
break
}
<#
.SYNOPSIS
.DESCRIPTION
.NOTES
Author: Kevin Elwell <Elwell1@gmail.com>
Version: 1.0 - 2016/11/16 - Initial release
1.1 - 2016/11/18 - New functionality
1.2 - 2016/12/8 - Added PACLI functions
1.3 - 2016/12/20 - Cleaned up code/comments, base64 images for buttons and form icon
1.3.3 - 2016/12/22 - Disabled contextual menus and added version to display on form
1.4.1 - 2017/2/8 - Fixed PACLI functions, added Help button that launches documentation
1.5.0 - 2017/3/27 - Updated functionality to read vault.ini, logonfile.ini and stationsuspended.ini
.TODO
troubleshoot "not responding" issues - possibly use start-job, get-job, receive-job, stop-job, wait-job cmdlets
manually test and document results
finalize script
create custom connector to be able to run this tool from the CyberArk PSM
#>
#CyberArk Station Suspended Tool Version
$toolver = "1.5.0"
#----------------------------------------------
#region Application Functions
#----------------------------------------------
function OnApplicationLoad {
#Note: This function runs before the form is created
#Note: To get the script directory in the Packager use: Split-Path $hostinvocation.MyCommand.path
#Important: Form controls cannot be accessed in this function
# Read sections/values of StationSuspendedTool.ini into variables to be used within this tool (Oliver Lipkau <oliver@lipkau.net>)
Function Get-IniContent {
<#
.Synopsis
Gets the content of an INI file
.Description
Gets the content of an INI file and returns it as a hashtable
.Notes
Author : Oliver Lipkau <oliver@lipkau.net>
Source : https://github.com/lipkau/PsIni
http://gallery.technet.microsoft.com/scriptcenter/ea40c1ef-c856-434b-b8fb-ebd7a76e8d91
Version : 1.0.0 - 2010/03/12 - OL - Initial release
1.0.1 - 2014/12/11 - OL - Typo (Thx SLDR)
Typo (Thx Dave Stiff)
1.0.2 - 2015/06/06 - OL - Improvment to switch (Thx Tallandtree)
1.0.3 - 2015/06/18 - OL - Migrate to semantic versioning (GitHub issue#4)
1.0.4 - 2015/06/18 - OL - Remove check for .ini extension (GitHub Issue#6)
1.1.0 - 2015/07/14 - CB - Improve round-tripping and be a bit more liberal (GitHub Pull #7)
OL - Small Improvments and cleanup
1.1.1 - 2015/07/14 - CB - changed .outputs section to be OrderedDictionary
1.1.2 - 2016/08/18 - SS - Add some more verbose outputs as the ini is parsed,
allow non-existent paths for new ini handling,
test for variable existence using local scope,
added additional debug output.
#Requires -Version 2.0
.Inputs
System.String
.Outputs
System.Collections.Specialized.OrderedDictionary
.Parameter FilePath
Specifies the path to the input file.
.Parameter CommentChar
Specify what characters should be describe a comment.
Lines starting with the characters provided will be rendered as comments.
Default: ";"
.Parameter IgnoreComments
Remove lines determined to be comments from the resulting dictionary.
.Example
$FileContent = Get-IniContent "C:\myinifile.ini"
-----------
Description
Saves the content of the c:\myinifile.ini in a hashtable called $FileContent
.Example
$inifilepath | $FileContent = Get-IniContent
-----------
Description
Gets the content of the ini file passed through the pipe into a hashtable called $FileContent
.Example
C:\PS>$FileContent = Get-IniContent "c:\settings.ini"
C:\PS>$FileContent["Section"]["Key"]
-----------
Description
Returns the key "Key" of the section "Section" from the C:\settings.ini file
.Link
Out-IniFile
#>
[CmdletBinding()]
[OutputType(
[System.Collections.Specialized.OrderedDictionary]
)]
Param(
[ValidateNotNullOrEmpty()]
[Parameter(ValueFromPipeline=$True,Mandatory=$True)]
[string]$FilePath,
[char[]]$CommentChar = @(";"),
[switch]$IgnoreComments
)
Begin
{
Write-Debug "PsBoundParameters:"
$PSBoundParameters.GetEnumerator() | ForEach-Object { Write-Debug $_ }
if ($PSBoundParameters['Debug']) { $DebugPreference = 'Continue' }
Write-Debug "DebugPreference: $DebugPreference"
Write-Verbose "$($MyInvocation.MyCommand.Name):: Function started"
$commentRegex = "^([$($CommentChar -join '')].*)$"
Write-Debug ("commentRegex is {0}." -f $commentRegex)
}
Process
{
Write-Verbose "$($MyInvocation.MyCommand.Name):: Processing file: $Filepath"
$ini = New-Object System.Collections.Specialized.OrderedDictionary([System.StringComparer]::OrdinalIgnoreCase)
if (!(Test-Path $Filepath))
{
Write-Verbose ("Warning: `"{0}`" was not found." -f $Filepath)
return $ini
}
$commentCount = 0
switch -regex -file $FilePath
{
"^\s*\[(.+)\]\s*$" # Section
{
$section = $matches[1]
Write-Verbose "$($MyInvocation.MyCommand.Name):: Adding section : $section"
$ini[$section] = New-Object System.Collections.Specialized.OrderedDictionary([System.StringComparer]::OrdinalIgnoreCase)
$CommentCount = 0
continue
}
$commentRegex # Comment
{
if (!$IgnoreComments)
{
if (!(test-path "variable:local:section"))
{
$section = $script:NoSection
$ini[$section] = New-Object System.Collections.Specialized.OrderedDictionary([System.StringComparer]::OrdinalIgnoreCase)
}
$value = $matches[1]
$CommentCount++
Write-Debug ("Incremented CommentCount is now {0}." -f $CommentCount)
$name = "Comment" + $CommentCount
Write-Verbose "$($MyInvocation.MyCommand.Name):: Adding $name with value: $value"
$ini[$section][$name] = $value
}
else { Write-Debug ("Ignoring comment {0}." -f $matches[1]) }
continue
}
"(.+?)\s*=\s*(.*)" # Key
{
if (!(test-path "variable:local:section"))
{
$section = $script:NoSection
$ini[$section] = New-Object System.Collections.Specialized.OrderedDictionary([System.StringComparer]::OrdinalIgnoreCase)
}
$name,$value = $matches[1..2]
Write-Verbose "$($MyInvocation.MyCommand.Name):: Adding key $name with value: $value"
$ini[$section][$name] = $value
continue
}
}
Write-Verbose "$($MyInvocation.MyCommand.Name):: Finished Processing file: $FilePath"
Return $ini
}
End
{Write-Verbose "$($MyInvocation.MyCommand.Name):: Function ended"}
}
# Name of the Section, in case the ini file had none
# Available in the scope of the script as `$script:NoSection`
$script:NoSection = "_"
# Get the directory this script is executing in
Function Get-ScriptDirectory {
Return Split-Path -parent $PSCommandPath
}
# Function to check if an Active Directory Group exists
Function ADGroupExists {
<#
.SYNOPSIS
Function that queries a Active Directory to check if an Active Directory Group exists
.DESCRIPTION
This function will use the parameter passed as the group name to query Active Directory to ssee if the group exists
The function has a mandatory string parameter of an Active Directory user
.EXAMPLE
ADGroupExists 'ADGroup1'
The above example will check to see if the Active Directory group ADGroup1 exists.
.PARAMETER string
The string passed as a parameter to the function is the Active Directory group name to query
.NOTES
Author: Kevin Elwell <Elwell1@gmail.com>
Version: 1.0 - 2017/1/10 - Initial release
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[string]$ADGroupName
)
$ADGroupexists = $(Try{Get-ADGroup -Identity $ADGroupName} Catch {$null})
Return $ADGroupexists
}
$UserName = $ENV:USERNAME
$Script:AuthorizedUserName = $UserName.ToUpper()
$ComputerName = $ENV:ComputerName
$Script:CompName = $ComputerName.ToUpper()
# Get the directory this script is executing in into a global variable
$Script:scriptPath = Get-ScriptDirectory
# Define the paths to the StationSuspendedTool.ini, Vault.ini and logonfile.ini
$Script:INIPath = "$scriptPath\PACLI\StationSuspendedTool.ini"
$Script:VaultIni = "$scriptPath\PACLI\Vault.ini"
$Script:logonIni = "$scriptPath\PACLI\logonfile.ini"
$Script:PathtoPACLI = "$scriptPath\PACLI\pacli.exe"
# Validate the $INIPath exists. If not, popup error message. Otherwise, retrieve contents of INI file
If(!(Test-Path $INIPath)) {
# Display error dialog popup
$message = "ERROR: UNABLE TO VALIDATE ""$INIPath"".`r`n`r`nPLEASE CHECK THE INI FILE EXISTS AND THE FULL PATH TO THE INI IS PROVIDED."
$caption = "ERROR"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
$msgbox96 = [System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
Break
}else{
# Define the path to the StationSuspendedTool.ini and retrieve the contents
$Script:FileContent = Get-IniContent $INIPath -ErrorAction SilentlyContinue #-Verbose
}
# Validate the $VaultIni exists. If not, popup error message. Otherwise, retrieve contents of INI file
If(!(Test-Path $VaultIni)) {
# Display error dialog popup
$message = "ERROR: UNABLE TO VALIDATE ""$VaultIni"".`r`n`r`nPLEASE CHECK THE INI FILE EXISTS AND THE FULL PATH TO THE INI IS PROVIDED."
$caption = "ERROR"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
$msgbox97 = [System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
Break
}else{
# Retrieve contents of the Vault.ini
$Script:VaultContent = Get-IniContent $VaultIni -ErrorAction SilentlyContinue #-Verbose
}
# Validate the $logonIniContent exists. If not, popup error message. Otherwise, retrieve contents of INI file
If(!(Test-Path $logonIni)) {
# Display error dialog popup
$message = "ERROR: UNABLE TO VALIDATE ""$logonIni"".`r`n`r`nPLEASE CHECK THE INI FILE EXISTS AND THE FULL PATH TO THE INI IS PROVIDED."
$caption = "ERROR"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
$msgbox98 = [System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
Break
}else{
# Define the path to the logonfile.ini and retrieve the contents
$Script:logonContent = Get-IniContent $logonIni -ErrorAction SilentlyContinue #-Verbose
}
# Validate the $PathtoPACLI exists. If not, popup error message.
If(!(Test-Path $PathtoPACLI)) {
# Display error dialog popup
$message = "ERROR: UNABLE TO VALIDATE ""$PathtoPACLI"".`r`n`r`nPLEASE CHECK THE EXE FILE EXISTS AND THE FULL PATH TO THE EXE IS PROVIDED."
$caption = "ERROR"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
$msgbox99 = [System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
Break
}
# Define the Active Directory Support Group that grants permissions to run this utility from the StationSuspended.ini file
$CASupportGroup = $FileContent["ActiveDirectory"]["CyberArkADSupportGroup"]
# Initialize some variables to $false
[boolean]$inADGroup = $false
$Groupexists = $(Try{Get-ADGroup -Identity $CASupportGroup} Catch {$null})
If($Groupexists = ADGroupExists $CASupportGroup){
If($ADUser = Get-ADUser -filter {sAMACCOUNTName -eq $AuthorizedUserName} -properties givenName, Surname, samAccountName, Enabled | Select givenName, Surname, SamAccountName, Enabled -ErrorAction Stop) {
# If the user object exists in Active Directory, check to see if its a member of the $CASupportGroup Active Directory group
$CASupportGroupMembers = Get-ADGroupMember -Identity $CASupportGroup -Recursive | Select -ExpandProperty samAccountName -ErrorAction Stop
# Based on checking Active Directory group membership, assign true/false to $inADGroup variable for use later in script
if ($CASupportGroupMembers -eq $AuthorizedUserName) {
return $true #return true for success or false for failure
}
}
}
}
function OnApplicationExit {
#Note: This function runs after the form is closed
#TODO: Add custom code to clean up and unload snapins when the application exits
$script:ExitCode = 0 #Set the exit code
}
function quitscript {
$form1.Close()
[System.Windows.Forms.Application]::exit($null)
}
#endregion
Function GenerateForm {
#----------------------------------------------
#region Import Assemblies
#----------------------------------------------
[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
[void][reflection.assembly]::Load("mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[void][reflection.assembly]::Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
#endregion Import Assemblies
#----------------------------------------------
#region Generated Form Objects
#----------------------------------------------
[System.Windows.Forms.Application]::EnableVisualStyles()
$form1 = New-Object System.Windows.Forms.Form
$ToolVersion = New-Object System.Windows.Forms.Label
$ADConnStatus = New-Object System.Windows.Forms.Label
$VaultStatus = New-Object System.Windows.Forms.Label
$PSMStatus = New-Object System.Windows.Forms.Label
$InputBoxLabel = New-Object System.Windows.Forms.Label
$InputBox = New-Object System.Windows.Forms.TextBox
$outputBoxLabel = New-Object System.Windows.Forms.Label
$outputBox = New-Object System.Windows.Forms.TextBox
$outputBox1 = New-Object System.Windows.Forms.TextBox
$outputBox3 = New-Object System.Windows.Forms.TextBox
$outputBox4 = New-Object System.Windows.Forms.TextBox
$outputBoxLabel1 = New-Object System.Windows.Forms.Label
$outputBoxLabel2 = New-Object System.Windows.Forms.Label
$outputBoxLabel3 = New-Object System.Windows.Forms.Label
$outputBoxLabel4 = New-Object System.Windows.Forms.Label
$pictureBox = New-Object Windows.Forms.PictureBox
$ButtonSearch = New-Object System.Windows.Forms.Button
$ButtonActivate = New-Object System.Windows.Forms.Button
$ButtonReset = New-Object System.Windows.Forms.Button
$ButtonExit = New-Object System.Windows.Forms.Button
$ButtonHelpYou = New-Object System.Windows.Forms.Button
$tooltip1 = New-Object System.Windows.Forms.ToolTip
$ButtonHelp = New-Object System.Windows.Forms.Button
$tooltip1.IsBalloon = $true
$contextMenuStrip = New-Object System.Windows.Forms.ContextMenuStrip
$menuItem1 = New-Object System.Windows.Forms.ToolStripMenuItem
#endregion Generated Form Objects
#----------------------------------------------
# User Generated Script
#----------------------------------------------
############################################## Start functions
#region FormEvent_Load
# ONLY DO PING-HOST, CHECK-ADMODULE, GET-INICONTENT, GET-CURRIP WITHIN $FormEvent_Load={} AND DISPLAY LABELS LOGIC
$FormEvent_Load={
#region Disable contextual menus for all textboxes
$InputBox.ContextMenuStrip = $contextMenuStrip
$outputBox.ContextMenuStrip = $contextMenuStrip
$outputBox1.ContextMenuStrip = $contextMenuStrip
$outputBox3.ContextMenuStrip = $contextMenuStrip
$outputBox4.ContextMenuStrip = $contextMenuStrip
$contextMenuStrip.Visible = $false
#endregion Disable contextual menu for all textboxes
# Initialize the $ButtonSearch.Enabled Variable to $false so when the form initially loads, the button is not enabled until
# the user enters something into the textbox
$ButtonSearch.Enabled = $false
# Get the IP address this script is being executed on and compare to the IP address in the .ini file
Function Get-CurrIP {
$ThisIP = Get-CIMInstance Win32_networkAdapterconfiguration -filter "ipenabled = 'True'" | Select IPAddress
[string]$CurrIP = $ThisIP.ipaddress[0]
Return $CurrIP
}
# Check if the Active Directory PowerShell module exists
Function Check-ADModule {
<#
.SYNOPSIS
This function will check if a PowerShell module exists (PowerShell module name is passed as a parameter to the function)
.DESCRIPTION
This function will use the parameter passed as the name of the PowerShell module to check to see if it exists
The function has a mandator parameter of a string that you want written to the log file.
.EXAMPLE
CheckADModule "ActiveDirectory"
The above example will check to see if the ActiveDirectory PowerShell module is present
.PARAMETER string
The string passed as a parameter to the function is the PowerShell module name you want to check if it exists
.NOTES
Author: Kevin Elwell <Elwell1@gmail.com>
Version: 1.0 - 2016/11/12 - Initial release
.NOTE This has only been tested/validated wo work when the PowerShell Module is in the C:\Windows\System32\WindowsPowerShell\v1.0\Modules or C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules directories.
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
# [Alias("ADModule")]
[string]$ADModule
)
# Initialize $ModuleExists variable to false
$ModuleExists = $false
# Get list of available PowerShell modules to see if the Active Directory module is present
$ADModuleExists = Get-Module -ListAvailable -Name $ADModule -ErrorAction SilentlyContinue
[bool]$ModuleExists = Test-Path $ADModuleExists.Path -ErrorAction SilentlyContinue
$output =@()
$output += $ModuleExists
Return $output
}
# Function to ping a remote machine
Function Ping-Host {
param (
[parameter(Mandatory=$true)]
[string]$host2ping
)
# Initialize $Online variable to $false
$Online = $false
# Ping the host name/IP passed as a parameter
[bool]$Online = Test-Connection -Computername $host2ping -Quiet -Count 2
#Return the bool result of the ping
Return $Online
}
#region ADModuleCheck
# Execute the CheckADModule function and pipe output into $connStatus variable
$connStatus = Check-ADModule "ActiveDirectory" -ErrorAction SilentlyContinue
# Display results of Check-ADModule function to user and disable search button if Active Directory PowerShell module is missing
If($connStatus) {
$ADConnStatus.BackColor = [Drawing.Color]::Green
$ADConnStatus.ForeColor = [Drawing.Color]::White
$ADConnStatus.font = New-Object System.Drawing.Font("arial",10,[System.Drawing.FontStyle]::Bold)
$ADConnStatus.Text = "ACTIVE DIRECTORY MODULE PRESENT"
# Import Active Directory PowerShell module
Try {
Import-Module ActiveDirectory -ErrorAction Stop >$null
}
Catch
{
Write-Host $_
Break
}
}
If(!($connStatus)) {
$ADConnStatus.BackColor = [Drawing.Color]::Red
$ADConnStatus.ForeColor = [Drawing.Color]::Black
$ADConnStatus.font = New-Object System.Drawing.Font("arial",10,[System.Drawing.FontStyle]::Bold)
$ADConnStatus.Text = "ERROR: ACTIVE DIRECTORY MODULE MISSING"
$tooltip1.SetToolTip($ADConnStatus, "THIS UTILITY REQUIRES THE MICROSOFT ACTIVE DIRECTORY POWERSHELL CMDLETS.")
$ButtonSearch.Enabled = $false
$InputBoxLabel.Visible = $false
$InputBox.Visible = $false
}
#endregion
#region Ping CyberArk vault IP address
# Define Vault IP address from Vault.ini file
[string]$VaultIP = $VaultContent["_"]["Address"]
# Ping Vault IP address to make sure its up and running
$vaultUp = Ping-Host $vaultIP
# Display results of Ping-Host function to user and disable search button if vault not online
If($VaultUp){
$VaultStatus.BackColor = [Drawing.Color]::Green
$VaultStatus.ForeColor = [Drawing.Color]::White
$VaultStatus.font = New-Object System.Drawing.Font("arial",10,[System.Drawing.FontStyle]::Bold)
$VaultStatus.Text = "CYBERARK VAULT IS ONLINE"
}
If(!($VaultUp)){
$VaultStatus.BackColor = [Drawing.Color]::Red
$VaultStatus.ForeColor = [Drawing.Color]::Black
$VaultStatus.font = New-Object System.Drawing.Font("arial",10,[System.Drawing.FontStyle]::Bold)
$VaultStatus.Text = "CYBERARK VAULT IS OFFLINE"
$tooltip1.SetToolTip($VaultStatus, "UNABLE TO COMMUNICATE WITH THE CYBERARK VAULT. PLEASE CONTACT IT SECURITY.")
$ButtonSearch.Enabled = $false
$InputBoxLabel.Visible = $false
$InputBox.Visible = $false
}
#endregion
#region Check if this script is running from the PSM
# Compare the PSM IP address from the StationSuspendedTool.ini to the IP address this script is running on
$MyIP = Get-CurrIP
# Define PSM IP from StationSuspendedTool.ini file
$PSMIP = $FileContent["CyberArk"]["PSMIP"]
# Display results of comparing IP addresses to user and disable search button if the IP addresses are not the same
If ($MyIP -eq $PSMIP) {
$PSMStatus.BackColor = [Drawing.Color]::Green
$PSMStatus.ForeColor = [Drawing.Color]::White
$PSMStatus.font = New-Object System.Drawing.Font("arial",10,[System.Drawing.FontStyle]::Bold)
#$PSMStatus.Text = "RUNNING FROM PSM"
$PSMStatus.Text = "RUNNING FROM SERVER"
}
If ($MyIP -ne $PSMIP) {
$PSMStatus.BackColor = [Drawing.Color]::Red
$PSMStatus.ForeColor = [Drawing.Color]::Black
$PSMStatus.font = New-Object System.Drawing.Font("arial",10,[System.Drawing.FontStyle]::Bold)
#####################################################################################################################################
# Use code below for running from a secure server
$PSMStatus.Text = "NOT RUNNING FROM SERVER"
$tooltip1.SetToolTip($PSMStatus, "THIS UTILITY MUST BE EXECUTED FROM A SECURE SERVER.")
#####################################################################################################################################
#####################################################################################################################################
# Use code below for running from custom connector on PSM
#$PSMStatus.Text = "NOT RUNNING FROM PSM"
#$tooltip1.SetToolTip($PSMStatus, "THIS UTILITY MUST BE EXECUTED FROM THE PRIVILEGED SESSION MANAGER.")
#####################################################################################################################################
$ButtonSearch.Enabled = $false
$InputBoxLabel.Visible = $false
$InputBox.Visible = $false
}
#endregion
}
#endregion FormEvent_Load
#region Form_StateCorrection_Load
$Form_StateCorrection_Load=
{
#Correct the initial state of the form to prevent the .Net maximized form issue
$form1.WindowState = $InitialFormWindowState
}
#endregion Form_StateCorrection_Load
#region Get-UserInfo Function
# Function to check if the user ID entered is in the Active Directory group that provides access into CyberArk
Function Get-UserInfo {
<#
.SYNOPSIS
Function that queries a Active Directory user object to retrieve attributes
.DESCRIPTION
This function will use the parameter passed as the user name to query Active Directory and retrieve several user object attributes
The function has a mandatory string parameter of an Active Directory user
.EXAMPLE
Get-UserInfo 'john'
The above example will check to see if the user exists in Active Directory. If the user exists, query the user object
to get the givenName, surName, samAccountName, if the account is enabled and is a member of the Active Directory group that is
contained within the StationSuspendedTool.ini
.EXAMPLE
$allusersoutput, $userfound, $grpmember, $fail = Get-UserInfo 'john'
.PARAMETER string
The string passed as a parameter to the function is the Active Directory user name to query
.NOTES
Author: Kevin Elwell <Elwell1@gmail.com>
Version: 1.0 - 2016/12/6 - Initial release
Version: 1.3 - 2016/12/9 - Added input validation and message boxes
#>
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[string]$ADUserNAme
)
#region Super Secret Admin
# By providing a special alphanumeric character prefix, we enable a hidden button that will run the DEACTIVATETRUSTEDNETWORKAREA function
# and then the ACTIVATETRUSTEDNETWORKAREA function. IMPORTANT: the prefix defined in the StationSuspendedTool.ini MUST BE NUMBERS OR CAPITAL LETTERS
# Get CyberArk Active Directory group from the StationSuspendedTool.ini and check if the user name passed to the function is a member of the group
$SSAPrefix = $FileContent["AdminFunctions"]["SuperSecretAdminPrefix"]
# Initialize $IsSecretAdmin to $False
$IsSecretAdmin = $False
# Check to see if $ADUserNAme starts with the super secret characters
$SuperSecretAdmin = $ADUserNAme.StartsWith("$SSAPrefix")
If($SuperSecretAdmin) {
# Set $IsSecretAdmin to $True
$IsSecretAdmin = $True
# Since the user entered is a super secret admin, trim off $SSAPrefix from $ADUserNAme
$ADUserNAme = $ADUserNAme.TrimStart("$SSAPrefix")
}
#endregion Super Secret Admin
# Validate the $ADUserNAme does not contail illegal characters
If($ADUserNAme -cnotmatch "^[a-zA-Z0-9]*$") {
# Display error dialog popup
$message = "ERROR: THE USERNAME YOU ENTERED ""$ADUserNAme""CONTAINS NON-ALPHANUMERIC CHARACTERS AND/OR SPACES.`r`n`r`nPLEASE TRY AGAIN."
$caption = "ERROR"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
$msgbox1 = [System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
}
# Get CyberArk Active Directory group from the StationSuspendedTool.ini and check if the user name passed to the function is a member of the group
$CAADUserGroup = $FileContent["ActiveDirectory"]["CyberArkADUserGroup"]
# Initialize some variables to $false
[boolean]$returnValue = $false
[boolean]$failed = $false
[boolean]$found = $false
# Create array for the results to be stored in
$output = @()
# Query Active Directory user object attributes "givenName, Surname, SamAccountName and Enabled" for the user object passed to the function
Try {
If($allusers = Get-ADUser -filter {sAMACCOUNTName -eq $ADUserNAme} -properties givenName, Surname, samAccountName, Enabled | Select givenName, Surname, SamAccountName, Enabled -ErrorAction Stop) {
# Add results to the array
$output += $allusers
# User object exists in Active Directory, proceed to checking user object group membership
# Set variable $found to $true
[boolean]$found = $true
# If the user object exists in Active Directory, check to see if its a member of the CyberArk Active Directory group
$CAADGroupMembers = Get-ADGroupMember -Identity $CAADUserGroup -Recursive | Select -ExpandProperty samAccountName -ErrorAction Stop
# Based on checking Active Directory group membership, assign true/false to $returnVal variable for use later in script
if ($CAADGroupMembers -eq $ADUserNAme) {
# Set variable $returnValue to $true
[boolean]$returnValue = $true
}else{
# If $returnValue = $false, the user exists in Active Directory but is not in the $CAADUserGroup. Display error message to user.
If($returnValue -eq $false) {
# Display error dialog popup
$message = "ERROR: ""$ADUserNAme"" WAS FOUND IN ACTIVE DIRECTORY.`r`n`r`nHOWEVER, THE USER IS NOT IN THE ""$CAADUserGroup"" ACTIVE DIRECTORY GROUP."
$caption = "ERROR"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
$msgbox2 = [System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
}
}
}else{
# User object does NOT exist in Active Directory
# Set variable $allusers to $false
[boolean]$allusers = $false
# User object does NOT exist in Active Directory
If($allusers -eq $false) {
# Display error dialog popup
$message = "ERROR: ""$ADUserNAme"" WAS NOT FOUND IN ACTIVE DIRECTORY."
$caption = "ERROR"
$buttons = [System.Windows.Forms.MessageBoxButtons]::OK
$icon = [System.Windows.Forms.MessageBoxIcon]::Error
$msgbox3 = [System.Windows.Forms.MessageBox]::Show($message,$caption,$buttons,$icon)
}
}
}
# Catch errors here
Catch {
Write-host $_.Exception.Message
[boolean]$failed = $true
}
Return $output, $found, $returnValue, $failed, $IsSecretAdmin
}
#endregion Get-UserInfo Function
#region PACLI Functions
Function PACLIinit {
# Initialize the $ex Variable to a null value
$ex = ""
# Initialize the PACLI
& $PathtoPACLI INIT
# Capture the exit code
$ex = $LASTEXITCODE
Return $ex
}
Function PACLIparamfile {
# Initialize the $ex Variable to a null value
$ex = ""
# Define parameters from various ini files
[string]$VaultName = $VaultContent["_"]["Vault"]
# Trim off the leading/trailing space if present
[string]$VaultName = $VaultName.Trim()
# Trim off the double quotes if present
[string]$VaultName = $VaultName.Replace('"',"")
# Define param file
& $PathtoPACLI DEFINEFROMFILE VAULT=`"$VaultName`" PARMFILE=`"$VaultIni`"
# Capture the exit code
$ex = $LASTEXITCODE
Return $ex
}
Function PACLIlogon {
# Initialize the $ex Variable to a null value
$ex = ""
# Define parameters from various ini files
[string]$VaultName = $VaultContent["_"]["Vault"]
# Trim off the leading/trailing space if present
[string]$VaultName = $VaultName.Trim()
# Trim off the double quotes if present
[string]$VaultName = $VaultName.Replace('"',"")
[string]$LogonUser = $logonContent["_"]["Username"]
#PACLI logon
& $PathtoPACLI LOGON VAULT=`"$VaultName`" USER=`"$LogonUser`" LOGONFILE=`"$logonIni`"
# Capture the exit code
$ex = $LASTEXITCODE
Return $ex
}
Function PACLIuserinfo {
# Initialize the $ex Variable to a null value
$ex = ""
# Define parameters from various ini files
[string]$VaultName = $VaultContent["_"]["Vault"]
# Trim off the leading/trailing space if present
[string]$VaultName = $VaultName.Trim()
# Trim off the double quotes if present
[string]$VaultName = $VaultName.Replace('"',"")
[string]$LogonUser = $logonContent["_"]["Username"]
# PACLI get user info
$PACLICheckLockedOut = & $PathtoPACLI TRUSTEDNETWORKAREASLIST VAULT=`"$VaultName`" USER=`"$LogonUser`" TRUSTERNAME=`"$networkID`" --% OUTPUT(NAME,ACTIVE,VIOLATIONCOUNT)
# Split results of get user info into 3 variables
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$trustedNetworkName, $UserActive, $failCount = $PACLICheckLockedOut.Split(' ',3, $option)
# Station suspended ($UserActive -eq "YES")
If($UserActive -eq "YES"-and $failCount -ne 5){
$UserActive = "FALSE"
}
# Station suspended due to 5 or more failed login attempts ($UserActive -eq "YES" and $failCount -eq 5)
If($UserActive -eq "YES" -and $failCount -eq 5){
$UserActive = "TRUE"
}
# Station NOT suspended ($UserActive -eq "NO")
If($UserActive -eq "NO"){
$UserActive = "TRUE"
}
# Capture the exit code
$ex = $LASTEXITCODE
Return $ex, $trustedNetworkName, $UserActive, $failCount
}
Function PACLIactivateuser {
# Initialize the $ex Variable to a null value
$ex = ""
# Define parameters from various ini files
[string]$VaultName = $VaultContent["_"]["Vault"]
# Trim off the leading/trailing space if present
[string]$VaultName = $VaultName.Trim()
# Trim off the double quotes if present
[string]$VaultName = $VaultName.Replace('"',"")
[string]$LogonUser = $logonContent["_"]["Username"]
[string]$networkArea = $FileContent["CyberArk"]["NetworkArea"]
# Activate user
& $PathtoPACLI ACTIVATETRUSTEDNETWORKAREA VAULT=`"$VaultName`" USER=`"$LogonUser`" TRUSTERNAME=`"$networkID`" NETWORKAREA=`"$networkArea`"
# Capture the exit code
$ex = $LASTEXITCODE
Return $ex
}
Function PACLIdeactivateuser {
# Initialize the $ex Variable to a null value
$ex = ""
# Define parameters from various ini files
[string]$VaultName = $VaultContent["_"]["Vault"]
# Trim off the leading/trailing space if present
[string]$VaultName = $VaultName.Trim()
# Trim off the double quotes if present
[string]$VaultName = $VaultName.Replace('"',"")
[string]$LogonUser = $logonContent["_"]["Username"]
[string]$networkArea = $FileContent["CyberArk"]["NetworkArea"]
# Deactivate user
& $PathtoPACLI DEACTIVATETRUSTEDNETWORKAREA VAULT=`"$VaultName`" USER=`"$LogonUser`" TRUSTERNAME=`"$networkID`" NETWORKAREA=`"$networkArea`"
# Capture the exit code
$ex = $LASTEXITCODE
Return $ex
}
Function PACLIlogoff {
# Initialize the $ex Variable to a null value
$ex = ""
# Define parameters from various ini files
[string]$VaultName = $VaultContent["_"]["Vault"]
# Trim off the leading/trailing space if present
[string]$VaultName = $VaultName.Trim()
# Trim off the double quotes if present
[string]$VaultName = $VaultName.Replace('"',"")
[string]$LogonUser = $logonContent["_"]["Username"]
#PACLI logoff
& $PathtoPACLI LOGOFF VAULT=`"$VaultName`" USER=`"$LogonUser`"
# Capture the exit code
$ex = $LASTEXITCODE
Return $ex
}
Function PACLIterm {
# Initialize the $ex Variable to a null value
$ex = ""
# PACLI TERM
& $PathtoPACLI TERM
# Capture the exit code
$ex = $LASTEXITCODE
Return $ex
}
#endregion PACLI Functions
#region handler_btnSearch_Click
$handler_btnSearch_Click={
# Get the username entered
#$UserName = $InputBox.Text
$Script:UserName = $InputBox.Text
[boolean]$enabled = "False"
#Clear the inputbox text after clicking the Search button
$InputBox.Clear()
$outputBox.Clear()
$outputBox1.Clear()
$outputBox3.Clear()
$outputBox4.Clear()
$outputBox.Refresh()
$outputBox1.Refresh()
$outputBox3.Refresh()
$outputBox4.Refresh()
$form1.controls.Remove($pictureBox)
# Disable Search button after a search
$ButtonSearch.Enabled = $false
# Execute the Get-UserInfo function and get the results into several variables
$allusersoutput, $userfound, $grpmember, $fail, $IsSSA = Get-UserInfo $UserName
################ code broken here ################
# need to NOT execute the PACLI functions if the user is NOT in the correct AD group