use of javax.security.sasl.SaslException in project adempiere by adempiere.
the class EMailOAuth2SaslClient method evaluateChallenge.
@Override
public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
if (isComplete) {
return new byte[] {};
}
NameCallback nameCallback = new NameCallback("Enter name");
Callback[] callbacks = new Callback[] { nameCallback };
try {
callback.handle(callbacks);
} catch (UnsupportedCallbackException e) {
throw new SaslException("Unsupported callback: " + e);
} catch (IOException e) {
throw new SaslException("Failed to execute callback: " + e);
}
String email = nameCallback.getName();
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", email, token).getBytes();
isComplete = true;
return response;
}
use of javax.security.sasl.SaslException in project zm-mailbox by Zimbra.
the class OAuth2SaslClient method evaluateChallenge.
public byte[] evaluateChallenge(byte[] challenge) throws SaslException {
if (isComplete) {
// Empty final response from server, just ignore it.
return new byte[] {};
}
NameCallback nameCallback = new NameCallback("Enter name");
Callback[] callbacks = new Callback[] { nameCallback };
try {
callbackHandler.handle(callbacks);
} catch (UnsupportedCallbackException e) {
throw new SaslException("Unsupported callback: " + e);
} catch (IOException e) {
throw new SaslException("Failed to execute callback: " + e);
}
String username = nameCallback.getName();
byte[] response = String.format("user=%s\1auth=Bearer %s\1\1", username, oauthToken).getBytes();
isComplete = true;
return response;
}
use of javax.security.sasl.SaslException in project drill by apache.
the class UserClient method connect.
/**
* Connects, and if required, authenticates. This method blocks until both operations are complete.
*
* @param endpoint endpoint to connect to
* @param properties properties
* @param credentials credentials
* @throws RpcException if either connection or authentication fails
*/
public void connect(final DrillbitEndpoint endpoint, final DrillProperties properties, final UserCredentials credentials) throws RpcException {
final UserToBitHandshake.Builder hsBuilder = UserToBitHandshake.newBuilder().setRpcVersion(UserRpcConfig.RPC_VERSION).setSupportListening(true).setSupportComplexTypes(supportComplexTypes).setSupportTimeout(true).setCredentials(credentials).setClientInfos(UserRpcUtils.getRpcEndpointInfos(clientName)).setSaslSupport(SaslSupport.SASL_PRIVACY).setProperties(properties.serializeForServer());
// Only used for testing purpose
if (properties.containsKey(DrillProperties.TEST_SASL_LEVEL)) {
hsBuilder.setSaslSupport(SaslSupport.valueOf(Integer.parseInt(properties.getProperty(DrillProperties.TEST_SASL_LEVEL))));
}
connect(hsBuilder.build(), endpoint).checkedGet();
// Check if client needs encryption and server is not configured for encryption.
final boolean clientNeedsEncryption = properties.containsKey(DrillProperties.SASL_ENCRYPT) && Boolean.parseBoolean(properties.getProperty(DrillProperties.SASL_ENCRYPT));
if (clientNeedsEncryption && !connection.isEncryptionEnabled()) {
throw new NonTransientRpcException("Client needs encrypted connection but server is not configured for " + "encryption. Please check connection parameter or contact your administrator");
}
if (serverAuthMechanisms != null) {
try {
authenticate(properties).checkedGet();
} catch (final SaslException e) {
throw new NonTransientRpcException(e);
}
}
}
use of javax.security.sasl.SaslException in project drill by apache.
the class UserClient method authenticate.
private CheckedFuture<Void, SaslException> authenticate(final DrillProperties properties) {
final Map<String, String> propertiesMap = properties.stringPropertiesAsMap();
// Set correct QOP property and Strength based on server needs encryption or not.
// If ChunkMode is enabled then negotiate for buffer size equal to wrapChunkSize,
// If ChunkMode is disabled then negotiate for MAX_WRAPPED_SIZE buffer size.
propertiesMap.putAll(SaslProperties.getSaslProperties(connection.isEncryptionEnabled(), connection.getMaxWrappedSize()));
// use handleAuthFailure to setException
final SettableFuture<Void> authSettable = SettableFuture.create();
final CheckedFuture<Void, SaslException> authFuture = new AbstractCheckedFuture<Void, SaslException>(authSettable) {
@Override
protected SaslException mapException(Exception e) {
if (e instanceof ExecutionException) {
final Throwable cause = Throwables.getRootCause(e);
if (cause instanceof SaslException) {
return new SaslException(String.format("Authentication failed. [Details: %s, Error %s]", connection.getEncryptionCtxtString(), cause.getMessage()), cause);
}
}
return new SaslException(String.format("Authentication failed unexpectedly. [Details: %s, Error %s]", connection.getEncryptionCtxtString(), e.getMessage()), e);
}
};
final AuthenticatorFactory factory;
final String mechanismName;
final UserGroupInformation ugi;
final SaslClient saslClient;
try {
factory = getAuthenticatorFactory(properties);
mechanismName = factory.getSimpleName();
logger.trace("Will try to authenticate to server using {} mechanism with encryption context {}", mechanismName, connection.getEncryptionCtxtString());
ugi = factory.createAndLoginUser(propertiesMap);
saslClient = factory.createSaslClient(ugi, propertiesMap);
if (saslClient == null) {
throw new SaslException(String.format("Cannot initiate authentication using %s mechanism. Insufficient " + "credentials or selected mechanism doesn't support configured security layers?", factory.getSimpleName()));
}
connection.setSaslClient(saslClient);
} catch (final IOException e) {
authSettable.setException(e);
return authFuture;
}
logger.trace("Initiating SASL exchange.");
new AuthenticationOutcomeListener<>(this, connection, RpcType.SASL_MESSAGE, ugi, new RpcOutcomeListener<Void>() {
@Override
public void failed(RpcException ex) {
authSettable.setException(ex);
}
@Override
public void success(Void value, ByteBuf buffer) {
authComplete = true;
authSettable.set(null);
}
@Override
public void interrupted(InterruptedException e) {
authSettable.setException(e);
}
}).initiate(mechanismName);
return authFuture;
}
use of javax.security.sasl.SaslException in project drill by apache.
the class UserServer method getHandshakeHandler.
@Override
protected ServerHandshakeHandler<UserToBitHandshake> getHandshakeHandler(final BitToUserConnection connection) {
return new ServerHandshakeHandler<UserToBitHandshake>(RpcType.HANDSHAKE, UserToBitHandshake.PARSER) {
@Override
protected void consumeHandshake(ChannelHandlerContext ctx, UserToBitHandshake inbound) throws Exception {
BitToUserHandshake handshakeResp = getHandshakeResponse(inbound);
OutboundRpcMessage msg = new OutboundRpcMessage(RpcMode.RESPONSE, this.handshakeType, coordinationId, handshakeResp);
ctx.writeAndFlush(msg);
if (handshakeResp.getStatus() != HandshakeStatus.SUCCESS && handshakeResp.getStatus() != HandshakeStatus.AUTH_REQUIRED) {
// If handling handshake results in an error, throw an exception to terminate the connection.
throw new RpcException("Handshake request failed: " + handshakeResp.getErrorMessage());
}
}
@Override
public BitToUserHandshake getHandshakeResponse(UserToBitHandshake inbound) throws Exception {
logger.trace("Handling handshake from user to bit. {}", inbound);
// if timeout is unsupported or is set to false, disable timeout.
if (!inbound.hasSupportTimeout() || !inbound.getSupportTimeout()) {
connection.disableReadTimeout();
logger.warn("Timeout Disabled as client doesn't support it.", connection.getName());
}
BitToUserHandshake.Builder respBuilder = BitToUserHandshake.newBuilder().setRpcVersion(UserRpcConfig.RPC_VERSION).setServerInfos(UserRpcUtils.getRpcEndpointInfos(SERVER_NAME)).addAllSupportedMethods(UserRpcConfig.SUPPORTED_SERVER_METHODS);
try {
if (inbound.getRpcVersion() != UserRpcConfig.RPC_VERSION) {
final String errMsg = String.format("Invalid rpc version. Expected %d, actual %d.", UserRpcConfig.RPC_VERSION, inbound.getRpcVersion());
return handleFailure(respBuilder, HandshakeStatus.RPC_VERSION_MISMATCH, errMsg, null);
}
connection.setHandshake(inbound);
if (!config.isAuthEnabled()) {
connection.finalizeSession(inbound.getCredentials().getUserName());
respBuilder.setStatus(HandshakeStatus.SUCCESS);
return respBuilder.build();
}
final boolean clientSupportsSasl = inbound.hasSaslSupport() && (inbound.getSaslSupport().ordinal() > SaslSupport.UNKNOWN_SASL_SUPPORT.ordinal());
final int saslSupportOrdinal = (clientSupportsSasl) ? inbound.getSaslSupport().ordinal() : SaslSupport.UNKNOWN_SASL_SUPPORT.ordinal();
if (saslSupportOrdinal <= SaslSupport.SASL_AUTH.ordinal() && config.isEncryptionEnabled()) {
throw new UserAuthenticationException("The server doesn't allow client without encryption support." + " Please upgrade your client or talk to your system administrator.");
}
if (!clientSupportsSasl) {
// for backward compatibility < 1.10
final String userName = inbound.getCredentials().getUserName();
if (logger.isTraceEnabled()) {
logger.trace("User {} on connection {} is likely using an older client.", userName, connection.getRemoteAddress());
}
try {
String password = "";
final UserProperties props = inbound.getProperties();
for (int i = 0; i < props.getPropertiesCount(); i++) {
Property prop = props.getProperties(i);
if (DrillProperties.PASSWORD.equalsIgnoreCase(prop.getKey())) {
password = prop.getValue();
break;
}
}
final PlainFactory plainFactory;
try {
plainFactory = (PlainFactory) config.getAuthProvider().getAuthenticatorFactory(PlainFactory.SIMPLE_NAME);
} catch (final SaslException e) {
throw new UserAuthenticationException("The server no longer supports username/password" + " based authentication. Please talk to your system administrator.");
}
plainFactory.getAuthenticator().authenticate(userName, password);
connection.changeHandlerTo(config.getMessageHandler());
connection.finalizeSession(userName);
respBuilder.setStatus(HandshakeStatus.SUCCESS);
if (logger.isTraceEnabled()) {
logger.trace("Authenticated {} successfully using PLAIN from {}", userName, connection.getRemoteAddress());
}
return respBuilder.build();
} catch (UserAuthenticationException ex) {
return handleFailure(respBuilder, HandshakeStatus.AUTH_FAILED, ex.getMessage(), ex);
}
}
// Offer all the configured mechanisms to client. If certain mechanism doesn't support encryption
// like PLAIN, those should fail during the SASL handshake negotiation.
respBuilder.addAllAuthenticationMechanisms(config.getAuthProvider().getAllFactoryNames());
// set the encrypted flag in handshake message. For older clients this field is optional so will be ignored
respBuilder.setEncrypted(connection.isEncryptionEnabled());
respBuilder.setMaxWrappedSize(connection.getMaxWrappedSize());
// for now, this means PLAIN credentials will be sent over twice
// (during handshake and during sasl exchange)
respBuilder.setStatus(HandshakeStatus.AUTH_REQUIRED);
return respBuilder.build();
} catch (Exception e) {
return handleFailure(respBuilder, HandshakeStatus.UNKNOWN_FAILURE, e.getMessage(), e);
}
}
};
}
Aggregations