Search in sources :

Example 1 with UnauthorizedException

use of org.jivesoftware.openfire.auth.UnauthorizedException in project Openfire by igniterealtime.

the class AuthenticateUser method execute.

@Override
public void execute(SessionData data, Element command) {
    Element note = command.addElement("note");
    JID account;
    try {
        account = new JID(data.getData().get("accountjid").get(0));
    } catch (NullPointerException ne) {
        note.addAttribute("type", "error");
        note.setText("JID required parameter.");
        return;
    }
    if (!XMPPServer.getInstance().isLocal(account)) {
        note.addAttribute("type", "error");
        note.setText("Cannot authenticate remote user.");
        return;
    }
    String password = data.getData().get("password").get(0);
    // Get requested user
    User user;
    try {
        user = UserManager.getInstance().getUser(account.getNode());
    } catch (UserNotFoundException e) {
        // User not found
        note.addAttribute("type", "error");
        note.setText("User does not exists.");
        return;
    }
    try {
        AuthFactory.authenticate(user.getUsername(), password);
    } catch (UnauthorizedException | ConnectionException | InternalUnauthenticatedException e) {
        // Auth failed
        note.addAttribute("type", "error");
        note.setText("Authentication failed.");
        return;
    }
    // Answer that the operation was successful
    note.addAttribute("type", "info");
    note.setText("Operation finished successfully.");
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) User(org.jivesoftware.openfire.user.User) JID(org.xmpp.packet.JID) Element(org.dom4j.Element) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) InternalUnauthenticatedException(org.jivesoftware.openfire.auth.InternalUnauthenticatedException) ConnectionException(org.jivesoftware.openfire.auth.ConnectionException)

Example 2 with UnauthorizedException

use of org.jivesoftware.openfire.auth.UnauthorizedException in project Openfire by igniterealtime.

the class LocalMUCRoom method joinRoom.

@Override
public LocalMUCRole joinRoom(String nickname, String password, HistoryRequest historyRequest, LocalMUCUser user, Presence presence) throws UnauthorizedException, UserAlreadyExistsException, RoomLockedException, ForbiddenException, RegistrationRequiredException, ConflictException, ServiceUnavailableException, NotAcceptableException {
    if (((MultiUserChatServiceImpl) mucService).getMUCDelegate() != null) {
        if (!((MultiUserChatServiceImpl) mucService).getMUCDelegate().joiningRoom(this, user.getAddress())) {
            // Delegate said no, reject join.
            throw new UnauthorizedException();
        }
    }
    LocalMUCRole joinRole = null;
    lock.writeLock().lock();
    boolean clientOnlyJoin = false;
    // A "client only join" here is one where the client is already joined, but has re-joined.
    try {
        // If the room has a limit of max user then check if the limit has been reached
        if (!canJoinRoom(user)) {
            throw new ServiceUnavailableException();
        }
        final JID bareJID = user.getAddress().asBareJID();
        boolean isOwner = owners.includes(bareJID);
        // If the room is locked and this user is not an owner raise a RoomLocked exception
        if (isLocked()) {
            if (!isOwner) {
                throw new RoomLockedException();
            }
        }
        // Check if the nickname is already used in the room
        if (occupantsByNickname.containsKey(nickname.toLowerCase())) {
            List<MUCRole> occupants = occupantsByNickname.get(nickname.toLowerCase());
            MUCRole occupant = occupants.size() > 0 ? occupants.get(0) : null;
            if (occupant != null && !occupant.getUserAddress().toBareJID().equals(bareJID.toBareJID())) {
                // Nickname is already used, and not by the same JID
                throw new UserAlreadyExistsException();
            }
            if (occupant.getUserAddress().equals(user.getAddress())) {
                // This user is already an occupant. The client thinks it isn't. (Or else this is a broken gmail).
                clientOnlyJoin = true;
            }
        }
        // Unauthorized exception
        if (isPasswordProtected()) {
            if (password == null || !password.equals(getPassword())) {
                throw new UnauthorizedException();
            }
        }
        // raise a ConflictException
        if (members.containsValue(nickname.toLowerCase())) {
            if (!nickname.toLowerCase().equals(members.get(bareJID))) {
                throw new ConflictException();
            }
        }
        if (isLoginRestrictedToNickname()) {
            String reservedNickname = members.get(bareJID);
            if (reservedNickname != null && !nickname.toLowerCase().equals(reservedNickname)) {
                throw new NotAcceptableException();
            }
        }
        // Set the corresponding role based on the user's affiliation
        MUCRole.Role role;
        MUCRole.Affiliation affiliation;
        if (isOwner) {
            // The user is an owner. Set the role and affiliation accordingly.
            role = MUCRole.Role.moderator;
            affiliation = MUCRole.Affiliation.owner;
        } else if (mucService.isSysadmin(bareJID)) {
            // The user is a system administrator of the MUC service. Treat him as an owner
            // although he won't appear in the list of owners
            role = MUCRole.Role.moderator;
            affiliation = MUCRole.Affiliation.owner;
        } else if (admins.includes(bareJID)) {
            // The user is an admin. Set the role and affiliation accordingly.
            role = MUCRole.Role.moderator;
            affiliation = MUCRole.Affiliation.admin;
        } else // explicit outcast status has higher precedence than member status
        if (outcasts.contains(bareJID)) {
            // The user is an outcast. Raise a "Forbidden" exception.
            throw new ForbiddenException();
        } else if (members.includesKey(bareJID)) {
            // The user is a member. Set the role and affiliation accordingly.
            role = MUCRole.Role.participant;
            affiliation = MUCRole.Affiliation.member;
        } else // this checks if the user is an outcast implicitly (via a group)
        if (outcasts.includes(bareJID)) {
            // The user is an outcast. Raise a "Forbidden" exception.
            throw new ForbiddenException();
        } else {
            // The user has no affiliation (i.e. NONE). Set the role accordingly.
            if (isMembersOnly()) {
                // "Registration Required" exception.
                throw new RegistrationRequiredException();
            }
            role = (isModerated() ? MUCRole.Role.visitor : MUCRole.Role.participant);
            affiliation = MUCRole.Affiliation.none;
        }
        if (!clientOnlyJoin) {
            // Create a new role for this user in this room
            joinRole = new LocalMUCRole(mucService, this, nickname, role, affiliation, user, presence, router);
            // Add the new user as an occupant of this room
            List<MUCRole> occupants = occupantsByNickname.get(nickname.toLowerCase());
            if (occupants == null) {
                occupants = new ArrayList<>();
                occupantsByNickname.put(nickname.toLowerCase(), occupants);
            }
            occupants.add(joinRole);
            // Update the tables of occupants based on the bare and full JID
            List<MUCRole> list = occupantsByBareJID.get(bareJID);
            if (list == null) {
                list = new ArrayList<>();
                occupantsByBareJID.put(bareJID, list);
            }
            list.add(joinRole);
            occupantsByFullJID.put(user.getAddress(), joinRole);
        } else {
            // Grab the existing one.
            joinRole = (LocalMUCRole) occupantsByFullJID.get(user.getAddress());
        }
    } finally {
        lock.writeLock().unlock();
    }
    // Notify other cluster nodes that a new occupant joined the room
    CacheFactory.doClusterTask(new OccupantAddedEvent(this, joinRole));
    // Send presence of existing occupants to new occupant
    sendInitialPresences(joinRole);
    // It is assumed that the room is new based on the fact that it's locked and
    // that it was locked when it was created.
    boolean isRoomNew = isLocked() && creationDate.getTime() == lockedTime;
    try {
        // Send the presence of this new occupant to existing occupants
        Presence joinPresence = joinRole.getPresence().createCopy();
        broadcastPresence(joinPresence, true);
    } catch (Exception e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
    }
    // confirmed" message
    if (!isRoomNew && isLocked()) {
        // http://xmpp.org/extensions/xep-0045.html#enter-locked
        Presence presenceItemNotFound = new Presence(Presence.Type.error);
        presenceItemNotFound.setError(PacketError.Condition.item_not_found);
        presenceItemNotFound.setFrom(role.getRoleAddress());
        joinRole.send(presenceItemNotFound);
    }
    if (historyRequest == null) {
        Iterator<Message> history = roomHistory.getMessageHistory();
        while (history.hasNext()) {
            joinRole.send(history.next());
        }
    } else {
        historyRequest.sendHistory(joinRole, roomHistory);
    }
    Message roomSubject = roomHistory.getChangedSubject();
    if (roomSubject != null) {
        joinRole.send(roomSubject);
    }
    if (!clientOnlyJoin) {
        // Update the date when the last occupant left the room
        setEmptyDate(null);
        // Fire event that occupant joined the room
        MUCEventDispatcher.occupantJoined(getRole().getRoleAddress(), user.getAddress(), joinRole.getNickname());
    }
    return joinRole;
}
Also used : ForbiddenException(org.jivesoftware.openfire.muc.ForbiddenException) GroupJID(org.jivesoftware.openfire.group.GroupJID) JID(org.xmpp.packet.JID) Message(org.xmpp.packet.Message) ConflictException(org.jivesoftware.openfire.muc.ConflictException) OccupantAddedEvent(org.jivesoftware.openfire.muc.cluster.OccupantAddedEvent) ServiceUnavailableException(org.jivesoftware.openfire.muc.ServiceUnavailableException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) ForbiddenException(org.jivesoftware.openfire.muc.ForbiddenException) GroupNotFoundException(org.jivesoftware.openfire.group.GroupNotFoundException) RoomLockedException(org.jivesoftware.openfire.muc.RoomLockedException) CannotBeInvitedException(org.jivesoftware.openfire.muc.CannotBeInvitedException) NotAllowedException(org.jivesoftware.openfire.muc.NotAllowedException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) NotFoundException(org.jivesoftware.util.NotFoundException) ConflictException(org.jivesoftware.openfire.muc.ConflictException) RegistrationRequiredException(org.jivesoftware.openfire.muc.RegistrationRequiredException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) IOException(java.io.IOException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) NotAcceptableException(org.jivesoftware.openfire.muc.NotAcceptableException) ServiceUnavailableException(org.jivesoftware.openfire.muc.ServiceUnavailableException) MUCRole(org.jivesoftware.openfire.muc.MUCRole) NotAcceptableException(org.jivesoftware.openfire.muc.NotAcceptableException) RoomLockedException(org.jivesoftware.openfire.muc.RoomLockedException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) Presence(org.xmpp.packet.Presence) UpdatePresence(org.jivesoftware.openfire.muc.cluster.UpdatePresence) RegistrationRequiredException(org.jivesoftware.openfire.muc.RegistrationRequiredException)

