Ejemplo n.º 1
0
    def handle(self, tree, msg, lastRetVal=None):
        iq = tree
        id = iq.get('id')
        if id:
            bind = iq[0]
            if len(bind) > 0:
                resource = bind[0].text
            else:
                # generate an id
                resource = generateId()[:6]

            # TODO: check that we don't already have such a resource
            jid = msg.conn.data['user']['jid']
            bindResource(msg, resource)

            res = Element('iq', {'type' : 'result', 'id' : id})
            bind = Element('bind', {'xmlns' : 'urn:ietf:params:xml:ns:xmpp-bind'})
            jidEl = Element('jid')
            jidEl.text = '%s/%s' % (jid, resource)
            bind.append(jidEl)
            res.append(bind)

            return chainOutput(lastRetVal, res)
        else:
            logging.warning("[%s] No id in <iq>:\n%s", self.__class__, tostring(iq))

        return lastRetVal
Ejemplo n.º 2
0
    def handle(self, tree, msg, lastRetVal=None):
        iq = tree
        id = iq.get("id")
        if id:
            bind = iq[0]
            if len(bind) > 0:
                resource = bind[0].text
            else:
                # generate an id
                resource = generateId()[:6]

            # TODO: check that we don't already have such a resource
            jid = msg.conn.data["user"]["jid"]
            bindResource(msg, resource)

            res = Element("iq", {"type": "result", "id": id})
            bind = Element("bind", {"xmlns": "urn:ietf:params:xml:ns:xmpp-bind"})
            jidEl = Element("jid")
            jidEl.text = "%s/%s" % (jid, resource)
            bind.append(jidEl)
            res.append(bind)

            return chainOutput(lastRetVal, res)
        else:
            logging.warning("[%s] No id in <iq>:\n%s", self.__class__, tostring(iq))

        return lastRetVal
Ejemplo n.º 3
0
    def createRosterQuery(cjid,
                          subName,
                          name=None,
                          groups=None,
                          itemArgs=None):
        """Creates and returns a <query> item for sending in an <iq> in a
        roster push.
        cjid -- jid as a str for the contact in a roster item.
        subName -- name of the subscription as a str.
        name -- name for the contact. Can be None.
        groups -- list of group names as strings.
        """
        itemArgs = itemArgs or {}
        query = Element('query', {'xmlns': 'jabber:iq:roster'})

        d = {
            'jid': cjid,
            'subscription': subName,
        }
        if name:
            d['name'] = name

        d.update(itemArgs)

        item = SubElement(query, 'item', d)

        for groupName in groups:
            if groupName:  # don't want empty groups
                group = Element('group')
                group.text = groupName
                item.append(group)

        return query
Ejemplo n.º 4
0
    def createRosterQuery(cjid, subName, name=None, groups=None, itemArgs=None):
        """Creates and returns a <query> item for sending in an <iq> in a
        roster push.
        cjid -- jid as a str for the contact in a roster item.
        subName -- name of the subscription as a str.
        name -- name for the contact. Can be None.
        groups -- list of group names as strings.
        """
        itemArgs = itemArgs or {}
        query = Element('query', {'xmlns' : 'jabber:iq:roster'})

        d = {
             'jid' : cjid,
             'subscription' : subName,
             }
        if name:
            d['name'] = name

        d.update(itemArgs)

        item = SubElement(query, 'item', d)

        for groupName in groups:
            if groupName: # don't want empty groups
                group = Element('group')
                group.text = groupName
                item.append(group)

        return query
Ejemplo n.º 5
0
    def handle(self, tree, msg, lastRetVal=None):
        iq = tree
        id = iq.get('id')
        if id:
            bind = iq[0]
            if len(bind) > 0:
                resource = bind[0].text
            else:
                # generate an id
                resource = generateId()[:6]

            # TODO: check that we don't already have such a resource
            jid = msg.conn.data['user']['jid']
            bindResource(msg, resource)

            res = Element('iq', {'type': 'result', 'id': id})
            bind = Element('bind',
                           {'xmlns': 'urn:ietf:params:xml:ns:xmpp-bind'})
            jidEl = Element('jid')
            jidEl.text = '%s/%s' % (jid, resource)
            bind.append(jidEl)
            res.append(bind)

            return chainOutput(lastRetVal, res)
        else:
            logging.warning("[%s] No id in <iq>:\n%s", self.__class__,
                            tostring(iq))

        return lastRetVal
