use of javax.security.sasl.SaslException in project Openfire by igniterealtime.
the class ScramSha1SaslServer method generateServerFinalMessage.
/**
* Final response returns the server signature.
*/
private byte[] generateServerFinalMessage(final byte[] response) throws SaslException {
String clientFinalMessage = new String(response, StandardCharsets.UTF_8);
Matcher m = CLIENT_FINAL_MESSAGE.matcher(clientFinalMessage);
if (!m.matches()) {
throw new SaslException("Invalid client final message");
}
String clientFinalMessageWithoutProof = m.group(1);
// String channelBinding = m.group(2);
String clientNonce = m.group(3);
String proof = m.group(4);
if (!nonce.equals(clientNonce)) {
throw new SaslException("Client final message has incorrect nonce value");
}
try {
String authMessage = clientFirstMessageBare + "," + serverFirstMessage + "," + clientFinalMessageWithoutProof;
byte[] storedKey = getStoredKey(username);
if (storedKey == null) {
throw new SaslException("No stored key for user '" + username + "'");
}
byte[] serverKey = getServerKey(username);
if (serverKey == null) {
throw new SaslException("No server key for user '" + username + "'");
}
byte[] clientSignature = ScramUtils.computeHmac(storedKey, authMessage);
byte[] serverSignature = ScramUtils.computeHmac(serverKey, authMessage);
byte[] clientKey = clientSignature.clone();
byte[] decodedProof = DatatypeConverter.parseBase64Binary(proof);
for (int i = 0; i < clientKey.length; i++) {
clientKey[i] ^= decodedProof[i];
}
if (!Arrays.equals(storedKey, MessageDigest.getInstance("SHA-1").digest(clientKey))) {
throw new SaslException("Authentication failed");
}
return ("v=" + DatatypeConverter.printBase64Binary(serverSignature)).getBytes(StandardCharsets.UTF_8);
} catch (UserNotFoundException | NoSuchAlgorithmException e) {
throw new SaslException(e.getMessage(), e);
}
}
use of javax.security.sasl.SaslException in project Openfire by igniterealtime.
the class ScramSha1SaslServer method generateServerFirstMessage.
/**
* First response returns:
* - the nonce (client nonce appended with our own random UUID)
* - the salt
* - the number of iterations
*/
private byte[] generateServerFirstMessage(final byte[] response) throws SaslException {
String clientFirstMessage = new String(response, StandardCharsets.UTF_8);
Matcher m = CLIENT_FIRST_MESSAGE.matcher(clientFirstMessage);
if (!m.matches()) {
throw new SaslException("Invalid first client message");
}
// String gs2Header = m.group(1);
// String gs2CbindFlag = m.group(2);
// String gs2CbindName = m.group(3);
// String authzId = m.group(4);
clientFirstMessageBare = m.group(5);
username = m.group(6);
String clientNonce = m.group(7);
nonce = clientNonce + UUID.randomUUID().toString();
try {
serverFirstMessage = String.format("r=%s,s=%s,i=%d", nonce, DatatypeConverter.printBase64Binary(getSalt(username)), getIterations(username));
} catch (UserNotFoundException e) {
throw new SaslException(e.getMessage(), e);
}
return serverFirstMessage.getBytes(StandardCharsets.UTF_8);
}
use of javax.security.sasl.SaslException in project zookeeper by apache.
the class ZooKeeperSaslServer method createSaslServer.
private SaslServer createSaslServer(final Login login) {
synchronized (login) {
Subject subject = login.getSubject();
if (subject != null) {
// server is using a JAAS-authenticated subject: determine service principal name and hostname from zk server's subject.
if (subject.getPrincipals().size() > 0) {
try {
final Object[] principals = subject.getPrincipals().toArray();
final Principal servicePrincipal = (Principal) principals[0];
// e.g. servicePrincipalNameAndHostname := "zookeeper/myhost.foo.com@FOO.COM"
final String servicePrincipalNameAndHostname = servicePrincipal.getName();
int indexOf = servicePrincipalNameAndHostname.indexOf("/");
// e.g. serviceHostnameAndKerbDomain := "myhost.foo.com@FOO.COM"
final String serviceHostnameAndKerbDomain = servicePrincipalNameAndHostname.substring(indexOf + 1, servicePrincipalNameAndHostname.length());
int indexOfAt = serviceHostnameAndKerbDomain.indexOf("@");
// Handle Kerberos Service as well as User Principal Names
final String servicePrincipalName, serviceHostname;
if (indexOf > 0) {
// e.g. servicePrincipalName := "zookeeper"
servicePrincipalName = servicePrincipalNameAndHostname.substring(0, indexOf);
// e.g. serviceHostname := "myhost.foo.com"
serviceHostname = serviceHostnameAndKerbDomain.substring(0, indexOfAt);
} else {
servicePrincipalName = servicePrincipalNameAndHostname.substring(0, indexOfAt);
serviceHostname = null;
}
// TODO: should depend on zoo.cfg specified mechs, but if subject is non-null, it can be assumed to be GSSAPI.
final String mech = "GSSAPI";
LOG.debug("serviceHostname is '" + serviceHostname + "'");
LOG.debug("servicePrincipalName is '" + servicePrincipalName + "'");
LOG.debug("SASL mechanism(mech) is '" + mech + "'");
boolean usingNativeJgss = Boolean.getBoolean("sun.security.jgss.native");
if (usingNativeJgss) {
// """
try {
GSSManager manager = GSSManager.getInstance();
Oid krb5Mechanism = new Oid("1.2.840.113554.1.2.2");
GSSName gssName = manager.createName(servicePrincipalName + "@" + serviceHostname, GSSName.NT_HOSTBASED_SERVICE);
GSSCredential cred = manager.createCredential(gssName, GSSContext.DEFAULT_LIFETIME, krb5Mechanism, GSSCredential.ACCEPT_ONLY);
subject.getPrivateCredentials().add(cred);
if (LOG.isDebugEnabled()) {
LOG.debug("Added private credential to subject: " + cred);
}
} catch (GSSException ex) {
LOG.warn("Cannot add private credential to subject; " + "clients authentication may fail", ex);
}
}
try {
return Subject.doAs(subject, new PrivilegedExceptionAction<SaslServer>() {
public SaslServer run() {
try {
SaslServer saslServer;
saslServer = Sasl.createSaslServer(mech, servicePrincipalName, serviceHostname, null, login.callbackHandler);
return saslServer;
} catch (SaslException e) {
LOG.error("Zookeeper Server failed to create a SaslServer to interact with a client during session initiation: " + e);
e.printStackTrace();
return null;
}
}
});
} catch (PrivilegedActionException e) {
// TODO: exit server at this point(?)
LOG.error("Zookeeper Quorum member experienced a PrivilegedActionException exception while creating a SaslServer using a JAAS principal context:" + e);
e.printStackTrace();
}
} catch (IndexOutOfBoundsException e) {
LOG.error("server principal name/hostname determination error: ", e);
}
} else {
// TODO: use 'authMech=' value in zoo.cfg.
try {
SaslServer saslServer = Sasl.createSaslServer("DIGEST-MD5", "zookeeper", "zk-sasl-md5", null, login.callbackHandler);
return saslServer;
} catch (SaslException e) {
LOG.error("Zookeeper Quorum member failed to create a SaslServer to interact with a client during session initiation", e);
}
}
}
}
LOG.error("failed to create saslServer object.");
return null;
}
use of javax.security.sasl.SaslException in project hive by apache.
the class TestRpc method testBadHello.
@Test
public void testBadHello() throws Exception {
RpcServer server = autoClose(new RpcServer(emptyConfig));
Future<Rpc> serverRpcFuture = server.registerClient("client", "newClient", new TestDispatcher());
NioEventLoopGroup eloop = new NioEventLoopGroup();
Future<Rpc> clientRpcFuture = Rpc.createClient(emptyConfig, eloop, "localhost", server.getPort(), "client", "wrongClient", new TestDispatcher());
try {
autoClose(clientRpcFuture.get(10, TimeUnit.SECONDS));
fail("Should have failed to create client with wrong secret.");
} catch (ExecutionException ee) {
// On failure, the SASL handler will throw an exception indicating that the SASL
// negotiation failed.
assertTrue("Unexpected exception: " + ee.getCause(), ee.getCause() instanceof SaslException);
}
serverRpcFuture.cancel(true);
}
use of javax.security.sasl.SaslException in project hive by apache.
the class PlainSaslServer method evaluateResponse.
@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
try {
// parse the response
// message = [authzid] UTF8NUL authcid UTF8NUL passwd'
Deque<String> tokenList = new ArrayDeque<String>();
StringBuilder messageToken = new StringBuilder();
for (byte b : response) {
if (b == 0) {
tokenList.addLast(messageToken.toString());
messageToken = new StringBuilder();
} else {
messageToken.append((char) b);
}
}
tokenList.addLast(messageToken.toString());
// validate response
if (tokenList.size() < 2 || tokenList.size() > 3) {
throw new SaslException("Invalid message format");
}
String passwd = tokenList.removeLast();
user = tokenList.removeLast();
// optional authzid
String authzId;
if (tokenList.isEmpty()) {
authzId = user;
} else {
authzId = tokenList.removeLast();
}
if (user == null || user.isEmpty()) {
throw new SaslException("No user name provided");
}
if (passwd == null || passwd.isEmpty()) {
throw new SaslException("No password name provided");
}
NameCallback nameCallback = new NameCallback("User");
nameCallback.setName(user);
PasswordCallback pcCallback = new PasswordCallback("Password", false);
pcCallback.setPassword(passwd.toCharArray());
AuthorizeCallback acCallback = new AuthorizeCallback(user, authzId);
Callback[] cbList = { nameCallback, pcCallback, acCallback };
handler.handle(cbList);
if (!acCallback.isAuthorized()) {
throw new SaslException("Authentication failed");
}
} catch (IllegalStateException eL) {
throw new SaslException("Invalid message format", eL);
} catch (IOException eI) {
throw new SaslException("Error validating the login", eI);
} catch (UnsupportedCallbackException eU) {
throw new SaslException("Error validating the login", eU);
}
return null;
}
Aggregations