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

The following examples show how to use javax.security.sasl.SaslServer#evaluateResponse() . 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: TestSaslRPC.java    From big-c with Apache License 2.0 6 votes vote down vote up
private void runNegotiation(CallbackHandler clientCbh,
                            CallbackHandler serverCbh)
                                throws SaslException {
  String mechanism = AuthMethod.PLAIN.getMechanismName();

  SaslClient saslClient = Sasl.createSaslClient(
      new String[]{ mechanism }, null, null, null, null, clientCbh);
  assertNotNull(saslClient);

  SaslServer saslServer = Sasl.createSaslServer(
      mechanism, null, "localhost", null, serverCbh);
  assertNotNull("failed to find PLAIN server", saslServer);
  
  byte[] response = saslClient.evaluateChallenge(new byte[0]);
  assertNotNull(response);
  assertTrue(saslClient.isComplete());

  response = saslServer.evaluateResponse(response);
  assertNull(response);
  assertTrue(saslServer.isComplete());
  assertNotNull(saslServer.getAuthorizationID());
}
 
Example 2
Source File: ClientServerTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example 3
Source File: ClientServerTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example 4
Source File: ClientServerTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example 5
Source File: SaslTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void testSaslServerClient(SaslServer server, SaslClient client) throws SaslException {
    byte[] message = new byte[]{};
    if (client.hasInitialResponse()) message = client.evaluateChallenge(message);
    while(!server.isComplete() || !client.isComplete()) {
        if (!server.isComplete()) message = server.evaluateResponse(message);
        if (!client.isComplete()) message = client.evaluateChallenge(message);
    }
}
 
Example 6
Source File: ClientServerTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example 7
Source File: ClientServerTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example 8
Source File: ClientServerTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private byte[] processData(byte[] data, SaslEndpoint endpoint,
        SaslServer server) throws SaslException, IOException {
    try {
        return server.evaluateResponse(data);
    } catch (SaslException e) {
        endpoint.send(new Message(SaslStatus.FAILURE, null));
        System.out.println("Error while processing data");
        throw e;
    }
}
 
Example 9
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 10
Source File: NoQuoteParams.java    From dragonwell8_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 11
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 12
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 13
Source File: NoQuoteParams.java    From hottub 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 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 15
Source File: SaslGSS.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 {

        String name = "host." + OneKDC.REALM.toLowerCase(Locale.US);

        new OneKDC(null).writeJAASConf();
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

        // Client in JGSS so that it can control wrap privacy mode
        GSSManager m = GSSManager.getInstance();
        GSSContext sc = m.createContext(
                        m.createName(OneKDC.SERVER, GSSUtil.NT_GSS_KRB5_PRINCIPAL),
                        GSSUtil.GSS_KRB5_MECH_OID,
                        null,
                        GSSContext.DEFAULT_LIFETIME);
        sc.requestMutualAuth(false);

        // Server in SASL
        final HashMap props = new HashMap();
        props.put(Sasl.QOP, "auth-conf");
        SaslServer ss = Sasl.createSaslServer("GSSAPI", "server",
                name, props,
                new CallbackHandler() {
                    public void handle(Callback[] callbacks)
                            throws IOException, UnsupportedCallbackException {
                        for (Callback cb : callbacks) {
                            if (cb instanceof RealmCallback) {
                                ((RealmCallback) cb).setText(OneKDC.REALM);
                            } else if (cb instanceof AuthorizeCallback) {
                                ((AuthorizeCallback) cb).setAuthorized(true);
                            }
                        }
                    }
                });

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        PrintStream oldErr = System.err;
        System.setErr(new PrintStream(bout));

        Logger.getLogger("javax.security.sasl").setLevel(Level.ALL);
        Handler h = new ConsoleHandler();
        h.setLevel(Level.ALL);
        Logger.getLogger("javax.security.sasl").addHandler(h);

        byte[] token = new byte[0];

        try {
            // Handshake
            token = sc.initSecContext(token, 0, token.length);
            token = ss.evaluateResponse(token);
            token = sc.unwrap(token, 0, token.length, new MessageProp(0, false));
            token[0] = (byte)(((token[0] & 4) != 0) ? 4 : 2);
            token = sc.wrap(token, 0, token.length, new MessageProp(0, false));
            ss.evaluateResponse(token);
        } finally {
            System.setErr(oldErr);
        }

        // Talk
        // 1. Client sends a auth-int message
        byte[] hello = "hello".getBytes();
        MessageProp qop = new MessageProp(0, false);
        token = sc.wrap(hello, 0, hello.length, qop);
        // 2. Server accepts it anyway
        ss.unwrap(token, 0, token.length);
        // 3. Server sends a message
        token = ss.wrap(hello, 0, hello.length);
        // 4. Client accepts, should be auth-conf
        sc.unwrap(token, 0, token.length, qop);
        if (!qop.getPrivacy()) {
            throw new Exception();
        }

        for (String s: bout.toString().split("\\n")) {
            if (s.contains("KRB5SRV04") && s.contains("NULL")) {
                return;
            }
        }
        System.out.println("=======================");
        System.out.println(bout.toString());
        System.out.println("=======================");
        throw new Exception("Haven't seen KRB5SRV04 with NULL");
    }
 
