use of org.apache.geode.security.AuthenticationFailedException in project geode by apache.
the class HandShake method readCredentials.
// This assumes that authentication is the last piece of info in handshake
public static Properties readCredentials(DataInputStream dis, DataOutputStream dos, DistributedSystem system) throws GemFireSecurityException, IOException {
boolean requireAuthentication = securityService.isClientSecurityRequired();
Properties credentials = null;
try {
byte secureMode = dis.readByte();
throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
if (secureMode == CREDENTIALS_NORMAL) {
if (requireAuthentication) {
credentials = DataSerializer.readProperties(dis);
} else {
// ignore the credentials
DataSerializer.readProperties(dis);
}
} else if (secureMode == CREDENTIALS_DHENCRYPT) {
boolean sendAuthentication = dis.readBoolean();
InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter();
// Get the symmetric encryption algorithm to be used
String skAlgo = DataSerializer.readString(dis);
// Get the public key of the other side
byte[] keyBytes = DataSerializer.readByteArray(dis);
byte[] challenge = null;
PublicKey pubKey = null;
if (requireAuthentication) {
// Generate PublicKey from encoded form
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFact = KeyFactory.getInstance("DH");
pubKey = keyFact.generatePublic(x509KeySpec);
// Send the public key to other side
keyBytes = dhPublicKey.getEncoded();
challenge = new byte[64];
random.nextBytes(challenge);
// sign the challenge from client.
if (sendAuthentication) {
// Get the challenge string from client
byte[] clientChallenge = DataSerializer.readByteArray(dis);
if (privateKeyEncrypt == null) {
throw new AuthenticationFailedException(LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE.toLocalizedString());
}
// Sign the challenge from client and send it to the client
Signature sig = Signature.getInstance(privateKeySignAlgo);
sig.initSign(privateKeyEncrypt);
sig.update(clientChallenge);
byte[] signedBytes = sig.sign();
dos.writeByte(REPLY_OK);
DataSerializer.writeByteArray(keyBytes, dos);
// DataSerializer.writeString(privateKeyAlias, dos);
DataSerializer.writeString(privateKeySubject, dos);
DataSerializer.writeByteArray(signedBytes, dos);
securityLogWriter.fine("HandShake: sent the signed client challenge");
} else {
// These two lines should not be moved before the if{} statement in
// a common block for both if...then...else parts. This is to handle
// the case when an AuthenticationFailedException is thrown by the
// if...then part when sending the signature.
dos.writeByte(REPLY_OK);
DataSerializer.writeByteArray(keyBytes, dos);
}
// Now send the server challenge
DataSerializer.writeByteArray(challenge, dos);
securityLogWriter.fine("HandShake: sent the public key and challenge");
dos.flush();
// Read and decrypt the credentials
byte[] encBytes = DataSerializer.readByteArray(dis);
KeyAgreement ka = KeyAgreement.getInstance("DH");
ka.init(dhPrivateKey);
ka.doPhase(pubKey, true);
Cipher decrypt;
int keysize = getKeySize(skAlgo);
int blocksize = getBlockSize(skAlgo);
if (keysize == -1 || blocksize == -1) {
SecretKey sKey = ka.generateSecret(skAlgo);
decrypt = Cipher.getInstance(skAlgo);
decrypt.init(Cipher.DECRYPT_MODE, sKey);
} else {
String algoStr = getDhAlgoStr(skAlgo);
byte[] sKeyBytes = ka.generateSecret();
SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr);
IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize);
decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding");
decrypt.init(Cipher.DECRYPT_MODE, sks, ivps);
}
byte[] credentialBytes = decrypt.doFinal(encBytes);
ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes);
DataInputStream dinp = new DataInputStream(bis);
credentials = DataSerializer.readProperties(dinp);
byte[] challengeRes = DataSerializer.readByteArray(dinp);
// Check the challenge string
if (!Arrays.equals(challenge, challengeRes)) {
throw new AuthenticationFailedException(LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT.toLocalizedString());
}
dinp.close();
} else {
if (sendAuthentication) {
// Read and ignore the client challenge
DataSerializer.readByteArray(dis);
}
dos.writeByte(REPLY_AUTH_NOT_REQUIRED);
dos.flush();
}
} else if (secureMode == SECURITY_MULTIUSER_NOTIFICATIONCHANNEL) {
// hitesh there will be no credential CCP will get credential(Principal) using
// ServerConnection..
logger.debug("readCredential where multiuser mode creating callback connection");
}
} catch (IOException ex) {
throw ex;
} catch (GemFireSecurityException ex) {
throw ex;
} catch (Exception ex) {
throw new AuthenticationFailedException(LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex);
}
return credentials;
}
use of org.apache.geode.security.AuthenticationFailedException in project geode by apache.
the class HandShake method readCredential.
// This assumes that authentication is the last piece of info in handshake
public Properties readCredential(DataInputStream dis, DataOutputStream dos, DistributedSystem system) throws GemFireSecurityException, IOException {
Properties credentials = null;
boolean requireAuthentication = securityService.isClientSecurityRequired();
try {
byte secureMode = dis.readByte();
throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE);
if (secureMode == CREDENTIALS_NORMAL) {
this.appSecureMode = CREDENTIALS_NORMAL;
/*
* if (requireAuthentication) { credentials = DataSerializer.readProperties(dis); } else {
* DataSerializer.readProperties(dis); // ignore the credentials }
*/
} else if (secureMode == CREDENTIALS_DHENCRYPT) {
this.appSecureMode = CREDENTIALS_DHENCRYPT;
boolean sendAuthentication = dis.readBoolean();
InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter();
// Get the symmetric encryption algorithm to be used
// String skAlgo = DataSerializer.readString(dis);
this.clientSKAlgo = DataSerializer.readString(dis);
// Get the public key of the other side
byte[] keyBytes = DataSerializer.readByteArray(dis);
byte[] challenge = null;
// PublicKey pubKey = null;
if (requireAuthentication) {
// Generate PublicKey from encoded form
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFact = KeyFactory.getInstance("DH");
this.clientPublicKey = keyFact.generatePublic(x509KeySpec);
// Send the public key to other side
keyBytes = dhPublicKey.getEncoded();
challenge = new byte[64];
random.nextBytes(challenge);
// sign the challenge from client.
if (sendAuthentication) {
// Get the challenge string from client
byte[] clientChallenge = DataSerializer.readByteArray(dis);
if (privateKeyEncrypt == null) {
throw new AuthenticationFailedException(LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE.toLocalizedString());
}
// Sign the challenge from client and send it to the client
Signature sig = Signature.getInstance(privateKeySignAlgo);
sig.initSign(privateKeyEncrypt);
sig.update(clientChallenge);
byte[] signedBytes = sig.sign();
dos.writeByte(REPLY_OK);
DataSerializer.writeByteArray(keyBytes, dos);
// DataSerializer.writeString(privateKeyAlias, dos);
DataSerializer.writeString(privateKeySubject, dos);
DataSerializer.writeByteArray(signedBytes, dos);
securityLogWriter.fine("HandShake: sent the signed client challenge");
} else {
// These two lines should not be moved before the if{} statement in
// a common block for both if...then...else parts. This is to handle
// the case when an AuthenticationFailedException is thrown by the
// if...then part when sending the signature.
dos.writeByte(REPLY_OK);
DataSerializer.writeByteArray(keyBytes, dos);
}
// Now send the server challenge
DataSerializer.writeByteArray(challenge, dos);
securityLogWriter.fine("HandShake: sent the public key and challenge");
dos.flush();
// Read and decrypt the credentials
byte[] encBytes = DataSerializer.readByteArray(dis);
Cipher c = getDecryptCipher(this.clientSKAlgo, this.clientPublicKey);
byte[] credentialBytes = decryptBytes(encBytes, c);
ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes);
DataInputStream dinp = new DataInputStream(bis);
// credentials = DataSerializer.readProperties(dinp);//Hitesh: we don't send in handshake
// now
byte[] challengeRes = DataSerializer.readByteArray(dinp);
// Check the challenge string
if (!Arrays.equals(challenge, challengeRes)) {
throw new AuthenticationFailedException(LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT.toLocalizedString());
}
dinp.close();
} else {
if (sendAuthentication) {
// Read and ignore the client challenge
DataSerializer.readByteArray(dis);
}
dos.writeByte(REPLY_AUTH_NOT_REQUIRED);
dos.flush();
}
}
} catch (IOException ex) {
throw ex;
} catch (GemFireSecurityException ex) {
throw ex;
} catch (Exception ex) {
throw new AuthenticationFailedException(LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex);
}
return credentials;
}
use of org.apache.geode.security.AuthenticationFailedException in project geode by apache.
the class ServerConnection method removeUserAuth.
public boolean removeUserAuth(Message msg, boolean keepalive) {
try {
byte[] secureBytes = msg.getSecureBytes();
secureBytes = ((HandShake) this.handshake).decryptBytes(secureBytes);
// need to decrypt it first then get connectionid
AuthIds aIds = new AuthIds(secureBytes);
long connId = aIds.getConnectionId();
if (connId != this.connectionId) {
throw new AuthenticationFailedException("Authentication failed");
}
try {
// first try integrated security
boolean removed = this.clientUserAuths.removeSubject(aIds.getUniqueId());
// if not successfull, try the old way
if (!removed)
removed = this.clientUserAuths.removeUserId(aIds.getUniqueId(), keepalive);
return removed;
} catch (NullPointerException npe) {
// Bug #52023.
logger.debug("Exception {}", npe);
return false;
}
} catch (Exception ex) {
throw new AuthenticationFailedException("Authentication failed", ex);
}
}
use of org.apache.geode.security.AuthenticationFailedException in project geode by apache.
the class CacheClientNotifier method registerGFEClient.
protected void registerGFEClient(DataInputStream dis, DataOutputStream dos, Socket socket, boolean isPrimary, long startTime, Version clientVersion, long acceptorId, boolean notifyBySubscription) throws IOException {
// Read the ports and throw them away. We no longer need them
int numberOfPorts = dis.readInt();
for (int i = 0; i < numberOfPorts; i++) {
dis.readInt();
}
// Read the handshake identifier and convert it to a string member id
ClientProxyMembershipID proxyID = null;
CacheClientProxy proxy;
AccessControl authzCallback = null;
byte clientConflation = HandShake.CONFLATION_DEFAULT;
try {
proxyID = ClientProxyMembershipID.readCanonicalized(dis);
if (getBlacklistedClient().contains(proxyID)) {
writeException(dos, HandShake.REPLY_INVALID, new Exception("This client is blacklisted by server"), clientVersion);
return;
}
proxy = getClientProxy(proxyID);
DistributedMember member = proxyID.getDistributedMember();
DistributedSystem system = this.getCache().getDistributedSystem();
Properties sysProps = system.getProperties();
String authenticator = sysProps.getProperty(SECURITY_CLIENT_AUTHENTICATOR);
if (clientVersion.compareTo(Version.GFE_603) >= 0) {
byte[] overrides = HandShake.extractOverrides(new byte[] { (byte) dis.read() });
clientConflation = overrides[0];
} else {
clientConflation = (byte) dis.read();
}
switch(clientConflation) {
case HandShake.CONFLATION_DEFAULT:
case HandShake.CONFLATION_OFF:
case HandShake.CONFLATION_ON:
break;
default:
writeException(dos, HandShake.REPLY_INVALID, new IllegalArgumentException("Invalid conflation byte"), clientVersion);
return;
}
proxy = registerClient(socket, proxyID, proxy, isPrimary, clientConflation, clientVersion, acceptorId, notifyBySubscription);
Properties credentials = HandShake.readCredentials(dis, dos, system);
if (credentials != null && proxy != null) {
if (securityLogWriter.fineEnabled()) {
securityLogWriter.fine("CacheClientNotifier: verifying credentials for proxyID: " + proxyID);
}
Object subject = HandShake.verifyCredentials(authenticator, credentials, system.getSecurityProperties(), this.logWriter, this.securityLogWriter, member);
if (subject instanceof Principal) {
Principal principal = (Principal) subject;
if (securityLogWriter.fineEnabled()) {
securityLogWriter.fine("CacheClientNotifier: successfully verified credentials for proxyID: " + proxyID + " having principal: " + principal.getName());
}
String postAuthzFactoryName = sysProps.getProperty(SECURITY_CLIENT_ACCESSOR_PP);
if (postAuthzFactoryName != null && postAuthzFactoryName.length() > 0) {
if (principal == null) {
securityLogWriter.warning(LocalizedStrings.CacheClientNotifier_CACHECLIENTNOTIFIER_POST_PROCESS_AUTHORIZATION_CALLBACK_ENABLED_BUT_AUTHENTICATION_CALLBACK_0_RETURNED_WITH_NULL_CREDENTIALS_FOR_PROXYID_1, new Object[] { SECURITY_CLIENT_AUTHENTICATOR, proxyID });
}
Method authzMethod = ClassLoadUtil.methodFromName(postAuthzFactoryName);
authzCallback = (AccessControl) authzMethod.invoke(null, (Object[]) null);
authzCallback.init(principal, member, this.getCache());
}
proxy.setPostAuthzCallback(authzCallback);
} else if (subject instanceof Subject) {
proxy.setSubject((Subject) subject);
}
}
} catch (ClassNotFoundException e) {
throw new IOException(LocalizedStrings.CacheClientNotifier_CLIENTPROXYMEMBERSHIPID_OBJECT_COULD_NOT_BE_CREATED_EXCEPTION_OCCURRED_WAS_0.toLocalizedString(e));
} catch (AuthenticationRequiredException ex) {
securityLogWriter.warning(LocalizedStrings.CacheClientNotifier_AN_EXCEPTION_WAS_THROWN_FOR_CLIENT_0_1, new Object[] { proxyID, ex });
writeException(dos, HandShake.REPLY_EXCEPTION_AUTHENTICATION_REQUIRED, ex, clientVersion);
return;
} catch (AuthenticationFailedException ex) {
securityLogWriter.warning(LocalizedStrings.CacheClientNotifier_AN_EXCEPTION_WAS_THROWN_FOR_CLIENT_0_1, new Object[] { proxyID, ex });
writeException(dos, HandShake.REPLY_EXCEPTION_AUTHENTICATION_FAILED, ex, clientVersion);
return;
} catch (CacheException e) {
logger.warn(LocalizedMessage.create(LocalizedStrings.CacheClientNotifier_0_REGISTERCLIENT_EXCEPTION_ENCOUNTERED_IN_REGISTRATION_1, new Object[] { this, e }), e);
IOException io = new IOException(LocalizedStrings.CacheClientNotifier_EXCEPTION_OCCURRED_WHILE_TRYING_TO_REGISTER_INTEREST_DUE_TO_0.toLocalizedString(e.getMessage()));
io.initCause(e);
throw io;
} catch (Exception ex) {
logger.warn(LocalizedMessage.create(LocalizedStrings.CacheClientNotifier_AN_EXCEPTION_WAS_THROWN_FOR_CLIENT_0_1, new Object[] { proxyID, "" }), ex);
writeException(dos, Acceptor.UNSUCCESSFUL_SERVER_TO_CLIENT, ex, clientVersion);
return;
}
this.statistics.endClientRegistration(startTime);
}
use of org.apache.geode.security.AuthenticationFailedException in project geode by apache.
the class ShellCommands method jmxConnect.
private Result jmxConnect(Map<String, String> sslConfigProps, ConnectionEndpoint memberRmiHostPort, ConnectionEndpoint locatorTcpHostPort, boolean useSsl, String userName, String passwordToUse, String gfSecurityPropertiesPath, boolean retry) {
ConnectionEndpoint hostPortToConnect = null;
Gfsh gfsh = getGfsh();
try {
// locator to find the rmi host port
if (memberRmiHostPort != null) {
hostPortToConnect = memberRmiHostPort;
} else {
// Used for gfsh->locator connection & not needed for gfsh->manager connection
if (useSsl || !sslConfigProps.isEmpty()) {
sslConfigProps.put(MCAST_PORT, String.valueOf(0));
sslConfigProps.put(LOCATORS, "");
String sslInfoLogMsg = "Connecting to Locator via SSL.";
if (useSsl) {
sslInfoLogMsg = CliStrings.CONNECT__USE_SSL + " is set to true. " + sslInfoLogMsg;
}
gfsh.logToFile(sslInfoLogMsg, null);
}
Gfsh.println(CliStrings.format(CliStrings.CONNECT__MSG__CONNECTING_TO_LOCATOR_AT_0, new Object[] { locatorTcpHostPort.toString(false) }));
ConnectToLocatorResult connectToLocatorResult = connectToLocator(locatorTcpHostPort.getHost(), locatorTcpHostPort.getPort(), CONNECT_LOCATOR_TIMEOUT_MS, sslConfigProps);
hostPortToConnect = connectToLocatorResult.getMemberEndpoint();
// (jmx-manager-ssl=false)
if ((useSsl || !sslConfigProps.isEmpty()) && !connectToLocatorResult.isJmxManagerSslEnabled()) {
gfsh.logInfo(CliStrings.CONNECT__USE_SSL + " is set to true. But JMX Manager doesn't support SSL, connecting without SSL.", null);
sslConfigProps.clear();
}
}
if (!sslConfigProps.isEmpty()) {
gfsh.logToFile("Connecting to manager via SSL.", null);
}
// print out the connecting endpoint
if (!retry) {
Gfsh.println(CliStrings.format(CliStrings.CONNECT__MSG__CONNECTING_TO_MANAGER_AT_0, new Object[] { hostPortToConnect.toString(false) }));
}
InfoResultData infoResultData = ResultBuilder.createInfoResultData();
JmxOperationInvoker operationInvoker = new JmxOperationInvoker(hostPortToConnect.getHost(), hostPortToConnect.getPort(), userName, passwordToUse, sslConfigProps, gfSecurityPropertiesPath);
gfsh.setOperationInvoker(operationInvoker);
infoResultData.addLine(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, hostPortToConnect.toString(false)));
LogWrapper.getInstance().info(CliStrings.format(CliStrings.CONNECT__MSG__SUCCESS, hostPortToConnect.toString(false)));
return ResultBuilder.buildResult(infoResultData);
} catch (Exception e) {
// all other exceptions, just logs it and returns a connection error
if (!(e instanceof SecurityException) && !(e instanceof AuthenticationFailedException)) {
return handleExcpetion(e, hostPortToConnect);
}
// connection error
if (userName != null) {
return handleExcpetion(e, hostPortToConnect);
}
// otherwise, prompt for username and password and retry the conenction
try {
userName = gfsh.readText(CliStrings.CONNECT__USERNAME + ": ");
passwordToUse = gfsh.readPassword(CliStrings.CONNECT__PASSWORD + ": ");
// avoid a stack overflow.
if (userName == null && passwordToUse == null)
return handleExcpetion(e, hostPortToConnect);
return jmxConnect(sslConfigProps, hostPortToConnect, null, useSsl, userName, passwordToUse, gfSecurityPropertiesPath, true);
} catch (IOException ioe) {
return handleExcpetion(ioe, hostPortToConnect);
}
} finally {
Gfsh.redirectInternalJavaLoggers();
}
}
Aggregations