Search in sources :

Example 41 with SmackException

use of org.jivesoftware.smack.SmackException in project Smack by igniterealtime.

the class Socks5ClientForInitiatorTest method shouldFailIfTargetIsNotConnectedToLocalSocks5Proxy.

/**
     * If the target is not connected to the local SOCKS5 proxy an exception should be thrown.
     * 
     * @throws Exception should not happen
     */
@Test
public void shouldFailIfTargetIsNotConnectedToLocalSocks5Proxy() throws Exception {
    // start a local SOCKS5 proxy
    Socks5Proxy.setLocalSocks5ProxyPort(proxyPort);
    Socks5Proxy socks5Proxy = Socks5Proxy.getSocks5Proxy();
    socks5Proxy.start();
    // build stream host information for local SOCKS5 proxy
    StreamHost streamHost = new StreamHost(connection.getUser(), loopbackAddress, socks5Proxy.getPort());
    // create digest to get the socket opened by target
    String digest = Socks5Utils.createDigest(sessionID, initiatorJID, targetJID);
    Socks5ClientForInitiator socks5Client = new Socks5ClientForInitiator(streamHost, digest, connection, sessionID, targetJID);
    try {
        socks5Client.getSocket(10000);
        fail("exception should be thrown");
    } catch (SmackException e) {
        assertTrue(e.getMessage().contains("target is not connected to SOCKS5 proxy"));
        // assert no XMPP messages were sent
        protocol.verifyAll();
    }
    socks5Proxy.stop();
}
Also used : SmackException(org.jivesoftware.smack.SmackException) StreamHost(org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream.StreamHost) Test(org.junit.Test)

Example 42 with SmackException

use of org.jivesoftware.smack.SmackException in project Smack by igniterealtime.

the class Socks5ClientTest method shouldCloseSocketIfServerRepliesInUnsupportedWay.

/**
     * The SOCKS5 client should close connection if server replies in an unsupported way.
     * 
     * @throws Exception should not happen
     */
@Test
public void shouldCloseSocketIfServerRepliesInUnsupportedWay() throws Exception {
    // start thread to connect to SOCKS5 proxy
    Thread serverThread = new Thread() {

        @Override
        public void run() {
            StreamHost streamHost = new StreamHost(proxyJID, serverAddress, serverPort);
            Socks5Client socks5Client = new Socks5Client(streamHost, digest);
            try {
                socks5Client.getSocket(10000);
                fail("exception should be thrown");
            } catch (SmackException e) {
                assertTrue(e.getMessage().contains("Unsupported SOCKS5 address type"));
            } catch (Exception e) {
                fail(e.getMessage());
            }
        }
    };
    serverThread.start();
    // accept connection from client
    Socket socket = serverSocket.accept();
    DataInputStream in = new DataInputStream(socket.getInputStream());
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    // validate authentication request
    // version
    assertEquals((byte) 0x05, (byte) in.read());
    // number of supported auth methods
    assertEquals((byte) 0x01, (byte) in.read());
    // no-authentication method
    assertEquals((byte) 0x00, (byte) in.read());
    // respond that no no-authentication method is used
    out.write(new byte[] { (byte) 0x05, (byte) 0x00 });
    out.flush();
    Socks5Utils.receiveSocks5Message(in);
    // reply with unsupported address type
    out.write(new byte[] { (byte) 0x05, (byte) 0x00, (byte) 0x00, (byte) 0x01, (byte) 0x00 });
    out.flush();
    // wait for client to shutdown
    serverThread.join();
    // assert socket is closed
    assertEquals(-1, in.read());
}
Also used : DataOutputStream(java.io.DataOutputStream) SmackException(org.jivesoftware.smack.SmackException) DataInputStream(java.io.DataInputStream) StreamHost(org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream.StreamHost) SmackException(org.jivesoftware.smack.SmackException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) Test(org.junit.Test)

Example 43 with SmackException

use of org.jivesoftware.smack.SmackException in project Smack by igniterealtime.

the class Socks5ByteStreamManagerTest method shouldFailIfNoSocks5ProxyFound1.

/**
     * Invoking {@link Socks5BytestreamManager#establishSession(org.jxmpp.jid.Jid, String)} should fail if XMPP
     * server doesn't return any proxies.
     */
