Example usage for javax.security.sasl SaslServer isComplete

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

Introduction

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

Prototype

public abstract boolean isComplete();

Source Link

Document

Determines whether the authentication exchange has completed.

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// ww  w  .  j  a  va 2 s .c  o  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 w w  . j  a va2 s . c  o  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);/*ww  w.jav  a  2 s .  c om*/

    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);// w w  w  .  ja va 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  a2  s .  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);/*  w w  w. j  a  v a  2s  .  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, 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   w w w.j a va2  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 testRfc3163Example() throws Exception {
    // This test uses the example from page 10 in RFC 3163 (https://tools.ietf.org/html/rfc3163#section-5)
    mockRandom(new byte[] { 18, 56, -105, 88, 121, -121, 71, -104 });

    KeyStore emptyTrustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    emptyTrustStore.load(null, null);/*  www. j  a v a2 s  . c  o  m*/
    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC,
            "", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), emptyTrustStore);
    assertNotNull(saslServer);
    assertFalse(saslServer.isComplete());

    byte[] tokenBA1 = saslServer.evaluateResponse(new byte[0]);
    byte[] expectedTokenBA1 = CodePointIterator.ofString("MAoECBI4l1h5h0eY").base64Decode().drain();
    assertArrayEquals(expectedTokenBA1, tokenBA1);
    assertFalse(saslServer.isComplete());

    byte[] tokenAB = CodePointIterator.ofString(
            "MIIBAgQIIxh5I0h5RYegD4INc2FzbC1yLXVzLmNvbaFPFk1odHRwOi8vY2VydHMtci11cy5jb20vY2VydD9paD1odmNOQVFFRkJRQURnWUVBZ2hBR2hZVFJna0ZqJnNuPUVQOXVFbFkzS0RlZ2pscjCBkzANBgkqhkiG9w0BAQUFAAOBgQCkuC2GgtYcxGG1NEzLA4bh5lqJGOZySACMmc+mDrV7A7KAgbpO2OuZpMCl7zvNt/L3OjQZatiX8d1XbuQ40l+g2TJzJt06o7ogomxdDwqlA/3zp2WMohlI0MotHmfDSWEDZmEYDEA3/eGgkWyi1v1lEVdFuYmrTr8E4wE9hxdQrA==")
            .base64Decode().drain();
    try {
        saslServer.evaluateResponse(tokenAB);
        fail("Expected SaslException not thrown");
    } catch (SaslException expected) {
        // The example specifies the client's certificate using a fake URL (http://certs-r-us.com/cert?ih=hvcNAQEFBQADgYEAghAGhYTRgkFj&sn=EP9uElY3KDegjlr)
        // so we can actually make use of it.
        assertTrue(expected.getCause().getMessage().contains("certificate"));
    }
    assertFalse(saslServer.isComplete());
}

From source file:org.wso2.andes.server.security.auth.manager.PrincipalDatabaseAuthenticationManager.java

/**
 * @see org.wso2.andes.server.security.auth.manager.AuthenticationManager#authenticate(SaslServer, byte[])
 *//*from  w  w  w .j  av  a2 s  .  c  o  m*/
public AuthenticationResult authenticate(SaslServer server, byte[] response) {
    try {
        // Process response from the client
        byte[] challenge = server.evaluateResponse(response != null ? response : new byte[0]);

        if (server.isComplete()) {
            final Subject subject = new Subject();
            subject.getPrincipals().add(new UsernamePrincipal(server.getAuthorizationID()));
            return new AuthenticationResult(subject);
        } else {
            return new AuthenticationResult(challenge, AuthenticationResult.AuthenticationStatus.CONTINUE);
        }
    } catch (SaslException e) {
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    }
}