Citrix Netscaler: Full backup of Netscaler config - part I. Encrypting Credentials




In first part of article "Full backup of Netscaler config" I've prepared first powershell script which can store password for specific account in encrypted text file. In production scripts, putting your passwords in plain text should be a cardinal sin. When password is encrypted in file, only one account which can read file as plain text is this same account. The second great limitation is that this file can by decrypted only in operating system, which has been used for encryption. Very clear explanation how it works is here.
My final script save password to .txt file in destination where script was run.

encrypt_pass_for_user.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
function msgbox {
    param (
        [string]$Message,
        [string]$Title = 'Info',   
        [string]$buttons = 'OK'
    )
    # This function displays a message box by calling the .Net Windows.Forms (MessageBox class)
     
    # Load the assembly
    Add-Type -AssemblyName System.Windows.Forms | Out-Null
     
    # Define the button types
    switch ($buttons) {
       'ok' {$btn = [System.Windows.Forms.MessageBoxButtons]::OK; break}
       'okcancel' {$btn = [System.Windows.Forms.MessageBoxButtons]::OKCancel; break}
       'AbortRetryIgnore' {$btn = [System.Windows.Forms.MessageBoxButtons]::AbortRetryIgnore; break}
       'YesNoCancel' {$btn = [System.Windows.Forms.MessageBoxButtons]::YesNoCancel; break}
       'YesNo' {$btn = [System.Windows.Forms.MessageBoxButtons]::yesno; break}
       'RetryCancel'{$btn = [System.Windows.Forms.MessageBoxButtons]::RetryCancel; break}
       default {$btn = [System.Windows.Forms.MessageBoxButtons]::RetryCancel; break}
    }
     
      # Display the message box
      $Return=[System.Windows.Forms.MessageBox]::Show($Message,$Title,$btn)
      $Return
}

(Get-Credential).Password | ConvertFrom-SecureString | Out-File "SFTP_user.txt"

if (Test-Path "SFTP_user.txt") {
    msgbox "Password saved to SFTP_user.txt"
}
else {
    msgbox "Can not save password to SFTP_user.txt"
}


When we want load password from file to variable, we have to use this par of code in our script:
1
2
3
4
$SFTP_user_file = "SFTP_user.txt"
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR((Get-Content $SFTP_user_file | ConvertTo-SecureString))
$nspass = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($BSTR)


Now we can use variable $nspass anywhare in code, for example when we want connect to Netscaler:
1
$payload = @{"login" = @{"username"=$nsuser;"password"=$nspass;"timeout"=60}}

sources:
[1] - https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-1/
[2] - https://www.pdq.com/blog/secure-password-with-powershell-encrypting-credentials-part-2/

Comments

Popular Posts