Ejemplo n.º 6
0
        def act():
            d = msg.conn.data

            retVal = lastRetVal

            jid = d['user']['jid']
            resource = d['user']['resource']

            roster = Roster(jid)

            presTree = deepcopy(tree)
            presTree.set('from', '%s/%s' % (jid, resource))

            probes = []
            init_rosters = []
            offline_msgs = []
            if tree.get('to') is None and not d['user']['active']:
                # initial presence
                # TODO: we don't need to do it every time. we can cache the
                # data after the first resource is active and just resend
                # that to all new resources
                d['user']['active'] = True

                # get jids of the contacts whose status we're interested in
                cjids = roster.getPresenceSubscriptions()

                probeTree = Element('presence', {
                                                 'type': 'probe',
                                                 'from' : '%s/%s' \
                                                    % (jid, resource)
                                                 })

                # TODO: replace this with a more efficient router handler
                for cjid in cjids:
                    probeTree.set('to', cjid)
                    probeRouteData = {
                                      'to' : cjid,
                                      'data' : deepcopy(probeTree)
                                      }
                    probes.append(probeRouteData)
                    # they're sent first. see below

                # send initial roster list to this user
                rosterTree = Element('presence', {
                                                 'type': 'unavailable',
                                                 'to' : '%s/%s' \
                                                    % (jid, resource)
                                                 })
                for cjid in cjids:
                    rosterTree.set('from', cjid)
                    rosterRouterData = {
                                           'to' : '%s/%s' % (jid, resource),
                                           'data' : deepcopy(rosterTree)
                                       }
                    init_rosters.append(rosterRouterData)

                # send offline message to this user
                try:
                    con = DB()
                    result = []
                    to_jid = JID(jid)
                    with closing(con.cursor()) as cursor:
                        cursor.execute("SELECT fromid, time, content FROM offline WHERE toid = %d ORDER BY time DESC" %
                                       (to_jid.getNumId()))
                        con.commit()
                        result = cursor.fetchall()
                    with closing(con.cursor()) as cursor:
                        cursor.execute("DELETE FROM offline WHERE toid = %d" %
                                       (to_jid.getNumId()))
                        con.commit()
                    for fromid, time, content in result:
                        fromJID = JID(fromid, True).getBare()
                        toJID = '%s/%s' % (jid, resource)

                        reply = Element('message', {
                            'to': toJID,
                            'from': fromJID,
                            'type': 'chat'
                        })

                        body = Element('body')
                        body.text = content
                        reply.append(body)

                        delay = Element('delay', {
                            'xmlns': 'urn:xmpp:delay',
                            'from': fromJID,
                            'stamp': time.strftime("%Y-%m-%dT%H:%M:%SZ")
                        })
                        reply.append(delay)

                        routeData = {
                            'to' : toJID,
                            'data': reply
                        }
                        offline_msgs.append(routeData)
                    logging.debug("[%s] Sending %d offline messages to %s", self.__class__, len(offline_msgs), to_jid.getBare())
                except Exception as e:
                    logging.warning("[%s] Failed to read offline messages: %s", self.__class__, str(e))

                # broadcast to other resources of this user
                retVal = self.broadcastToOtherResources(presTree, msg, retVal, jid, resource)

            elif tree.get('to') is not None:
                # TODO: directed presence
                return
            elif tree.get('type') == 'unavailable':
                # broadcast to other resources of this user
                d['user']['active'] = False
                retVal = self.broadcastToOtherResources(presTree, msg, retVal, jid, resource)

            # record this stanza as the last presence sent from this client
            lastPresence = deepcopy(tree)
            lastPresence.set('from', '%s/%s' % (jid, resource))
            d['user']['lastPresence'] = lastPresence

            # lookup contacts interested in presence
            cjids = roster.getPresenceSubscribers()

            # TODO: replace this with another router handler that would send
            # it out to all cjids in a batch instead of queuing a handler
            # for each
            for cjid in cjids:
                presTree.set('to', cjid)
                presRouteData = {
                     'to' : cjid,
                     'data' : deepcopy(presTree)
                     }
                retVal = chainOutput(retVal, presRouteData)
                msg.setNextHandler('route-server')

            # send the probes first
            for probe in probes:
                msg.setNextHandler('route-server')
                retVal = chainOutput(retVal, probe)

            # send initial rosters
            for init_roster in init_rosters:
                msg.setNextHandler('route-client')
                retVal = chainOutput(retVal, init_roster)

            # send offline messages
            for offline_msg in offline_msgs:
                msg.setNextHandler('route-client')
                retVal = chainOutput(retVal, offline_msg)

            return retVal
