Obfuscating sensitive text in shell scripts

For many years I’ve been using a simple method of obfuscating sensitive information in shell scripts. I can’t take the credit for this, as it was something inherited in my work environment.

This technique uses openssl to encrypt and decrypt a string of text without having to embed the sensitive data in plain text. Note, this isn’t proper private/public key-pair encryption, so treat this as simply obfuscating text.

First step in the process is to generate what can be referred to as a key file. The key file must contain a random string. The easiest way I find to do this is to use ssh-keygen and copy a large chunk of text either from the private key, or the public key, and save it in a file.

For example, key.txt contains the following:

AAAAB3NzaC1yc2EAAAADAQABAAABAQCpppktHMeS0D2wgxd0NdGAeNHIqcPNUoQ7LdYZLkDA4Y6Mq25wrkVh4ihekNhwiEyz+cdmhkpF4oMXu8ccg1vxRASBqq2GIJuwHMpkFVKmbxCq6+G5uQz8shvOLE5Egy6rWgltNkUSJpCJ9LJO2tI8Jvlyr34lrJvYTitI9E+4bGGXcmSXrG236RJKto6g4bV+IYszjAM6EHaIJwzILplhRApAETq23hEE9TVOw1POa6DbGhCSz+jwh2ZCSiod7yTeZy9DtPJ5rNm8FLJMH65wt48rRqgfy4UuUy8NYw79LS4S8XJ3PiklBhpkPApTWrGRCa91D1PownCjTMiz1c5r

The shell script below is an example of this obfuscation/de-obfuscation in process.

#!/bin/sh
password="test"
secret="cat /var/root/key.txt"
generated_secret=$(echo ${password} | openssl enc -aes-256-cbc -pass "pass:${secret}" -a -e)
cleartext_secret=$(echo ${generated_secret} | openssl enc -aes-256-cbc -pass "pass:${secret}" -a -d)
echo "Obfuscated password: ${generated_secret}"
echo "De-obfuscated password: ${cleartext_secret}"

When this is run:

[frodo@mordor]: # sudo ./foo
Obfuscated password: U2FsdGVkX18FWNJ0K3nFa0QPyb9YksGxavWE0p4Km7g=
De-obfuscated password: test

To make this a little more obscure, the key.txt file should exist somewhere that normal users cannot access, but still readable by root.
For example, /var/root/key.txt with read-only permission for root. Any script that needs to de-obfuscate sensitive information therefore needs to be run as root, or have a suid set.
Additionally, any script that uses this technique should be kept seperate from the key file, and when used in any shell script, make sure any variable containing the de-obfuscated text is used only where required, and unset/destroyed after use.

I typically only use this in single use scripts – for example, creating a local user account when a machine is imaged/deployed.