Skip to content

Instantly share code, notes, and snippets.

@cnelson
Created July 10, 2017 20:11
Show Gist options
  • Save cnelson/a5ad54bde656d3224b9daaabaffe45e3 to your computer and use it in GitHub Desktop.
Save cnelson/a5ad54bde656d3224b9daaabaffe45e3 to your computer and use it in GitHub Desktop.
#!/bin/bash
if [ "$#" -ne 2 ]; then
echo "USAGE: $0 <APP_NAME> <PORT>"
echo "Replicate the behaivor of cf ssh on a port not advertised by /v2/info"
echo "https://docs.cloudfoundry.org/devguide/deploy-apps/ssh-apps.html#other-ssh-access"
exit 99
fi
set -eu
# get the app guid
APPGUID=$(cf app ${1} --guid)
INFO=$(cf curl /v2/info)
# strip the port off our ssh proxy, to get the hostname
SSHPROXY=$(echo ${INFO} | jq -r '.app_ssh_endpoint | sub(":\\d+$"; "")')
# This is the fingerprint we should expect
INFO_FINGERPRINT=$(echo ${INFO} | jq -r .app_ssh_host_key_fingerprint)
# verify that the proxy is returning the correct fingerprint instead of making a human do it
TEMP_HOSTS_FILE=$(mktemp)
trap "{ rm -f ${TEMP_HOSTS_FILE}; }" EXIT
ssh-keyscan -p ${2} ${SSHPROXY} >${TEMP_HOSTS_FILE} 2>/dev/null
if [ -z "$(cat ${TEMP_HOSTS_FILE})" ]; then
echo "Could not find ssh on ${SSHPROXY}:${2}."
exit 1
fi
#convert the fingerprint to md5 which is what /v2/info still responds
ACTUAL_FINGERPRINT=$(
ssh-keygen -E md5 -l -f <(cat ${TEMP_HOSTS_FILE}) \
| grep -v "^#" | cut -d" " -f2 | cut -d":" -f2-
)
# ensure they match
if [ "${INFO_FINGERPRINT}" != "${ACTUAL_FINGERPRINT}" ]; then
echo "Unable to verify fingerprint. Expected: '${INFO_FINGERPRINT}'; Got: '${ACTUAL_FINGERPRINT}'"
exit 2
fi
# get the one time password and present it to the user
echo "Your one-time-use SSH password is: $(cf ssh-code)"
# let ssh handle it from here
set -x
exec ssh \
-o UserKnownHostsFile=${TEMP_HOSTS_FILE} \
-o LogLevel=ERROR \
-p ${2} \
cf:${APPGUID}/0@${SSHPROXY}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment