Skip to content

Instantly share code, notes, and snippets.

@monkut
Created November 26, 2025 00:34
Show Gist options
  • Select an option

  • Save monkut/b9f5eb014e97419829b750ef03b840bd to your computer and use it in GitHub Desktop.

Select an option

Save monkut/b9f5eb014e97419829b750ef03b840bd to your computer and use it in GitHub Desktop.
step-ssh.sh - SSH wrapper with automatic Smallstep certificate authentication
#!/bin/bash
# step-ssh.sh - SSH wrapper with automatic Smallstep certificate authentication
#
# Usage: step-ssh [ssh-options] user@host [command]
#
# For 192.168.1.* hosts, automatically checks for valid certificate
# and obtains one via Google OAuth if needed.
#
# Add to ~/.bashrc or ~/.zshrc:
# alias ssh='/home/{USER}/.local/bin/step-ssh.sh'
set -e
# Configuration
NETWORK_PREFIX="192.168.1."
PROVISIONER="Google"
# Parse the target from SSH arguments
# Find user@host pattern in arguments
TARGET=""
SSH_ARGS=()
for arg in "$@"; do
if [[ "$arg" =~ ^[^-].*@.*$ ]] && [[ -z "$TARGET" ]]; then
TARGET="$arg"
fi
SSH_ARGS+=("$arg")
done
# Extract host from user@host
if [[ "$TARGET" =~ @(.+)$ ]]; then
HOST="${BASH_REMATCH[1]}"
else
HOST="$TARGET"
fi
# Check if host is on our network
if [[ "$HOST" == ${NETWORK_PREFIX}* ]]; then
# Check for valid certificate in SSH agent
CERT_VALID=false
if command -v step &>/dev/null; then
# Check if we have a valid (non-expired) certificate
if step ssh list 2>/dev/null | grep -q "ECDSA-CERT"; then
# Verify certificate hasn't expired
CERT_INFO=$(ssh-add -L 2>/dev/null | grep "ecdsa-sha2-nistp256-cert" | head -1)
if [[ -n "$CERT_INFO" ]]; then
# Extract expiry from certificate
EXPIRY=$(echo "$CERT_INFO" | ssh-keygen -Lf - 2>/dev/null | grep "Valid:" | sed 's/.*to //')
if [[ -n "$EXPIRY" ]]; then
EXPIRY_EPOCH=$(date -d "$EXPIRY" +%s 2>/dev/null || echo 0)
NOW_EPOCH=$(date +%s)
if [[ "$EXPIRY_EPOCH" -gt "$NOW_EPOCH" ]]; then
CERT_VALID=true
fi
fi
fi
fi
if [[ "$CERT_VALID" == false ]]; then
echo "No valid SSH certificate found for $HOST"
echo "Obtaining certificate via Google OAuth..."
echo ""
# Let step prompt for email
step ssh login --provisioner "$PROVISIONER"
echo ""
echo "Certificate obtained. Connecting to $HOST..."
echo ""
fi
else
echo "Warning: step CLI not installed, proceeding with standard SSH"
fi
fi
# Execute SSH with original arguments
exec ssh "${SSH_ARGS[@]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment