reguire gnupg1 on f>=31; sense the system to use gpg1 when installed
[nodemanager.git] / ticket.py
1 """An extremely simple interface to the signing/verifying capabilities
2 of gnupg.
3
4 You must already have the key in the keyring.
5 """
6
7 from subprocess import PIPE, Popen
8 from xmlrpc.client import dumps, loads
9
10 # see also myplc/plc.d/gpg
11 import os.path
12 GPG = '/usr/bin/gpg1' if os.path.exists("/usr/bin/gpg1") else "/usr/bin/gpg"
13
14 def _popen_gpg(*args):
15     """Return a Popen object to GPG."""
16     return Popen((GPG, '--batch', '--no-tty') + args,
17                  stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
18
19 def sign(data):
20     """Return <data> signed with the default GPG key."""
21     msg = dumps((data,), methodresponse = True)
22     p = _popen_gpg('--armor', '--sign', '--keyring', '/etc/planetlab/secring.gpg', '--no-default-keyring')
23     p.stdin.write(msg)
24     p.stdin.close()
25     signed_msg = p.stdout.read()
26     p.stdout.close()
27     p.stderr.close()
28     p.wait()
29     return signed_msg
30
31 def verify(signed_msg):
32     """If <signed_msg> is a valid signed document, return its contents.  Otherwise, return None."""
33     p = _popen_gpg('--decrypt', '--keyring', '/usr/boot/pubring.gpg', '--no-default-keyring')
34     p.stdin.write(signed_msg)
35     p.stdin.close()
36     msg = p.stdout.read()
37     p.stdout.close()
38     p.stderr.close()
39     if p.wait():
40         return None  # verification failed
41     else:
42         data, = loads(msg)[0]
43         return data