Skip to content

Instantly share code, notes, and snippets.

@wmertens
Last active February 2, 2024 10:01
Show Gist options
  • Save wmertens/c4f2c4186c04dc5442bbe3396f2c12f6 to your computer and use it in GitHub Desktop.
Save wmertens/c4f2c4186c04dc5442bbe3396f2c12f6 to your computer and use it in GitHub Desktop.
ssh-crypt: bash function to encrypt using ssh-agent and openssl
#!/usr/bin/env bash
#
# ssh-crypt
#
# Bash function to encrypt/decrypt with your ssh-agent private key.
# Requires the commands gzip, ssh-add, ssh-keygen and openssl.
#
# Uses bash-specific extensions like <<<$var to securely pass data.
#
# Wout.Mertens@gmail.com 2021-11-11 - MIT Licensed
#
# Copyright 2021 Wout Mertens
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge, publish, distribute,
# sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial
# portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
# LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
# NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
ssh-crypt() {
if [ "$1" != -e ] && [ "$1" != -d ]; then
echo "Usage: ssh-crypt -<e|d> [seed] [pubkey-match] < infile > outfile" >&2
echo >&2
echo "* -e for encrypt, -d for decrypt" >&2
echo "* seed is used to generate the secret, recommended so you don't use the same secret everywhere" >&2
echo "* pubkey-match is used to select the first matching pubkey in the ssh-agent" >&2
echo "* define CRYPT_PUBKEY to provide your own" >&2
return 2
fi
# === Select pubkey
local pk
if [ -n "$CRYPT_PUBKEY" ]; then
pk="$CRYPT_PUBKEY"
else
# we can't use ecdsa, it always gives different signatures
local keys=$(ssh-add -L | grep -v ecdsa)
if [ -n "$3" ]; then
keys=$(grep -- "$3" <<<"$keys")
fi
read pk <<<"$keys"
fi
if [ -z "$pk" ]; then
echo "!!! Could not select a public key to use - verify ssh-add -L"
return 1
fi
# === Generate secret
# We pass the pubkey as a file so ssh-keygen will look up the private key in the agent
local secretText=$(ssh-keygen -Y sign -n hi -q -f /dev/fd/4 4<<<"$pk" <<<"$2")
if [ $? -ne 0 ] || [ -z "$secretText" ]; then
echo "!!! Cannot generate secret, is ssh-agent available?" >&2
return 1
fi
# Get it on one line
local secret=$(openssl dgst -sha512 -r <<<"$secretText")
if [ $? -ne 0 ] || [ -z "$secret" ]; then
echo "!!! Cannot generate secret, is openssl available?" >&2
return 1
fi
# === Encrypt/decrypt
# specify all settings so openssl upgrades don't change encryption
local opts="-aes-256-cbc -md sha512 -pbkdf2 -iter 239823 -pass fd:4"
# we use gzip both for compression and detecting bad secrets early
if [ "$1" = -e ]; then
gzip | openssl enc -e $opts 4<<<"$secret"
else
openssl enc -d $opts 4<<<"$secret" | gzip -d
fi
}
# When sourcing this file for use in other scripts, use `LOAD_ONLY=true source ssh-crypt.bash`
if [ -z "$LOAD_ONLY" ]; then
ssh-crypt "$@"
fi
@robd
Copy link

robd commented Nov 16, 2021

Hey. This looks great! Was wondering - is this available for other folks to use, if so under what license - and could you add license info to the file?

@wmertens
Copy link
Author

Ah yes good idea! I added the MIT license now.

@robd
Copy link

robd commented Nov 16, 2021

Ah that's great - many thanks!

@robd
Copy link

robd commented Nov 17, 2021

Hey @wmertens - not sure if you have a feel for this - I see an error when running this under git bash on Windows - Invalid password argument "fd:4". This seems to be a problem with the file descriptor when passed into the openssl enc command. Any idea what this could be? Thank you!

@wmertens
Copy link
Author

wmertens commented Nov 17, 2021

@robd it passes the password via file descriptor 4 via the 4<<< operator. Perhaps Windows openssl doesn't support that fd:4 syntax for the filename? Try /dev/fd/4 perhaps?

@robd
Copy link

robd commented Nov 17, 2021

I think you are right - perhaps file descriptors or the fd: file type don't work properly on windows. FWIW I'm on OpenSSL 1.1.1k, running via git bash. I played with trying /dev/fd/4 syntax, but wasn't get things working. Going back to the previous, stdin based version works well. Thanks again for this!

@wmertens
Copy link
Author

You could also try -pass file:<(echo "$secret"). Did you try -pass file:/dev/fd/4?

@robd
Copy link

robd commented Jan 5, 2022

Sorry for the delay in coming back here. I did eventually try these, but they don't seem to work. I found that the earlier version worked though.

For -pass file:/dev/fd/4 see an error:

24700:error:02001003:system library:fopen:No such process:../openssl-1.1.k/crypto/bio/bss_file.c:69:fopen('/dev/fd/4','r')

For -pass file:<(echo "$secret") I see:

Extra arguments given.
enc: Use -help for summary.

FWIW I found that the earlier version of the script works, so not a big deal. Probably not a priority to support Windows / gitbash.

@wmertens
Copy link
Author

wmertens commented Jan 6, 2022

very odd - indeed the <(...) syntax would be the most basic and it should work on bash. Can you run cat <(echo hello) on windows? But indeed, happy that the old version works for you.

@robd
Copy link

robd commented Jan 7, 2022

Yes, it's interesting - cat <(echo hello) does work fine. Not totally sure what is going wrong there. I wonder if it's an OpenSSL version incompatibility either because we're on an old version (1.1.1k), or windows?

@izak-hoot
Copy link

izak-hoot commented Aug 4, 2022

ssh-keygen -Y sign -n hi -q -f /dev/fd/4 4<<<"$pk" <<<"$2"
This is awesome!

@wmertens
Copy link
Author

wmertens commented Aug 8, 2022

@izak-hoot thanks :-)

@martin-braun
Copy link

martin-braun commented Jan 30, 2024

Hi @wmertens. First of all, thank you, your script was helping me a lot. I think this solution is great for things like API keys in public dot file repositories, hence I took it a step further and build an SSH store system around it, but I also significantly decreased its code size, as I know that I work with id_rsa exclusively. I also noticed a few things that confused me and that I decided to skip over in the rewrite process:

  1. I noticed that you hash your signature (secretText) using openssh dgst before using it as symmetrical key via openssl enc (secret). Why? It's not necessary and feels redundant to me. You can just pass the entire signature as -k argument to openssl enc and you are good to go.
  2. ssh-keygen sign doesn't require you to feed it with the public key to derive the private key. You can just give it the private key and it will work.
  3. As time progresses, so should the encryption level, but you can't update the encryption without making old data unreadable, so I think a versioning system would be nice.
  4. The whole file descriptor thing works, but is less portable.

I came up with this function:

sshstore() {
	sign() { echo "$1" | ssh-keygen -Y sign -n store -f "$2" -q; }
	v=1
	identity="$HOME/.ssh/id_rsa"
	if [ $# -lt 1 ] || [ "$1" = "-h" ] || [ "$1" = "--help" ]; then
		echo "Loads or saves a symmetrically encrypted data from/to the SSH store using $identity."
		echo "Usage: sshstore [-h] [--help] name [-s data] [-s < data] > data"
		echo ''
		echo "The private identity key within the SSH agent is used to sign the given name."
		echo "The resulting signature is used to symmetrically encrypt or decrypt the data."
		echo "Note: This function is backward compatible with older identities and encryption methods."
		return 129
	fi
	store="$HOME/.ssh/store"
	name="$(echo "$1" | tr -cd '[:alnum:]_-')"
	mkdir -p "$store"
	if [ "$2" = "-s" ]; then
		data="$3"
		test -n "$data" || { stdin=$(mktemp) && timeout 1 cat > "$stdin" && data="$(cat "$stdin")"; rm "$stdin"; }
		test -n "$data" || { echo Missing data to encryt. >&2 && return 1; }
		rm "$store/$name.*" 2>/dev/null
		echo "$data" | gzip | openssl enc -e -aes-256-cbc -md sha512 -pbkdf2 -iter 69420 -k "$(sign "$name" "$identity")" > "$store/$name.$v"
		data=""
	fi
	test -s "$store/$name.$v" && openssl enc -d -aes-256-cbc -md sha512 -pbkdf2 -iter 69420 -k "$(sign "$name" "$identity")" < "$store/$name.$v" | gzip -d && return 0
	# test -s "$store/$name.1" && openssl enc -d -aes-256-cbc -md sha512 -pbkdf2 -iter 69420 -k "$(sign "$name" "$HOME/.ssh/id_rsa")" < "$store/$name.1" | gzip -d && return 0
	echo "Could not find $name to decrypt." >&2 && return 1
}

Now I can store some sensitive data using echo "DATA" | sshstore my-secret -s or sshstore my-secret -s "DATA" and access it securely via $(sshstore my-secret) where I need it.

I would love to get your personal opinion about this function as I try to get something secure to use confidently.

About the script:

  • It is designed to work with secrets like API keys, but should be usable for anything
  • The encrypted data is never outputted, but instead stored in $HOME/.ssh/store, the function always outputs unencrypted data
  • v=1 is the version of the encryption and key, so if I change either of these, I can out-comment the 2nd openssl enc -d line to fallback to previous versions and so on ... however, new data will always be encrypted with my newest key and method, so I can slowly refresh my secrets with improved methods in the future
  • I decreased the -iter by approx. 180k to improve execution time, it still should be sufficient enough against brute force attacks, especially as those secrets will be obsolete and already refreshed to quantum safe methods before quantum is a thing

As a final note: Kudos on using gzip to validate falsy data, that's such a clever way to prevent false positives when decrypting data.

@wmertens
Copy link
Author

Hi @martin-braun, your changes make a lot of sense to me, thanks!

I think I did the hashing to be sure the input to enc is of reasonable size and doesn't contain weird characters, but indeed I suppose enc already takes care of that.

@wmertens
Copy link
Author

Hmm looking at the script closer I'm worried about echo "$data", that will show up in the process table, limits the size of the secret, and adds a \n.

@martin-braun
Copy link

@wmertens Great catch, I'm a bit confused now, though: In my testing using echo would work as expected. If I replace echo "$data" | gzip | ... with printf "%s" "$data" | gzip | ... the output of gzip -d would miss the last character. It's almost like gzip removes and adds the the \n for me, but that sounds wrong on many levels.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment