Java Code Examples for javax.security.sasl.SaslServer#isComplete()

The following examples show how to use javax.security.sasl.SaslServer#isComplete() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClientServerTest.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void processConnection(SaslEndpoint endpoint)
        throws SaslException, IOException, ClassNotFoundException {
    System.out.println("process connection");
    endpoint.send(SUPPORT_MECHS);
    Object o = endpoint.receive();
    if (!(o instanceof String)) {
        throw new RuntimeException("Received unexpected object: " + o);
    }
    String mech = (String) o;
    SaslServer saslServer = createSaslServer(mech);
    Message msg = getMessage(endpoint.receive());
    while (!saslServer.isComplete()) {
        byte[] data = processData(msg.getData(), endpoint,
                saslServer);
        if (saslServer.isComplete()) {
            System.out.println("server is complete");
            endpoint.send(new Message(SaslStatus.SUCCESS, data));
        } else {
            System.out.println("server continues");
            endpoint.send(new Message(SaslStatus.CONTINUE, data));
            msg = getMessage(endpoint.receive());
        }
    }
}
 
Example 2
Source File: ClientServerTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
private void processConnection(SaslEndpoint endpoint)
        throws SaslException, IOException, ClassNotFoundException {
    System.out.println("process connection");
    endpoint.send(SUPPORT_MECHS);
    Object o = endpoint.receive();
    if (!(o instanceof String)) {
        throw new RuntimeException("Received unexpected object: " + o);
    }
    String mech = (String) o;
    SaslServer saslServer = createSaslServer(mech);
    Message msg = getMessage(endpoint.receive());
    while (!saslServer.isComplete()) {
        byte[] data = processData(msg.getData(), endpoint,
                saslServer);
        if (saslServer.isComplete()) {
            System.out.println("server is complete");
            endpoint.send(new Message(SaslStatus.SUCCESS, data));
        } else {
            System.out.println("server continues");
            endpoint.send(new Message(SaslStatus.CONTINUE, data));
            msg = getMessage(endpoint.receive());
        }
    }
}
 
Example 3
Source File: ClientServerTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private void processConnection(SaslEndpoint endpoint)
        throws SaslException, IOException, ClassNotFoundException {
    System.out.println("process connection");
    endpoint.send(SUPPORT_MECHS);
    Object o = endpoint.receive();
    if (!(o instanceof String)) {
        throw new RuntimeException("Received unexpected object: " + o);
    }
    String mech = (String) o;
    SaslServer saslServer = createSaslServer(mech);
    Message msg = getMessage(endpoint.receive());
    while (!saslServer.isComplete()) {
        byte[] data = processData(msg.getData(), endpoint,
                saslServer);
        if (saslServer.isComplete()) {
            System.out.println("server is complete");
            endpoint.send(new Message(SaslStatus.SUCCESS, data));
        } else {
            System.out.println("server continues");
            endpoint.send(new Message(SaslStatus.CONTINUE, data));
            msg = getMessage(endpoint.receive());
        }
    }
}
 
Example 4
Source File: ClientServerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void processConnection(SaslEndpoint endpoint)
        throws SaslException, IOException, ClassNotFoundException {
    System.out.println("process connection");
    endpoint.send(SUPPORT_MECHS);
    Object o = endpoint.receive();
    if (!(o instanceof String)) {
        throw new RuntimeException("Received unexpected object: " + o);
    }
    String mech = (String) o;
    SaslServer saslServer = createSaslServer(mech);
    Message msg = getMessage(endpoint.receive());
    while (!saslServer.isComplete()) {
        byte[] data = processData(msg.getData(), endpoint,
                saslServer);
        if (saslServer.isComplete()) {
            System.out.println("server is complete");
            endpoint.send(new Message(SaslStatus.SUCCESS, data));
        } else {
            System.out.println("server continues");
            endpoint.send(new Message(SaslStatus.CONTINUE, data));
            msg = getMessage(endpoint.receive());
        }
    }
}
 