Example 3 with UnauthorizedException

use of org.jivesoftware.openfire.auth.UnauthorizedException in project Openfire by igniterealtime.

the class LocalMUCUser method process.

public void process(Presence packet) {
    // Ignore presences of type ERROR sent to a room
    if (Presence.Type.error == packet.getType()) {
        return;
    }
    lastPacketTime = System.currentTimeMillis();
    JID recipient = packet.getTo();
    String group = recipient.getNode();
    if (group != null) {
        MUCRole role = roles.get(group);
        Element mucInfo = packet.getChildElement("x", "http://jabber.org/protocol/muc");
        if (role == null || mucInfo != null) {
            // Alternative is that mucInfo is not null, in which case the client thinks it isn't in the room, so we should join anyway.
            if (recipient.getResource() != null && recipient.getResource().trim().length() > 0) {
                if (packet.isAvailable()) {
                    try {
                        // Get or create the room
                        MUCRoom room = server.getChatRoom(group, packet.getFrom());
                        // User must support MUC in order to create a room
                        HistoryRequest historyRequest = null;
                        String password = null;
                        // Check for password & requested history if client supports MUC
                        if (mucInfo != null) {
                            password = mucInfo.elementTextTrim("password");
                            if (mucInfo.element("history") != null) {
                                historyRequest = new HistoryRequest(mucInfo);
                            }
                        }
                        // The user joins the room
                        role = room.joinRoom(recipient.getResource().trim(), password, historyRequest, this, packet.createCopy());
                        // unlock the room thus creating an "instant" room
                        if (mucInfo == null && room.isLocked() && !room.isManuallyLocked()) {
                            room.unlock(role);
                        }
                    } catch (UnauthorizedException e) {
                        sendErrorPacket(packet, PacketError.Condition.not_authorized);
                    } catch (ServiceUnavailableException e) {
                        sendErrorPacket(packet, PacketError.Condition.service_unavailable);
                    } catch (UserAlreadyExistsException | ConflictException e) {
                        sendErrorPacket(packet, PacketError.Condition.conflict);
                    } catch (RoomLockedException e) {
                        // If a user attempts to enter a room while it is "locked" (i.e., before the room creator provides an initial configuration and therefore before the room officially exists), the service MUST refuse entry and return an <item-not-found/> error to the user
                        sendErrorPacket(packet, PacketError.Condition.item_not_found);
                    } catch (ForbiddenException e) {
                        sendErrorPacket(packet, PacketError.Condition.forbidden);
                    } catch (RegistrationRequiredException e) {
                        sendErrorPacket(packet, PacketError.Condition.registration_required);
                    } catch (NotAcceptableException e) {
                        sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                    } catch (NotAllowedException e) {
                        sendErrorPacket(packet, PacketError.Condition.not_allowed);
                    }
                } else {
                // TODO: send error message to user (can't send presence to group you
                // haven't joined)
                }
            } else {
                if (packet.isAvailable()) {
                    // A resource is required in order to join a room
                    // http://xmpp.org/extensions/xep-0045.html#enter
                    // If the user does not specify a room nickname (note the bare JID on the 'from' address in the following example), the service MUST return a <jid-malformed/> error
                    sendErrorPacket(packet, PacketError.Condition.jid_malformed);
                }
            // TODO: send error message to user (can't send packets to group you haven't
            // joined)
            }
        } else {
            // In other words, another user already has this nickname
            if (!role.getUserAddress().equals(packet.getFrom())) {
                sendErrorPacket(packet, PacketError.Condition.conflict);
            } else {
                if (Presence.Type.unavailable == packet.getType()) {
                    try {
                        // TODO Consider that different nodes can be creating and processing this presence at the same time (when remote node went down)
                        removeRole(group);
                        role.getChatRoom().leaveRoom(role);
                    } catch (Exception e) {
                        Log.error(e.getMessage(), e);
                    }
                } else {
                    try {
                        String resource = (recipient.getResource() == null || recipient.getResource().trim().length() == 0 ? null : recipient.getResource().trim());
                        if (resource == null || role.getNickname().equalsIgnoreCase(resource)) {
                            // Occupant has changed his availability status
                            role.getChatRoom().presenceUpdated(role, packet);
                        } else {
                            // Check if occupants are allowed to change their nicknames
                            if (!role.getChatRoom().canChangeNickname()) {
                                sendErrorPacket(packet, PacketError.Condition.not_acceptable);
                            } else // Answer a conflic error if the new nickname is taken
                            if (role.getChatRoom().hasOccupant(resource)) {
                                sendErrorPacket(packet, PacketError.Condition.conflict);
                            } else {
                                // Send "unavailable" presence for the old nickname
                                Presence presence = role.getPresence().createCopy();
                                // Switch the presence to OFFLINE
                                presence.setType(Presence.Type.unavailable);
                                presence.setStatus(null);
                                // Add the new nickname and status 303 as properties
                                Element frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
                                frag.element("item").addAttribute("nick", resource);
                                frag.addElement("status").addAttribute("code", "303");
                                role.getChatRoom().send(presence);
                                // Send availability presence for the new nickname
                                String oldNick = role.getNickname();
                                role.getChatRoom().nicknameChanged(role, packet, oldNick, resource);
                            }
                        }
                    } catch (Exception e) {
                        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
                    }
                }
            }
        }
    } else {
        // Packets to the groupchat server. This should not occur (should be handled by MultiUserChatServiceImpl instead)
        Log.warn(LocaleUtils.getLocalizedString("muc.error.not-supported") + " " + packet.toString());
    }
}
Also used : Element(org.dom4j.Element) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) PacketException(org.jivesoftware.openfire.PacketException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) NotFoundException(org.jivesoftware.util.NotFoundException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException)

