def execute(self): log.debug("Configured with {0}".format(self.config.parent.items())) if "entities" in self.config: entityIds = self.config["entities"] else: entityIds = yield self.pub.listEntities() p = self._getMaxLen(entityIds) for eid in entityIds: try: ent = yield self.pub.getEntity(eid) keyInfos = yield ent.listKeys() for (keyId, (keyType, comment)) in keyInfos.iteritems(): if self.config["fingerprint"]: pubKey = yield ent.getKey(keyId) keyData = pubKey.data.decode("base64") key = crypto.Key.fromString(keyData) keyId = key.fingerprint() print "{eid:{p}} {type} {kid} {comment} ".format( eid=eid, p=p, kid=keyId, type=keyType, comment=comment) except EntityNotFound: print >>sys.stderr, "{eid:{p}} Not found".format(eid=eid, p=p) self.returnValue = 1
def authorize(self, scheme, **params): identifier = self.getIdentifierInRealm(params["realm"]) if identifier: log.debug("Using idenitifier {0} for realm {1[realm]}".format( identifier, params), system=repr(self)) cred = {"challenge": params["challenge"], "realm": params["realm"], "id": identifier, } log.debug("Signing challenge with {0.key.id}".format(self)) try: cred["signature"] = yield self.signAuth(cred) log.debug("Signed challenge") auth = ", ".join(["{0}=\"{1}\"".format(*i) for i in cred.items()]) authorization = "{0} {1}".format(scheme, auth) log.debug("Authorization: {0}".format(authorization)) except: log.err() raise else: log.debug("{0.key.id} has no idenitifier in realm {1}".format( self, params["realm"]), system=repr(self)) authorization = None yield succeed(True) returnValue(authorization)
def agentDetached(self, agent, reason): log.debug("Detached from SSH agent: {0}".format(agent)) try: self.agents.remove(agent) except: log.err() self._pruneAgentKeys(agent)
def eb_setExitValue(self, reason): if reason.check(SystemExit): self.exitValue = reason.value.code else: self.exitValue = os.EX_SOFTWARE log.debug("Setting exit value to {0} from {1}".format( self.exitValue, reason.getErrorMessage())) return reason
def decode(self, response, request): """Decode an authorization response into a SignedAuthorization.""" log.debug("Decoding authorization.") auth = self._parseAuth(response) try: self._verifyChallenge(auth["challenge"], request) creds = self.buildCredentials(auth, request) except KeyError, ke: raise LoginFailed("{0!r} not in authorization".format(*ke.args))
def default(self, obj): log.debug("Finding JSON representation for {0!r}".format(obj)) if IEntity.providedBy(obj): return {"id": obj.id, "species": obj.species, "primaryKeyId": obj.primaryKeyId} elif IPublicKey.providedBy(obj): return {"id": obj.id, "type": obj.type, "data": obj.data, "comment": obj.comment, "entityId": obj.entityId} elif isinstance(obj, Exception): return {"type": obj.__class__.__name__, "args": obj.args} else: return super(PubJSONEncoder, self).default(obj)
def _selectParseHeader(self, header): """Find an authentication scheme in a case-insensitive way.""" log.debug("Finding an authenticator for {0}".format(header)) scheme, elements = header.split(' ', 1) for fact in self._credentialFactories: if fact.scheme.lower() == scheme.lower(): log.debug("Found an authenticator: {0}".format(fact)) return (fact, elements) log.warn("No matching authenticator found for {0}".format(scheme)) return (None, None)
def startService(self): """Initiate execution.""" Service.startService(self) ds = [] for svc in self: log.debug("{0} starting service: {1}".format(self, svc)) d = maybeDeferred(svc.startService) ds.append(d) yield gatherResults(ds) yield self._execute()
def __init__(self, config): super(PubService, self).__init__() self.config = config self.baseUrl = config["server"] self.auth = config.authenticator if self.auth: log.debug("PubService authenticator: {0.auth}".format(self)) self.auth.setServiceParent(self) self.agent = config.agent
def _completed(self, value): """Called when command execution is complete. Stops the reactor. Attributes: value -- The return value of command.execute, or a Failure. Returns: value """ log.debug("Completed execution: {0}".format(value)) log.debug("Exit value: {0}".format(self.exitValue)) self.stopReactor() return value
def registerKey(self, key, comment, _tx=None): log.debug("Registering key: {0.id}".format(key)) pk = self._buildKey(key, comment) log.debug("Registering key: {0.id}".format(pk)) if _tx: # Already in a transaction self._db_registerKey(_tx, pk) return succeed(pk) else: return self._db.runInteraction(self._db_registerKey, pk)
def buildCredentials(self, auth, request): log.debug("Building credentials from {0!r}".format(auth)) if not auth.get("id"): raise LoginFailed("No identifier") if not auth.get("realm"): raise LoginFailed("No realm") client = request.getClientIP() or '0.0.0.0' data = self._authFmt.format(a=auth, s=self.sep) sig = auth["signature"].decode("base64") creds = PubAuthorization(auth["id"], auth["realm"], client, data, sig) return creds
def execute(self): log.debug("Registering an entity") try: ent = yield self.pub.getEntity(self.config["id"]) pubKey = yield ent.registerKey( self.config["key"], self.config["comment"]) except KeyAlreadyExists: print >>sys.stderr, "Key already exists: {0}".format( self.config["key"].id) else: log.debug("Registered a key") print self._keyFmt.format(pubKey)
def execute(self): log.debug("Registering an entity") entId = self.config["id"] try: ent = yield self.pub.registerEntity(entId, self.config["species"], self.config["key"]) except EntityAlreadyExists: print >>sys.stderr, "Entity already exists: {0!s}".format(entId) raise SystemExit(1) else: log.debug("Registered an entity") print self._entFmt.format(ent)
def _registerKey(self, request): posted = json.load(request.content) keyInfo = posted["key"] if "entityId" in keyInfo and keyInfo["entityId"] != self.entity.id: raise RuntimeError("Bad entity ID") keyData = keyInfo["data"].decode("base64") log.debug("Registering key: {0}".format(keyInfo["id"])) key = yield self.entity.registerKey(keyData, keyInfo["comment"]) log.debug("Registered key: {0}".format(key)) request.setHeader("Content-type", "application/json") self.jsonize({"key": key}, request) request.finish()
def buildPubService(self): url = self["server"] log.debug("Building PubService({0})".format(url)) # TODO (Jersey) Plugins? pubBuilders = { "http": self._buildPubService_http, "https": self._buildPubService_http, "sqlite3": self._buildPubService_sqlite3, } scheme = url.scheme.lower() buildService = pubBuilders.get(scheme) if buildService is None: raise cli.UsageError("Unsupported scheme: {0}".format(url)) return buildService(url)
def _verifyChallenge(self, challenge, request): """Verify a challenge as returned from _generateChallenge. """ log.debug("Verifying challenge: {0}".format(challenge)) try: signature, encoded = challenge.split(self.sep) raw = encoded.decode("base64") realm, clientIP, sigTime, seed = raw.split(self.sep) except ValueError: raise LoginFailed("Invalid challenge value") if not self._verify(signature, raw): raise LoginFailed("Invalid signature") if realm != self.realm: raise LoginFailed("Incorrect realm") if self._timeExpired(sigTime): raise LoginFailed("Session expired") if clientIP != (request.getClientIP() or "0.0.0.0"): raise LoginFailed("Incorrect client") return True
def requestAvatar(self, avatarId, _mind, *interfaces): log.msg("{0} is requesting an avatar for {1}.".format(avatarId, " or ".join(i.__name__ for i in interfaces))) if IResource in interfaces: if avatarId in self._seen: a = self._seen[avatarId] else: a = self._seen[avatarId] = self.avatarClass(avatarId) a.loggedIn() interface = IResource avatar = AuthorizedPubResource(a, IResource(self.pubSvc)) logOut = a.loggedOut else: raise NotImplemented(interfaces) log.debug("Avatar: {0!r} {1!r}".format(interface.__name__, avatar.id)) return (interface, avatar, logOut)
def registerKey(self, key, comment): url = self.baseUrl.click("keys/") pubKey = self._buildKey(key, comment) try: rsp = yield self.agent.open(url, method="POST", data=ws.jsonize({"key": pubKey})) except WebError, err: if int(err.status) == http.BAD_REQUEST: try: errInfo = json.loads(err.response.content)["error"] except: log.err() raise err else: log.debug("Decoded JSON error") if errInfo.get("type") == "KeyAlreadyExists": raise iface.KeyAlreadyExists(pubKey) log.err() raise
def showTimeline(self): try: log.debug(("Requesting {0.config[watchee]} timeline since " "{0._lastPrintedId}").format(self)) watchee = self.config["watchee"] params = dict() if self._lastPrintedId: params["since_id"] = self._lastPrintedId messages = yield self.vtwt.getTimeline(watchee, params) messages = self._limitMessages(messages, self.config["limit"]) if messages: self._printMessages(messages) self._lastPrintedId = messages[-1].id except Exception, e: if repr(self._lastError) != repr(e): print >>sys.stderr, self.failWhale(e) self._lastError = e
def registerEntity(self, entId, species, key): url = self.baseUrl.click("entities/") ent = self._buildEntity(entId, species, key.id) pubKey = self._buildKey(key, entId, "primary") try: rsp = yield self.agent.open(url, method="POST", data=ws.jsonize({"entity": ent, "key": pubKey, })) except WebError, err: if int(err.status) == http.BAD_REQUEST: try: errInfo = json.loads(err.response.content)["error"] except: log.err() raise err else: log.debug("Decoded JSON error") if errInfo.get("type") == "EntityAlreadyExists": raise iface.EntityAlreadyExists(entId) log.err() raise
def test_commandsUsage(self): self.assertEquals(self.expectedSynopsis, self.options.getSynopsis()) for name in self.plugins.iterkeys(): if not name.startswith("_"): plugin = self.options.getCommand(name) self.assertNotEquals(None, plugin) self.assertEquals(name, plugin.name) self.assertEquals(name[0], plugin.shortcut) self.assertTrue(plugin.description) self.assertRaises(KeyError, self.options.getCommand, "donkey") usage = self.options.getUsage() log.debug("USAGE: {0!r}".format(usage)) usageLines = usage.splitlines() self.assertEquals(len(self.expectedUsageLines), len(usageLines), "Unexpected usage statement\n{0!r}".format("\n".join(usageLines))) for expected, got in zip(self.expectedUsageLines, usageLines): self.assertEquals(expected, got.strip())
def startService(self): klass = self.__class__.__name__ log.debug("Starting: {0}".format(self)) self._waiting = Deferred() Service.startService(self) i = 0 for svc in self: i += 1 log.debug("{0} starting [{2}]: {1.__class__.__name__}".format( klass, svc, i)) yield maybeDeferred(svc.startService) log.debug("{0} waiting for agents".format(klass)) yield self._waiting log.debug("{0} loading keys".format(klass)) yield self.loadKeys()
def requestAvatarId(self, cred): log.debug("{0} is requesting an avatar ID.".format(cred.identifier)) try: entity = yield self.svc.getEntity(cred.identifier) keyInfo = yield entity.listKeys() keys = [] for keyId in keyInfo.iterkeys(): try: key = yield entity.getKey(keyId) except KeyNotFound, knf: # Weidness afoot log.warn("Key disappeared! {0}".format(keyId)) else: log.debug("{0} {2} {1}".format(key.id, keyId, "==" if key.id == keyId else "!=")) keys.append(key) except EntityNotFound: raise self.UnauthorizedLogin("Invalid entity", cred.identifier) if not self._verifySignatureByKeys(cred, keys): raise self.UnauthorizedLogin("Invalid signature") returnValue(cred.identifier)
def loadKeys(self): log.debug("Loading keys from auth {0} agents".format(len(self.agents))) keys = {} for agent in self.agents: log.debug("Requesting keys from {0}".format(agent)) rawKeys = yield agent.requestIdentities() log.debug("Loaded {0} keys from {1}".format(len(rawKeys), agent)) for blob, comment in rawKeys: k = Key.fromString(blob) k.comment = comment k.agent = agent keys[k.id] = k log.debug("Loaded {0} keys from {1} agents".format( len(keys), len(self.agents))) self._updateKeys(keys) returnValue(keys)
def registerEntity(self, id, species, primaryKey, _tx=None): """ Arguments: id -- Entity id species -- Entity species name. primaryKey -- Entity's primary public key. Instance of pub.crypto.Key. """ log.debug("Registering entity: {0}".format(id)) ent = self._buildEntity(id, species, primaryKey.id) try: if _tx: yield self._db_registerEntity(_tx, ent, primaryKey) else: yield self._db.runInteraction( self._db_registerEntity, ent, primaryKey) except IntegrityError, err: if err.args[0] == "column id is not unique": raise iface.EntityAlreadyExists(id) else: raise err
def done(self): self.json = None if "Content-type" in self.headers: ctype = self.headers["Content-type"][0] log.debug("Content-type is: {0}".format(ctype)) if ctype == self._jsonType: self.json = json.loads(self.content) else: log.debug("No content-type in headers: {0}".format( self.headers)) log.debug("Content: {0}".format(self.content))
def _verifySignatureByKeys(credentials, keys): log.debug("Verifying signature") verified = False while len(keys) and not verified: key = keys.pop() verified = key.verify(credentials.signature, credentials.data) if not verified: log.debug("Signature verification failure: {0.id}".format(key)) if verified: log.debug("Signature verifified: {0.id}".format(key)) return verified
def startService(self): klass = self.__class__.__name__ log.debug("Starting: {0}".format(klass)) Service.startService(self) ds = [] for svc in self: log.debug("{0} starting service: {1}".format(klass, svc)) d = maybeDeferred(svc.startService) ds.append(d) yield gatherResults(ds) if self.auth: self.agent.authenticators = auths = self.auth.buildAuthenticators() log.debug("Built {1} authenticators: {0}".format(auths, len(auths)))
def render(self, request): log.debug("Rendering authorized root: {0!r}".format(self.root)) return self.root.render(request)