Example 5
Source File: ClientServerTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private void processConnection(SaslEndpoint endpoint)
        throws SaslException, IOException, ClassNotFoundException {
    System.out.println("process connection");
    endpoint.send(SUPPORT_MECHS);
    Object o = endpoint.receive();
    if (!(o instanceof String)) {
        throw new RuntimeException("Received unexpected object: " + o);
    }
    String mech = (String) o;
    SaslServer saslServer = createSaslServer(mech);
    Message msg = getMessage(endpoint.receive());
    while (!saslServer.isComplete()) {
        byte[] data = processData(msg.getData(), endpoint,
                saslServer);
        if (saslServer.isComplete()) {
            System.out.println("server is complete");
            endpoint.send(new Message(SaslStatus.SUCCESS, data));
        } else {
            System.out.println("server continues");
            endpoint.send(new Message(SaslStatus.CONTINUE, data));
            msg = getMessage(endpoint.receive());
        }
    }
}
 
Example 6
Source File: SaslAuthenticationStrategy.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(int channel, ChannelHandlerContext ctx, AmqpConnectionHandler connectionHandler,
                   ShortString mechanism, LongString response) throws BrokerException {
    try {
        SaslServer saslServer = authManager
                .createSaslServer(hostName, mechanism.toString());
        byte[] challenge = saslServer.evaluateResponse(response.getBytes());
        if (saslServer.isComplete()) {
            Subject subject = UsernamePrincipal.createSubject(saslServer.getAuthorizationID());
            connectionHandler.attachBroker(brokerFactory.getBroker(subject));
            ctx.writeAndFlush(new ConnectionTune(256, 65535, 0));
        } else {
            ctx.channel().attr(AttributeKey.valueOf(SASL_SERVER_ATTRIBUTE)).set(saslServer);
            ctx.writeAndFlush(new ConnectionSecure(channel, LongString.parse(challenge)));
        }
    } catch (SaslException e) {
        throw new BrokerException("Exception occurred while handling authentication with Sasl", e);
    }
}
 
Example 7
Source File: SaslAuthenticationStrategy.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
@Override
public void handleChallengeResponse(int channel,
                                    ChannelHandlerContext ctx,
                                    AmqpConnectionHandler connectionHandler,
                                    LongString response) throws BrokerException {
    Attribute<SaslServer> saslServerAttribute = ctx.channel().attr(AttributeKey.valueOf(SASL_SERVER_ATTRIBUTE));
    SaslServer saslServer;
    if (saslServerAttribute != null && (saslServer = saslServerAttribute.get()) != null) {
        byte[] challenge = evaluateResponse(response, saslServer);
        if (saslServer.isComplete()) {
            Subject subject = UsernamePrincipal.createSubject(saslServer.getAuthorizationID());
            connectionHandler.attachBroker(brokerFactory.getBroker(subject));
            ctx.writeAndFlush(new ConnectionTune(256, 65535, 0));
            ctx.channel().attr(AttributeKey.valueOf(SASL_SERVER_ATTRIBUTE)).set(null);
        } else {
            ctx.writeAndFlush(new ConnectionSecure(channel, LongString.parse(challenge)));
        }
    } else {
        throw new BrokerException("Sasl server hasn't been set during connection start");
    }
}
 
Example 8
Source File: ClientServerTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void processConnection(SaslEndpoint endpoint)
        throws SaslException, IOException, ClassNotFoundException {
    System.out.println("process connection");
    endpoint.send(SUPPORT_MECHS);
    Object o = endpoint.receive();
    if (!(o instanceof String)) {
        throw new RuntimeException("Received unexpected object: " + o);
    }
    String mech = (String) o;
    SaslServer saslServer = createSaslServer(mech);
    Message msg = getMessage(endpoint.receive());
    while (!saslServer.isComplete()) {
        byte[] data = processData(msg.getData(), endpoint,
                saslServer);
        if (saslServer.isComplete()) {
            System.out.println("server is complete");
            endpoint.send(new Message(SaslStatus.SUCCESS, data));
        } else {
            System.out.println("server continues");
            endpoint.send(new Message(SaslStatus.CONTINUE, data));
            msg = getMessage(endpoint.receive());
        }
    }
}
 