Example 16
Source File: SecurityRealmServiceUtilTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Test
public void testSaslAuthenticationFactoryDigest() throws Exception {
    registerElytronProviders();
    try {
        File propsFile = createPropertyFile(TESTNAME + "-users.properties", "user1", "password1");
        ServiceTarget serviceTarget = container.subTarget();
        final Supplier<String> tmpDirSupplier = () -> tmpDir.toAbsolutePath().toString();

        // register a realm service with a properties file to perform a SASL DIGEST-MD5 login
        final ServiceName realmServiceName = SecurityRealm.ServiceUtil.createServiceName(TESTNAME);
        final ServiceBuilder<?> realmBuilder = serviceTarget.addService(realmServiceName);
        final Consumer<SecurityRealm> securityRealmConsumer = realmBuilder.provides(realmServiceName, SecurityRealm.ServiceUtil.createLegacyServiceName(TESTNAME));
        // create the properties service to check username/password
        final ServiceName propsServiceName = PropertiesCallbackHandler.ServiceUtil.createServiceName("PropertiesRealm");
        final ServiceBuilder<?> propsBuilder = serviceTarget.addService(propsServiceName);
        final Consumer<CallbackHandlerService> chsConsumer = propsBuilder.provides(propsServiceName);
        propsBuilder.setInstance(new PropertiesCallbackHandler(chsConsumer, null, TESTNAME, propsFile.getAbsolutePath(), null, true));
        propsBuilder.setInitialMode(ServiceController.Mode.ON_DEMAND);
        propsBuilder.install();
        final SecurityRealmService securityRealmService = new SecurityRealmService(
                securityRealmConsumer, null, null, null, null, tmpDirSupplier,
                Collections.singleton(CallbackHandlerService.ServiceUtil.requires(realmBuilder, propsServiceName)),
                TESTNAME, false);
        realmBuilder.setInstance(securityRealmService);
        realmBuilder.install();

        // wait for server stability
        container.awaitStability(60, TimeUnit.SECONDS);

        // get the sasl factory for DIGEST-MD5 and create the sasl server with it
        SaslAuthenticationFactory saslAuthFact = securityRealmService.getSaslAuthenticationFactory(new String[]{"DIGEST-MD5"}, true);
        Assert.assertNotNull("Server Sasl Factory is not null", saslAuthFact);
        SaslServer server = saslAuthFact.createMechanism("DIGEST-MD5");

        // now create a sasl client and perform the sasl dance
        final AuthenticationConfiguration authConfig = AuthenticationConfiguration.empty()
                        .useName("user1")
                        .usePassword("password1")
                        .useRealm(TESTNAME)
                        .setSaslMechanismSelector(SaslMechanismSelector.NONE.addMechanism(SaslMechanismInformation.Names.DIGEST_MD5));
        AuthenticationContextConfigurationClient contextConfigurationClient = AccessController.doPrivileged(AuthenticationContextConfigurationClient.ACTION);
        SaslClient client = contextConfigurationClient.createSaslClient(new URI("unknown://server"), authConfig, Collections.singletonList("DIGEST-MD5"));
        Assert.assertNotNull("Sasl client is not null", client);
        Assert.assertFalse("Sasl client has no initial response", client.hasInitialResponse());
        byte[] message = server.evaluateResponse(new byte[0]);
        message = client.evaluateChallenge(message);
        server.evaluateResponse(message);
        Assert.assertTrue("Sasl server is complete", server.isComplete());
        Assert.assertEquals("Correct user is logged in", "user1", server.getAuthorizationID());
    } finally {
        removeElytronProviders();
    }
}
 