Ejemplo n.º 7
0
    def handle(self, data=None):
        """Performs DIGEST-MD5 auth based on current state.

        data -- either None for initial challenge, base64-encoded text when
                the client responds to challenge 1, or the tree when the client
                responds to challenge 2.
        """

        # TODO: authz
        # TODO: subsequent auth

        qop = 'qop="auth"'
        charset = 'charset=utf-8'
        algo = 'algorithm=md5-sess'

        if self.state == SASLDigestMD5.INIT:  # initial challenge
            self.nonce = generateId()
            self.state = SASLDigestMD5.SENT_CHALLENGE1

            nonce = 'nonce="%s"' % self.nonce
            realm = 'realm="%s"' % self.realm

            res = Element('challenge',
                          {'xmlns': 'urn:ietf:params:xml:ns:xmpp-sasl'})
            res.text = base64.b64encode(','.join(
                [realm, qop, nonce, charset, algo]))

            return res
        elif self.state == SASLDigestMD5.SENT_CHALLENGE1 and data:
            # response to client's reponse (ie. challenge 2)
            try:
                text = fromBase64(data)
            except:
                raise SASLIncorrectEncodingError

            pairs = self._parse(text)
            try:
                username = pairs['username']
                nonce = pairs['nonce']
                realm = pairs['realm']
                cnonce = pairs['cnonce']
                nc = pairs['nc']
                qop = pairs['qop']
                response = pairs['response']
                digest_uri = pairs['digest-uri']
            except KeyError:
                self._handleFailure()
                raise SASLAuthError

            self.username = username

            # authz is ignored for now
            if nonce != self.nonce or realm != self.realm \
                or int(nc, 16) != 1 or qop[0] != 'auth' or not response\
                or not digest_uri:
                self._handleFailure()
                raise SASLAuthError

            # fetch the password now
            con = DBautocommit()
            c = con.cursor()
            c.execute(
                "SELECT password FROM jids WHERE \
                jid = ?", (username + '@%s' % self.msg.conn.server.hostname, ))
            for row in c:
                password = row['password']
                break
            else:
                self._handleFailure()
                c.close()
                con.close()
                raise SASLAuthError
            c.close()
            con.close()

            # compute the digest as per RFC 2831
            a1 = "%s:%s:%s" % (H("%s:%s:%s" %
                                 (username, realm, password)), nonce, cnonce)
            a2 = ":%s" % digest_uri
            a2client = "AUTHENTICATE:%s" % digest_uri

            digest = HEX(
                KD(
                    HEX(H(a1)), "%s:%s:%s:%s:%s" %
                    (nonce, nc, cnonce, "auth", HEX(H(a2client)))))

            if digest == response:
                rspauth = HEX(
                    KD(
                        HEX(H(a1)), "%s:%s:%s:%s:%s" %
                        (nonce, nc, cnonce, "auth", HEX(H(a2)))))

                self.state = SASLDigestMD5.SENT_CHALLENGE2

                res = Element('challenge',
                              {'xmlns': 'urn:ietf:params:xml:ns:xmpp-sasl'})
                res.text = base64.b64encode(u"rspauth=%s" % rspauth)

                return res

            else:
                self._handleFailure()
                raise SASLAuthError
        elif self.state == SASLDigestMD5.SENT_CHALLENGE2 and isinstance(
                data, Element):
            # expect to get <response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>
            respInd = data.tag.find(
                '{urn:ietf:params:xml:ns:xmpp-sasl}response')
            d = self.msg.conn.data
            if respInd != -1 and len(data) == 0:
                self.state = SASLDigestMD5.INIT
                d['sasl']['complete'] = True
                d['sasl']['in-progress'] = False
                d['user']['jid'] = '%s@%s' % (self.username,
                                              self.msg.conn.server.hostname)

                # record the JID for local delivery
                self.msg.conn.server.conns[self.msg.conn.id] = (JID(
                    d['user']['jid']), self.msg.conn)

                self.msg.conn.parser.resetParser()

                res = Element('success',
                              {'xmlns': 'urn:ietf:params:xml:ns:xmpp-sasl'})
                return res
            else:
                self._handleFailure()
                raise SASLAuthError
        else:
            self._handleFailure()
            raise SASLAuthError
