#!/usr/bin/env bash # Generate one Ed25519 SSH key per service name in ~/.ssh. # # Existing keys are never overwritten or modified. set -euo pipefail SCRIPT_DIR="$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")" && pwd -P)" # shellcheck source=lib/common.sh source "$SCRIPT_DIR/lib/common.sh" usage() { cat <<'EOF' Usage: gen-keys.sh [--passphrase] [--] SERVICE... Creates ~/.ssh/id_ (+ .pub) for each SERVICE, an Ed25519 key with the comment "@". Services whose key already exists are skipped. --passphrase prompt for a passphrase for each key (default: no passphrase) -h, --help show this help SERVICE may contain letters, digits, '.', '_' and '-' and must start with a letter or digit. Exit codes: 0 ok, 1 a key could not be created, 2 usage error. EOF } main() { local use_passphrase=0 local -a services=() while (($#)); do case "$1" in -h|--help) usage; exit 0 ;; --passphrase) use_passphrase=1; shift ;; --) shift; services+=("$@"); break ;; -*) die "unknown option: $1 (see --help)" 2 ;; *) services+=("$1"); shift ;; esac done if ((${#services[@]} == 0)); then log "No services specified; nothing to do." return 0 fi # Validate everything up front so a typo in the last name doesn't leave # us with half the keys created. local s for s in "${services[@]}"; do [[ "$s" =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] \ || die "invalid service name: '$s' (letters, digits, . _ - only; max 64 chars)" 2 done : "${HOME:?HOME is not set}" need_cmd ssh-keygen if ((use_passphrase)) && [[ ! -t 0 ]]; then die "--passphrase needs an interactive terminal" 2 fi local ssh_dir="$HOME/.ssh" umask 077 mkdir -p -- "$ssh_dir" chmod 700 -- "$ssh_dir" local host_short host_short="$(hostname -s 2>/dev/null || hostname 2>/dev/null || uname -n)" host_short="${host_short//[^A-Za-z0-9._-]/_}" local failed=0 priv pub local -a seen=() for s in "${services[@]}"; do # Skip duplicates on the command line. if [[ " ${seen[*]:-} " == *" $s "* ]]; then continue; fi seen+=("$s") priv="$ssh_dir/id_$s" pub="$priv.pub" if [[ -e "$priv" || -L "$priv" ]]; then log "skipping: $priv already exists" continue fi if [[ -e "$pub" || -L "$pub" ]]; then err "refusing: $pub exists without a matching private key; move it away first" failed=1 continue fi log "generating: $priv" # If interrupted mid-generation, don't leave half a keypair behind. trap 'rm -f -- "$priv" "$pub"; exit 130' INT trap 'rm -f -- "$priv" "$pub"; exit 143' TERM local -a pass_args=(-N "") ((use_passphrase)) && pass_args=() if ssh-keygen -q -t ed25519 -f "$priv" -C "$s@$host_short" "${pass_args[@]+"${pass_args[@]}"}"; then trap - INT TERM info "public key: $pub" else trap - INT TERM rm -f -- "$priv" "$pub" err "ssh-keygen failed for '$s'" failed=1 fi done return "$failed" } main "$@"