From c7f3356a710183982f88a5d6f40c1396896c7efc Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Mon, 29 Oct 2018 12:11:18 +0100 Subject: [PATCH] Adjust to work only with vault hosted keys Signed-off-by: Knut Ahlers --- bin/vault-rotate-sshkey-passphrase | 50 ++++++++++++++---------------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/bin/vault-rotate-sshkey-passphrase b/bin/vault-rotate-sshkey-passphrase index 2fcb5b2..450cbac 100755 --- a/bin/vault-rotate-sshkey-passphrase +++ b/bin/vault-rotate-sshkey-passphrase @@ -1,35 +1,33 @@ -#!/bin/bash -e +#!/bin/bash +set -euo pipefail -keyfile=$1 +source "${HOME}/bin/script_framework.sh" -if [ -z "$keyfile" ] || [ ! -e "${keyfile}" ]; then - echo "Keyfile not provided or not found: '${keyfile}'" - exit 1 +keyname=${1:-} + +[ -z "${keyname}" ] && fail "Key name not provided" + +if [ ! -e "/tmp/${keyname}" ]; then + vault read -field=private "/secret/ssh-key/${keyname}" >"/tmp/${keyname}" + chmod 0600 \ + "/tmp/${keyname}" fi -KEYNAME=$(basename ${keyfile}) +function cleanup() { + rm -f \ + "/tmp/${keyname}" +} +trap cleanup EXIT -OLDPASS=$(vault read -field=passphrase "/secret/ssh-key/${KEYNAME}") +OLDPASS=$(vault read -field=passphrase "/secret/ssh-key/${keyname}") || fail "Unable to retrieve old passphrase" +NEWPASS=$(password get -l 64) || fail "Unable to generate a new passphrase" -if [ $? -gt 0 ]; then - echo "Unable to retrieve old passphrase." - exit 1 -fi +[ -z "${NEWPASS}" ] && fail "Unable to generate a new passphrase" -NEWPASS=$(password get -l 64) - -if [ -z "$NEWPASS" ]; then - echo "Unable to generate a new passphrase" - exit 1 -fi - -vault write "/secret/ssh-key/${KEYNAME}" passphrase="${NEWPASS}" - -if ! (ssh-keygen -p -P "${OLDPASS}" -N "${NEWPASS}" -f "${keyfile}"); then - echo "Key has not been changed successfully. Writing old secret back to vault." - echo "A backup of the new password has been written to 'tmp_passphrase' attribute." - vault write "/secret/ssh-key/${KEYNAME}" passphrase="${OLDPASS}" tmp_passphrase="${NEWPASS}" - exit 1 -fi +ssh-keygen -p -P "${OLDPASS}" -N "${NEWPASS}" -f "/tmp/${keyname}" || fail "Was not able to modify key with new passphrase" +vault-patch --log-level=warn "/secret/ssh-key/${keyname}" \ + passphrase="${NEWPASS}" \ + private=@/tmp/${keyname} \ + passphrase_changed=$(date +%Y-%m-%dT%H:%M:%S%z) echo "Everything was fine, key has been changed."