Script to verify a signature with GPG

6

3

You can feed GPG a file that has been signed and it will spit out a "signature is good" message, and save the plaintext:

[gh403@shillig-arch ~]$ gpg test.gpg 
gpg: Signature made Thu Nov  1 14:19:08 2012 CDT using RSA key ID D1FEC5F4
gpg: Good signature from "gh403 <gh403@***********>"

and I can look at its output and verify that, yes, gh403 signed this and that yes, the signature is good.

What I would like to be able to do is script this behavior. Specifically, I need a script that will check to see that the signature is good and that the key that it has been signed with has a certain ID.

Is there a plain GPG call to do this? Or would I need a more elaborate script? Thanks for any thoughts!

thirtythreeforty

Posted 2012-11-01T19:34:17.957

Reputation: 946

Answers

8

If you add --status-fd <fd>, gpg will output computer-readable status text to the given file descriptor (1 for stdout). For example:

$ gpg --status-fd 1 --verify authorized_keys.txt 
gpg: Signature made 2012-08-18T19:25:12 EEST
gpg:                using RSA key D24F6CB2C1B52632
[GNUPG:] SIG_ID BOn6PNVb1ya/KuUc2F9sfG9HeRE 2012-08-18 1345307112
[GNUPG:] GOODSIG D24F6CB2C1B52632 Mantas Mikulėnas <grawity@nullroute.eu.org>
gpg: Good signature from "Mantas Mikulėnas <grawity@nullroute.eu.org>"
gpg:                 aka "Mantas Mikulėnas <grawity@gmail.com>"
[GNUPG:] VALIDSIG 2357E10CEF4F7ED27E233AD5D24F6CB2C1B52632 2012-08-18 1345307112 0 4 0 1 2 00 2357E10CEF4F7ED27E233AD5D24F6CB2C1B52632
[GNUPG:] TRUST_ULTIMATE

Then just discard the default output (by redirecting 2> /dev/null) and check for VALIDSIG fingerprint.

I use the following:

fprint="2357E10CEF4F7ED27E233AD5D24F6CB2C1B52632"

verify_signature() {
    local file=$1 out=
    if out=$(gpg --status-fd 1 --verify "$file" 2>/dev/null) &&
       echo "$out" | grep -qs "^\[GNUPG:\] VALIDSIG $fprint " &&
       echo "$out" | grep -qs "^\[GNUPG:\] TRUST_ULTIMATE\$"; then
        return 0
    else
        echo "$out" >&2
        return 1
    fi
}

if verify_signature foo.txt; then
    ...
fi

You will probably need to remove the TRUST_ULTIMATE check, but keep VALIDSIG.

user1686

Posted 2012-11-01T19:34:17.957

Reputation: 283 655

Beautiful. Exactly what I was looking for! – thirtythreeforty – 2012-11-01T23:53:31.810