Example 9
Source File: ClientServerTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private void processConnection(SaslEndpoint endpoint)
        throws SaslException, IOException, ClassNotFoundException {
    System.out.println("process connection");
    endpoint.send(SUPPORT_MECHS);
    Object o = endpoint.receive();
    if (!(o instanceof String)) {
        throw new RuntimeException("Received unexpected object: " + o);
    }
    String mech = (String) o;
    SaslServer saslServer = createSaslServer(mech);
    Message msg = getMessage(endpoint.receive());
    while (!saslServer.isComplete()) {
        byte[] data = processData(msg.getData(), endpoint,
                saslServer);
        if (saslServer.isComplete()) {
            System.out.println("server is complete");
            endpoint.send(new Message(SaslStatus.SUCCESS, data));
        } else {
            System.out.println("server continues");
            endpoint.send(new Message(SaslStatus.CONTINUE, data));
            msg = getMessage(endpoint.receive());
        }
    }
}
 
Example 10
Source File: AbstractSaslServerNegotiator.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
public AuthenticationResult handleResponse(final byte[] response)
{
    SaslServer saslServer = getSaslServer();
    if (saslServer == null)
    {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, getSaslServerCreationException());
    }
    try
    {

        byte[] challenge = saslServer.evaluateResponse(response != null ? response : new byte[0]);

        if (saslServer.isComplete())
        {
            final String userId = saslServer.getAuthorizationID();
            return new AuthenticationResult(new UsernamePrincipal(userId, getAuthenticationProvider()),
                                            challenge);
        }
        else
        {
            return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.CONTINUE);
        }
    }
    catch (SaslException | IllegalStateException e)
    {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    }
}
 
Example 11
Source File: NoQuoteParams.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        Map<String, String> props = new TreeMap<String, String>();
        props.put(Sasl.QOP, "auth");

        // client
        SaslClient client = Sasl.createSaslClient(new String[]{ DIGEST_MD5 },
            "user1", "xmpp", "127.0.0.1", props, authCallbackHandler);
        if (client == null) {
            throw new Exception("Unable to find client implementation for: " +
                DIGEST_MD5);
        }

        byte[] response = client.hasInitialResponse()
            ? client.evaluateChallenge(EMPTY) : EMPTY;
        logger.info("initial: " + new String(response));

        // server
        byte[] challenge = null;
        SaslServer server = Sasl.createSaslServer(DIGEST_MD5, "xmpp",
          "127.0.0.1", props, authCallbackHandler);
        if (server == null) {
            throw new Exception("Unable to find server implementation for: " +
                DIGEST_MD5);
        }

        if (!client.isComplete() || !server.isComplete()) {
            challenge = server.evaluateResponse(response);

            logger.info("challenge: " + new String(challenge));

            if (challenge != null) {
                response = client.evaluateChallenge(challenge);
            }
        }

        String challengeString = new String(challenge, "UTF-8").toLowerCase();

        if (challengeString.indexOf("\"md5-sess\"") > 0 ||
            challengeString.indexOf("\"utf-8\"") > 0) {
            throw new Exception("The challenge string's charset and " +
                "algorithm values must not be enclosed within quotes");
        }

        client.dispose();
        server.dispose();
    }
 
Example 12
Source File: NoQuoteParams.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        Map<String, String> props = new TreeMap<String, String>();
        props.put(Sasl.QOP, "auth");

        // client
        SaslClient client = Sasl.createSaslClient(new String[]{ DIGEST_MD5 },
            "user1", "xmpp", "127.0.0.1", props, authCallbackHandler);
        if (client == null) {
            throw new Exception("Unable to find client implementation for: " +
                DIGEST_MD5);
        }

        byte[] response = client.hasInitialResponse()
            ? client.evaluateChallenge(EMPTY) : EMPTY;
        logger.info("initial: " + new String(response));

        // server
        byte[] challenge = null;
        SaslServer server = Sasl.createSaslServer(DIGEST_MD5, "xmpp",
          "127.0.0.1", props, authCallbackHandler);
        if (server == null) {
            throw new Exception("Unable to find server implementation for: " +
                DIGEST_MD5);
        }

        if (!client.isComplete() || !server.isComplete()) {
            challenge = server.evaluateResponse(response);

            logger.info("challenge: " + new String(challenge));

            if (challenge != null) {
                response = client.evaluateChallenge(challenge);
            }
        }

        String challengeString = new String(challenge, "UTF-8").toLowerCase();

        if (challengeString.indexOf("\"md5-sess\"") > 0 ||
            challengeString.indexOf("\"utf-8\"") > 0) {
            throw new Exception("The challenge string's charset and " +
                "algorithm values must not be enclosed within quotes");
        }

        client.dispose();
        server.dispose();
    }
 