Example 17
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 18
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 19
Source File: SaslGSS.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        String name = "host." + OneKDC.REALM.toLowerCase(Locale.US);

        new OneKDC(null).writeJAASConf();
        System.setProperty("javax.security.auth.useSubjectCredsOnly", "false");

        // Client in JGSS so that it can control wrap privacy mode
        GSSManager m = GSSManager.getInstance();
        GSSContext sc = m.createContext(
                        m.createName(OneKDC.SERVER, GSSUtil.NT_GSS_KRB5_PRINCIPAL),
                        GSSUtil.GSS_KRB5_MECH_OID,
                        null,
                        GSSContext.DEFAULT_LIFETIME);
        sc.requestMutualAuth(false);

        // Server in SASL
        final HashMap props = new HashMap();
        props.put(Sasl.QOP, "auth-conf");
        SaslServer ss = Sasl.createSaslServer("GSSAPI", "server",
                name, props,
                new CallbackHandler() {
                    public void handle(Callback[] callbacks)
                            throws IOException, UnsupportedCallbackException {
                        for (Callback cb : callbacks) {
                            if (cb instanceof RealmCallback) {
                                ((RealmCallback) cb).setText(OneKDC.REALM);
                            } else if (cb instanceof AuthorizeCallback) {
                                ((AuthorizeCallback) cb).setAuthorized(true);
                            }
                        }
                    }
                });

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        PrintStream oldErr = System.err;
        System.setErr(new PrintStream(bout));

        Logger.getLogger("javax.security.sasl").setLevel(Level.ALL);
        Handler h = new ConsoleHandler();
        h.setLevel(Level.ALL);
        Logger.getLogger("javax.security.sasl").addHandler(h);

        byte[] token = new byte[0];

        try {
            // Handshake
            token = sc.initSecContext(token, 0, token.length);
            token = ss.evaluateResponse(token);
            token = sc.unwrap(token, 0, token.length, new MessageProp(0, false));
            token[0] = (byte)(((token[0] & 4) != 0) ? 4 : 2);
            token = sc.wrap(token, 0, token.length, new MessageProp(0, false));
            ss.evaluateResponse(token);
        } finally {
            System.setErr(oldErr);
        }

        // Talk
        // 1. Client sends a auth-int message
        byte[] hello = "hello".getBytes();
        MessageProp qop = new MessageProp(0, false);
        token = sc.wrap(hello, 0, hello.length, qop);
        // 2. Server accepts it anyway
        ss.unwrap(token, 0, token.length);
        // 3. Server sends a message
        token = ss.wrap(hello, 0, hello.length);
        // 4. Client accepts, should be auth-conf
        sc.unwrap(token, 0, token.length, qop);
        if (!qop.getPrivacy()) {
            throw new Exception();
        }

        for (String s: bout.toString().split("\\n")) {
            if (s.contains("KRB5SRV04") && s.contains("NULL")) {
                return;
            }
        }
        System.out.println("=======================");
        System.out.println(bout.toString());
        System.out.println("=======================");
        throw new Exception("Haven't seen KRB5SRV04 with NULL");
    }
 
Example 20
Source File: NoQuoteParams.java    From TencentKona-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();
    }