Ejemplo n.º 8
0
    def handle(self, data=None):
        """Performs DIGEST-MD5 auth based on current state.

        data -- either None for initial challenge, base64-encoded text when
                the client responds to challenge 1, or the tree when the client
                responds to challenge 2.
        """

        # TODO: authz
        # TODO: subsequent auth

        qop = 'qop="auth"'
        charset = 'charset=utf-8'
        algo = 'algorithm=md5-sess'

        if self.state == SASLDigestMD5.INIT: # initial challenge
            self.nonce = generateId()
            self.state = SASLDigestMD5.SENT_CHALLENGE1

            nonce = 'nonce="%s"' % self.nonce
            realm = 'realm="%s"' % self.realm

            res = Element('challenge',
                          {'xmlns' : 'urn:ietf:params:xml:ns:xmpp-sasl'})
            res.text = base64.b64encode(','.join([realm, qop, nonce, charset, algo]))

            return res
        elif self.state == SASLDigestMD5.SENT_CHALLENGE1 and data:
            # response to client's reponse (ie. challenge 2)
            try:
                text = fromBase64(data)
            except:
                raise SASLIncorrectEncodingError

            pairs = self._parse(text)
            try:
                username = pairs['username']
                nonce = pairs['nonce']
                realm = pairs['realm']
                cnonce = pairs['cnonce']
                nc = pairs['nc']
                qop = pairs['qop']
                response = pairs['response']
                digest_uri = pairs['digest-uri']
            except KeyError:
                self._handleFailure()
                raise SASLAuthError

            self.username = username

            # authz is ignored for now
            if nonce != self.nonce or realm != self.realm \
                or int(nc, 16) != 1 or qop[0] != 'auth' or not response\
                or not digest_uri:
                self._handleFailure()
                raise SASLAuthError

            # fetch the password now
            con = DBautocommit()
            c = con.cursor()
            c.execute("SELECT password FROM jids WHERE \
                jid = ?", (username + '@%s' % self.msg.conn.server.hostname,))
            for row in c:
                password = row['password']
                break
            else:
                self._handleFailure()
                c.close()
                con.close()
                raise SASLAuthError
            c.close()
            con.close()

            # compute the digest as per RFC 2831
            a1 = "%s:%s:%s" % (H("%s:%s:%s" % (username, realm, password)),
                               nonce, cnonce)
            a2 = ":%s" % digest_uri
            a2client = "AUTHENTICATE:%s" % digest_uri

            digest = HEX(KD(HEX(H(a1)),
                            "%s:%s:%s:%s:%s" % (nonce, nc,
                                                  cnonce, "auth",
                                                  HEX(H(a2client)))))

            if digest == response:
                rspauth = HEX(KD(HEX(H(a1)),
                                 "%s:%s:%s:%s:%s" % (nonce, nc,
                                                       cnonce, "auth",
                                                       HEX(H(a2)))))

                self.state = SASLDigestMD5.SENT_CHALLENGE2

                res = Element('challenge',
                              {'xmlns' : 'urn:ietf:params:xml:ns:xmpp-sasl'})
                res.text = base64.b64encode(u"rspauth=%s" % rspauth)

                return res

            else:
                self._handleFailure()
                raise SASLAuthError
        elif self.state == SASLDigestMD5.SENT_CHALLENGE2 and isinstance(data, Element):
            # expect to get <response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>
            respInd = data.tag.find('{urn:ietf:params:xml:ns:xmpp-sasl}response')
            d = self.msg.conn.data
            if respInd != -1 and len(data) == 0:
                self.state = SASLDigestMD5.INIT
                d['sasl']['complete'] = True
                d['sasl']['in-progress'] = False
                d['user']['jid'] = '%s@%s' % (self.username,
                                            self.msg.conn.server.hostname)

                # record the JID for local delivery
                self.msg.conn.server.conns[self.msg.conn.id] = (JID(d['user']['jid']),
                                                                self.msg.conn)

                self.msg.conn.parser.resetParser()

                res = Element('success',
                              {'xmlns' : 'urn:ietf:params:xml:ns:xmpp-sasl'})
                return res
            else:
                self._handleFailure()
                raise SASLAuthError
        else:
            self._handleFailure()
            raise SASLAuthError