Example usage for javax.security.sasl SaslServer evaluateResponse

List of usage examples for javax.security.sasl SaslServer evaluateResponse

Introduction

In this page you can find the example usage for javax.security.sasl SaslServer evaluateResponse.

Prototype

public abstract byte[] evaluateResponse(byte[] response) throws SaslException;

Source Link

Document

Evaluates the response data and generates a challenge.

Usage

From source file:org.apache.directory.server.ldap.handlers.request.BindRequestHandler.java

/**
 * For challenge/response exchange, generate the challenge. 
 * If the exchange is complete then send bind success.
 *
 * @param ldapSession//from   w w  w.j  a v  a 2  s  .  co  m
 * @param ss
 * @param bindRequest
 */
private void generateSaslChallengeOrComplete(LdapSession ldapSession, SaslServer ss, BindRequest bindRequest)
        throws Exception {
    BindResponse bindResponse = (BindResponse) bindRequest.getResultResponse();

    LdapResult result = bindResponse.getLdapResult();

    // SaslServer will throw an exception if the credentials are null.
    if (bindRequest.getCredentials() == null) {
        bindRequest.setCredentials(Strings.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, bindResponse, 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);

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

            // Switch to SASLAuthPending
            ldapSession.setSaslAuthPending();

            // And write back the response
            ldapSession.getIoSession().write(new BindResponseDecorator(getLdapApiService(), bindResponse));

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

From source file:org.apache.qpid.server.management.plugin.servlet.rest.SaslServlet.java

private void evaluateSaslResponse(final HttpServletRequest request, final HttpServletResponse response,
        final HttpSession session, final String saslResponse, final SaslServer saslServer,
        SubjectCreator subjectCreator) throws IOException {
    final String id;
    byte[] challenge;
    try {//from  w  ww. j  a  v  a  2s  .  co m
        challenge = saslServer.evaluateResponse(
                saslResponse == null ? new byte[0] : Base64.decodeBase64(saslResponse.getBytes()));
    } catch (SaslException e) {
        session.removeAttribute(ATTR_ID);
        session.removeAttribute(ATTR_SASL_SERVER);
        session.removeAttribute(ATTR_EXPIRY);
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);

        return;
    }

    if (saslServer.isComplete()) {
        Subject subject = subjectCreator.createSubjectWithGroups(saslServer.getAuthorizationID());

        try {
            authoriseManagement(request, subject);
        } catch (AccessControlException ace) {
            sendError(response, HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        setAuthorisedSubjectInSession(subject, request, session);
        session.removeAttribute(ATTR_ID);
        session.removeAttribute(ATTR_SASL_SERVER);
        session.removeAttribute(ATTR_EXPIRY);

        response.setStatus(HttpServletResponse.SC_OK);
    } else {
        Random rand = getRandom(session);
        id = String.valueOf(rand.nextLong());
        session.setAttribute(ATTR_ID, id);
        session.setAttribute(ATTR_SASL_SERVER, saslServer);
        session.setAttribute(ATTR_EXPIRY, System.currentTimeMillis() + SASL_EXCHANGE_EXPIRY);

        response.setStatus(HttpServletResponse.SC_OK);

        Map<String, Object> outputObject = new LinkedHashMap<String, Object>();
        outputObject.put("id", id);
        outputObject.put("challenge", new String(Base64.encodeBase64(challenge)));

        final PrintWriter writer = response.getWriter();

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);
        mapper.writeValue(writer, outputObject);
    }
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testSimpleUnilateralSha1WithRsaAuthentication() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);/*from  w  w  w . j a v a 2 s.c  o  m*/

    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
            "testserver1.example.com", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), serverTrustStore);
    assertNotNull(saslServer);
    assertFalse(saslServer.isComplete());

    final String[] mechanisms = new String[] { SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC };
    CallbackHandler cbh = createClientCallbackHandler(mechanisms, clientKeyStore, CLIENT_KEYSTORE_ALIAS,
            KEYSTORE_PASSWORD, null);
    final SaslClient saslClient = clientFactory.createSaslClient(mechanisms, null, "test",
            "testserver1.example.com", Collections.<String, Object>emptyMap(), cbh);
    assertNotNull(saslClient);
    assertTrue(saslClient instanceof EntitySaslClient);
    assertFalse(saslClient.hasInitialResponse());
    assertFalse(saslClient.isComplete());

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslClient.evaluateChallenge(message);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslServer.evaluateResponse(message);
    assertTrue(saslServer.isComplete());
    assertNull(message);
    assertNull(saslClient.evaluateChallenge(message));
    assertTrue(saslClient.isComplete());
    assertEquals("cn=test client 1,ou=jboss,o=red hat,l=raleigh,st=north carolina,c=us",
            saslServer.getAuthorizationID());
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testUnilateralSha1WithRsaAuthenticationWithTrustedAuthorities() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);//from w  ww .  jav  a 2  s.c  o  m

    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
            "testserver1.example.com", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), serverTrustStore);
    assertNotNull(saslServer);
    assertFalse(saslServer.isComplete());

    final String[] mechanisms = new String[] { SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC };
    CallbackHandler cbh = createClientCallbackHandler(mechanisms,
            getX509KeyManager(clientKeyStore, KEYSTORE_PASSWORD), null);
    final SaslClient saslClient = clientFactory.createSaslClient(mechanisms, null, "test",
            "testserver1.example.com", Collections.<String, Object>emptyMap(), cbh);
    assertNotNull(saslClient);
    assertTrue(saslClient instanceof EntitySaslClient);
    assertFalse(saslClient.hasInitialResponse());
    assertFalse(saslClient.isComplete());

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslClient.evaluateChallenge(message);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslServer.evaluateResponse(message);
    assertTrue(saslServer.isComplete());
    assertNull(message);
    assertNull(saslClient.evaluateChallenge(message));
    assertTrue(saslClient.isComplete());
    assertEquals("cn=signed test client,ou=jboss,o=red hat,st=north carolina,c=us",
            saslServer.getAuthorizationID());
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testUnilateralSha1WithRsaAuthenticationWithAuthorizationId() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);//from   w w  w .jav a 2s . co  m

    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
            "testserver1.example.com", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), serverTrustStore);

    final String[] mechanisms = new String[] { SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC };
    CallbackHandler cbh = createClientCallbackHandler(mechanisms, clientKeyStore, CLIENT_KEYSTORE_ALIAS,
            KEYSTORE_PASSWORD, null);
    final SaslClient saslClient = clientFactory.createSaslClient(mechanisms,
            "cn=test client 1,ou=jboss,o=red hat,l=raleigh,st=north carolina,c=us", "test",
            "testserver1.example.com", Collections.<String, Object>emptyMap(), cbh);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslClient.evaluateChallenge(message);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslServer.evaluateResponse(message);
    assertTrue(saslServer.isComplete());
    assertNull(message);
    assertNull(saslClient.evaluateChallenge(message));
    assertTrue(saslClient.isComplete());
    assertEquals("cn=test client 1,ou=jboss,o=red hat,l=raleigh,st=north carolina,c=us",
            saslServer.getAuthorizationID());
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testSimpleMutualSha1WithRsaAuthentication() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);//from   w  w  w .  j  a  va 2s . co  m

    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC,
            "testserver1.example.com", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), serverTrustStore);

    final String[] mechanisms = new String[] { SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC };
    CallbackHandler cbh = createClientCallbackHandler(mechanisms, clientKeyStore, CLIENT_KEYSTORE_ALIAS,
            KEYSTORE_PASSWORD, getX509TrustManager(clientTrustStore));
    final SaslClient saslClient = clientFactory.createSaslClient(mechanisms, null, "test",
            "testserver1.example.com", Collections.<String, Object>emptyMap(), cbh);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslClient.evaluateChallenge(message);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslServer.evaluateResponse(message);
    assertNotNull(message);
    message = saslClient.evaluateChallenge(message);
    assertNull(message);
    assertTrue(saslClient.isComplete());
    assertTrue(saslServer.isComplete());
    assertEquals("cn=test client 1,ou=jboss,o=red hat,l=raleigh,st=north carolina,c=us",
            saslServer.getAuthorizationID());
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testMutualAuthenticationWithDNSInCNField() throws Exception {
    // Although specifying a DNS name using the Common Name field has been deprecated, it is
    // still used in practice (e.g., see http://tools.ietf.org/html/rfc2818). This test makes
    // sure that general name matching during authentication still works in this case.
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);//from   ww  w  .ja  v a2 s .  c o  m

    final KeyStore keyStore = loadKeyStore(serverKeyStore);
    final Certificate[] certificateChain = keyStore.getCertificateChain("dnsInCNServer");
    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_M_DSA_SHA1,
            "testserver2.example.com", serverTrustStore,
            (PrivateKey) keyStore.getKey("dnsInCNServer", KEYSTORE_PASSWORD),
            Arrays.copyOf(certificateChain, certificateChain.length, X509Certificate[].class));

    final String[] mechanisms = new String[] { SaslMechanismInformation.Names.IEC_ISO_9798_M_DSA_SHA1 };
    CallbackHandler cbh = createClientCallbackHandler(mechanisms, clientKeyStore, "dnsInCNClient",
            KEYSTORE_PASSWORD, getX509TrustManager(clientTrustStore));
    final SaslClient saslClient = clientFactory.createSaslClient(mechanisms, null, "test",
            "testserver2.example.com", Collections.<String, Object>emptyMap(), cbh);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslClient.evaluateChallenge(message);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslServer.evaluateResponse(message);
    assertNotNull(message);

    message = saslClient.evaluateChallenge(message);
    assertNull(message);
    assertTrue(saslClient.isComplete());
    assertTrue(saslServer.isComplete());
    assertEquals("cn=testclient2.example.com,ou=jboss,o=red hat,l=raleigh,st=north carolina,c=us",
            saslServer.getAuthorizationID());
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testServerNameMismatch() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);//  w ww .  ja v a 2 s  . co  m

    // The server name specified by the client doesn't match the server's actual name
    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC,
            "testserver1.example.com", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), serverTrustStore);

    final String[] mechanisms = new String[] { SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC };
    CallbackHandler cbh = createClientCallbackHandler(mechanisms, clientKeyStore, CLIENT_KEYSTORE_ALIAS,
            KEYSTORE_PASSWORD, getX509TrustManager(clientTrustStore));
    final SaslClient saslClient = clientFactory.createSaslClient(mechanisms, null, "test",
            "anotherserver.example.com", Collections.<String, Object>emptyMap(), cbh);

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    try {
        saslClient.evaluateChallenge(message);
        fail("Expected SaslException not thrown");
    } catch (SaslException expected) {
    }
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testClientNotTrustedByServer() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);/*from w  w w .  j  av  a2s .c o  m*/

    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC,
            "testserver1.example.com", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), (KeyStore) null);

    final String[] mechanisms = new String[] { SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC };
    CallbackHandler cbh = createClientCallbackHandler(mechanisms, clientKeyStore, CLIENT_KEYSTORE_ALIAS,
            KEYSTORE_PASSWORD, getX509TrustManager(clientTrustStore));
    final SaslClient saslClient = clientFactory.createSaslClient(mechanisms, null, "test",
            "testserver1.example.com", Collections.<String, Object>emptyMap(), cbh);

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    message = saslClient.evaluateChallenge(message);
    try {
        saslServer.evaluateResponse(message);
        fail("Expected SaslException not thrown");
    } catch (SaslException expected) {
    }
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testServerNotTrustedByClient() throws Exception {
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);/*from  w  w  w .  j  av  a2 s.c o  m*/

    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC,
            "testserver1.example.com", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), serverTrustStore);

    final String[] mechanisms = new String[] { SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC };
    CallbackHandler cbh = createClientCallbackHandler(mechanisms, clientKeyStore, CLIENT_KEYSTORE_ALIAS,
            KEYSTORE_PASSWORD, null);
    final SaslClient saslClient = clientFactory.createSaslClient(mechanisms, null, "test",
            "testserver1.example.com", Collections.<String, Object>emptyMap(), cbh);

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    message = saslClient.evaluateChallenge(message);
    message = saslServer.evaluateResponse(message);
    try {
        saslClient.evaluateChallenge(message);
        fail("Expected SaslException not thrown");
    } catch (SaslException expected) {
    }
}