Example 4 with UnauthorizedException

use of org.jivesoftware.openfire.auth.UnauthorizedException in project Openfire by igniterealtime.

the class MultiUserChatServiceImpl method process.

/**
     * Returns true if the IQ packet was processed. This method should only process disco packets
     * as well as jabber:iq:register packets sent to the MUC service.
     *
     * @param iq the IQ packet to process.
     * @return true if the IQ packet was processed.
     */
private boolean process(IQ iq) {
    Element childElement = iq.getChildElement();
    String namespace = null;
    // Ignore IQs of type ERROR
    if (IQ.Type.error == iq.getType()) {
        return false;
    }
    if (iq.getTo().getResource() != null) {
        // Ignore IQ packets sent to room occupants
        return false;
    }
    if (childElement != null) {
        namespace = childElement.getNamespaceURI();
    }
    if ("jabber:iq:register".equals(namespace)) {
        IQ reply = registerHandler.handleIQ(iq);
        router.route(reply);
    } else if ("jabber:iq:search".equals(namespace)) {
        IQ reply = searchHandler.handleIQ(iq);
        router.route(reply);
    } else if ("http://jabber.org/protocol/disco#info".equals(namespace)) {
        // TODO MUC should have an IQDiscoInfoHandler of its own when MUC becomes
        // a component
        IQ reply = XMPPServer.getInstance().getIQDiscoInfoHandler().handleIQ(iq);
        router.route(reply);
    } else if ("http://jabber.org/protocol/disco#items".equals(namespace)) {
        // TODO MUC should have an IQDiscoItemsHandler of its own when MUC becomes
        // a component
        IQ reply = XMPPServer.getInstance().getIQDiscoItemsHandler().handleIQ(iq);
        router.route(reply);
    } else if ("urn:xmpp:ping".equals(namespace)) {
        router.route(IQ.createResultIQ(iq));
    } else if (this.iqHandlers != null) {
        IQHandler h = this.iqHandlers.get(namespace);
        if (h != null) {
            try {
                IQ reply = h.handleIQ(iq);
                if (reply != null) {
                    router.route(reply);
                }
            } catch (UnauthorizedException e) {
                IQ reply = IQ.createResultIQ(iq);
                reply.setType(IQ.Type.error);
                reply.setError(PacketError.Condition.service_unavailable);
                router.route(reply);
            }
            return true;
        }
        return false;
    } else {
        return false;
    }
    return true;
}
Also used : IQHandler(org.jivesoftware.openfire.handler.IQHandler) Element(org.dom4j.Element) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException)