Example 13
Source File: NoQuoteParams.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        Map<String, String> props = new TreeMap<String, String>();
        props.put(Sasl.QOP, "auth");

        // client
        SaslClient client = Sasl.createSaslClient(new String[]{ DIGEST_MD5 },
            "user1", "xmpp", "127.0.0.1", props, authCallbackHandler);
        if (client == null) {
            throw new Exception("Unable to find client implementation for: " +
                DIGEST_MD5);
        }

        byte[] response = client.hasInitialResponse()
            ? client.evaluateChallenge(EMPTY) : EMPTY;
        logger.info("initial: " + new String(response));

        // server
        byte[] challenge = null;
        SaslServer server = Sasl.createSaslServer(DIGEST_MD5, "xmpp",
          "127.0.0.1", props, authCallbackHandler);
        if (server == null) {
            throw new Exception("Unable to find server implementation for: " +
                DIGEST_MD5);
        }

        if (!client.isComplete() || !server.isComplete()) {
            challenge = server.evaluateResponse(response);

            logger.info("challenge: " + new String(challenge));

            if (challenge != null) {
                response = client.evaluateChallenge(challenge);
            }
        }

        String challengeString = new String(challenge, "UTF-8").toLowerCase();

        if (challengeString.indexOf("\"md5-sess\"") > 0 ||
            challengeString.indexOf("\"utf-8\"") > 0) {
            throw new Exception("The challenge string's charset and " +
                "algorithm values must not be enclosed within quotes");
        }

        client.dispose();
        server.dispose();
    }
 
Example 14
Source File: NoQuoteParams.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        Map<String, String> props = new TreeMap<String, String>();
        props.put(Sasl.QOP, "auth");

        // client
        SaslClient client = Sasl.createSaslClient(new String[]{ DIGEST_MD5 },
            "user1", "xmpp", "127.0.0.1", props, authCallbackHandler);
        if (client == null) {
            throw new Exception("Unable to find client implementation for: " +
                DIGEST_MD5);
        }

        byte[] response = client.hasInitialResponse()
            ? client.evaluateChallenge(EMPTY) : EMPTY;
        logger.info("initial: " + new String(response));

        // server
        byte[] challenge = null;
        SaslServer server = Sasl.createSaslServer(DIGEST_MD5, "xmpp",
          "127.0.0.1", props, authCallbackHandler);
        if (server == null) {
            throw new Exception("Unable to find server implementation for: " +
                DIGEST_MD5);
        }

        if (!client.isComplete() || !server.isComplete()) {
            challenge = server.evaluateResponse(response);

            logger.info("challenge: " + new String(challenge));

            if (challenge != null) {
                response = client.evaluateChallenge(challenge);
            }
        }

        String challengeString = new String(challenge, "UTF-8").toLowerCase();

        if (challengeString.indexOf("\"md5-sess\"") > 0 ||
            challengeString.indexOf("\"utf-8\"") > 0) {
            throw new Exception("The challenge string's charset and " +
                "algorithm values must not be enclosed within quotes");
        }

        client.dispose();
        server.dispose();
    }
 
