Search in sources :

Example 6 with StreamError

use of org.xmpp.packet.StreamError in project Openfire by igniterealtime.

the class SparkManager method closeSession.

/**
     * Sends an unsupported version error and name of client the user attempted to connect with.
     *
     * @param session    the users current session.
     * @param clientName the name of the client they were connecting with.
     */
private void closeSession(final Session session, String clientName) {
    // Increase the number of logins not allowed by 1.
    disconnects.incrementAndGet();
    Log.debug("Closed connection to client attempting to connect from " + clientName);
    // Send message information user.
    final Message message = new Message();
    message.setFrom(serviceName + "." + componentManager.getServerName());
    message.setTo(session.getAddress());
    message.setBody("You are using an invalid client, and therefore will be disconnected. " + "Please ask your system administrator for client choices.");
    // Send Message
    sendPacket(message);
    // Disconnect user after 5 seconds.
    taskEngine.schedule(new TimerTask() {

        @Override
        public void run() {
            // Include the not-authorized error in the response
            StreamError error = new StreamError(StreamError.Condition.policy_violation);
            session.deliverRawText(error.toXML());
            // Close the underlying connection
            session.close();
        }
    }, 5000);
}
Also used : StreamError(org.xmpp.packet.StreamError) Message(org.xmpp.packet.Message) TimerTask(java.util.TimerTask)

Example 7 with StreamError

use of org.xmpp.packet.StreamError in project Openfire by igniterealtime.

the class ServerDialback method createOutgoingSession.

/**
     * Creates a new connection from the Originating Server to the Receiving Server for
     * authenticating the specified domain.
     *
     * @param localDomain domain of the Originating Server to authenticate with the Receiving Server.
     * @param remoteDomain IP address or hostname of the Receiving Server.
     * @param port port of the Receiving Server.
     * @return an OutgoingServerSession if the domain was authenticated or <tt>null</tt> if none.
     */
public LocalOutgoingServerSession createOutgoingSession(String localDomain, String remoteDomain, int port) {
    final Logger log = LoggerFactory.getLogger(Log.getName() + "[Acting as Originating Server: Create Outgoing Session from: " + localDomain + " to RS at: " + remoteDomain + " (port: " + port + ")]");
    log.debug("Creating new outgoing session...");
    String hostname = null;
    int realPort = port;
    try {
        // Establish a TCP connection to the Receiving Server
        final Socket socket = SocketUtil.createSocketToXmppDomain(remoteDomain, port);
        if (socket == null) {
            log.info("Unable to create new outgoing session: Cannot create a plain socket connection with any applicable remote host.");
            return null;
        }
        connection = new SocketConnection(XMPPServer.getInstance().getPacketDeliverer(), socket, false);
        log.debug("Send the stream header and wait for response...");
        StringBuilder stream = new StringBuilder();
        stream.append("<stream:stream");
        stream.append(" xmlns:stream=\"http://etherx.jabber.org/streams\"");
        stream.append(" xmlns=\"jabber:server\"");
        stream.append(" to=\"").append(remoteDomain).append("\"");
        stream.append(" from=\"").append(localDomain).append("\"");
        stream.append(" xmlns:db=\"jabber:server:dialback\"");
        stream.append(">");
        connection.deliverRawText(stream.toString());
        // Set a read timeout (of 5 seconds) so we don't keep waiting forever
        int soTimeout = socket.getSoTimeout();
        socket.setSoTimeout(RemoteServerManager.getSocketTimeout());
        XMPPPacketReader reader = new XMPPPacketReader();
        reader.setXPPFactory(FACTORY);
        reader.getXPPParser().setInput(new InputStreamReader(ServerTrafficCounter.wrapInputStream(socket.getInputStream()), CHARSET));
        // Get the answer from the Receiving Server
        XmlPullParser xpp = reader.getXPPParser();
        for (int eventType = xpp.getEventType(); eventType != XmlPullParser.START_TAG; ) {
            eventType = xpp.next();
        }
        log.debug("Got a response. Check if the remote server supports dialback...");
        if ("jabber:server:dialback".equals(xpp.getNamespace("db"))) {
            log.debug("Dialback seems to be supported by the remote server.");
            // Restore default timeout
            socket.setSoTimeout(soTimeout);
            String id = xpp.getAttributeValue("", "id");
            OutgoingServerSocketReader socketReader = new OutgoingServerSocketReader(reader);
            if (authenticateDomain(socketReader, localDomain, remoteDomain, id)) {
                log.debug("Successfully authenticated the connection with dialback.");
                // Domain was validated so create a new OutgoingServerSession
                StreamID streamID = BasicStreamIDFactory.createStreamID(id);
                LocalOutgoingServerSession session = new LocalOutgoingServerSession(localDomain, connection, socketReader, streamID);
                connection.init(session);
                // Set the hostname as the address of the session
                session.setAddress(new JID(null, remoteDomain, null));
                log.debug("Successfully created new outgoing session!");
                return session;
            } else {
                log.debug("Failed to authenticate the connection with dialback.");
                // Close the connection
                connection.close();
            }
        } else {
            log.debug("Error! Invalid namespace in packet: '{}'. Closing connection.", xpp.getText());
            // Send an invalid-namespace stream error condition in the response
            connection.deliverRawText(new StreamError(StreamError.Condition.invalid_namespace).toXML());
            // Close the connection
            connection.close();
        }
    } catch (Exception e) {
        log.error("An exception occurred while creating outgoing session to remote server:", e);
        // Close the connection
        if (connection != null) {
            connection.close();
        }
    }
    log.warn("Unable to create a new outgoing session");
    return null;
}
Also used : XMPPPacketReader(org.dom4j.io.XMPPPacketReader) InputStreamReader(java.io.InputStreamReader) JID(org.xmpp.packet.JID) XmlPullParser(org.xmlpull.v1.XmlPullParser) Logger(org.slf4j.Logger) DocumentException(org.dom4j.DocumentException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) StreamError(org.xmpp.packet.StreamError) LocalOutgoingServerSession(org.jivesoftware.openfire.session.LocalOutgoingServerSession) Socket(java.net.Socket)

