|
| 1 | +#! /bin/bash |
| 2 | +# Generate, regenerate or display the TOTP secret used by OTP_ACCESS. |
| 3 | + |
| 4 | +set -e |
| 5 | + |
| 6 | +# absolute, and matching the secret= passed to pam_google_authenticator, so the |
| 7 | +# helper and the PAM module always agree on the file regardless of $HOME |
| 8 | +SECRET_FILE=/config/.google_authenticator |
| 9 | + |
| 10 | +usage() { |
| 11 | + cat << EOF |
| 12 | +Usage: |
| 13 | + otp-setup Generate a TOTP secret, or regenerate it after asking. |
| 14 | + Prints the QR code, the secret and the scratch codes. |
| 15 | + otp-setup --show Print the current secret file again. |
| 16 | + otp-setup --help Show this help. |
| 17 | +EOF |
| 18 | +} |
| 19 | + |
| 20 | +case "${1:-}" in |
| 21 | + --show|-s) |
| 22 | + if [[ ! -f "$SECRET_FILE" ]]; then |
| 23 | + echo "No OTP secret yet. Run 'otp-setup' to create one." |
| 24 | + exit 1 |
| 25 | + fi |
| 26 | + echo "This prints your secret and scratch codes in clear text. Make sure" |
| 27 | + echo "nobody is watching and that this session is not being recorded." |
| 28 | + echo |
| 29 | + echo "=== ${SECRET_FILE} ===" |
| 30 | + echo "First line is the base32 secret, the trailing digit lines are the" |
| 31 | + echo "emergency scratch codes." |
| 32 | + echo |
| 33 | + cat "$SECRET_FILE" |
| 34 | + ;; |
| 35 | + --help|-h) |
| 36 | + usage |
| 37 | + ;; |
| 38 | + "") |
| 39 | + if [[ -f "$SECRET_FILE" ]]; then |
| 40 | + read -r -p "A secret already exists in ${SECRET_FILE}. Regenerating invalidates the old one. Continue? [y/N] " answer || answer="" |
| 41 | + if [[ ! "$answer" =~ ^[Yy]$ ]]; then |
| 42 | + echo "Aborted." |
| 43 | + exit 0 |
| 44 | + fi |
| 45 | + backup="${SECRET_FILE}.bak.$(date +%s)" |
| 46 | + cp "$SECRET_FILE" "$backup" |
| 47 | + echo "Old secret kept in ${backup}" |
| 48 | + fi |
| 49 | + |
| 50 | + # typing the first code back catches a QR that was scanned wrong, but |
| 51 | + # there is nothing to type it with when this runs without a terminal, |
| 52 | + # as it does under docker exec |
| 53 | + confirm=() |
| 54 | + if [[ ! -t 0 ]]; then |
| 55 | + confirm=(--no-confirm) |
| 56 | + fi |
| 57 | + |
| 58 | + # -t time based, -d one use per code, -f write without asking, |
| 59 | + # -r 3 -R 30 three attempts per 30s, -W narrow the accepted time window |
| 60 | + google-authenticator -t -d -f -r 3 -R 30 -W "${confirm[@]}" -s "$SECRET_FILE" |
| 61 | + chmod 600 "$SECRET_FILE" |
| 62 | + |
| 63 | + echo |
| 64 | + echo "=== setup complete ===" |
| 65 | + echo "Scan the QR code above with your authenticator application." |
| 66 | + echo "Write down the scratch codes, they are the only way back in if you" |
| 67 | + echo "lose the application." |
| 68 | + echo "Your next login asks for a 6 digit code." |
| 69 | + ;; |
| 70 | + *) |
| 71 | + usage |
| 72 | + exit 2 |
| 73 | + ;; |
| 74 | +esac |
0 commit comments