#!/usr/bin/env bash # set-password: hash a login password (yescrypt) and store it, encrypted with # agenix recipients, as secrets/-password.age. set -euo pipefail USER_NAME=faumaray FLAKE_ARG= IDENTITY= FORCE=0 die() { printf 'error: %s\n' "$*" >&2 exit 1 } usage() { cat <<'EOF' Usage: set-password [--user NAME] [--flake DIR] [-i IDENTITY] [--force] Asks for a password, hashes it with 'mkpasswd -m yescrypt' and encrypts the hash to secrets/NAME-password.age (recipients: secrets/secrets.nix). --user NAME login name (default: faumaray) --flake DIR flake directory (default: the repository you are in) -i, --identity FILE verify the result decrypts with this private key -f, --force replace an existing secrets/NAME-password.age EOF } while [ "$#" -gt 0 ]; do case "$1" in --user) [ "$#" -ge 2 ] || die "--user needs a value" USER_NAME=$2 shift 2 ;; --flake) [ "$#" -ge 2 ] || die "--flake needs a value" FLAKE_ARG=$2 shift 2 ;; -i | --identity) [ "$#" -ge 2 ] || die "$1 needs a value" IDENTITY=$2 shift 2 ;; -f | --force) FORCE=1 shift ;; -h | --help) usage exit 0 ;; *) die "unknown argument: $1 (see --help)" ;; esac done case "$USER_NAME" in '' | *[!A-Za-z0-9_-]*) die "invalid user name: '$USER_NAME'" ;; esac args=("$USER_NAME-password.age" -) if [ -n "$FLAKE_ARG" ]; then args+=(--flake "$FLAKE_ARG"); fi if [ -n "$IDENTITY" ]; then args+=(--identity "$IDENTITY"); fi if [ "$FORCE" -eq 1 ]; then args+=(--force); fi [ -t 0 ] || die "run this in a terminal: the password is read interactively" read -r -s -p "Password for $USER_NAME: " pw1 echo read -r -s -p "Repeat password: " pw2 echo [ -n "$pw1" ] || die "empty password" [ "$pw1" = "$pw2" ] || die "passwords differ" # The password goes through stdin only, never through argv. hash=$(printf '%s' "$pw1" | mkpasswd -m yescrypt -s) unset pw1 pw2 printf '%s\n' "$hash" | secret-from-file "${args[@]}" echo echo "Rebuild (switch-system) or reinstall to use the new password."