forked from cyberark/epv-api-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CreateAutomaticOnboardingRules.ps1
241 lines (213 loc) · 15.5 KB
/
CreateAutomaticOnboardingRules.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
###########################################################################
#
# NAME: Create Automatic Onboarding Rules using REST API
#
# AUTHOR: Assaf Miron
#
# COMMENT:
# This script will create an Automatic Onboarding rule for Discovered Privileged Local Accounts.
# The script will apply to the filters defined in the script parameters (Machine Type, Target Safe)
#
# VERSION HISTORY:
# 1.0 08/01/2017 - Initial release
# 1.1 10/01/2017 - Bug fixes and updates
# 1.2 16/01/2017 - Added parameter validations and better rules parsing
# 1.3 25/01/2017 - Added Get, Create and Delete use cases
#
###########################################################################
[CmdletBinding(DefaultParametersetName="Get")]
param
(
[Parameter(Mandatory=$true,HelpMessage="Enter the PVWA URL")]
[ValidateScript({Invoke-WebRequest -UseBasicParsing -DisableKeepAlive -Uri $_ -Method 'Head' -ErrorAction 'stop' -TimeoutSec 30})]
[Alias("url")]
[String]$PVWAURL,
# Use this switch to get rules details only
[Parameter(ParameterSetName='Get',Mandatory=$false)][switch]$Get,
# Use this switch to create new rules
[Parameter(ParameterSetName='Create',Mandatory=$false)][switch]$Create,
[Parameter(ParameterSetName='Create',Mandatory=$false)]
[ValidateSet("Windows","Unix")]
[String]$SystemType,
[Parameter(ParameterSetName='Create',Mandatory=$false)]
[ValidateSet("Server","Workstation")]
[String]$MachineType,
[Parameter(ParameterSetName='Create',Mandatory=$false,HelpMessage="Enter a filter User name")]
[String]$UserName,
[Parameter(ParameterSetName='Create',Mandatory=$false,HelpMessage="Enter the destination Safe name")]
[String]$SafeName,
# User this switch to delete a rule
[Parameter(ParameterSetName='Delete',Mandatory=$false)][switch]$Delete,
[Parameter(ParameterSetName='Delete',Mandatory=$false,HelpMessage="Enter the Rule ID for deletion")]
[int]$RuleID
)
# Get Script Location
$ScriptLocation = Split-Path -Parent $MyInvocation.MyCommand.Path
# Global URLS
# -----------
$URL_PVWAWebServices = $PVWAURL+"/WebServices"
$URL_PVWAAPI = $PVWAURL+"/api"
$URL_CyberArkAuthentication = $URL_PVWAWebServices+"/auth/Cyberark/CyberArkAuthenticationService.svc"
#$URL_CyberArkAuthentication = $URL_PVWAAPI+"/auth/cyberark"
$URL_CyberArkLogon = $URL_CyberArkAuthentication+"/Logon"
$URL_CyberArkLogoff = $URL_CyberArkAuthentication+"/Logoff"
# URL Methods
# -----------
$URL_OnboardRules = $URL_PVWAAPI+"/AutomaticOnboardingRules"
# Initialize Script Variables
# ---------------------------
$rstusername = $rstpassword = ""
$logonToken = ""
$Platform = ""
$isUID = $False
#region Functions
Function Test-CommandExists
{
Param ($command)
$oldPreference = $ErrorActionPreference
$ErrorActionPreference = 'stop'
try {if(Get-Command $command){RETURN $true}}
Catch {Write-Host "$command does not exist"; RETURN $false}
Finally {$ErrorActionPreference=$oldPreference}
} #end function test-CommandExists
#endregion
If (Test-CommandExists Invoke-RestMethod)
{
# Check that the PVWA URL is OK
If ($PVWAURL -ne "")
{
If ($PVWAURL.Substring($PVWAURL.Length-1) -eq "/")
{
$PVWAURL = $PVWAURL.Substring(0,$PVWAURL.Length-1)
}
}
else
{
Write-Host -ForegroundColor Red "PVWA URL can not be empty"
exit
}
#region [Logon]
# Get Credentials to Login
# ------------------------
$caption = "Create Automatic Onboarding Rule"
$msg = "Enter your User name and Password";
$creds = $Host.UI.PromptForCredential($caption,$msg,"","")
$rstusername = $creds.username.Replace('\','');
$rstpassword = $creds.GetNetworkCredential().password
# Create the POST Body for the Logon
# ----------------------------------
$logonBody = @{ username=$rstusername;password=$rstpassword }
$logonBody = $logonBody | ConvertTo-Json
try{
# Logon
$logonResult = Invoke-RestMethod -Method Post -Uri $URL_CyberArkLogon -Body $logonBody -ContentType "application/json"
# Save the Logon Result - The Logon Token
$logonToken = $logonResult.CyberArkLogonResult
}
catch
{
Write-Host -ForegroundColor Red $_.Exception.Response.StatusDescription
$logonToken = ""
}
If ($logonToken -eq "")
{
Write-Host -ForegroundColor Red "Logon Token is Empty - Cannot login"
exit
}
# Create a Logon Token Header (This will be used through out all the script)
# ---------------------------
$logonHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$logonHeader.Add("Authorization", $logonToken)
#endregion
# Validate input
switch($PsCmdlet.ParameterSetName)
{
"Get"
{
# Get all available Automatic Rules defined
Write-Host "Retriving rules..."
try {
$GetRuleResponse = Invoke-RestMethod -Method Get -Uri $URL_OnboardRules -Headers $logonHeader -ContentType "application/json" -TimeoutSec 3600000
} catch {
Write-Error $_.Exception.Response.StatusDescription
}
if($GetRuleResponse.AutomaticOnboardingRules.Length -eq 0)
{
Write-Host "Currently No rules defined"
}
else
{
Write-Host "Currently available rules:"
$arrRules = @()
foreach($rule in $GetRuleResponse.AutomaticOnboardingRules){
$arrRules += $($rule | Select RuleId, RuleName, DecisionPlatformId, DecisionSafeName, UserNameFilter)
}
$arrRules | Format-Table -AutoSize
}
}
"Create"
{
if ($SystemType -eq "") { $SystemType = "Windows" }
if($SystemType -match "Win")
{
if(($MachineType -match "Server") -or ($MachineType -match "srv"))
{
$SystemType = "Windows"
$MachineType = "Server"
$Platform = "WinServerLocal"
}
elseif($MachineType -match "Workstation")
{
$SystemType = "Windows"
$MachineType = "Workstation"
$Platform = "WinDesktopLocal"
}
else{
$SystemType = "Windows"
$MachineType = "Server"
$Platform = "WinServerLocal"
}
}
elseif($SystemType -match "nix")
{
$SystemType = "Unix"
$MachineType = "Server"
$Platform = "UnixSSH"
$isUID=$True
}
if($UserName.Trim().length -eq 0)
{ $UserName = $null }
Write-Host "Creating rule..."
$bodyRule = @{DecisionPlatformId=$Platform;DecisionSafeName=$SafeName;IsAdminUIDFilter=$isUID;MachineTypeFilter=$MachineType;SystemTypeFilter=$SystemType;UserNameFilter=$UserName }
$restRuleCreate = $bodyRule | ConvertTo-Json
Write-Debug "[DEBUG] $restRuleCreate"
try {
# Create the Rule
$CreateRuleResponse = Invoke-RestMethod -Method Post -Uri $URL_OnboardRules -Headers $logonHeader -Body $restRuleCreate -ContentType "application/json" -TimeoutSec 3600000
} catch {
Write-Error $_.Exception.Response.StatusDescription
}
$CreateRuleResponse | Select RuleId, RuleName, DecisionPlatformId, DecisionSafeName, UserNameFilter | Format-Table -AutoSize
}
"Delete"
{
# Delete a specific Automatic Rule by ID
Write-Host "Deleting rule ID $RuleID..."
try {
$DeleteRuleResponse = Invoke-RestMethod -Method Delete -Uri "$URL_OnboardRules/$RuleID" -Headers $logonHeader -ContentType "application/json" -TimeoutSec 3600000
} catch {
Write-Error $_.Exception.Response.StatusDescription
}
If($DeleteRuleResponse -eq "")
{ Write-Host "Rule deleted successfully"}
}
}
# Logoff the session
# ------------------
Write-Host "Logoff Session..."
Invoke-RestMethod -Method Post -Uri $URL_CyberArkLogoff -Headers $logonHeader -ContentType "application/json" | Out-Null
}
else
{
Write-Error "This script requires Powershell version 3 or above"
}