Example 15
Source File: Cram.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    if (args.length == 0) {
        pwfile = "pw.properties";
        namesfile = "names.properties";
        auto = true;
    } else {
        int i = 0;
        if (args[i].equals("-m")) {
            i++;
            auto = false;
        }
        if (args.length > i) {
            pwfile = args[i++];

            if (args.length > i) {
                namesfile = args[i++];
            }
        } else {
            pwfile = "pw.properties";
            namesfile = "names.properties";
        }
    }

    CallbackHandler clntCbh = new ClientCallbackHandler(auto);

    CallbackHandler srvCbh =
        new PropertiesFileCallbackHandler(pwfile, namesfile, null);

    SaslClient clnt = Sasl.createSaslClient(
        new String[]{MECH}, null, PROTOCOL, SERVER_FQDN, null, clntCbh);

    SaslServer srv = Sasl.createSaslServer(MECH, PROTOCOL, SERVER_FQDN, null,
        srvCbh);

    if (clnt == null) {
        throw new IllegalStateException(
            "Unable to find client impl for " + MECH);
    }
    if (srv == null) {
        throw new IllegalStateException(
            "Unable to find server impl for " + MECH);
    }

    byte[] response = (clnt.hasInitialResponse()?
        clnt.evaluateChallenge(EMPTY) : EMPTY);
    byte[] challenge;

    while (!clnt.isComplete() || !srv.isComplete()) {
        challenge = srv.evaluateResponse(response);

        if (challenge != null) {
            response = clnt.evaluateChallenge(challenge);
        }
    }

    if (clnt.isComplete() && srv.isComplete()) {
        if (verbose) {
            System.out.println("SUCCESS");
            System.out.println("authzid is " + srv.getAuthorizationID());
        }
    } else {
        throw new IllegalStateException("FAILURE: mismatched state:" +
            " client complete? " + clnt.isComplete() +
            " server complete? " + srv.isComplete());
    }
}
 
Example 16
Source File: NoQuoteParams.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        Map<String, String> props = new TreeMap<String, String>();
        props.put(Sasl.QOP, "auth");

        // client
        SaslClient client = Sasl.createSaslClient(new String[]{ DIGEST_MD5 },
            "user1", "xmpp", "127.0.0.1", props, authCallbackHandler);
        if (client == null) {
            throw new Exception("Unable to find client implementation for: " +
                DIGEST_MD5);
        }

        byte[] response = client.hasInitialResponse()
            ? client.evaluateChallenge(EMPTY) : EMPTY;
        logger.info("initial: " + new String(response));

        // server
        byte[] challenge = null;
        SaslServer server = Sasl.createSaslServer(DIGEST_MD5, "xmpp",
          "127.0.0.1", props, authCallbackHandler);
        if (server == null) {
            throw new Exception("Unable to find server implementation for: " +
                DIGEST_MD5);
        }

        if (!client.isComplete() || !server.isComplete()) {
            challenge = server.evaluateResponse(response);

            logger.info("challenge: " + new String(challenge));

            if (challenge != null) {
                response = client.evaluateChallenge(challenge);
            }
        }

        String challengeString = new String(challenge, "UTF-8").toLowerCase();

        if (challengeString.indexOf("\"md5-sess\"") > 0 ||
            challengeString.indexOf("\"utf-8\"") > 0) {
            throw new Exception("The challenge string's charset and " +
                "algorithm values must not be enclosed within quotes");
        }

        client.dispose();
        server.dispose();
    }
 
Example 17
Source File: NoQuoteParams.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        Map<String, String> props = new TreeMap<String, String>();
        props.put(Sasl.QOP, "auth");

        // client
        SaslClient client = Sasl.createSaslClient(new String[]{ DIGEST_MD5 },
            "user1", "xmpp", "127.0.0.1", props, authCallbackHandler);
        if (client == null) {
            throw new Exception("Unable to find client implementation for: " +
                DIGEST_MD5);
        }

        byte[] response = client.hasInitialResponse()
            ? client.evaluateChallenge(EMPTY) : EMPTY;
        logger.info("initial: " + new String(response));

        // server
        byte[] challenge = null;
        SaslServer server = Sasl.createSaslServer(DIGEST_MD5, "xmpp",
          "127.0.0.1", props, authCallbackHandler);
        if (server == null) {
            throw new Exception("Unable to find server implementation for: " +
                DIGEST_MD5);
        }

        if (!client.isComplete() || !server.isComplete()) {
            challenge = server.evaluateResponse(response);

            logger.info("challenge: " + new String(challenge));

            if (challenge != null) {
                response = client.evaluateChallenge(challenge);
            }
        }

        String challengeString = new String(challenge, "UTF-8").toLowerCase();

        if (challengeString.indexOf("\"md5-sess\"") > 0 ||
            challengeString.indexOf("\"utf-8\"") > 0) {
            throw new Exception("The challenge string's charset and " +
                "algorithm values must not be enclosed within quotes");
        }

        client.dispose();
        server.dispose();
    }
 
