Setting tag nodemanager-1.8-39
[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 xmlrpclib import dumps, loads
9
10 GPG = '/usr/bin/gpg'
11
12
13 def sign(data):
14     """Return <data> signed with the default GPG key."""
15     msg = dumps((data,), methodresponse = True)
16     p = _popen_gpg('--armor', '--sign', '--keyring', '/etc/planetlab/secring.gpg', '--no-default-keyring')
17     p.stdin.write(msg)
18     p.stdin.close()
19     signed_msg = p.stdout.read()
20     p.stdout.close()
21     p.stderr.close()
22     p.wait()
23     return signed_msg
24
25 def verify(signed_msg):
26     """If <signed_msg> is a valid signed document, return its contents.  Otherwise, return None."""
27     p = _popen_gpg('--decrypt', '--keyring', '/usr/boot/pubring.gpg', '--no-default-keyring')
28     p.stdin.write(signed_msg)
29     p.stdin.close()
30     msg = p.stdout.read()
31     p.stdout.close()
32     p.stderr.close()
33     if p.wait(): return None  # verification failed
34     else:
35         data, = loads(msg)[0]
36         return data
37
38 def _popen_gpg(*args):
39     """Return a Popen object to GPG."""
40     return Popen((GPG, '--batch', '--no-tty') + args, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)