@Test
public void shouldFailIfNoSocks5ProxyFound1() {
    // disable clients local SOCKS5 proxy
    Socks5Proxy.setLocalSocks5ProxyEnabled(false);
    // get Socks5ByteStreamManager for connection
    Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
    /**
         * create responses in the order they should be queried specified by the XEP-0065
         * specification
         */
    // build discover info that supports the SOCKS5 feature
    DiscoverInfo discoverInfo = Socks5PacketUtils.createDiscoverInfo(targetJID, initiatorJID);
    discoverInfo.addFeature(Bytestream.NAMESPACE);
    // return that SOCKS5 is supported if target is queried
    protocol.addResponse(discoverInfo, Verification.correspondingSenderReceiver, Verification.requestTypeGET);
    // build discover items with no proxy items
    DiscoverItems discoverItems = Socks5PacketUtils.createDiscoverItems(xmppServer, initiatorJID);
    // return the item with no proxy if XMPP server is queried
    protocol.addResponse(discoverItems, Verification.correspondingSenderReceiver, Verification.requestTypeGET);
    try {
        // start SOCKS5 Bytestream
        byteStreamManager.establishSession(targetJID, sessionID);
        fail("exception should be thrown");
    } catch (SmackException e) {
        protocol.verifyAll();
        assertTrue(e.getMessage().contains("no SOCKS5 proxies available"));
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
Also used : DiscoverInfo(org.jivesoftware.smackx.disco.packet.DiscoverInfo) SmackException(org.jivesoftware.smack.SmackException) DiscoverItems(org.jivesoftware.smackx.disco.packet.DiscoverItems) SmackException(org.jivesoftware.smack.SmackException) FeatureNotSupportedException(org.jivesoftware.smack.SmackException.FeatureNotSupportedException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) XMPPErrorException(org.jivesoftware.smack.XMPPException.XMPPErrorException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) XMPPException(org.jivesoftware.smack.XMPPException) Test(org.junit.Test)

Example 44 with SmackException

use of org.jivesoftware.smack.SmackException in project Smack by igniterealtime.

the class Socks5ByteStreamManagerTest method shouldFailIfNoSocks5ProxyFound2.

/**
     * Invoking {@link Socks5BytestreamManager#establishSession(org.jxmpp.jid.Jid, String)} should fail if no
     * proxy is a SOCKS5 proxy.
     */
@Test
public void shouldFailIfNoSocks5ProxyFound2() {
    // disable clients local SOCKS5 proxy
    Socks5Proxy.setLocalSocks5ProxyEnabled(false);
    // get Socks5ByteStreamManager for connection
    Socks5BytestreamManager byteStreamManager = Socks5BytestreamManager.getBytestreamManager(connection);
    /**
         * create responses in the order they should be queried specified by the XEP-0065
         * specification
         */
    // build discover info that supports the SOCKS5 feature
    DiscoverInfo discoverInfo = Socks5PacketUtils.createDiscoverInfo(targetJID, initiatorJID);
    discoverInfo.addFeature(Bytestream.NAMESPACE);
    // return that SOCKS5 is supported if target is queried
    protocol.addResponse(discoverInfo, Verification.correspondingSenderReceiver, Verification.requestTypeGET);
    // build discover items containing a proxy item
    DiscoverItems discoverItems = Socks5PacketUtils.createDiscoverItems(xmppServer, initiatorJID);
    Item item = new Item(proxyJID);
    discoverItems.addItem(item);
    // return the proxy item if XMPP server is queried
    protocol.addResponse(discoverItems, Verification.correspondingSenderReceiver, Verification.requestTypeGET);
    // build discover info for proxy containing information about NOT being a Socks5
    // proxy
    DiscoverInfo proxyInfo = Socks5PacketUtils.createDiscoverInfo(proxyJID, initiatorJID);
    Identity identity = new Identity("noproxy", proxyJID.toString(), "bytestreams");
    proxyInfo.addIdentity(identity);
    // return the proxy identity if proxy is queried
    protocol.addResponse(proxyInfo, Verification.correspondingSenderReceiver, Verification.requestTypeGET);
    try {
        // start SOCKS5 Bytestream
        byteStreamManager.establishSession(targetJID, sessionID);
        fail("exception should be thrown");
    } catch (SmackException e) {
        protocol.verifyAll();
        assertTrue(e.getMessage().contains("no SOCKS5 proxies available"));
    } catch (Exception e) {
        fail(e.getMessage());
    }
}
Also used : DiscoverInfo(org.jivesoftware.smackx.disco.packet.DiscoverInfo) Item(org.jivesoftware.smackx.disco.packet.DiscoverItems.Item) SmackException(org.jivesoftware.smack.SmackException) DiscoverItems(org.jivesoftware.smackx.disco.packet.DiscoverItems) Identity(org.jivesoftware.smackx.disco.packet.DiscoverInfo.Identity) SmackException(org.jivesoftware.smack.SmackException) FeatureNotSupportedException(org.jivesoftware.smack.SmackException.FeatureNotSupportedException) ConnectException(java.net.ConnectException) IOException(java.io.IOException) XMPPErrorException(org.jivesoftware.smack.XMPPException.XMPPErrorException) XmppStringprepException(org.jxmpp.stringprep.XmppStringprepException) XMPPException(org.jivesoftware.smack.XMPPException) Test(org.junit.Test)

Example 45 with SmackException

use of org.jivesoftware.smack.SmackException in project Smack by igniterealtime.

the class SASLDigestMD5Mechanism method evaluateChallenge.

@Override
protected byte[] evaluateChallenge(byte[] challenge) throws SmackException {
    if (challenge.length == 0) {
        throw new SmackException("Initial challenge has zero length");
    }
    String challengeString;
    try {
        challengeString = new String(challenge, StringUtils.UTF8);
    } catch (UnsupportedEncodingException e) {
        throw new AssertionError(e);
    }
    String[] challengeParts = challengeString.split(",");
    byte[] response = null;
    switch(state) {
        case INITIAL:
            for (String part : challengeParts) {
                String[] keyValue = part.split("=");
                assert (keyValue.length == 2);
                String key = keyValue[0];
                // RFC 2831 ยง 7.1 about the formating of the digest-challenge:
                // "The full form is "<n>#<m>element" indicating at least <n> and
                // at most <m> elements, each separated by one or more commas
                // (",") and OPTIONAL linear white space (LWS)."
                // Which means the key value may be preceded by whitespace,
                // which is what we remove: *Only the preceding whitespace*.
                key = key.replaceFirst("^\\s+", "");
                String value = keyValue[1];
                if ("nonce".equals(key)) {
                    if (nonce != null) {
                        throw new SmackException("Nonce value present multiple times");
                    }
                    nonce = value.replace("\"", "");
                } else if ("qop".equals(key)) {
                    value = value.replace("\"", "");
                    if (!value.equals("auth")) {
                        throw new SmackException("Unsupported qop operation: " + value);
                    }
                }
            }
            if (nonce == null) {
                // abort the authentication exchange."
                throw new SmackException("nonce value not present in initial challenge");
            }
            // RFC 2831 2.1.2.1 defines A1, A2, KD and response-value
            byte[] a1FirstPart = MD5.bytes(authenticationId + ':' + serviceName + ':' + password);
            cnonce = StringUtils.randomString(32);
            byte[] a1 = ByteUtils.concact(a1FirstPart, toBytes(':' + nonce + ':' + cnonce));
            digestUri = "xmpp/" + serviceName;
            hex_hashed_a1 = StringUtils.encodeHex(MD5.bytes(a1));
            String responseValue = calcResponse(DigestType.ClientResponse);
            // @formatter:off
            // See RFC 2831 2.1.2 digest-response
            String authzid;
            if (authorizationId == null) {
                authzid = "";
            } else {
                authzid = ",authzid=\"" + authorizationId + '"';
            }
            String saslString = "username=\"" + quoteBackslash(authenticationId) + '"' + authzid + ",realm=\"" + serviceName + '"' + ",nonce=\"" + nonce + '"' + ",cnonce=\"" + cnonce + '"' + ",nc=" + INITAL_NONCE + ",qop=auth" + ",digest-uri=\"" + digestUri + '"' + ",response=" + responseValue + ",charset=utf-8";
            // @formatter:on
            response = toBytes(saslString);
            state = State.RESPONSE_SENT;
            break;
        case RESPONSE_SENT:
            if (verifyServerResponse) {
                String serverResponse = null;
                for (String part : challengeParts) {
                    String[] keyValue = part.split("=");
                    assert (keyValue.length == 2);
                    String key = keyValue[0];
                    String value = keyValue[1];
                    if ("rspauth".equals(key)) {
                        serverResponse = value;
                        break;
                    }
                }
                if (serverResponse == null) {
                    throw new SmackException("No server response received while performing " + NAME + " authentication");
                }
                String expectedServerResponse = calcResponse(DigestType.ServerResponse);
                if (!serverResponse.equals(expectedServerResponse)) {
                    throw new SmackException("Invalid server response  while performing " + NAME + " authentication");
                }
            }
            state = State.VALID_SERVER_RESPONSE;
            break;
        default:
            throw new IllegalStateException();
    }
    return response;
}
Also used : SmackException(org.jivesoftware.smack.SmackException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

SmackException (org.jivesoftware.smack.SmackException)50 IOException (java.io.IOException)21 XMPPException (org.jivesoftware.smack.XMPPException)17 XMPPErrorException (org.jivesoftware.smack.XMPPException.XMPPErrorException)10 Test (org.junit.Test)9 Socket (java.net.Socket)8 StreamHost (org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream.StreamHost)6 FeatureNotSupportedException (org.jivesoftware.smack.SmackException.FeatureNotSupportedException)5 NoResponseException (org.jivesoftware.smack.SmackException.NoResponseException)5 DiscoverInfo (org.jivesoftware.smackx.disco.packet.DiscoverInfo)5 XmppStringprepException (org.jxmpp.stringprep.XmppStringprepException)5 DataInputStream (java.io.DataInputStream)4 DataOutputStream (java.io.DataOutputStream)4 ConnectException (java.net.ConnectException)4 DiscoverItems (org.jivesoftware.smackx.disco.packet.DiscoverItems)4 InputStream (java.io.InputStream)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 ServerSocket (java.net.ServerSocket)3 NotConnectedException (org.jivesoftware.smack.SmackException.NotConnectedException)3 XMPPConnection (org.jivesoftware.smack.XMPPConnection)3