Example 18
Source File: NoQuoteParams.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        Map<String, String> props = new TreeMap<String, String>();
        props.put(Sasl.QOP, "auth");

        // client
        SaslClient client = Sasl.createSaslClient(new String[]{ DIGEST_MD5 },
            "user1", "xmpp", "127.0.0.1", props, authCallbackHandler);
        if (client == null) {
            throw new Exception("Unable to find client implementation for: " +
                DIGEST_MD5);
        }

        byte[] response = client.hasInitialResponse()
            ? client.evaluateChallenge(EMPTY) : EMPTY;
        logger.info("initial: " + new String(response));

        // server
        byte[] challenge = null;
        SaslServer server = Sasl.createSaslServer(DIGEST_MD5, "xmpp",
          "127.0.0.1", props, authCallbackHandler);
        if (server == null) {
            throw new Exception("Unable to find server implementation for: " +
                DIGEST_MD5);
        }

        if (!client.isComplete() || !server.isComplete()) {
            challenge = server.evaluateResponse(response);

            logger.info("challenge: " + new String(challenge));

            if (challenge != null) {
                response = client.evaluateChallenge(challenge);
            }
        }

        String challengeString = new String(challenge, "UTF-8").toLowerCase();

        if (challengeString.indexOf("\"md5-sess\"") > 0 ||
            challengeString.indexOf("\"utf-8\"") > 0) {
            throw new Exception("The challenge string's charset and " +
                "algorithm values must not be enclosed within quotes");
        }

        client.dispose();
        server.dispose();
    }
 
Example 19
Source File: BindRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
/**
 * For challenge/response exchange, generate the challenge. 
 * If the exchange is complete then send bind success.
 *
 * @param ldapSession
 * @param ss
 * @param bindRequest
 */
private void generateSaslChallengeOrComplete( LdapSession ldapSession, SaslServer ss,
    BindRequest bindRequest ) throws Exception
{
    LdapResult result = bindRequest.getResultResponse().getLdapResult();

    // SaslServer will throw an exception if the credentials are null.
    if ( bindRequest.getCredentials() == null )
    {
        bindRequest.setCredentials( StringConstants.EMPTY_BYTES );
    }

    try
    {
        // Compute the challenge
        byte[] tokenBytes = ss.evaluateResponse( bindRequest.getCredentials() );

        if ( ss.isComplete() )
        {
            // This is the end of the C/R exchange
            if ( tokenBytes != null )
            {
                /*
                 * There may be a token to return to the client.  We set it here
                 * so it will be returned in a SUCCESS message, after an LdapContext
                 * has been initialized for the client.
                 */
                ldapSession.putSaslProperty( SaslConstants.SASL_CREDS, tokenBytes );
            }

            LdapPrincipal ldapPrincipal = ( LdapPrincipal ) ldapSession
                .getSaslProperty( SaslConstants.SASL_AUTHENT_USER );

            if ( ldapPrincipal != null )
            {
                DirectoryService ds = ldapSession.getLdapServer().getDirectoryService();
                String saslMechanism = bindRequest.getSaslMechanism();
                byte[] password = null;

                if ( ldapPrincipal.getUserPasswords() != null )
                {
                    password = ldapPrincipal.getUserPasswords()[0];
                }

                CoreSession userSession = ds.getSession( ldapPrincipal.getDn(),
                    password, saslMechanism, null );

                // Set the user session into the ldap session 
                ldapSession.setCoreSession( userSession );

                // Store the IoSession in the coreSession
                ( ( DefaultCoreSession ) userSession ).setIoSession( ldapSession.getIoSession() );
            }

            // Mark the user as authenticated
            ldapSession.setAuthenticated();

            // Call the cleanup method for the selected mechanism
            MechanismHandler handler = ( MechanismHandler ) ldapSession
                .getSaslProperty( SaslConstants.SASL_MECH_HANDLER );
            handler.cleanup( ldapSession );

            // Return the successful response
            sendBindSuccess( ldapSession, bindRequest, tokenBytes );
        }
        else
        {
            // The SASL bind must continue, we are sending the computed challenge
            LOG.info( "Continuation token had length " + tokenBytes.length );

            // Build the response
            result.setResultCode( ResultCodeEnum.SASL_BIND_IN_PROGRESS );
            BindResponse resp = bindRequest.getResultResponse();

            // Store the challenge
            resp.setServerSaslCreds( tokenBytes );

            // Switch to SASLAuthPending
            ldapSession.setSaslAuthPending();

            // And write back the response
            ldapSession.getIoSession().write( resp );

            LOG.debug( "Returning final authentication data to client to complete context." );
        }
    }
    catch ( SaslException se )
    {
        sendInvalidCredentials( ldapSession, bindRequest, se );
    }
}
 
