Guest User

Untitled

a guest
Apr 5th, 2018
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.53 KB | None | 0 0
  1. [CmdletBinding()]
  2. Param (
  3. [Parameter(Mandatory=$True)]
  4. [string]$file,
  5.  
  6. [Parameter(Mandatory=$True)]
  7. [string]$cred
  8.  
  9. )
  10.  
  11.  
  12.  
  13. #================================================================================================
  14. # LOAD DLL AES Encrypt
  15. #================================================================================================
  16.  
  17. #Add-Type -Path "$PSScriptRoot\AESDLL.dll"
  18.  
  19. [System.Reflection.Assembly]::LoadFrom("D:\Scheduled_Tasks\CyberArkAutoChange\AESDLL.dll")
  20.  
  21. $hex = New-Object AESClass.cCrypt
  22.  
  23.  
  24. #================================================================================================
  25. # functions
  26. #================================================================================================
  27.  
  28. Function Parse-IniFile ($file)
  29. {
  30. $ini = @{ }
  31. $section = "_NO_SECTION"
  32. $ini[$section] = @{ }
  33. switch -regex (Get-Content $file)
  34. {
  35. '^\[(.+)\]$'
  36. {
  37. $section = $matches[1].Trim()
  38. if (-not $ini.ContainsKey($section)) { $ini[$section] = @{ } }
  39. }
  40. '^\s*([^#\[;].+?)\s*=\s*(.*)'
  41. {
  42. $name, $value = $matches[1 .. 2]
  43. $ini[$section][$name] = $value.Trim()
  44. }
  45. '^\s*([^;\[#][^=]+?)$'
  46. {
  47. $name = $matches[1].Trim()
  48. $value = ''
  49. $ini[$section][$name] = $value.Trim()
  50. }
  51. }
  52. $ini
  53. }
  54.  
  55. Function WriteLogFile
  56. {
  57.  
  58. Param ($Message, $checkHost)
  59.  
  60. $ScriptLogPath = "$PSScriptRoot\Logs\" # + "\Log\"
  61.  
  62. #Separate Creation Log
  63.  
  64. if($checkHost)
  65. {
  66. $LogFileName = $checkHost + "_CyberArkWebReq_Created_$cred.txt"
  67. }
  68. else
  69. {
  70. $LogFileName = "CyberArkWebReq_$cred.txt"
  71. }
  72.  
  73. $path = [System.IO.Path]::Combine($ScriptLogPath, $LogFileName)
  74. $mode = [System.IO.FileMode]::Append
  75. $access = [System.IO.FileAccess]::Write
  76.  
  77. $fs = New-Object IO.FileStream($path, $mode, $access)
  78. $sw = New-Object System.IO.StreamWriter($fs)
  79.  
  80. $a = Get-Date
  81. $Now = $a.ToShortDateString() + " " + $a.ToShortTimeString()
  82.  
  83. $sw.WriteLine("$Now - $Message")
  84. $sw.Close()
  85. $fs.Close()
  86.  
  87. }
  88.  
  89. #Initial Variables
  90.  
  91. Write-Host "file ist $file"
  92. Write-Host "cred ist $cred"
  93. WriteLogFile "[INFORMATION] Credentials zum Anmelden: $cred"
  94.  
  95. $files = Get-ChildItem -Path D:\WEBROOT\CyberArkRequest\data
  96.  
  97. #random File picker
  98. $RandomFile = Get-Random -InputObject $files -Count 1
  99.  
  100. write-host $files -ForegroundColor Green
  101.  
  102.  
  103.  
  104. $fileNotDel = $false
  105. #Decrypt file
  106. $dataToDecrypt = $file
  107. write-host $dataToDecrypt -ForegroundColor Yellow
  108.  
  109. $hex.HexToString($dataToDecrypt);
  110. $hex.Decrypt(256, $hex.NormalString, "")
  111. $decryptData = $hex.DecryptedString
  112.  
  113. if($decryptData -eq "4625")
  114. {
  115. WriteLogFile "[ERROR] File $decryptData konnte nicht verschlüsselt werden"
  116. write-host $decryptData -ForegroundColor Red
  117. }
  118. elseif($decryptData -eq "4626")
  119. {
  120. WriteLogFile "[ERROR] File $decryptData konnte nicht entschlüsselt werden"
  121. write-host $decryptData -ForegroundColor Red
  122. }
  123. else
  124. {
  125.  
  126. #Preparing File for Password Change
  127. $splitFile = $decryptData -split ("_")
  128. $hostname = $splitFile[0]
  129. $domain = ($splitFile[1]).Replace("client.", "")
  130. $ip = $splitFile[2]
  131.  
  132.  
  133. WriteLogFile "[INFORMATION] Hostüberprüfung $hostname mit $ip wird druchgeführt"
  134.  
  135. $HostFQDN = $hostname + "." + $domain
  136.  
  137. $ADResult = Get-ADComputer $hostname -Server $domain -Properties CanonicalName
  138.  
  139. $return = $ADResult.CanonicalName.Contains("")
  140.  
  141. $SpecialComp = Parse-IniFile "D:\Scheduled_Tasks\CyberArkAutoChange\config.ini"
  142.  
  143. write-host "hostname ist: $hostname" -ForegroundColor Yellow
  144. write-host "domain ist: $domain"
  145. #write-host "safe ist: $CASafe" -ForegroundColor Yellow
  146. $CASafe = $null
  147. $CAPolicy = $null
  148.  
  149. if(($SpecialComp.ADTeamComp.Values).contains($hostname) -eq $true)
  150. {
  151. $CASafe = ""
  152. $CAPolicy = ""
  153. }
  154.  
  155. write-host "safe ist: $CASafe" -ForegroundColor Yellow
  156. WriteLogFile "[INFORMATION] $hostname ist im Safe $CASafe abgelegt"
  157.  
  158. #========================================================================================
  159. # Cyberark Trigger Configuration
  160. #========================================================================================
  161.  
  162. # configuration file
  163. $ConfigFile = "$PSScriptRoot\autoChangeAccountConfig.xml"
  164.  
  165. # read configuration file
  166. If (Test-Path $ConfigFile)
  167. {
  168. # config file exists :-) read it!
  169. $cfg = Import-Clixml $ConfigFile
  170. }
  171. Else
  172. {
  173. WriteLogFile "[INFORMATION] $ConfigFile existiert nicht. Es wird ein neues angelegt. Bitte prüfen!"
  174. # config file does not exist :-/ - create it with default values
  175. $cfg = @{}
  176. $cfg.CyberArkUser = "LogonUser"
  177.  
  178. $cfg.CyberArkVaultName = "Vault"
  179. $cfg.CyberArkPathToPacli = "D:\Cyberark\Pacli\Pacli.exe"
  180. $cfg.CyberArkPathToVaultIni = "D:\Cyberark\Pacli\Vault.ini"
  181. $cfg.PacliDebugOutput = "true"
  182. $cfg | Export-Clixml $ConfigFile
  183. Write-Host "no config file found. created a sample config. please review!"
  184. break
  185. }
  186.  
  187. # apply config to correct variables for pacli_functions.ps1 to work
  188. #$username = $cfg.CyberArkUser
  189. $username = $cred
  190. $vault = $cfg.CyberArkVaultName
  191. $pacli_path = $cfg.CyberArkPathToPacli
  192. $parm_file = $cfg.CyberArkPathToVaultIni
  193. $output_command = $cfg.PacliDebugOutput
  194.  
  195. # path configuration
  196. $scriptPath = $PSScriptRoot
  197. $cred_file_path = $scriptPath
  198. $global:logfile = "$scriptPath\Logs\log.txt"
  199.  
  200. # delete logfile if older than the $limit.
  201. $limit = (Get-Date).AddDays(-5)
  202. if(Test-Path $logfile)
  203. {
  204. $logfile | Where-Object {$_.CreationTime -lt $limit } | Remove-Item -Force
  205. Write-Host "Logfile is olden than $limit - delete"
  206. #WriteLogFile "[WARNING] Logfile is older than $limit - delete"
  207. }
  208.  
  209. #========================================================================================
  210. # Cyberark Trigger start
  211. #========================================================================================
  212.  
  213. WriteLogFile "[INFORMATION] Trigger wird nun bearbeitet"
  214.  
  215. # Include Pacli Functions
  216. ."D:\Cyberark\Scripts\Functions\pacli_functions.ps1"
  217.  
  218. $AccountName = "Administrator@" + $HostFQDN
  219. $Safe = $CASafe
  220.  
  221. # Log Parameters
  222. writelog $username "i" "============ Start Script ============="
  223. writelog $username "i" "CyberArk User = $username"
  224. writelog $username "i" "CyberArk Vault Name = $vault"
  225. writelog $username "i" "CyberArk Path To Pacli = $pacli_path"
  226. writelog $username "i" "CyberArk Path To Vault.ini = $parm_file"
  227. writelog $username "i" "CREDFILE Path = $cred_file_path"
  228. writelog $username "i" ""
  229. writelog $username "i" "Safe = $Safe"
  230. writelog $username "i" "AccountName = $AccountName"
  231. writelog $username "i" ""
  232.  
  233. # Check if Pacli Executable is available
  234. test_path $pacli_path
  235.  
  236. # Initialize PACLI Session
  237. if(pacli_init -eq "failed"){
  238. writelog $username "e" " -- Error on Function PACLI INIT, check Vault Connection"
  239. WriteLogFile "[ERROR] $username e -- Error on Function PACLI INIT, check Vault Connection"
  240. break
  241. }
  242.  
  243. # Set PACLI defaults
  244. if(pacli_definesafe -eq "failed"){
  245. writelog $username "e" " -- on Function PACLI Definesafe, check Vault Connection"
  246. WriteLogFile "[ERROR] $username e -- on Function PACLI Definesafe, check Vault Connection"
  247. pacli_term
  248. break
  249. }
  250.  
  251. # Logon on Vault Server
  252. if(pacli_logon $username -eq "failed"){
  253. writelog $username "e" " -- PACLI Logon failed, check credential file"
  254. WriteLogFile "[ERROR] $username e -- PACLI Logon failed, check credential file"
  255. pacli_term
  256. break
  257.  
  258. }
  259.  
  260. # Schedule Account for Reconcile (CPM will start reconciliation with next scan as defined in Platform: ImmediateInterval)
  261. writelog $username "i" "Mark Account for Changing Password ..."
  262.  
  263. # open safe
  264. pacli_open_safe $Safe
  265.  
  266. # Updating Client IP Address
  267. $UpdateReturn = pacli_filecategory_update $AccountName $Safe "Address" "$HostFQDN"
  268.  
  269.  
  270. WriteLogFile "[INFORMATION] Safe überprüfung $UpdateReturn"
  271.  
  272. #Checking if Account is exists
  273. if($UpdateReturn -match "ITATS053E")
  274. {
  275.  
  276. $AccountPassword = ""
  277. $AccountUsername = $AccountName.Split("@")[0]
  278.  
  279. $CA_UserName = $AccountUsername
  280. $CA_DeviceType = "Operating System"
  281. $CA_PolicyID = $CAPolicy
  282. $CA_Description = "Client $hostname"
  283. write-host $CA_UserName
  284. Write-Host $CA_DeviceType
  285. Write-Host $CA_PolicyID
  286. Write-Host $CA_Description
  287.  
  288. try
  289. {
  290. WriteLogFile "[INFORMATION] Host $hostname is im Safe $CASafe nicht vorhanden"
  291. WriteLogFile "[INFORMATION] Host $hostname wird im Safe $CASafe angelegt"
  292. $ADDAccountState = pacli_add_account $Safe $AccountName $AccountUsername $AccountPassword
  293.  
  294. #pause;
  295.  
  296. pacli_filecategory_add $AccountName $Safe "RCH_Description" $CA_Description
  297. #pause;
  298. pacli_filecategory_add $AccountName $Safe "PolicyID" $CA_PolicyID
  299. pacli_filecategory_add $AccountName $Safe "DeviceType" $CA_DeviceType
  300. pacli_filecategory_add $AccountName $Safe "UserName" $CA_UserName
  301.  
  302. write-host $ADDAccountState -ForegroundColor Yellow
  303.  
  304. pacli_filecategory_delete $AccountName $Safe "ResetImmediately"
  305. pacli_filecategory_add $AccountName $Safe "RetriesCount" "-1"
  306. pacli_filecategory_add $AccountName $Safe "ResetImmediately" "ReconcileTask"
  307.  
  308.  
  309. pacli_filecategory_delete $AccountName $Safe "CPMErrorDetails"
  310. pacli_filecategory_delete $AccountName $Safe "CPMStatus"
  311. pacli_filecategory_delete $AccountName $Safe "RetriesCount"
  312. pacli_filecategory_delete $AccountName $Safe "CPMDisabled"
  313. pacli_filecategory_delete $AccountName $Safe "LastTask"
  314. pacli_filecategory_delete $AccountName $Safe "LastFailDate"
  315.  
  316. $fileNotDel = $true
  317.  
  318. }
  319. catch
  320. {
  321. WriteLogFile "[ERROR] Host $hostname konnte im Safe $CASafe nicht angelegt werden" $hostname
  322. }
  323.  
  324.  
  325.  
  326. }
  327. else
  328. {
  329. WriteLogFile "[INFORMATION] Host $hostname is im Safe $CASafe vorhanden"
  330. $fileNotDel = $false
  331. # set for change task
  332.  
  333. $AccountUsername = $AccountName.Split("@")[0]
  334.  
  335. $CA_UserName = $AccountUsername
  336. $CA_DeviceType = "Operating System"
  337. $CA_PolicyID = $CAPolicy
  338. $CA_Description = "Client $hostname"
  339. write-host $CA_UserName
  340. Write-Host $CA_DeviceType
  341. Write-Host $CA_PolicyID
  342. Write-Host $CA_Description
  343.  
  344. pacli_filecategory_add $AccountName $Safe "RCH_Description" $CA_Description
  345.  
  346. pacli_filecategory_add $AccountName $Safe "PolicyID" $CA_PolicyID
  347. pacli_filecategory_add $AccountName $Safe "DeviceType" $CA_DeviceType
  348. pacli_filecategory_add $AccountName $Safe "UserName" $CA_UserName
  349.  
  350. pacli_filecategory_delete $AccountName $Safe "ResetImmediately"
  351. pacli_filecategory_add $AccountName $Safe "RetriesCount" "-1"
  352. pacli_filecategory_add $AccountName $Safe "ResetImmediately" "ReconcileTask"
  353.  
  354.  
  355. pacli_filecategory_delete $AccountName $Safe "CPMErrorDetails"
  356. pacli_filecategory_delete $AccountName $Safe "CPMStatus"
  357. pacli_filecategory_delete $AccountName $Safe "RetriesCount"
  358. pacli_filecategory_delete $AccountName $Safe "CPMDisabled"
  359. pacli_filecategory_delete $AccountName $Safe "LastTask"
  360. pacli_filecategory_delete $AccountName $Safe "LastFailDate"
  361.  
  362. }
  363.  
  364.  
  365.  
  366. # close safe
  367. pacli_close_safe $Safe
  368.  
  369. # Logoff from Vault
  370. pacli_logoff
  371.  
  372. # Terminate Session
  373. pacli_term
  374.  
  375. writelog $username "i" "============ Script finished ============="
  376. #WriteLogFile "[SUCCESSFULL] Trigger für den User $AccountName wurde erfolgreich ausgelöst"
  377.  
  378. #Removing File
  379.  
  380. $deletefile = Get-ChildItem -Path "D:\WEBROOT\CyberArkRequest\data\$file"
  381.  
  382. if($fileNotDel -eq $true)
  383. {
  384. $filename = $deletefile.Name
  385. WriteLogFile "[INFORMATION] File not deleted: $filename" $hostname
  386. #WriteLogFile "[INFORMATION] File not deleted: $filename"
  387.  
  388. }
  389. else
  390. {
  391. $filename = $deletefile.Name
  392. try
  393. {
  394. $deletefile | Remove-Item -Force
  395. WriteLogFile "[INFORMATION] File deleted: $filename"
  396. WriteLogFile "[SUCCESSFULL] Trigger für den User $AccountName wurde erfolgreich ausgelöst"
  397. }
  398. catch
  399. {
  400. $exceptionMessage = $_.exception.message
  401. WriteLogFile "[ERROR] File not deleted: $exceptionMessage"
  402. }
  403.  
  404. }
  405.  
  406. }
Add Comment
Please, Sign In to add comment