use of javax.security.auth.callback.CallbackHandler in project ddf by codice.
the class UsernameTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.debug("Validating UsernameToken");
if (parser == null) {
throw new IllegalStateException("XMLParser must be configured.");
}
if (failedLoginDelayer == null) {
throw new IllegalStateException("Failed Login Delayer must be configured");
}
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
Crypto sigCrypto = stsProperties.getSignatureCrypto();
CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(sigCrypto);
WSSConfig wssConfig = WSSConfig.getNewInstance();
requestData.setWssConfig(wssConfig);
requestData.setCallbackHandler(callbackHandler);
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(ReceivedToken.STATE.INVALID);
response.setToken(validateTarget);
if (!validateTarget.isUsernameToken()) {
return response;
}
//
// Turn the JAXB UsernameTokenType into a DOM Element for validation
//
UsernameTokenType usernameTokenType = (UsernameTokenType) validateTarget.getToken();
JAXBElement<UsernameTokenType> tokenType = new JAXBElement<>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
Document doc = DOMUtils.createDocument();
Element rootElement = doc.createElement("root-element");
List<String> ctxPath = new ArrayList<>(1);
ctxPath.add(UsernameTokenType.class.getPackage().getName());
Element usernameTokenElement = null;
ParserConfigurator configurator = parser.configureParser(ctxPath, UsernameTokenValidator.class.getClassLoader());
try {
parser.marshal(configurator, tokenType, rootElement);
usernameTokenElement = (Element) rootElement.getFirstChild();
} catch (ParserException ex) {
LOGGER.info("Unable to parse username token", ex);
return response;
}
//
try {
boolean allowNamespaceQualifiedPasswordTypes = requestData.isAllowNamespaceQualifiedPasswordTypes();
UsernameToken ut = new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, new BSPEnforcer());
// The parsed principal is set independent whether validation is successful or not
response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
if (ut.getPassword() == null) {
failedLoginDelayer.delay(ut.getName());
return response;
}
Credential credential = new Credential();
credential.setUsernametoken(ut);
//Only this section is new, the rest is copied from the apache class
Set<Map.Entry<String, Validator>> entries = validators.entrySet();
for (Map.Entry<String, Validator> entry : entries) {
try {
entry.getValue().validate(credential, requestData);
validateTarget.setState(ReceivedToken.STATE.VALID);
break;
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to validate user against {}" + entry.getKey(), ex);
}
}
if (ReceivedToken.STATE.INVALID.equals(validateTarget.getState())) {
failedLoginDelayer.delay(ut.getName());
return response;
}
//end new section
Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
response.setPrincipal(principal);
response.setTokenRealm(null);
validateTarget.setState(ReceivedToken.STATE.VALID);
validateTarget.setPrincipal(principal);
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to validate token.", ex);
}
return response;
}
use of javax.security.auth.callback.CallbackHandler in project storm by apache.
the class PlainSaslTransportPlugin method getServerTransportFactory.
@Override
protected TTransportFactory getServerTransportFactory() throws IOException {
//create an authentication callback handler
CallbackHandler serverCallbackHandler = new PlainServerCallbackHandler();
if (Security.getProvider(SaslPlainServer.SecurityProvider.SASL_PLAIN_SERVER) == null) {
Security.addProvider(new SaslPlainServer.SecurityProvider());
}
//create a transport factory that will invoke our auth callback for digest
TSaslServerTransport.Factory factory = new TSaslServerTransport.Factory();
factory.addServerDefinition(PLAIN, AuthUtils.SERVICE, "localhost", null, serverCallbackHandler);
LOG.info("SASL PLAIN transport factory will be used");
return factory;
}
use of javax.security.auth.callback.CallbackHandler in project jetty.project by eclipse.
the class JAASLoginService method login.
/* ------------------------------------------------------------ */
@Override
public UserIdentity login(final String username, final Object credentials, final ServletRequest request) {
try {
CallbackHandler callbackHandler = null;
if (_callbackHandlerClass == null) {
callbackHandler = new CallbackHandler() {
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
((NameCallback) callback).setName(username);
} else if (callback instanceof PasswordCallback) {
((PasswordCallback) callback).setPassword((char[]) credentials.toString().toCharArray());
} else if (callback instanceof ObjectCallback) {
((ObjectCallback) callback).setObject(credentials);
} else if (callback instanceof RequestParameterCallback) {
RequestParameterCallback rpc = (RequestParameterCallback) callback;
if (request != null)
rpc.setParameterValues(Arrays.asList(request.getParameterValues(rpc.getParameterName())));
} else
throw new UnsupportedCallbackException(callback);
}
}
};
} else {
Class<?> clazz = Loader.loadClass(_callbackHandlerClass);
callbackHandler = (CallbackHandler) clazz.newInstance();
}
//set up the login context
//TODO jaspi requires we provide the Configuration parameter
Subject subject = new Subject();
LoginContext loginContext = new LoginContext(_loginModuleName, subject, callbackHandler);
loginContext.login();
//login success
JAASUserPrincipal userPrincipal = new JAASUserPrincipal(getUserName(callbackHandler), subject, loginContext);
subject.getPrincipals().add(userPrincipal);
return _identityService.newUserIdentity(subject, userPrincipal, getGroups(subject));
} catch (LoginException e) {
LOG.warn(e);
} catch (IOException e) {
LOG.warn(e);
} catch (UnsupportedCallbackException e) {
LOG.warn(e);
} catch (InstantiationException e) {
LOG.warn(e);
} catch (IllegalAccessException e) {
LOG.warn(e);
} catch (ClassNotFoundException e) {
LOG.warn(e);
}
return null;
}
use of javax.security.auth.callback.CallbackHandler in project Smack by igniterealtime.
the class XMPPTCPConnection method proceedTLSReceived.
/**
* The server has indicated that TLS negotiation can start. We now need to secure the
* existing plain connection and perform a handshake. This method won't return until the
* connection has finished the handshake or an error occurred while securing the connection.
* @throws IOException
* @throws CertificateException
* @throws NoSuchAlgorithmException
* @throws NoSuchProviderException
* @throws KeyStoreException
* @throws UnrecoverableKeyException
* @throws KeyManagementException
* @throws SmackException
* @throws Exception if an exception occurs.
*/
@SuppressWarnings("LiteralClassName")
private void proceedTLSReceived() throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException, KeyManagementException, SmackException {
SSLContext context = this.config.getCustomSSLContext();
KeyStore ks = null;
KeyManager[] kms = null;
PasswordCallback pcb = null;
SmackDaneVerifier daneVerifier = null;
if (config.getDnssecMode() == DnssecMode.needsDnssecAndDane) {
SmackDaneProvider daneProvider = DNSUtil.getDaneProvider();
if (daneProvider == null) {
throw new UnsupportedOperationException("DANE enabled but no SmackDaneProvider configured");
}
daneVerifier = daneProvider.newInstance();
if (daneVerifier == null) {
throw new IllegalStateException("DANE requested but DANE provider did not return a DANE verifier");
}
}
if (context == null) {
final String keyStoreType = config.getKeystoreType();
final CallbackHandler callbackHandler = config.getCallbackHandler();
final String keystorePath = config.getKeystorePath();
if ("PKCS11".equals(keyStoreType)) {
try {
Constructor<?> c = Class.forName("sun.security.pkcs11.SunPKCS11").getConstructor(InputStream.class);
String pkcs11Config = "name = SmartCard\nlibrary = " + config.getPKCS11Library();
ByteArrayInputStream config = new ByteArrayInputStream(pkcs11Config.getBytes(StringUtils.UTF8));
Provider p = (Provider) c.newInstance(config);
Security.addProvider(p);
ks = KeyStore.getInstance("PKCS11", p);
pcb = new PasswordCallback("PKCS11 Password: ", false);
callbackHandler.handle(new Callback[] { pcb });
ks.load(null, pcb.getPassword());
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
} else if ("Apple".equals(keyStoreType)) {
ks = KeyStore.getInstance("KeychainStore", "Apple");
ks.load(null, null);
//pcb = new PasswordCallback("Apple Keychain",false);
//pcb.setPassword(null);
} else if (keyStoreType != null) {
ks = KeyStore.getInstance(keyStoreType);
if (callbackHandler != null && StringUtils.isNotEmpty(keystorePath)) {
try {
pcb = new PasswordCallback("Keystore Password: ", false);
callbackHandler.handle(new Callback[] { pcb });
ks.load(new FileInputStream(keystorePath), pcb.getPassword());
} catch (Exception e) {
LOGGER.log(Level.WARNING, "Exception", e);
ks = null;
}
} else {
ks.load(null, null);
}
}
if (ks != null) {
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
try {
if (pcb == null) {
kmf.init(ks, null);
} else {
kmf.init(ks, pcb.getPassword());
pcb.clearPassword();
}
kms = kmf.getKeyManagers();
} catch (NullPointerException npe) {
LOGGER.log(Level.WARNING, "NullPointerException", npe);
}
}
// If the user didn't specify a SSLContext, use the default one
context = SSLContext.getInstance("TLS");
final SecureRandom secureRandom = new java.security.SecureRandom();
X509TrustManager customTrustManager = config.getCustomX509TrustManager();
if (daneVerifier != null) {
// User requested DANE verification.
daneVerifier.init(context, kms, customTrustManager, secureRandom);
} else {
TrustManager[] customTrustManagers = null;
if (customTrustManager != null) {
customTrustManagers = new TrustManager[] { customTrustManager };
}
context.init(kms, customTrustManagers, secureRandom);
}
}
Socket plain = socket;
// Secure the plain connection
socket = context.getSocketFactory().createSocket(plain, host, plain.getPort(), true);
final SSLSocket sslSocket = (SSLSocket) socket;
// Immediately set the enabled SSL protocols and ciphers. See SMACK-712 why this is
// important (at least on certain platforms) and it seems to be a good idea anyways to
// prevent an accidental implicit handshake.
TLSUtils.setEnabledProtocolsAndCiphers(sslSocket, config.getEnabledSSLProtocols(), config.getEnabledSSLCiphers());
// Initialize the reader and writer with the new secured version
initReaderAndWriter();
// Proceed to do the handshake
sslSocket.startHandshake();
if (daneVerifier != null) {
daneVerifier.finish(sslSocket);
}
final HostnameVerifier verifier = getConfiguration().getHostnameVerifier();
if (verifier == null) {
throw new IllegalStateException("No HostnameVerifier set. Use connectionConfiguration.setHostnameVerifier() to configure.");
} else if (!verifier.verify(getXMPPServiceDomain().toString(), sslSocket.getSession())) {
throw new CertificateException("Hostname verification of certificate failed. Certificate does not authenticate " + getXMPPServiceDomain());
}
// Set that TLS was successful
secureSocket = sslSocket;
}
use of javax.security.auth.callback.CallbackHandler in project Smack by igniterealtime.
the class SASLAuthentication method authenticate.
/**
* Performs SASL authentication of the specified user. If SASL authentication was successful
* then resource binding and session establishment will be performed. This method will return
* the full JID provided by the server while binding a resource to the connection.<p>
*
* The server may assign a full JID with a username or resource different than the requested
* by this method.
*
* @param username the username that is authenticating with the server.
* @param password the password to send to the server.
* @param authzid the authorization identifier (typically null).
* @param sslSession the optional SSL/TLS session (if one was established)
* @throws XMPPErrorException
* @throws SASLErrorException
* @throws IOException
* @throws SmackException
* @throws InterruptedException
*/
public void authenticate(String username, String password, EntityBareJid authzid, SSLSession sslSession) throws XMPPErrorException, SASLErrorException, IOException, SmackException, InterruptedException {
currentMechanism = selectMechanism(authzid);
final CallbackHandler callbackHandler = configuration.getCallbackHandler();
final String host = connection.getHost();
final DomainBareJid xmppServiceDomain = connection.getXMPPServiceDomain();
synchronized (this) {
if (callbackHandler != null) {
currentMechanism.authenticate(host, xmppServiceDomain, callbackHandler, authzid, sslSession);
} else {
currentMechanism.authenticate(username, host, xmppServiceDomain, password, authzid, sslSession);
}
final long deadline = System.currentTimeMillis() + connection.getReplyTimeout();
while (!authenticationSuccessful && saslException == null) {
final long now = System.currentTimeMillis();
if (now >= deadline)
break;
// Wait until SASL negotiation finishes
wait(deadline - now);
}
}
if (saslException != null) {
if (saslException instanceof SmackException) {
throw (SmackException) saslException;
} else if (saslException instanceof SASLErrorException) {
throw (SASLErrorException) saslException;
} else {
throw new IllegalStateException("Unexpected exception type", saslException);
}
}
if (!authenticationSuccessful) {
throw NoResponseException.newWith(connection, "successful SASL authentication");
}
}
Aggregations