@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); 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", getX509TrustManager(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()); }
@Test public void testSimpleMutualSha1WithRsaAuthentication() throws Exception { final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class); assertNotNull(clientFactory); final SaslServer saslServer = createSaslServer( SaslMechanismInformation.Names.IEC_ISO_9798_M_RSA_SHA1_ENC, "testserver1.example.com", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), getX509TrustManager(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()); }
void receiveAuthResponse(final int id, final byte[] response) { log.tracef("Received authentication response for ID %08x", id); if (id == 0 || id == 1) { // ignore return; } getExecutor() .execute( () -> { Auth auth = authMap.get(id); if (auth == null) { auth = authMap.putIfAbsent(new Auth(id, new RejectingSaslServer())); if (auth == null) { // reject try { connectionHandler.sendAuthReject(id); } catch (IOException e1) { log.trace("Failed to send auth reject", e1); } return; } } final SaslServer saslServer = auth.getSaslServer(); final byte[] challenge; try { challenge = saslServer.evaluateResponse(response); } catch (SaslException e) { try { connectionHandler.sendAuthReject(id); } catch (IOException e1) { authMap.remove(auth); auth.dispose(); log.trace("Failed to send auth reject", e1); } return; } if (saslServer.isComplete()) { try { connectionHandler.sendAuthSuccess(id, challenge); } catch (IOException e) { authMap.remove(auth); auth.dispose(); log.trace("Failed to send auth success", e); } return; } else { try { connectionHandler.sendAuthChallenge(id, challenge); } catch (IOException e) { authMap.remove(auth); auth.dispose(); log.trace("Failed to send auth challenge", e); } return; } }); }
@Override public boolean needsWrapping() { if (server.isComplete()) { String qop = (String) server.getNegotiatedProperty(Sasl.QOP); return (qop != null && (qop.equalsIgnoreCase("auth-int") || qop.equalsIgnoreCase("auth-conf"))); } else { return false; } }
@Override public Message nextMessage(Address address, SaslHeader header) throws SaslException { Message message = new Message(address).setFlag(Message.Flag.OOB); byte[] challenge = server.evaluateResponse(header.getPayload()); if (server.isComplete()) { latch.countDown(); } if (challenge != null) { return message.putHeader(SASL.SASL_ID, new SaslHeader(Type.RESPONSE, challenge)); } else { return null; } }
@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); final SaslServer saslServer = createSaslServer( SaslMechanismInformation.Names.IEC_ISO_9798_U_RSA_SHA1_ENC, "", getX509KeyManager(serverKeyStore, KEYSTORE_PASSWORD), getX509TrustManager(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()); }
public void receiveSaslInit(final SaslInit saslInit) { Symbol mechanism = saslInit.getMechanism(); final Binary initialResponse = saslInit.getInitialResponse(); byte[] response = initialResponse == null ? new byte[0] : initialResponse.getArray(); try { _saslServer = _saslServerProvider.getSaslServer(mechanism.toString(), "localhost"); // Process response from the client byte[] challenge = _saslServer.evaluateResponse(response != null ? response : new byte[0]); if (_saslServer.isComplete()) { SaslOutcome outcome = new SaslOutcome(); outcome.setCode(SaslCode.OK); _saslFrameOutput.send(new SASLFrame(outcome), null); synchronized (getLock()) { _saslComplete = true; _authenticated = true; getLock().notifyAll(); } if (_onSaslCompleteTask != null) { _onSaslCompleteTask.run(); } } else { SaslChallenge challengeBody = new SaslChallenge(); challengeBody.setChallenge(new Binary(challenge)); _saslFrameOutput.send(new SASLFrame(challengeBody), null); } } catch (SaslException e) { SaslOutcome outcome = new SaslOutcome(); outcome.setCode(SaslCode.AUTH); _saslFrameOutput.send(new SASLFrame(outcome), null); synchronized (getLock()) { _saslComplete = true; _authenticated = false; getLock().notifyAll(); } if (_onSaslCompleteTask != null) { _onSaslCompleteTask.run(); } } }
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); } }
private boolean saslAuth(final Map<String, Object> props) throws AuthorizationException { try { SaslServer ss = (SaslServer) props.get("SaslServer"); if (ss == null) { Map<String, String> sasl_props = new TreeMap<String, String>(); sasl_props.put(Sasl.QOP, "auth"); ss = Sasl.createSaslServer( (String) props.get(MACHANISM_KEY), "xmpp", (String) props.get(SERVER_NAME_KEY), sasl_props, new SaslCallbackHandler(props)); props.put("SaslServer", ss); } // end of if (ss == null) String data_str = (String) props.get(DATA_KEY); byte[] in_data = ((data_str != null) ? Base64.decode(data_str) : new byte[0]); if (log.isLoggable(Level.FINEST)) { log.finest("response: " + new String(in_data)); } byte[] challenge = ss.evaluateResponse(in_data); if (log.isLoggable(Level.FINEST)) { log.finest("challenge: " + ((challenge != null) ? new String(challenge) : "null")); } String challenge_str = (((challenge != null) && (challenge.length > 0)) ? Base64.encode(challenge) : null); props.put(RESULT_KEY, challenge_str); if (ss.isComplete()) { return true; } else { return false; } // end of if (ss.isComplete()) else } catch (SaslException e) { throw new AuthorizationException("Sasl exception.", e); } // end of try-catch }
public void receiveSaslResponse(final SaslResponse saslResponse) { final Binary responseBinary = saslResponse.getResponse(); byte[] response = responseBinary == null ? new byte[0] : responseBinary.getArray(); try { // Process response from the client byte[] challenge = _saslServer.evaluateResponse(response != null ? response : new byte[0]); if (_saslServer.isComplete()) { SaslOutcome outcome = new SaslOutcome(); outcome.setCode(SaslCode.OK); _saslFrameOutput.send(new SASLFrame(outcome), null); synchronized (getLock()) { _saslComplete = true; _authenticated = true; getLock().notifyAll(); } if (_onSaslCompleteTask != null) { _onSaslCompleteTask.run(); } } else { SaslChallenge challengeBody = new SaslChallenge(); challengeBody.setChallenge(new Binary(challenge)); _saslFrameOutput.send(new SASLFrame(challengeBody), null); } } catch (SaslException e) { SaslOutcome outcome = new SaslOutcome(); outcome.setCode(SaslCode.AUTH); _saslFrameOutput.send(new SASLFrame(outcome), null); synchronized (getLock()) { _saslComplete = true; _authenticated = false; getLock().notifyAll(); } if (_onSaslCompleteTask != null) { _onSaslCompleteTask.run(); } } }
public boolean isComplete() { return saslServer.isComplete(); }
public static void main(String[] args) throws Exception { try { Sasl.createSaslClient( new String[] {"NTLM"}, "abc", "ldap", "server", new HashMap<String, Object>(), null); } catch (SaslException se) { System.out.println(se); } try { Sasl.createSaslServer("NTLM", "ldap", "server", new HashMap<String, Object>(), null); } catch (SaslException se) { System.out.println(se); } try { Sasl.createSaslClient( new String[] {"NTLM"}, "abc", "ldap", "server", null, new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {} }); } catch (SaslException se) { System.out.println(se); } try { SaslServer saslServer = Sasl.createSaslServer( "NTLM", "ldap", "abc", null, new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {} }); System.err.println("saslServer = " + saslServer); System.err.println("saslServer.isComplete() = " + saslServer.isComplete()); // IllegalStateException is expected here saslServer.getNegotiatedProperty("prop"); System.err.println("No IllegalStateException"); } catch (IllegalStateException se) { System.out.println(se); } try { SaslServer saslServer = Sasl.createSaslServer( "NTLM", "ldap", "abc", null, new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {} }); System.err.println("saslServer = " + saslServer); System.err.println("saslServer.isComplete() = " + saslServer.isComplete()); // IllegalStateException is expected here saslServer.getAuthorizationID(); System.err.println("No IllegalStateException"); } catch (IllegalStateException se) { System.out.println(se); } try { SaslServer saslServer = Sasl.createSaslServer( "NTLM", "ldap", "abc", null, new CallbackHandler() { @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {} }); System.err.println("saslServer = " + saslServer); System.err.println("saslServer.isComplete() = " + saslServer.isComplete()); // IllegalStateException is expected here saslServer.wrap(new byte[0], 0, 0); System.err.println("No IllegalStateException"); } catch (IllegalStateException se) { System.out.println(se); } }
public void receiveAuthRequest( final int id, final String mechName, final byte[] initialResponse) { log.tracef("Received authentication request for ID %08x, mech %s", id, mechName); if (id == 0 || id == 1) { // ignore return; } getExecutor() .execute( () -> { final SaslServer saslServer; final IntIndexHashMap<Auth> authMap = this.authMap; try { saslServer = authenticationFactory.createMechanism( mechName, f -> new ServerNameSaslServerFactory(f, endpoint.getName())); } catch (SaslException e) { log.trace("Authentication failed at mechanism creation", e); try { Auth oldAuth = authMap.put(new Auth(id, new RejectingSaslServer())); if (oldAuth != null) oldAuth.dispose(); connectionHandler.sendAuthReject(id); } catch (IOException e1) { log.trace("Failed to send auth reject", e1); } return; } // clear out any old auth final Auth auth = new Auth(id, saslServer); Auth oldAuth = authMap.put(auth); if (oldAuth != null) oldAuth.dispose(); final byte[] challenge; try { challenge = saslServer.evaluateResponse(initialResponse); } catch (SaslException e) { log.trace("Authentication failed at response evaluation", e); try { connectionHandler.sendAuthReject(id); } catch (IOException e1) { authMap.remove(auth); auth.dispose(); log.trace("Failed to send auth reject", e1); } return; } if (saslServer.isComplete()) { try { connectionHandler.sendAuthSuccess(id, challenge); } catch (IOException e) { authMap.remove(auth); auth.dispose(); log.trace("Failed to send auth success", e); } return; } else { try { connectionHandler.sendAuthChallenge(id, challenge); } catch (IOException e) { authMap.remove(auth); auth.dispose(); log.trace("Failed to send auth challenge", e); } return; } }); }
public static void main(String[] args) throws Exception { if (args.length == 0) { namesfile = null; auto = true; } else { int i = 0; if (args[i].equals("-m")) { i++; auto = false; } if (args.length > i) { namesfile = args[i++]; if (args.length > i) { proxyfile = args[i]; } } else { namesfile = null; } } CallbackHandler clntCbh = null; final CallbackHandler srvCbh = new PropertiesFileCallbackHandler(null, namesfile, proxyfile); Subject clntSubj = doLogin("client"); Subject srvSubj = doLogin("server"); final HashMap clntprops = new HashMap(); final HashMap srvprops = new HashMap(); clntprops.put(Sasl.QOP, "auth"); srvprops.put(Sasl.QOP, "auth,auth-int,auth-conf"); final SaslClient clnt = (SaslClient) Subject.doAs( clntSubj, new PrivilegedExceptionAction() { public Object run() throws Exception { return Sasl.createSaslClient( new String[] {MECH}, null, PROTOCOL, SERVER_FQDN, clntprops, null); } }); if (verbose) { System.out.println(clntSubj); System.out.println(srvSubj); } final SaslServer srv = (SaslServer) Subject.doAs( srvSubj, new PrivilegedExceptionAction() { public Object run() throws Exception { return Sasl.createSaslServer(MECH, PROTOCOL, SERVER_FQDN, srvprops, 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; byte[] challenge; response = (byte[]) Subject.doAs( clntSubj, new PrivilegedExceptionAction() { public Object run() throws Exception { return (clnt.hasInitialResponse() ? clnt.evaluateChallenge(EMPTY) : EMPTY); } }); while (!clnt.isComplete() || !srv.isComplete()) { final byte[] responseCopy = response; challenge = (byte[]) Subject.doAs( srvSubj, new PrivilegedExceptionAction() { public Object run() throws Exception { return srv.evaluateResponse(responseCopy); } }); if (challenge != null) { final byte[] challengeCopy = challenge; response = (byte[]) Subject.doAs( clntSubj, new PrivilegedExceptionAction() { public Object run() throws Exception { return clnt.evaluateChallenge(challengeCopy); } }); } } 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()); } if (verbose) { System.out.println(clnt.getNegotiatedProperty(Sasl.QOP)); } // Now try to use security layer byte[] clntBuf = new byte[] {0, 1, 2, 3}; try { byte[] wrapped = clnt.wrap(clntBuf, 0, clntBuf.length); throw new Exception("clnt wrap should not be allowed w/no security layer"); } catch (IllegalStateException e) { // expected } byte[] srvBuf = new byte[] {10, 11, 12, 13}; try { byte[] wrapped = srv.wrap(srvBuf, 0, srvBuf.length); throw new Exception("srv wrap should not be allowed w/no security layer"); } catch (IllegalStateException e) { // expected } try { byte[] unwrapped = clnt.unwrap(clntBuf, 0, clntBuf.length); throw new Exception("clnt wrap should not be allowed w/no security layer"); } catch (IllegalStateException e) { // expected } try { byte[] unwrapped = srv.unwrap(srvBuf, 0, srvBuf.length); throw new Exception("srv wrap should not be allowed w/no security layer"); } catch (IllegalStateException e) { // expected } }
@Override public boolean isSuccessful() { return server.isComplete(); }