this_dir="$(cd "$(dirname "$0")" && pwd)" exists() { command -v "$1" >/dev/null 2>&1; } # Check if command exists (is in path). if [[ "$(whoami)" == "root" ]]; then # find out who the normal user is based on $this_dir, # since $this_dir will be somewhere within /Users//... or /home//... # and then switch to that user, using exec to avoid forking # Cross-platform user detection user="" # Use uname to detect OS and choose appropriate stat command if command -v stat >/dev/null 2>&1; then if [[ "$(uname)" == "Darwin" ]]; then user="$(stat -f '%Su' "${this_dir}" 2>/dev/null || true)" elif [[ "$(uname)" == "Linux" ]]; then user="$(stat -c '%U' "${this_dir}" 2>/dev/null || true)" else >&2 echo "ERROR: Unsupported OS: $(uname)" exit 1 fi fi # Fallback method: Parse user from directory path if [[ -z "${user}" ]]; then # Extract username from path like /Users/username/... or /home/username/... if [[ "$(uname)" == "Darwin" ]] && [[ "${this_dir}" =~ ^/Users/([^/]+) ]]; then user="${BASH_REMATCH[1]}" elif [[ "$(uname)" == "Linux" ]] && [[ "${this_dir}" =~ ^/home/([^/]+) ]]; then user="${BASH_REMATCH[1]}" fi fi if [[ -n "${user}" ]]; then if id "${user}" >/dev/null 2>&1; then # exec to avoid forking, # and make sure to use a login shell # propagate all arguments using "$@" # The command structure: su - user -c "command" -- args # - su - user: switch to user with login shell # - -c "command": execute the quoted command # - -- args: separator, everything after -- goes to the command # - "$@": all original script arguments # - \"\$@\": escaped version for the inner command string exec su - "${user}" -c "exec bash -l $0 \"\$@\"" -- "$@" >&2 echo "ERROR: Failed to switch to user ${user}" else >&2 echo "ERROR: Detected user ${user} does not exist" fi else >&2 echo "WARN: Failed to determine user from szecret dir: ${this_dir}" fi >&2 echo "ERROR: Refusing to run szecret as root" exit 1 fi if ! exists age ; then >&2 cat <&2 cat </dev/null || true)" if [[ -z "$key_id" ]]; then >&2 echo "WARN: Invalid public key: ${public_key}" exit 1 fi private_key="${SZECRET_PRIVATE_KEY:-${private_key_dir}/${key_id}}" else store="" fi file_for() { local name="$1" echo "${store}/${name}.age" } local_key_name() { local local_store_name="$1" echo "local-key-${local_store_name}" } ensure_local_store() { local local_store_name="$1" local local_key_name local_key_name="$(local_key_name "${local_store_name}")" # Wherever its key is, the old store or a bucket; whether this machine can # open it is get's to say. if ! (find_secret "${local_key_name}" >/dev/null 2>&1); then >&2 echo "ERROR: Local store '${local_store_name}' does not exist (key: ${local_key_name})" exit 1 fi } get_local_private_key() { local local_store_name="$1" local local_key_name local_key_name="$(local_key_name "${local_store_name}")" "${this_dir}/get.sh" "${local_key_name}" } exists() { command -v "$1" >/dev/null 2>&1; } # Check if command exists (is in path). pathadd() { [[ -d "$1" ]] && PATH="$1"$(echo ":$PATH:" | sed "s|:$1:|:|" | sed 's|:$||'); } # Where cloud-setup installs the age plugins (age-plugin-tpm, age-plugin-se), # which age finds on PATH; launchd's default PATH leaves it out. if [[ ":${PATH}:" != *":/usr/local/bin:"* ]]; then pathadd /usr/local/bin || true fi ensure_age() { if exists age ; then return fi local bin="${this_dir}/.bin" pathadd "${bin}" if [[ -x "${bin}/age" ]]; then return fi local os local arch os="$(uname | tr "[:upper:]" "[:lower:]")" arch="$(uname -m)" if [[ "$arch" == "aarch64" ]]; then arch="arm64" elif [[ "$arch" == "x86_64" ]]; then arch="amd64" fi tar="$bin/age.tar.gz" # Pinned as cloud-setup's setup/age.sh pins it: buckets need age 1.3. curl -LSsfo "$tar" "https://dl.filippo.io/age/v1.3.2?for=${os}/${arch}" tar xf "$tar" -C "$bin" --strip-components=1 } private_key_is_setup() { check_legacy_private_key_migration if ! [[ -n "${private_key}" && -r "${private_key}" ]]; then >&2 echo "WARN: Missing age key: ${private_key}" fi [[ -r "${private_key}" ]] } ensure_private_key() { mkdir -p "${private_key_dir}" if private_key_is_setup; then return fi if [ ! -t 0 ]; then >&2 echo "ERROR: szecret private key not installed: ${public_key}" exit 1 fi ensure_age echo -n "Enter age private key ${public_key}: " read -s private_key_value echo local derived derived="$(age-keygen -y <<<"${private_key_value}" 2>/dev/null || true)" if [[ "$derived" != "$(cat "${public_key}")" ]]; then >&2 echo "ERROR: Invalid private key (does not match ${public_key})" exit 1 fi mkdir -p "${private_key_dir}" local target="${private_key_dir}/${derived}" echo "${private_key_value}" > "${target}" chmod 600 "${target}" 2>/dev/null || true } check_legacy_private_key_migration() { local f="${private_key_dir}/.id" if [[ ! -r "${f}" ]]; then return fi local pub pub="$(age-keygen -y "$f" 2>/dev/null || true)" if [[ -z "$pub" || "$pub" != age1* ]]; then >&2 echo "WARN: stray file in ${private_key_dir} that does not belong there: $f" return fi local target="${private_key_dir}/${pub}" mv "$f" "$target" } age_encrypt() { local pubkeyfile="$1" local outputfile="$2" cat | age --encrypt --recipients-file "${pubkeyfile}" --output "${outputfile}" } age_decrypt() { local privatekeyfile="$1" local inputfile="$2" age --decrypt --identity "${privatekeyfile}" "${inputfile}" } # Local store metadata helpers write_local_metadata() { local metadata_file="$1" local store_name="$2" local pubkey="$3" cat > "${metadata_file}" <&2 echo "ERROR: Invalid metadata format in ${metadata_file}" >&2 echo "Run 'szecret create-local [/] ' to recreate" return 1 fi } get_local_public_key() { local local_store_name="$1" local local_private_key local_private_key="$(get_local_private_key "${local_store_name}")" printf '%s\n' "${local_private_key}" | age-keygen -y } verify_local_pubkey() { local expected_pubkey="$1" local actual_pubkey="$2" local store_name="$3" if [[ "${expected_pubkey}" != "${actual_pubkey}" ]]; then >&2 echo "ERROR: Public key mismatch for store '${store_name}'" >&2 echo " Expected: ${expected_pubkey}" >&2 echo " Actual: ${actual_pubkey}" return 1 fi } # --- Buckets ------------------------------------------------------------------- # # A bucket is a directory: .age files, `recipients` (age public keys, one # a line, a comment above each naming its reader, written by cloud-setup's # bin/szecret-buckets) and `.szecret`, which only `rekey` writes: # # kind=bucket # encrypted-to= # name= one for each of those keys # # The admins, printed by SZECRET_ADMINS_COMMAND, are added to every # encryption, and nothing is encrypted without them. re_secret='^[A-Za-z0-9][A-Za-z0-9._-]*$' re_bucket='^[a-z0-9][a-z0-9._-]*$' # The stanza types a bucket's files may carry: age's own X25519 and p256tag # (age1tag1 keys: age-plugin-tpm, and age-plugin-se with tag recipients), and # age-plugin-se's piv-p256 (age1se1 keys). stanza_types="X25519 p256tag piv-p256" die() { >&2 echo "ERROR: $*"; exit 1; } sorted() { LC_ALL=C sort -u; } # keys_in : the keys in a recipients file, comments and blank lines dropped. keys_in() { sed -e 's/#.*//' -e 's/[[:space:]]//g' "$1" 2>/dev/null | grep -v '^$' || true } is_bucket_dir() { grep -qx 'kind=bucket' "$1/.szecret" 2>/dev/null; } # encrypted_to : the keys the bucket's files were last encrypted to. encrypted_to() { sed -n 's/^encrypted-to=//p' "$1/.szecret" 2>/dev/null | tr ' ' '\n' | grep -v '^$' | sorted || true } # bucket_label : its name for messages: the bucket's name, or a # repository bucket's path. bucket_label() { if [[ -n "${buckets}" && "$(dirname "$1")" == "${buckets}" ]]; then basename "$1" else echo "$1" fi } # admins_output: what SZECRET_ADMINS_COMMAND prints. With no command, or a # failed one, it fails and says why. admins_output() { if [[ -z "${SZECRET_ADMINS_COMMAND:-}" ]]; then >&2 echo "ERROR: no admins: SZECRET_ADMINS_COMMAND is not set, and nothing is encrypted without them" return 1 fi if ! bash -c "${SZECRET_ADMINS_COMMAND}" &2 echo "ERROR: no admins: '${SZECRET_ADMINS_COMMAND}' failed, and nothing is encrypted without them" return 1 fi } # admin_names : " " for each admin key a "# " # comment line names, the last comment above it as in a recipients file. Only # list uses the names; encryption reads the key lines alone. admin_names() { awk '/^[[:space:]]*#/ { sub(/^[[:space:]]*#[[:space:]]*/, ""); name = $0; next } /^age1[0-9a-z]+$/ { if (name != "") print $1, name; name = "" }' <<<"$1" } # admin_keys []: the admins, one a line. With none it fails and # says why. admin_keys() { local out if [[ $# -gt 0 ]]; then out="$1" else out="$(admins_output)" || return 1 fi out="$(grep -E '^age1[0-9a-z]+$' <<<"${out}" | sorted || true)" if [[ -z "${out}" ]]; then >&2 echo "ERROR: no admins: '${SZECRET_ADMINS_COMMAND}' printed none, and nothing is encrypted without them" return 1 fi echo "${out}" } # wanted_set : what the bucket's files should be encrypted to. wanted_set() { { keys_in "$1/recipients"; echo "$2"; } | grep -v '^$' | sorted } # key_names : " " for each key in its recipients, named by # the comment above it, then the names its last rekey recorded, so a reader # since removed still has one. key_names() { awk '/^[[:space:]]*#/ { sub(/^[[:space:]]*#[[:space:]]*/, ""); name = $0; next } /^[[:space:]]*$/ { next } { print $1, (name == "" ? "?" : name); name = "" }' "$1/recipients" 2>/dev/null || true sed -n 's/^name=//p' "$1/.szecret" 2>/dev/null || true } # name_of : who a key is. name_of() { local n if grep -qxF "$1" <<<"$3"; then echo "admin ${1:0:16}..." return fi n="$(awk -v k="$1" '$1 == k { $1 = ""; sub(/^ /, ""); print; exit }' <<<"$2")" echo "${n:-$1}" } # my_keys: this machine's public keys: its identity's, and the old key's while # it is here. my_keys() { if [[ -r "${identity_pub}" ]]; then keys_in "${identity_pub}" fi if [[ -n "${private_key}" && -r "${private_key}" ]]; then echo "${key_id}" fi return 0 } # is_reader : one of this machine's keys is among those the bucket was # last encrypted to. is_reader() { local to mine k to="$(encrypted_to "$1")" mine="$(my_keys)" [[ -n "${to}" && -n "${mine}" ]] || return 1 while read -r k; do if grep -qxF "${k}" <<<"${to}"; then return 0 fi done <<<"${mine}" return 1 } # load_identities: age's -i for each identity this machine has, in ids. Both # can be given at once: age passes over one whose plugin is missing when # another opens the file (tested 2026-11-18, age 1.3.2). load_identities() { ids=() if [[ -r "${identity}" ]]; then ids+=(-i "${identity}") fi if [[ -n "${private_key}" && -r "${private_key}" ]]; then ids+=(-i "${private_key}") fi if [[ ${#ids[@]} -eq 0 ]]; then die "no identity on this machine (${identity}): run szecret enrol" fi } decrypt() { load_identities age --decrypt "${ids[@]}" "$1" } # age_version_ok: age 1.3 or later, which encrypts to age1tag1 keys itself. age_version_ok() { local v major minor v="$(age --version 2>/dev/null || true)" v="${v#v}" major="${v%%.*}" minor="${v#*.}" minor="${minor%%.*}" if [[ "${major}" =~ ^[0-9]+$ && "${minor}" =~ ^[0-9]+$ ]] && (( major > 1 || (major == 1 && minor >= 3) )); then return 0 fi die "age ${v:-?} is older than 1.3, which buckets need: upgrade it (brew upgrade age, or cloud-setup's setup/age.sh)" } # plugin_for : the plugin age needs to encrypt to it; nothing for age's # own kinds. plugin_for() { local hrp="${1%1*}" hrp="${hrp#age1}" case "${hrp}" in age|tag|pq|tagpq) ;; *) echo "age-plugin-${hrp}" ;; esac } # stanzas_of : the type of each recipient stanza in its header, which # needs no key. stanzas_of() { LC_ALL=C awk 'NR == 1 && $0 != "age-encryption.org/v1" { print "(not an age file)"; exit } /^---/ { exit } /^-> / { print $2 }' "$1" } # encrypt_to : stdin, encrypted to each key (one a line), in # place at only once whole. encrypt_to() { local out="$1" k tmp args=() while read -r k; do if [[ -n "${k}" ]]; then args+=(-r "${k}") fi done <<<"$2" [[ ${#args[@]} -gt 0 ]] || die "nothing to encrypt $(basename "${out}") to" tmp="$(mktemp "$(dirname "${out}")/.put.XXXXXX")" || die "cannot write in $(dirname "${out}")" if ! age --encrypt "${args[@]}" -o "${tmp}"; then rm -f "${tmp}" die "age could not encrypt $(basename "${out}")" fi chmod 644 "${tmp}" mv "${tmp}" "${out}" } # bucket_set : the keys a new file in that bucket is encrypted to. Refuses # with no admins, before the bucket's first rekey, and when its readers or the # admins have changed since its last one, so a forgotten rekey can't leave a # removed reader reading new values. bucket_set() { local dir="$1" admins want [[ -d "${dir}" ]] || die "no bucket $(bucket_label "${dir}")" [[ -r "${dir}/recipients" ]] \ || die "bucket $(bucket_label "${dir}") has no recipients file (cloud-setup's bin/szecret-buckets writes it)" admins="$(admin_keys)" || exit 1 want="$(wanted_set "${dir}" "${admins}")" is_bucket_dir "${dir}" \ || die "bucket $(bucket_label "${dir}") has never been keyed: szecret rekey $(bucket_label "${dir}") first" if [[ "${want}" != "$(encrypted_to "${dir}")" ]]; then die "the readers of $(bucket_label "${dir}") or the admins changed since its last rekey: szecret rekey $(bucket_label "${dir}") first" fi echo "${want}" } # locate : every file holding that name: buckets first, then the old store. locate() { local f if [[ -n "${buckets}" ]]; then for f in "${buckets}"/*/"$1.age"; do if [[ -e "${f}" ]]; then echo "${f}" fi done fi if [[ -n "${store}" && -e "${store}/$1.age" ]]; then echo "${store}/$1.age" fi return 0 } # where_is : "/", or " in the old store". where_is() { local n n="$(basename "$1" .age)" if [[ -n "${store}" && "$(dirname "$1")" == "${store}" ]]; then echo "${n} in the old store" else echo "$(bucket_label "$(dirname "$1")")/${n}" fi } # find_secret : the one file it names, or an error. find_secret() { local arg="$1" b n found count if [[ "${arg}" == */* ]]; then b="${arg%%/*}" n="${arg#*/}" [[ "${b}" =~ ${re_bucket} && "${n}" =~ ${re_secret} ]] || die "not a secret's name: ${arg}" [[ -n "${buckets}" && -r "${buckets}/${b}/${n}.age" ]] || die "Secret '${arg}' not found" echo "${buckets}/${b}/${n}.age" return fi [[ "${arg}" =~ ${re_secret} ]] || die "not a secret's name: ${arg}" found="$(locate "${arg}")" count="$(grep -c . <<<"${found}" || true)" if [[ "${count}" -eq 0 ]]; then die "Secret '${arg}' not found" elif [[ "${count}" -gt 1 ]]; then die "'${arg}' is in more than one place: $(while read -r f; do where_is "${f}"; done <<<"${found}" | paste -sd ',' - | sed 's/,/, /g')" fi echo "${found}" }