summaryrefslogtreecommitdiff
path: root/secrets/common.sh
blob: 5eee8b69d56ae3fa5fe64b76d03850cad7649c04 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
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/<user>/... or /home/<user>/...
    # 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 <<EOF
ERROR: age tool not found

Install from: https://github.com/FiloSottile/age
EOF
    exit 1
fi

XDG_DATA_HOME=${XDG_DATA_HOME:-"$HOME/.local/share"}

# Private key directory. Files must be named after their public key (age1...).
# SZECRET_PRIVATE_KEY can still be used as a full single-file override (mainly for tests).
private_key_dir="${SZECRET_PRIVATE_KEY_DIR:-${XDG_DATA_HOME}/szecret}"

# Two kinds of store, side by side while secrets move from one to the other
# (cloud-setup docs/proposal-secret-roles.md). This code carries neither: a
# machine with only these scripts holds no secrets.
#
#   The old store: one directory of .age files, every one encrypted to the key
#   in id.pub. SZECRET_STORE / SZECRET_PUBLIC_KEY if set, else store/ and
#   id.pub in ~/.local/share/szecret, normally links into the checkout that
#   holds them.
#
#   Buckets: a directory of directories, each a set of secrets with one set of
#   readers. SZECRET_BUCKETS if set, else buckets/ in ~/.local/share/szecret.
#
# With neither, every command but enrol fails with the instructions below.
szecret_data_dir="${XDG_DATA_HOME}/szecret"

if [[ -n "${SZECRET_STORE:-}" ]]; then
    store="${SZECRET_STORE}"
    mkdir -p "${store}"
elif [[ -d "${szecret_data_dir}/store" ]]; then
    store="${szecret_data_dir}/store"
else
    store=""
fi

if [[ -n "${SZECRET_PUBLIC_KEY:-}" ]]; then
    public_key="${SZECRET_PUBLIC_KEY}"
else
    public_key="${szecret_data_dir}/id.pub"
fi

if [[ -n "${SZECRET_BUCKETS:-}" ]]; then
    buckets="${SZECRET_BUCKETS}"
    mkdir -p "${buckets}"
elif [[ -d "${szecret_data_dir}/buckets" ]]; then
    buckets="${szecret_data_dir}/buckets"
else
    buckets=""
fi

# This machine's identity: made here by `szecret enrol`, never copied off. Its
# public key is beside it, as a hardware key can't give it without its plugin.
# A path of its own, not the profile's: timers, systemd and launchd read no
# shell profile.
identity="${SZECRET_IDENTITY:-${szecret_data_dir}/identity}"
identity_pub="${identity}.pub"

# The old store counts only with the public key it is encrypted to.
if [[ -n "${store}" && ! -r "${public_key}" && -n "${buckets}" ]]; then
    store=""
fi

if [[ -z "${szecret_no_store_ok:-}" ]] && [[ -z "${buckets}" ]] && [[ -z "${store}" || ! -r "${public_key}" ]]; then
    # `ready` is asked by every interactive shell; a machine with no store is
    # simply not ready, which needs no explanation each time.
    if [[ -n "${szecret_quiet:-}" ]]; then
        exit 1
    fi
    >&2 cat <<MSG
ERROR: no szecret store on this machine.

Looked for ${szecret_data_dir}/buckets, and for ${szecret_data_dir}/store
with ${szecret_data_dir}/id.pub. Link them to an existing store, or point
SZECRET_BUCKETS (or SZECRET_STORE and SZECRET_PUBLIC_KEY) at one.

MSG
    exit 1
fi

key_id=""
private_key=""
if [[ -n "${store}" && -r "${public_key}" ]]; then
    key_id="$(cat "${public_key}" 2>/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 local_key_file
    local_key_name="$(local_key_name "${local_store_name}")"
    local_key_file="$(file_for "${local_key_name}")"

    if ! [[ -r "${local_key_file}" ]]; 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|:$||'); }

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}" <<EOF
store=${store_name}
pubkey=${pubkey}
EOF
}

# Read local metadata file
# Sets global variables: _metadata_store and _metadata_pubkey
read_local_metadata() {
    local metadata_file="$1"
    _metadata_store=""
    _metadata_pubkey=""

    if [[ ! -r "${metadata_file}" ]]; then
        return 1
    fi

    _metadata_store="$(grep '^store=' "${metadata_file}" | cut -d= -f2)"
    _metadata_pubkey="$(grep '^pubkey=' "${metadata_file}" | cut -d= -f2)"

    if [[ -z "${_metadata_store}" || -z "${_metadata_pubkey}" ]]; then
        >&2 echo "ERROR: Invalid metadata format in ${metadata_file}"
        >&2 echo "Run 'szecret create-local <store-name> <directory>' 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}")"
    age-keygen -y <<<"${local_private_key}"
}

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: <name>.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=<every key its files were last encrypted to, sorted>
#   name=<key> <who>        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 <file>: 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 <dir>: 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 <dir>: 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
}

# admin_keys: the admins, one a line. With none it fails and says why.
admin_keys() {
    local out
    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 ! out="$(bash -c "${SZECRET_ADMINS_COMMAND}" </dev/null)"; then
        >&2 echo "ERROR: no admins: '${SZECRET_ADMINS_COMMAND}' failed, and nothing is encrypted without them"
        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 <dir> <admins>: what the bucket's files should be encrypted to.
wanted_set() {
    { keys_in "$1/recipients"; echo "$2"; } | grep -v '^$' | sorted
}

# key_names <dir>: "<key> <name>" 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 <key> <key names> <admins>: 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 <dir>: 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 <key>: 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 <file>: 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 <out> <keys>: stdin, encrypted to each key (one a line), in
# place at <out> 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 <dir>: 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 <name>: 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 <file>: "<bucket>/<name>", or "<name> 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 <name or bucket/name>: 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}"
}