Example 20
Source File: BindRequestHandler.java    From MyVirtualDirectory with Apache License 2.0 4 votes vote down vote up
/**
 * For challenge/response exchange, generate the challenge. If the exchange is complete then send bind success.
 *
 * @param ldapSession
 * @param ss
 * @param bindRequest
 */
private void generateSaslChallengeOrComplete(LdapSession ldapSession, SaslServer ss,
                                             BindRequest bindRequest) throws Exception {
    LdapResult result = bindRequest.getResultResponse().getLdapResult();

    // SaslServer will throw an exception if the credentials are null.
    if (bindRequest.getCredentials() == null) {
        bindRequest.setCredentials(StringConstants.EMPTY_BYTES);
    }

    try {
        // Compute the challenge
        byte[] tokenBytes = ss.evaluateResponse(bindRequest.getCredentials());

        if (ss.isComplete()) {
            // This is the end of the C/R exchange
            if (tokenBytes != null) {
                /*
                 * There may be a token to return to the client.  We set it here
                 * so it will be returned in a SUCCESS message, after an LdapContext
                 * has been initialized for the client.
                 */
                ldapSession.putSaslProperty(SaslConstants.SASL_CREDS, tokenBytes);
            }

            LdapPrincipal ldapPrincipal = (LdapPrincipal) ldapSession
                    .getSaslProperty(SaslConstants.SASL_AUTHENT_USER);

            if (ldapPrincipal != null) {
                DirectoryService ds = ldapSession.getLdapServer().getDirectoryService();
                String saslMechanism = bindRequest.getSaslMechanism();
                byte[] password = null;

                if (ldapPrincipal.getUserPasswords() != null) {
                    password = ldapPrincipal.getUserPasswords()[0];
                }

                CoreSession userSession = ds.getSession(ldapPrincipal.getDn(),
                                                        password, saslMechanism, null);

                // Set the user session into the ldap session 
                ldapSession.setCoreSession(userSession);

                // Store the IoSession in the coreSession
                ((DefaultCoreSession) userSession).setIoSession(ldapSession.getIoSession());
            }

            // Mark the user as authenticated
            ldapSession.setAuthenticated();

            // Call the cleanup method for the selected mechanism
            MechanismHandler handler = (MechanismHandler) ldapSession
                    .getSaslProperty(SaslConstants.SASL_MECH_HANDLER);
            handler.cleanup(ldapSession);

            // Return the successful response
            sendBindSuccess(ldapSession, bindRequest, tokenBytes);
        } else {
            // The SASL bind must continue, we are sending the computed challenge
            LOG.info("Continuation token had length " + tokenBytes.length);

            // Build the response
            result.setResultCode(ResultCodeEnum.SASL_BIND_IN_PROGRESS);
            BindResponse resp = (BindResponse) bindRequest.getResultResponse();

            // Store the challenge
            resp.setServerSaslCreds(tokenBytes);

            // Switch to SASLAuthPending
            ldapSession.setSaslAuthPending();

            // And write back the response
            ldapSession.getIoSession().write(resp);

            LOG.debug("Returning final authentication data to client to complete context.");
        }
    } catch (SaslException se) {
        sendInvalidCredentials(ldapSession, bindRequest, se);
    }
}