Example 8 with StreamError

use of org.xmpp.packet.StreamError in project Openfire by igniterealtime.

the class LocalComponentSession method authenticate.

/**
     * Authenticate the external component using a digest method. The digest includes the
     * stream ID and the secret key of the main domain of the external component. A component
     * needs to authenticate just once but it may bind several domains.
     *
     * @param digest the digest sent in the handshake.
     * @return true if the authentication was successful.
     */
public boolean authenticate(String digest) {
    // Perform authentication. Wait for the handshake (with the secret key)
    String secretKey = ExternalComponentManager.getSecretForComponent(defaultSubdomain);
    String anticipatedDigest = AuthFactory.createDigest(getStreamID().getID(), secretKey);
    // Check that the provided handshake (secret key + sessionID) is correct
    if (!anticipatedDigest.equalsIgnoreCase(digest)) {
        Log.debug("LocalComponentSession: [ExComp] Incorrect handshake for component with domain: " + defaultSubdomain);
        //  The credentials supplied by the initiator are not valid (answer an error
        // and close the connection)
        conn.deliverRawText(new StreamError(StreamError.Condition.not_authorized).toXML());
        // Close the underlying connection
        conn.close();
        return false;
    } else {
        // Component has authenticated fine
        setStatus(STATUS_AUTHENTICATED);
        // Send empty handshake element to acknowledge success
        conn.deliverRawText("<handshake></handshake>");
        // Bind the domain to this component
        ExternalComponent component = getExternalComponent();
        try {
            InternalComponentManager.getInstance().addComponent(defaultSubdomain, component);
            Log.debug("LocalComponentSession: [ExComp] External component was registered SUCCESSFULLY with domain: " + defaultSubdomain);
            return true;
        } catch (ComponentException e) {
            Log.debug("LocalComponentSession: [ExComp] Another component is already using domain: " + defaultSubdomain);
            //  The credentials supplied by the initiator are not valid (answer an error
            // and close the connection)
            conn.deliverRawText(new StreamError(StreamError.Condition.conflict).toXML());
            // Close the underlying connection
            conn.close();
            return false;
        }
    }
}
Also used : StreamError(org.xmpp.packet.StreamError) ComponentException(org.xmpp.component.ComponentException)

Example 9 with StreamError

use of org.xmpp.packet.StreamError in project Openfire by igniterealtime.

the class LocalConnectionMultiplexerSession method createSession.

