2 Python interface to GnuPG.
4 This module is used to invoke GnuPG to check the digital signatures on interfaces.
6 @see: L{iface_cache.PendingFeed}
9 # Copyright (C) 2006, Thomas Leonard
10 # See the README file for details, or visit http://0install.net.
16 from trust
import trust_db
17 from model
import SafeException
20 """Abstract base class for signature check results."""
23 def __init__(self
, status
):
26 def is_trusted(self
, domain
= None):
30 """Returns the ID of the key that must be downloaded to check this signature."""
33 class ValidSig(Signature
):
34 """A valid signature check result."""
39 return "Valid signature from " + self
.status
[self
.FINGERPRINT
]
41 def is_trusted(self
, domain
= None):
42 return trust_db
.is_trusted(self
.status
[self
.FINGERPRINT
], domain
)
44 def get_timestamp(self
):
45 return int(self
.status
[self
.TIMESTAMP
])
47 fingerprint
= property(lambda self
: self
.status
[self
.FINGERPRINT
])
49 def get_details(self
):
50 cin
, cout
= os
.popen2(('gpg', '--with-colons', '--no-secmem-warning', '--list-keys', self
.fingerprint
))
54 details
.append(line
.split(':'))
58 class BadSig(Signature
):
59 """A bad signature (doesn't match the message)."""
63 return "BAD signature by " + self
.status
[self
.KEYID
] + \
64 " (the message has been tampered with)"
66 class ErrSig(Signature
):
67 """Error while checking a signature."""
73 msg
= "ERROR signature by %s: " % self
.status
[self
.KEYID
]
74 rc
= int(self
.status
[self
.RC
])
76 msg
+= "Unknown or unsupported algorithm '%s'" % self
.status
[self
.ALG
]
78 msg
+= "Unknown key. Try 'gpg --recv-key %s'" % self
.status
[self
.KEYID
]
80 msg
+= "Unknown reason code %d" % rc
84 rc
= int(self
.status
[self
.RC
])
86 return self
.status
[self
.KEYID
]
93 def __init__(self
, fingerprint
):
94 self
.fingerprint
= fingerprint
95 self
.name
= '(unknown)'
97 def get_short_name(self
):
98 return self
.name
.split(' (', 1)[0].split(' <', 1)[0]
100 def load_keys(fingerprints
):
101 """Load a set of keys at once.
102 This is much more efficient than making individual calls to L{load_key}.
103 @return: a list of loaded keys, indexed by fingerprint
104 @rtype: {str: L{Key}}
108 for fp
in fingerprints
:
113 cin
, cout
= os
.popen2(['gpg', '--fixed-list-mode', '--with-colons', '--list-keys', '--with-fingerprint'] + fingerprints
)
117 if line
.startswith('pub:'):
119 if line
.startswith('fpr:'):
120 assert current_fpr
is None
121 current_fpr
= line
.split(':')[9]
122 if line
.startswith('uid:'):
123 assert current_fpr
is not None
124 parts
= line
.split(':')
125 keys
[current_fpr
].name
= parts
[9]
131 def load_key(fingerprint
):
132 """Query gpg for information about this key.
136 return load_keys([fingerprint
])[fingerprint
]
138 def import_key(stream
):
139 """Run C{gpg --import} with this stream as stdin."""
140 errors
= tempfile
.TemporaryFile()
147 os
.dup2(stream
.fileno(), 0)
148 os
.dup2(errors
.fileno(), 2)
149 os
.execlp('gpg', 'gpg', '--no-secmem-warning', '--quiet', '--import')
151 traceback
.print_exc()
156 pid
, status
= os
.waitpid(child
, 0)
160 error_messages
= errors
.read().strip()
164 raise SafeException("Errors from 'gpg --import':\n%s" % error_messages
)
166 def _check_plain_stream(stream
):
167 data
= tempfile
.TemporaryFile() # Python2.2 does not support 'prefix'
168 errors
= tempfile
.TemporaryFile()
170 status_r
, status_w
= os
.pipe()
179 os
.dup2(stream
.fileno(), 0)
180 os
.dup2(data
.fileno(), 1)
181 os
.dup2(errors
.fileno(), 2)
182 os
.execlp('gpg', 'gpg', '--no-secmem-warning', '--decrypt',
183 # Not all versions support this:
184 #'--max-output', str(1024 * 1024),
186 '--status-fd', str(status_w
))
188 traceback
.print_exc()
197 sigs
= _get_sigs_from_gpg_status_stream(status_r
, child
, errors
)
202 def _check_xml_stream(stream
):
203 xml_comment_start
= '<!-- Base64 Signature'
205 data_to_check
= stream
.read()
207 last_comment
= data_to_check
.rfind('\n' + xml_comment_start
)
209 raise SafeException("No signature block in XML. Maybe this file isn't signed?")
210 last_comment
+= 1 # Include new-line in data
212 data
= tempfile
.TemporaryFile()
213 data
.write(data_to_check
[:last_comment
])
215 os
.lseek(data
.fileno(), 0, 0)
217 errors
= tempfile
.TemporaryFile()
219 sig_lines
= data_to_check
[last_comment
:].split('\n')
220 if sig_lines
[0].strip() != xml_comment_start
:
221 raise SafeException('Bad signature block: extra data on comment line')
222 while sig_lines
and not sig_lines
[-1].strip():
224 if sig_lines
[-1].strip() != '-->':
225 raise SafeException('Bad signature block: last line is not end-of-comment')
226 sig_data
= '\n'.join(sig_lines
[1:-1])
228 if re
.match('^[ A-Za-z0-9+/=\n]+$', sig_data
) is None:
229 raise SafeException("Invalid characters found in base 64 encoded signature")
231 sig_data
= base64
.decodestring(sig_data
) # (b64decode is Python 2.4)
232 except Exception, ex
:
233 raise SafeException("Invalid base 64 encoded signature: " + str(ex
))
235 sig_fd
, sig_name
= tempfile
.mkstemp(prefix
= 'injector-sig-')
237 sig_file
= os
.fdopen(sig_fd
, 'w')
238 sig_file
.write(sig_data
)
241 status_r
, status_w
= os
.pipe()
250 os
.dup2(data
.fileno(), 0)
251 os
.dup2(errors
.fileno(), 2)
252 os
.execlp('gpg', 'gpg', '--no-secmem-warning',
253 # Not all versions support this:
254 #'--max-output', str(1024 * 1024),
256 '--status-fd', str(status_w
),
257 '--verify', sig_name
, '-')
259 traceback
.print_exc()
268 sigs
= _get_sigs_from_gpg_status_stream(status_r
, child
, errors
)
270 os
.lseek(stream
.fileno(), 0, 0)
274 return (stream
, sigs
)
276 def _find_in_path(prog
):
277 for d
in os
.environ
['PATH'].split(':'):
278 path
= os
.path
.join(d
, prog
)
279 if os
.path
.isfile(path
):
283 def check_stream(stream
):
284 """Pass stream through gpg --decrypt to get the data, the error text,
285 and a list of signatures (good or bad). If stream starts with "<?xml "
286 then get the signature from a comment at the end instead (and the returned
287 data is the original stream). stream must be seekable.
288 @note: Stream returned may or may not be the one passed in. Be careful!
289 @return: (data_stream, [Signatures])"""
290 if not _find_in_path('gpg'):
291 raise SafeException("GnuPG is not installed ('gpg' not in $PATH). See http://gnupg.org")
297 start
= stream
.read(6)
299 if start
== "<?xml ":
300 return _check_xml_stream(stream
)
302 os
.lseek(stream
.fileno(), 0, 0)
303 return _check_plain_stream(stream
)
305 def _get_sigs_from_gpg_status_stream(status_r
, child
, errors
):
306 """Read messages from status_r and collect signatures from it.
307 When done, reap 'child'.
308 If there are no signatures, throw SafeException (using errors
309 for the error message if non-empty)."""
312 # Should we error out on bad signatures, even if there's a good
315 for line
in os
.fdopen(status_r
):
316 assert line
.endswith('\n')
317 assert line
.startswith('[GNUPG:] ')
319 split_line
= line
.split(' ')
321 args
= split_line
[1:]
322 if code
== 'VALIDSIG':
323 sigs
.append(ValidSig(args
))
324 elif code
== 'BADSIG':
325 sigs
.append(BadSig(args
))
326 elif code
== 'ERRSIG':
327 sigs
.append(ErrSig(args
))
329 pid
, status
= os
.waitpid(child
, 0)
334 error_messages
= errors
.read().strip()
339 raise SafeException("No signatures found. Errors from GPG:\n%s" % error_messages
)
341 raise SafeException("No signatures found. No error messages from GPG.")