38"""Abstract base class for signature check results. 39 @ivar status: the raw data returned by GPG 40 @ivar messages: any messages printed by GPG which may be relevant to this signature 41 """ 42status=None 43messages=None 44
128"""A GPG key.129 @since: 0.27130 @ivar fingerprint: the fingerprint of the key131 @type fingerprint: str132 @ivar name: a short name for the key, extracted from the full name133 @type name: str134 """
144"""Load a set of keys at once.145 This is much more efficient than making individual calls to L{load_key}.146 @type fingerprints: [str]147 @return: a list of loaded keys, indexed by fingerprint148 @rtype: {str: L{Key}}149 @since: 0.27"""150importcodecs151152keys={}153154# Otherwise GnuPG returns everything...155ifnotfingerprints:returnkeys156157forfpinfingerprints:158keys[fp]=Key(fp)159160current_fpr=None161current_uid=None162163child=_run_gpg(['--fixed-list-mode','--with-colons','--list-keys',164'--with-fingerprint','--with-fingerprint']+fingerprints,stdout=subprocess.PIPE)165try:166forlineinchild.stdout:167ifline.startswith('pub:'):168current_fpr=None169current_uid=None170ifline.startswith('fpr:'):171current_fpr=line.split(':')[9]172ifcurrent_fprinkeysandcurrent_uid:173# This is probably a subordinate key, where the fingerprint174# comes after the uid, not before. Note: we assume the subkey is175# cross-certified, as recent always ones are.176try:177keys[current_fpr].name=codecs.decode(current_uid,'utf-8')178except:179logger.warning("Not UTF-8: %s",current_uid)180keys[current_fpr].name=current_uid181ifline.startswith('uid:'):182assertcurrent_fprisnotNone183# Only take primary UID184ifcurrent_uid:continue185parts=line.split(':')186current_uid=parts[9]187ifcurrent_fprinkeys:188keys[current_fpr].name=current_uid189finally:190child.stdout.close()191192ifchild.wait():193logger.warning(_("gpg --list-keys failed with exit code %d")%child.returncode)194195returnkeys
198"""Query gpg for information about this key.199 @return: a new key200 @rtype: L{Key}201 @since: 0.27"""202returnload_keys([fingerprint])[fingerprint]
205"""Run C{gpg --import} with this stream as stdin.206 @type stream: file"""207withtempfile.TemporaryFile(mode='w+t')aserrors:208child=_run_gpg(['--quiet','--import','--batch'],209stdin=stream,stderr=errors)210211status=child.wait()212213errors.seek(0)214error_messages=errors.read().strip()215216ifstatus!=0:217iferror_messages:218raiseSafeException(_("Errors from 'gpg --import':\n%s")%error_messages)219else:220raiseSafeException(_("Non-zero exit code %d from 'gpg --import'")%status)221eliferror_messages:222logger.warning(_("Warnings from 'gpg --import':\n%s")%error_messages)
225"""@type stream: file226 @rtype: (file, [L{Signature}])"""227xml_comment_start=b'<!-- Base64 Signature'228229data_to_check=stream.read()230231last_comment=data_to_check.rfind(b'\n'+xml_comment_start)232iflast_comment<0:233raiseSafeException(_("No signature block in XML. Maybe this file isn't signed?"))234last_comment+=1# Include new-line in data235236# Copy the file to 'data', without the signature237# Copy the signature to 'sig'238239withtempfile.TemporaryFile(mode='w+b')asdata:240data.write(data_to_check[:last_comment])241data.flush()242os.lseek(data.fileno(),0,0)243244withtempfile.TemporaryFile('w+t')aserrors:245sig_lines=data_to_check[last_comment:].split(b'\n')246ifsig_lines[0].strip()!=xml_comment_start:247raiseSafeException(_('Bad signature block: extra data on comment line'))248whilesig_linesandnotsig_lines[-1].strip():249delsig_lines[-1]250ifsig_lines[-1].strip()!=b'-->':251raiseSafeException(_('Bad signature block: last line is not end-of-comment'))252sig_data=b'\n'.join(sig_lines[1:-1])253254ifre.match(b'^[ A-Za-z0-9+/=\n]+$',sig_data)isNone:255raiseSafeException(_("Invalid characters found in base 64 encoded signature"))256try:257ifhasattr(base64,'decodebytes'):258sig_data=base64.decodebytes(sig_data)# Python 3259else:260sig_data=base64.decodestring(sig_data)# Python 2261exceptExceptionasex:262raiseSafeException(_("Invalid base 64 encoded signature: %s")%str(ex))263264withtempfile.NamedTemporaryFile(prefix='injector-sig-',mode='wb',delete=False)assig_file:265sig_file.write(sig_data)266267try:268# Note: Should ideally close status_r in the child, but we want to support Windows too269child=_run_gpg([# Not all versions support this:270#'--max-output', str(1024 * 1024),271'--batch',272# Windows GPG can only cope with "1" here273'--status-fd','1',274# Don't try to download missing keys; we'll do that275'--keyserver-options','no-auto-key-retrieve',276'--verify',sig_file.name,'-'],277stdin=data,278stdout=subprocess.PIPE,279stderr=errors)280281try:282sigs=_get_sigs_from_gpg_status_stream(child.stdout,child,errors)283finally:284os.lseek(stream.fileno(),0,0)285errors.close()286child.stdout.close()287child.wait()288stream.seek(0)289finally:290os.unlink(sig_file.name)291return(stream,sigs)
294"""Verify the GPG signature at the end of stream.295 stream must be seekable.296 @type stream: file297 @return: (stream, [Signatures])298 @rtype: (file, [L{Signature}])"""299300stream.seek(0)301302start=stream.read(6)303stream.seek(0)304ifstart==b"<?xml ":305return_check_xml_stream(stream)306elifstart==b'-----B':307raiseSafeException(_("Plain GPG-signed feeds no longer supported"))308else:309raiseSafeException(_("This is not a Zero Install feed! It should be an XML document, but it starts:\n%s")%repr(stream.read(120)))
312"""Read messages from status_r and collect signatures from it.313 When done, reap 'child'.314 If there are no signatures, throw SafeException (using errors315 for the error message if non-empty).316 @type status_r: file317 @type child: L{subprocess.Popen}318 @type errors: file319 @rtype: [L{Signature}]"""320sigs=[]321322# Should we error out on bad signatures, even if there's a good323# signature too?324325forlineinstatus_r:326assertline.endswith('\n')327ifnotline.startswith('[GNUPG:] '):328# The docs says every line starts with this, but if auto-key-retrieve329# is on then they might not. See bug #3420548330logger.warning("Invalid output from GnuPG: %r",line)331continue332333line=line[9:-1]334split_line=line.split(' ')335code=split_line[0]336args=split_line[1:]337ifcode=='VALIDSIG':338sigs.append(ValidSig(args))339elifcode=='BADSIG':340sigs.append(BadSig(args))341elifcode=='ERRSIG':342sigs.append(ErrSig(args))343344errors.seek(0)345346error_messages=errors.read().strip()347348ifnotsigs:349iferror_messages:350raiseSafeException(_("No signatures found. Errors from GPG:\n%s")%error_messages)351else:352raiseSafeException(_("No signatures found. No error messages from GPG."))353eliferror_messages:354# Attach the warnings to all the signatures, in case they're useful.355forsinsigs:356s.messages=error_messages357358returnsigs