Example 5 with UnauthorizedException

use of org.jivesoftware.openfire.auth.UnauthorizedException in project Openfire by igniterealtime.

the class IQRosterHandler method handleIQ.

/**
     * Handles all roster queries. There are two major types of queries:
     *
     * <ul>
     *      <li>Roster remove - A forced removal of items from a roster. Roster
     *      removals are the only roster queries allowed to
     *      directly affect the roster from another user.
     *      </li>
     *      <li>Roster management - A local user looking up or updating their
     *      roster.
     *      </li>
     * </ul>
     *
     * @param packet The update packet
     * @return The reply or null if no reply
     */
@Override
public IQ handleIQ(IQ packet) throws UnauthorizedException, PacketException {
    try {
        IQ returnPacket;
        org.xmpp.packet.Roster roster = (org.xmpp.packet.Roster) packet;
        JID recipientJID = packet.getTo();
        // The packet is bound for the server and must be roster management
        if (recipientJID == null || recipientJID.equals(packet.getFrom().asBareJID())) {
            returnPacket = manageRoster(roster);
        } else {
            returnPacket = IQ.createResultIQ(packet);
            // The server MUST return a <forbidden/> stanza error to the client if the sender of the roster set is not authorized to update the roster
            // (where typically only an authenticated resource of the account itself is authorized).
            returnPacket.setError(PacketError.Condition.forbidden);
        }
        return returnPacket;
    } catch (SharedGroupException e) {
        IQ result = IQ.createResultIQ(packet);
        result.setChildElement(packet.getChildElement().createCopy());
        result.setError(PacketError.Condition.not_acceptable);
        return result;
    } catch (Exception e) {
        if (e.getCause() instanceof IDNAException || e.getCause() instanceof IllegalArgumentException) {
            Log.warn(LocaleUtils.getLocalizedString("admin.error") + e.getMessage());
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.jid_malformed);
            return result;
        } else {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            IQ result = IQ.createResultIQ(packet);
            result.setChildElement(packet.getChildElement().createCopy());
            result.setError(PacketError.Condition.internal_server_error);
            return result;
        }
    }
}
Also used : IDNAException(gnu.inet.encoding.IDNAException) Roster(org.jivesoftware.openfire.roster.Roster) JID(org.xmpp.packet.JID) IQ(org.xmpp.packet.IQ) SharedGroupException(org.jivesoftware.openfire.SharedGroupException) PacketException(org.jivesoftware.openfire.PacketException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) SharedGroupException(org.jivesoftware.openfire.SharedGroupException) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) IDNAException(gnu.inet.encoding.IDNAException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException)

Aggregations

UnauthorizedException (org.jivesoftware.openfire.auth.UnauthorizedException)30 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)13 Element (org.dom4j.Element)11 IQ (org.xmpp.packet.IQ)10 JID (org.xmpp.packet.JID)10 ConnectionException (org.jivesoftware.openfire.auth.ConnectionException)7 PacketException (org.jivesoftware.openfire.PacketException)6 InternalUnauthenticatedException (org.jivesoftware.openfire.auth.InternalUnauthenticatedException)6 UserAlreadyExistsException (org.jivesoftware.openfire.user.UserAlreadyExistsException)5 IOException (java.io.IOException)4 AuthToken (org.jivesoftware.openfire.auth.AuthToken)4 StreamError (org.xmpp.packet.StreamError)4 StringprepException (gnu.inet.encoding.StringprepException)3 WebApplicationException (javax.ws.rs.WebApplicationException)3 ClientSession (org.jivesoftware.openfire.session.ClientSession)3 LocalClientSession (org.jivesoftware.openfire.session.LocalClientSession)3 User (org.jivesoftware.openfire.user.User)3 NotFoundException (org.jivesoftware.util.NotFoundException)3 DataForm (org.xmpp.forms.DataForm)3 FormField (org.xmpp.forms.FormField)3