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