summaryrefslogtreecommitdiff
path: root/src/samizdat-password-agent
blob: 0fb26c64f913def6ddf633591199e99fd0fb7f8f (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
#!/bin/sh
[ "$(id -u)" -gt 0 ] && exec sudo "$0" "$@"

scan_gnupg_db()
{
  keylist=
  mainkeygrip=
  uid=
  local IFS='
'
  for record in $(gpg2 --with-fingerp --with-fingerp --with-colons -K | cut -d: -f1,5,10); do
    : "$record"
    case "$record" in
      fpr:*) keylist="$keylist ${record##*:}" ;;
      sec:*)
	if [ -z "$mainkeygrip" ]; then
	  mainkeygrip="${record#sec:}"
	  mainkeygrip="${mainkeygrip%%:*}"
	fi ;;
      uid:*) : ${uid:=${record#uid:*:}} ;;
    esac
  done
}

eval $(samizdat-gpg-agent)

gpg2_test_sign()
{
  GPG_TTY=none gpg2 \
    --ignore-valid-from --ignore-time-conflict --no-tty --batch --clearsign </dev/null >/dev/null 2>&1
}

if [ ! "$FORCE_PINENTRY" ] && gpg2_test_sign; then
  echo "Made signature with default key successfully.  No additional passphrase is needed." >&2
  exit
fi

scan_gnupg_db # get $uid

if [ "$uid" ]; then
  DESC='Please enter the passphrase to unlock the secret key for the OpenPGP certificate:%0A'"'$uid'."
else
  DESC='Please enter the passphrase to unlock the secret key for the OpenPGP certificate.'
fi

exec samizdat-pinentry \
  --setdesc "$DESC" \
  --ttyname "$(tty)" \
  --socket "${GPG_AGENT_INFO%%:*}" \
  --resocket /root/"${GPG_AGENT_INFO%%:*}" \
  --tell-immediately '
    read secret
    for grip in '"$keylist"' -; do
      read status || break
      printf "< %s\n" "$status" >&2
      [ -z "${status##OK*}" ] || break
      [ "$grip" = - ] && break
      printf "> PRESET_PASSPHRASE %s -1 %%s\n" "$grip" >&2
      printf "PRESET_PASSPHRASE %s -1 %s\n" "$grip" "$secret"
    done
  ' \
  --validate '
    exec 7<&0
    gpgoutput=$(gpg2 --batch --no-tty --ignore-valid-from --ignore-time-conflict \
      --passphrase-fd 7 --default-key '"$mainkeygrip"' --clearsign </dev/null >/dev/null)
    status=$?
    case "$gpgoutput" in
      *"Bad passphrase"*) echo "Error: Bad passphrase." ;;
      "") [ $status -eq 0 ] || echo "Error: gpg returned $status." ;;
      *) printf "gpg returned unexpected error (exit status $status):\n%s\n" "$gpgoutput" ;;
    esac
    exit $status
  ' \