Monday, September 9, 2013

Obfuscating passwords from nosy coworkers in PowerShell and batch script

First things first: Obfuscation IS NOT SECURITY! My usage case is assuming I’m not worried about security intrusions from malicious external sources. I have some scripts that run particular tasks automatically and I don't want them to prompt me for login. That requires credentials and passwords and such. I could leave plain text passwords lying around, but I don't want nosy coworkers finding them.

PowerShell

Let's obfuscate some passwords! First with PowerShell (Credit to Frank Richard):

Say your password is "ABCD" and you want to obfuscate it, let's start with the first letter, "A", in its byte character hexadecimal format. That's "41" (hex), or "65" in decimal.

The super-simple obfuscation will just add 1 to the decimal number and store it in a text file:

$pwd = "ABCD"
$pwdEncoded = ""
$pwd.ToCharArray() | Foreach { $pwdEncoded = $pwdEncoded = $pwdEncoded + ([BYTE][CHAR]($_)+1) + " " }

And that's it. Now $pwdEncoded contains each character of my password as its decimal representation + 1:

66 67 68 69

Store that string in a text file, and all you have to do to retrieve it again is this:

$strEncoded = Get-Content C:\pwdEncoded.txt
$pwd = ""

$strEncoded.Trim().Split(" ") | Foreach { $pwd = $pwd + [CHAR][BYTE](($_)-1) }

Now, $pwd contains your password and you can use it to create PowerShell credentials and so on.


Batch Script

I found that the easiest way to accomplish obfuscation in a batch script was using CertUtil.

Assuming your password is currently sitting in a text file, you can encode a binary file to Base64 (using the cmd console):

CertUtil -f -v -encode C:\pwd.txt C:\pwdout.txt

Using our previous example of "ABCD", our output would look like this in "pwdout.txt":

-----BEGIN CERTIFICATE-----
QUJDRA==
-----END CERTIFICATE-----

Now all we have to do to read is read the obfuscated password by decoding it again and getting rid of the evidence:

CertUtil -f -v -decode C:\pwdout.txt C:\pwdin.txt
set /p var=<C:\pwdin.txt
del C:\pwdout.txt
del C:\pwdin.txt

Now the password is stored in "var". Take careful note of the spacing on that particular line: 

var=<C:\pwdin.txt

It's important to notice that there are NO SPACES after the "=" sign. If I had, there would be an extra space in my password and I'd have to trim it out instead. This way I avoid that.

No comments:

Post a Comment