aboutsummaryrefslogtreecommitdiff
path: root/scripts/generate.sh
blob: 1d61bb50e103fa41a0c8e966537e70a2974170af (plain) (blame)
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
#!/usr/bin/env bash

#set -x  # uncomment to debug
set -o errtrace
set -o nounset
set -o pipefail

umask 077

export LC_ALL="C"

export GNUPGHOME=$(mktemp -d -t $(date +%Y.%m.%d)-XXXX)

cd "${GNUPGHOME}" ; printf "saving to %s\n" "$(pwd)"

export IDENTITY="YubiKey User <yubikey@example.domain>"

export KEY_TYPE="rsa4096"

export KEY_EXPIRATION="2027-05-01"

get_pass () {
    # Returns random passphrase.
    tr -dc "A-Z2-9" < /dev/urandom | \
        tr -d "IOUS5" | \
        fold  -w  ${PASS_GROUPSIZE:-4} | \
        paste -sd ${PASS_DELIMITER:--} - | \
        head  -c  ${PASS_LENGTH:-29}
}

export CERTIFY_PASS="$(get_pass)"

gen_key_certify () {
    # Generates Certify key with no expiration.
    echo "$CERTIFY_PASS" | \
        gpg --batch --passphrase-fd 0 \
            --quick-generate-key "$IDENTITY" \
            "$KEY_TYPE" "cert" "never"
}

set_key_id_fp () {
    # Sets Key ID and Fingerprint environment vars.
    export KEYID=$(gpg -k --with-colons "$IDENTITY" | \
        awk -F: '/^pub:/ { print $5; exit }')
    export KEYFP=$(gpg -k --with-colons "$IDENTITY" | \
        awk -F: '/^fpr:/ { print $10; exit }')
}

gen_key_certify

set_key_id_fp

printf "\nKey ID: %40s\nKey FP: %40s\n\n" "$KEYID" "$KEYFP"

gen_key_subs () {
    # Generates Subkeys with specified expiration.
    for SUBKEY in sign encrypt auth ; do \
        echo "$CERTIFY_PASS" | \
            gpg --batch --passphrase-fd 0 \
                --pinentry-mode=loopback \
                --quick-add-key "$KEYFP" \
                "$KEY_TYPE" "$SUBKEY" "$KEY_EXPIRATION"
    done
}

gen_key_subs

list_keys () {
    # Prints available secret keys.
    gpg --list-secret-keys
}

save_secrets () {
    # Exports secret keys to local files.
    echo "$CERTIFY_PASS" | \
        gpg --output $GNUPGHOME/$KEYID-Certify.key \
            --batch --pinentry-mode=loopback --passphrase-fd 0 \
            --armor --export-secret-keys $KEYID

    echo "$CERTIFY_PASS" | \
        gpg --output $GNUPGHOME/$KEYID-Subkeys.key \
            --batch --pinentry-mode=loopback --passphrase-fd 0 \
            --armor --export-secret-subkeys $KEYID
}

save_pubkey () {
    # Exports public key to local file.
    gpg --output $GNUPGHOME/$KEYID-$(date +%F).asc \
        --armor --export $KEYID
}

list_keys

save_secrets

save_pubkey

printf "CERTIFY PASS: \n$CERTIFY_PASS\n\n"

export LUKS_PASS="$(get_pass)"

printf "LUKS PASS:\n$LUKS_PASS\n\n"