public static LocalConnectionMultiplexerSession createSession(String serverName, XmlPullParser xpp, Connection connection) throws XmlPullParserException {
    String domain = xpp.getAttributeValue("", "to");
    Log.debug("LocalConnectionMultiplexerSession: [ConMng] Starting registration of new connection manager for domain: " + domain);
    // Default answer header in case of an error
    StringBuilder sb = new StringBuilder();
    sb.append("<?xml version='1.0' encoding='");
    sb.append(CHARSET);
    sb.append("'?>");
    sb.append("<stream:stream ");
    sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
    sb.append("xmlns=\"jabber:connectionmanager\" from=\"");
    sb.append(domain);
    sb.append("\" version=\"1.0\">");
    // Check that a domain was provided in the stream header
    if (domain == null) {
        Log.debug("LocalConnectionMultiplexerSession: [ConMng] Domain not specified in stanza: " + xpp.getText());
        // Include the bad-format in the response
        StreamError error = new StreamError(StreamError.Condition.bad_format);
        sb.append(error.toXML());
        connection.deliverRawText(sb.toString());
        // Close the underlying connection
        connection.close();
        return null;
    }
    // Get the requested domain
    JID address = new JID(domain);
    // Check that a secret key was configured in the server
    String secretKey = ConnectionMultiplexerManager.getDefaultSecret();
    if (secretKey == null) {
        Log.debug("LocalConnectionMultiplexerSession: [ConMng] A shared secret for connection manager was not found.");
        // Include the internal-server-error in the response
        StreamError error = new StreamError(StreamError.Condition.internal_server_error);
        sb.append(error.toXML());
        connection.deliverRawText(sb.toString());
        // Close the underlying connection
        connection.close();
        return null;
    }
    // Check that the requested subdomain is not already in use
    if (SessionManager.getInstance().getConnectionMultiplexerSession(address) != null) {
        Log.debug("LocalConnectionMultiplexerSession: [ConMng] Another connection manager is already using domain: " + domain);
        // Domain already occupied so return a conflict error and close the connection
        // Include the conflict error in the response
        StreamError error = new StreamError(StreamError.Condition.conflict);
        sb.append(error.toXML());
        connection.deliverRawText(sb.toString());
        // Close the underlying connection
        connection.close();
        return null;
    }
    // Indicate the TLS policy to use for this connection
    connection.setTlsPolicy(connection.getConfiguration().getTlsPolicy());
    // Indicate the compression policy to use for this connection
    connection.setCompressionPolicy(connection.getConfiguration().getCompressionPolicy());
    // Set the connection manager domain to use delivering a packet fails
    ((MultiplexerPacketDeliverer) connection.getPacketDeliverer()).setConnectionManagerDomain(address.getDomain());
    // Create a ConnectionMultiplexerSession for the new session originated
    // from the connection manager
    LocalConnectionMultiplexerSession session = SessionManager.getInstance().createMultiplexerSession(connection, address);
    // Set the address of the new session
    session.setAddress(address);
    connection.init(session);
    try {
        Log.debug("LocalConnectionMultiplexerSession: [ConMng] Send stream header with ID: " + session.getStreamID() + " for connection manager with domain: " + domain);
        // Build the start packet response
        sb = new StringBuilder();
        sb.append("<?xml version='1.0' encoding='");
        sb.append(CHARSET);
        sb.append("'?>");
        sb.append("<stream:stream ");
        sb.append("xmlns:stream=\"http://etherx.jabber.org/streams\" ");
        sb.append("xmlns=\"jabber:connectionmanager\" from=\"");
        sb.append(domain);
        sb.append("\" id=\"");
        sb.append(session.getStreamID().toString());
        sb.append("\" version=\"1.0\" >");
        connection.deliverRawText(sb.toString());
        // Announce stream features.
        sb = new StringBuilder(490);
        sb.append("<stream:features>");
        if (connection.getTlsPolicy() != Connection.TLSPolicy.disabled) {
            sb.append("<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\">");
            if (connection.getTlsPolicy() == Connection.TLSPolicy.required) {
                sb.append("<required/>");
            }
            sb.append("</starttls>");
        }
        // Include Stream features
        String specificFeatures = session.getAvailableStreamFeatures();
        if (specificFeatures != null) {
            sb.append(specificFeatures);
        }
        sb.append("</stream:features>");
        connection.deliverRawText(sb.toString());
        return session;
    } catch (Exception e) {
        Log.error("An error occured while creating a Connection Manager Session", e);
        // Close the underlying connection
        connection.close();
        return null;
    }
}
Also used : StreamError(org.xmpp.packet.StreamError) JID(org.xmpp.packet.JID) UnauthorizedException(org.jivesoftware.openfire.auth.UnauthorizedException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) MultiplexerPacketDeliverer(org.jivesoftware.openfire.multiplex.MultiplexerPacketDeliverer)

Example 10 with StreamError

use of org.xmpp.packet.StreamError in project Openfire by igniterealtime.

the class JustMarriedPlugin method deleteUser.

private static void deleteUser(User oldUser) {
    UserManager.getInstance().deleteUser(oldUser);
    final StreamError error = new StreamError(StreamError.Condition.not_authorized);
    for (ClientSession sess : SessionManager.getInstance().getSessions(oldUser.getUsername())) {
        sess.deliverRawText(error.toXML());
        sess.close();
    }
}
Also used : StreamError(org.xmpp.packet.StreamError) ClientSession(org.jivesoftware.openfire.session.ClientSession)

Aggregations

StreamError (org.xmpp.packet.StreamError)25 ClientSession (org.jivesoftware.openfire.session.ClientSession)7 IOException (java.io.IOException)6 UnauthorizedException (org.jivesoftware.openfire.auth.UnauthorizedException)6 XmlPullParserException (org.xmlpull.v1.XmlPullParserException)6 JID (org.xmpp.packet.JID)5 SSLHandshakeException (javax.net.ssl.SSLHandshakeException)4 DocumentException (org.dom4j.DocumentException)4 Element (org.dom4j.Element)4 LocalIncomingServerSession (org.jivesoftware.openfire.session.LocalIncomingServerSession)4 XmlPullParser (org.xmlpull.v1.XmlPullParser)4 StringprepException (gnu.inet.encoding.StringprepException)3 PacketException (org.jivesoftware.openfire.PacketException)3 LocalClientSession (org.jivesoftware.openfire.session.LocalClientSession)3 UserNotFoundException (org.jivesoftware.openfire.user.UserNotFoundException)3 Logger (org.slf4j.Logger)3 IQ (org.xmpp.packet.IQ)3 InputStreamReader (java.io.InputStreamReader)2 Socket (java.net.Socket)2 Connection (org.jivesoftware.openfire.Connection)2