1""" 2Records who we trust to sign feeds. 3 4Trust is divided up into domains, so that it is possible to trust a key 5in some cases and not others. 6 7@var trust_db: Singleton trust database instance. 8""" 9 10# Copyright (C) 2009, Thomas Leonard 11# See the README file for details, or visit http://0install.net. 12 13fromzeroinstallimport_,SafeException,logger 14importos 15 16fromzeroinstallimportsupport 17fromzeroinstall.supportimportbasedir,tasks 18from.namespacesimportconfig_site,config_prog,XMLNS_TRUST 19 20KEY_INFO_TIMEOUT=10# Maximum time to wait for response from key-info-server
23"""A database of trusted keys. 24 @ivar keys: maps trusted key fingerprints to a set of domains for which where it is trusted 25 @type keys: {str: set(str)} 26 @ivar watchers: callbacks invoked by L{notify} 27 @see: L{trust_db} - the singleton instance of this class""" 28__slots__=['keys','watchers','_dry_run'] 29
50"""Return the set of domains in which this key is trusted. 51 If the list includes '*' then the key is trusted everywhere. 52 @type fingerprint: str 53 @rtype: {str} 54 @since: 0.27""" 55self.ensure_uptodate() 56returnself.keys.get(fingerprint,set())
59"""Return the set of keys trusted for this domain. 60 @type domain: str 61 @rtype: {str} 62 @since: 0.27""" 63self.ensure_uptodate() 64returnset([fpforfpinself.keys 65ifdomaininself.keys[fp]])
68"""Add key to the list of trusted fingerprints. 69 @param fingerprint: base 16 fingerprint without any spaces 70 @type fingerprint: str 71 @param domain: domain in which key is to be trusted 72 @type domain: str 73 @note: call L{notify} after trusting one or more new keys""" 74ifself.is_trusted(fingerprint,domain):return 75 76ifself._dry_run: 77print(_("[dry-run] would trust key {key} for {domain}").format(key=fingerprint,domain=domain)) 78 79int(fingerprint,16)# Ensure fingerprint is valid 80 81iffingerprintnotinself.keys: 82self.keys[fingerprint]=set() 83 84#if domain == '*': 85# warn("Calling trust_key() without a domain is deprecated") 86 87self.keys[fingerprint].add(domain) 88self.save()
91"""@type key: str 92 @type domain: str""" 93ifself._dry_run: 94print(_("[dry-run] would untrust key {key} for {domain}").format(key=key,domain=domain)) 95self.ensure_uptodate() 96self.keys[key].remove(domain) 97 98ifnotself.keys[key]: 99# No more domains for this key100delself.keys[key]101102self.save()
132"""Call all watcher callbacks.133 This should be called after trusting or untrusting one or more new keys.134 @since: 0.25"""135forwinself.watchers:w()
138ifself._dry_run:139ifself.keysisNone:self.keys={}140return141fromxml.domimportminidom142143# This is a bit inefficient... (could cache things)144self.keys={}145146trust=basedir.load_first_config(config_site,config_prog,'trustdb.xml')147iftrust:148keys=minidom.parse(trust).documentElement149forkeyinkeys.getElementsByTagNameNS(XMLNS_TRUST,'key'):150domains=set()151self.keys[key.getAttribute('fingerprint')]=domains152fordomaininkey.getElementsByTagNameNS(XMLNS_TRUST,'domain'):153domains.add(domain.getAttribute('value'))154else:155# Convert old database to XML format156trust=basedir.load_first_config(config_site,config_prog,'trust')157iftrust:158#print "Loading trust from", trust_db159withopen(trust,'rt')asstream:160forkeyinstream:161ifkey:162self.keys[key]=set(['*'])
165"""Extract the trust domain for a URL.166 @param url: the feed's URL167 @type url: str168 @return: the trust domain169 @rtype: str170 @since: 0.27171 @raise SafeException: the URL can't be parsed"""172try:173importurlparse174exceptImportError:175fromurllibimportparseasurlparse# Python 3176177ifos.path.isabs(url):178raiseSafeException(_("Can't get domain from a local path: '%s'")%url)179domain=urlparse.urlparse(url)[1]180ifdomainanddomain!='*':181returndomain182raiseSafeException(_("Can't extract domain from URL '%s'")%url)
187"""A TrustMgr handles the process of deciding whether to trust new keys188 (contacting the key information server, prompting the user, accepting automatically, etc)189 @since: 0.53"""190191__slots__=['config','_current_confirm']192
194"""@type config: L{zeroinstall.injector.config.Config}"""195self.config=config196self._current_confirm=None# (a lock to prevent asking the user multiple questions at once)
200"""We don't trust any of the signatures yet. Collect information about them and add the keys to the201 trusted list, possibly after confirming with the user (via config.handler).202 Updates the L{trust} database, and then calls L{trust.TrustDB.notify}.203 @param pending: an object holding details of the updated feed204 @type pending: L{PendingFeed}205 @return: A blocker that triggers when the user has chosen, or None if already done.206 @rtype: None | L{Blocker}207 @since: 0.53"""208209assertpending.sigs210211fromzeroinstall.injectorimportgpg212valid_sigs=[sforsinpending.sigsifisinstance(s,gpg.ValidSig)]213ifnotvalid_sigs:214defformat_sig(sig):215msg=str(sig)216ifsig.messages:217msg+="\nMessages from GPG:\n"+sig.messages218returnmsg
219raiseSafeException(_('No valid signatures found on "%(url)s". Signatures:%(signatures)s')%220{'url':pending.url,'signatures':''.join(['\n- '+format_sig(s)forsinpending.sigs])})221222# Start downloading information about the keys...223fetcher=self.config.fetcher224kfs={}225forsiginvalid_sigs:226kfs[sig]=fetcher.fetch_key_info(sig.fingerprint)227228# Wait up to KEY_INFO_TIMEOUT seconds for key information to arrive. Avoids having the dialog229# box update while the user is looking at it, and may allow it to be skipped completely in some230# cases.231timeout=tasks.TimeoutBlocker(KEY_INFO_TIMEOUT,"key info timeout")232whileTrue:233key_info_blockers=[sig_info.blockerforsig_infoinkfs.values()ifsig_info.blockerisnotNone]234ifnotkey_info_blockers:235break236logger.info("Waiting for response from key-info server: %s",key_info_blockers)237yield[timeout]+key_info_blockers238iftimeout.happened:239logger.info("Timeout waiting for key info response")240break241242# If we're already confirming something else, wait for that to finish...243whileself._current_confirmisnotNone:244logger.info("Waiting for previous key confirmations to finish")245yieldself._current_confirm246247domain=domain_from_url(pending.url)248249ifself.config.auto_approve_keys:250existing_feed=self.config.iface_cache.get_feed(pending.url)251ifnotexisting_feed:252changes=False253trust_db._dry_run=self.config.handler.dry_run254forsig,kfinkfs.items():255forkey_infoinkf.info:256ifkey_info.getAttribute("vote")=="good":257logger.info(_("Automatically approving key for new feed %s based on response from key info server"),pending.url)258trust_db.trust_key(sig.fingerprint,domain)259changes=True260ifchanges:261trust_db.notify()262263# Check whether we still need to confirm. The user may have264# already approved one of the keys while dealing with another265# feed, or we may have just auto-approved it.266forsiginkfs:267is_trusted=trust_db.is_trusted(sig.fingerprint,domain)268ifis_trusted:269return270271# Take the lock and confirm this feed272self._current_confirm=lock=tasks.Blocker('confirm key lock')273try:274done=self.config.handler.confirm_import_feed(pending,kfs)275ifdoneisnotNone:276yielddone277tasks.check(done)278finally:279self._current_confirm=None280lock.trigger()