Search in sources :

Example 11 with UnauthorizedException

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

the class RoutingTableImpl method routeToLocalDomain.

/**
	 * Routes packets that are sent to the XMPP domain itself (excluding subdomains).
	 * 
	 * @param jid
	 *            the recipient of the packet to route.
	 * @param packet
	 *            the packet to route.
	 * @param fromServer
	 *            true if the packet was created by the server. This packets
	 *            should always be delivered
	 * @throws PacketException
	 *             thrown if the packet is malformed (results in the sender's
	 *             session being shutdown).
	 * @return <tt>true</tt> if the packet was routed successfully,
	 *         <tt>false</tt> otherwise.
	 */
private boolean routeToLocalDomain(JID jid, Packet packet, boolean fromServer) {
    boolean routed = false;
    Element privateElement = packet.getElement().element(QName.get("private", "urn:xmpp:carbons:2"));
    boolean isPrivate = privateElement != null;
    // The receiving server and SHOULD remove the <private/> element before delivering to the recipient.
    packet.getElement().remove(privateElement);
    if (jid.getResource() == null) {
        // Packet sent to a bare JID of a user
        if (packet instanceof Message) {
            // Find best route of local user
            routed = routeToBareJID(jid, (Message) packet, isPrivate);
        } else {
            throw new PacketException("Cannot route packet of type IQ or Presence to bare JID: " + packet.toXML());
        }
    } else {
        // Packet sent to local user (full JID)
        ClientRoute clientRoute = usersCache.get(jid.toString());
        if (clientRoute == null) {
            clientRoute = anonymousUsersCache.get(jid.toString());
        }
        if (clientRoute != null) {
            if (!clientRoute.isAvailable() && routeOnlyAvailable(packet, fromServer) && !presenceUpdateHandler.hasDirectPresence(packet.getTo(), packet.getFrom())) {
                Log.debug("Unable to route packet. Packet should only be sent to available sessions and the route is not available. {} ", packet.toXML());
                routed = false;
            } else {
                if (localRoutingTable.isLocalRoute(jid)) {
                    if (packet instanceof Message) {
                        Message message = (Message) packet;
                        if (message.getType() == Message.Type.chat && !isPrivate) {
                            List<JID> routes = getRoutes(jid.asBareJID(), null);
                            for (JID route : routes) {
                                // The receiving server MUST NOT send a forwarded copy to the full JID the original <message/> stanza was addressed to, as that recipient receives the original <message/> stanza.
                                if (!route.equals(jid)) {
                                    ClientSession clientSession = getClientRoute(route);
                                    if (clientSession.isMessageCarbonsEnabled()) {
                                        Message carbon = new Message();
                                        // The wrapping message SHOULD maintain the same 'type' attribute value;
                                        carbon.setType(message.getType());
                                        // the 'from' attribute MUST be the Carbons-enabled user's bare JID
                                        carbon.setFrom(route.asBareJID());
                                        // and the 'to' attribute MUST be the full JID of the resource receiving the copy
                                        carbon.setTo(route);
                                        // The content of the wrapping message MUST contain a <received/> element qualified by the namespace "urn:xmpp:carbons:2", which itself contains a <forwarded/> element qualified by the namespace "urn:xmpp:forward:0" that contains the original <message/>.
                                        carbon.addExtension(new Received(new Forwarded(message)));
                                        try {
                                            localRoutingTable.getRoute(route.toString()).process(carbon);
                                        } catch (UnauthorizedException e) {
                                            Log.error("Unable to route packet " + packet.toXML(), e);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    // This is a route to a local user hosted in this node
                    try {
                        localRoutingTable.getRoute(jid.toString()).process(packet);
                        routed = true;
                    } catch (UnauthorizedException e) {
                        Log.error("Unable to route packet " + packet.toXML(), e);
                    }
                } else {
                    // This is a route to a local user hosted in other node
                    if (remotePacketRouter != null) {
                        routed = remotePacketRouter.routePacket(clientRoute.getNodeID().toByteArray(), jid, packet);
                        if (!routed) {
                            // drop invalid client route
                            removeClientRoute(jid);
                        }
                    }
                }
            }
        }
    }
    return routed;
}
Also used : Element(org.dom4j.Element) Received(org.jivesoftware.openfire.carbons.Received) Forwarded(org.jivesoftware.openfire.forward.Forwarded) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException)

Example 12 with UnauthorizedException

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

the class OpenfireLoginService method login.

public UserIdentity login(String userName, Object credential) {
    UserIdentity identity = null;
    if (identities.containsKey(userName)) {
        identity = identities.get(userName);
        if (authTokens.containsKey(userName) == false) {
            Log.debug("UserIdentity login " + userName + " ");
            try {
                if (AdminManager.getInstance().isUserAdmin(userName, true)) {
                    AuthToken authToken = AuthFactory.authenticate(userName, (String) credential);
                    authTokens.put(userName, authToken);
                } else {
                    Log.error("access denied, not admin user " + userName);
                    return null;
                }
            } catch (UnauthorizedException e) {
                Log.error("access denied, bad password " + userName);
                return null;
            } catch (Exception e) {
                Log.error("access denied " + userName);
                return null;
            }
        }
    } else {
        Log.debug("UserIdentity login " + userName + " ");
        try {
            userManager.getUser(userName);
        } catch (UserNotFoundException e) {
            //Log.error( "user not found " + userName, e );
            return null;
        }
        try {
            if (AdminManager.getInstance().isUserAdmin(userName, true)) {
                AuthToken authToken = AuthFactory.authenticate(userName, (String) credential);
                authTokens.put(userName, authToken);
            } else {
                Log.error("access denied, not admin user " + userName);
                return null;
            }
        } catch (UnauthorizedException e) {
            Log.error("access denied, bad password " + userName);
            return null;
        } catch (Exception e) {
            Log.error("access denied " + userName);
            return null;
        }
        Principal userPrincipal = new KnownUser(userName, credential);
        Subject subject = new Subject();
        subject.getPrincipals().add(userPrincipal);
        subject.getPrivateCredentials().add(credential);
        subject.getPrincipals().add(new RolePrincipal("jmxweb"));
        subject.setReadOnly();
        identity = _identityService.newUserIdentity(subject, userPrincipal, new String[] { "jmxweb" });
        identities.put(userName, identity);
    }
    return identity;
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) UserIdentity(org.eclipse.jetty.server.UserIdentity) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) AuthToken(org.jivesoftware.openfire.auth.AuthToken) UserAlreadyExistsException(org.jivesoftware.openfire.user.UserAlreadyExistsException) IOException(java.io.IOException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) Principal(java.security.Principal) Subject(javax.security.auth.Subject)

Example 13 with UnauthorizedException

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

the class IQAuthHandler method authenticate.

/**
     * Authenticates a user with a username, token, and digest and returns an AuthToken.
     * The digest should be generated using the {@link AuthFactory#createDigest(String, String)} method.
     * If the username and digest do not match the record of any user in the system, the
     * method throws an UnauthorizedException.
     *
     * @param username the username.
     * @param token the token that was used with plain-text password to generate the digest.
     * @param digest the digest generated from plain-text password and unique token.
     * @return an AuthToken token if the username and digest are correct for the user's
     *      password and given token.
     * @throws UnauthorizedException if the username and password do not match any
     *      existing user or the account is locked out.
     */
public static AuthToken authenticate(String username, String token, String digest) throws UnauthorizedException, ConnectionException, InternalUnauthenticatedException {
    if (username == null || token == null || digest == null) {
        throw new UnauthorizedException();
    }
    if (LockOutManager.getInstance().isAccountDisabled(username)) {
        LockOutManager.getInstance().recordFailedLogin(username);
        throw new UnauthorizedException();
    }
    username = username.trim().toLowerCase();
    if (username.contains("@")) {
        // Check that the specified domain matches the server's domain
        int index = username.indexOf("@");
        String domain = username.substring(index + 1);
        if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
            username = username.substring(0, index);
        } else {
            // Unknown domain. Return authentication failed.
            throw new UnauthorizedException();
        }
    }
    try {
        String password = AuthFactory.getPassword(username);
        String anticipatedDigest = AuthFactory.createDigest(token, password);
        if (!digest.equalsIgnoreCase(anticipatedDigest)) {
            throw new UnauthorizedException();
        }
    } catch (UserNotFoundException unfe) {
        throw new UnauthorizedException();
    }
    // Got this far, so the user must be authorized.
    return new AuthToken(username);
}
Also used : UserNotFoundException(org.jivesoftware.openfire.user.UserNotFoundException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) AuthToken(org.jivesoftware.openfire.auth.AuthToken)

Example 14 with UnauthorizedException

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

the class SessionManager method createClientHttpSession.

/**
     * Creates a new <tt>ClientSession</tt> with the specified streamID.
     *
     * @param connection the connection to create the session from.
     * @param id the streamID to use for the new session.
     * @return a newly created session.
     */
public HttpSession createClientHttpSession(long rid, InetAddress address, StreamID id, HttpConnection connection, Locale language) throws UnauthorizedException {
    if (serverName == null) {
        throw new UnauthorizedException("Server not initialized");
    }
    PacketDeliverer backupDeliverer = server.getPacketDeliverer();
    HttpSession session = new HttpSession(backupDeliverer, serverName, address, id, rid, connection, language);
    Connection conn = session.getConnection();
    conn.init(session);
    conn.registerCloseListener(clientSessionListener, session);
    localSessionManager.getPreAuthenticatedSessions().put(session.getAddress().getResource(), session);
    connectionsCounter.incrementAndGet();
    return session;
}
Also used : HttpSession(org.jivesoftware.openfire.http.HttpSession) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) HttpConnection(org.jivesoftware.openfire.http.HttpConnection)

Example 15 with UnauthorizedException

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

the class LdapAuthProvider method authenticate.

@Override
public void authenticate(String username, String password) throws UnauthorizedException {
    if (username == null || password == null || "".equals(password.trim())) {
        throw new UnauthorizedException();
    }
    if (username.contains("@")) {
        // Check that the specified domain matches the server's domain
        int index = username.indexOf("@");
        String domain = username.substring(index + 1);
        if (domain.equals(XMPPServer.getInstance().getServerInfo().getXMPPDomain())) {
            username = username.substring(0, index);
        } else {
            // Unknown domain. Return authentication failed.
            throw new UnauthorizedException();
        }
    }
    // Un-escape username.
    username = JID.unescapeNode(username);
    // If cache is enabled, see if the auth is in cache.
    if (authCache != null && authCache.containsKey(username)) {
        String hash = authCache.get(username);
        if (StringUtils.hash(password).equals(hash)) {
            return;
        }
    }
    String userDN;
    try {
        // The username by itself won't help us much with LDAP since we
        // need a fully qualified dn. We could make the assumption that
        // the baseDN would always be the location of user profiles. For
        // example if the baseDN was set to "ou=People, o=jivesoftare, o=com"
        // then we would be able to directly load users from that node
        // of the LDAP tree. However, it's a poor assumption that only a
        // flat structure will be used. Therefore, we search all sub-trees
        // of the baseDN for the username (assuming the user has not disabled
        // sub-tree searching). So, if the baseDN is set to
        // "o=jivesoftware, o=com" then a search will include the "People"
        // node as well all the others under the base.
        userDN = manager.findUserDN(username);
        // See if the user authenticates.
        if (!manager.checkAuthentication(userDN, password)) {
            throw new UnauthorizedException("Username and password don't match");
        }
    } catch (CommunicationException e) {
        // Log error here since it will be wrapped with an UnauthorizedException that
        // is never logged
        Log.error("Error connecting to LDAP server", e);
        throw new UnauthorizedException(e);
    } catch (Exception e) {
        throw new UnauthorizedException(e);
    }
    // If cache is enabled, add the item to cache.
    if (authCache != null) {
        authCache.put(username, StringUtils.hash(password));
    }
}
Also used : CommunicationException(javax.naming.CommunicationException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) CommunicationException(javax.naming.CommunicationException) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) 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