use of javax.security.auth.callback.CallbackHandler in project ddf by codice.
the class PKITokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*
* @param tokenParameters
* @return TokenValidatorResponse
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.trace("Validating PKI Token");
STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
Crypto sigCrypto = stsProperties.getSignatureCrypto();
CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
RequestData requestData = new RequestData();
requestData.setSigVerCrypto(sigCrypto);
requestData.setWssConfig(WSSConfig.getNewInstance());
requestData.setCallbackHandler(callbackHandler);
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
PKIAuthenticationToken pkiToken = getPKITokenFromTarget(validateTarget);
if (pkiToken == null) {
return response;
}
BinarySecurityTokenType binarySecurityType = pkiToken.createBinarySecurityTokenType(pkiToken.getCredentials());
// Test the encoding type
String encodingType = binarySecurityType.getEncodingType();
if (!PKIAuthenticationToken.BASE64_ENCODING.equals(encodingType)) {
LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
return response;
}
//
// Turn the received JAXB object into a DOM element
//
Document doc = DOMUtils.createDocument();
BinarySecurity binarySecurity = new X509Security(doc);
binarySecurity.setEncodingType(encodingType);
binarySecurity.setValueType(binarySecurityType.getValueType());
String data = binarySecurityType.getValue();
Node textNode = doc.createTextNode(data);
binarySecurity.getElement().appendChild(textNode);
//
try {
Credential credential = new Credential();
credential.setBinarySecurityToken(binarySecurity);
if (merlin != null) {
byte[] token = binarySecurity.getToken();
if (token != null) {
X509Certificate[] certificates = merlin.getCertificatesFromBytes(token);
if (certificates != null) {
if (doPathValidation) {
credential.setCertificates(certificates);
} else {
credential.setCertificates(new X509Certificate[] { certificates[0] });
}
}
} else {
LOGGER.debug("Binary Security Token bytes were null.");
}
}
Credential returnedCredential = validator.validate(credential, requestData);
X500Principal subjectX500Principal = returnedCredential.getCertificates()[0].getSubjectX500Principal();
response.setPrincipal(subjectX500Principal);
if (response.getAdditionalProperties() == null) {
response.setAdditionalProperties(new HashMap<>());
}
try {
String emailAddress = SubjectUtils.getEmailAddress(subjectX500Principal);
if (emailAddress != null) {
response.getAdditionalProperties().put(SubjectUtils.EMAIL_ADDRESS_CLAIM_URI, emailAddress);
}
String country = SubjectUtils.getCountry(subjectX500Principal);
if (country != null) {
response.getAdditionalProperties().put(SubjectUtils.COUNTRY_CLAIM_URI, country);
}
} catch (Exception e) {
LOGGER.debug("Unable to set email address or country from certificate.", e);
}
validateTarget.setPrincipal(subjectX500Principal);
validateTarget.setState(STATE.VALID);
} catch (WSSecurityException ex) {
LOGGER.info("Unable to validate credentials.", ex);
}
return response;
}
use of javax.security.auth.callback.CallbackHandler in project ddf by codice.
the class UPBSTValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*
* @param tokenParameters
* @return TokenValidatorResponse
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOGGER.trace("Validating UPBST Token");
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);
requestData.setWssConfig(WSSConfig.getNewInstance());
requestData.setCallbackHandler(callbackHandler);
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(STATE.INVALID);
response.setToken(validateTarget);
if (!validateTarget.isBinarySecurityToken()) {
return response;
}
BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
// Test the encoding type
String encodingType = binarySecurityType.getEncodingType();
if (!UPAuthenticationToken.BASE64_ENCODING.equals(encodingType)) {
LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
return response;
}
UPAuthenticationToken usernameToken = getUsernameTokenFromTarget(validateTarget);
if (usernameToken == null) {
return response;
}
UsernameTokenType usernameTokenType = getUsernameTokenType(usernameToken);
// Marshall the received JAXB object into a DOM Element
Element usernameTokenElement = null;
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());
ParserConfigurator configurator = parser.configureParser(ctxPath, UPBSTValidator.class.getClassLoader());
try {
parser.marshal(configurator, tokenType, rootElement);
} catch (ParserException ex) {
LOGGER.info("Unable to parse username token", ex);
return response;
}
usernameTokenElement = (Element) rootElement.getFirstChild();
//
// Validate the token
//
WSSConfig wssConfig = WSSConfig.getNewInstance();
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) {
return response;
}
String tokenId = String.format("%s:%s:%s", usernameToken.getUsername(), usernameToken.getPassword(), usernameToken.getRealm());
// See if the UsernameToken is stored in the cache
int hash = tokenId.hashCode();
SecurityToken secToken = null;
if (tokenParameters.getTokenStore() != null) {
secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
if (secToken != null && secToken.getTokenHash() != hash) {
secToken = null;
} else if (secToken != null) {
validateTarget.setState(STATE.VALID);
}
}
if (secToken == null) {
Credential credential = new Credential();
credential.setUsernametoken(ut);
if (usernameToken.getRealm() != null && !"*".equals(usernameToken.getRealm())) {
Validator validator = validators.get(usernameToken.getRealm());
if (validator != null) {
try {
validator.validate(credential, requestData);
validateTarget.setState(STATE.VALID);
LOGGER.debug("Validated user against realm {}", usernameToken.getRealm());
} catch (WSSecurityException ex) {
LOGGER.debug("Not able to validate user against realm {}", usernameToken.getRealm());
}
}
} else {
Set<Map.Entry<String, Validator>> entries = validators.entrySet();
for (Map.Entry<String, Validator> entry : entries) {
try {
entry.getValue().validate(credential, requestData);
validateTarget.setState(STATE.VALID);
LOGGER.debug("Validated user against realm {}", entry.getKey());
break;
} catch (WSSecurityException ex) {
LOGGER.debug("Not able to validate user against realm {}", entry.getKey());
}
}
}
}
Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
// Store the successfully validated token in the cache
if (tokenParameters.getTokenStore() != null && secToken == null && STATE.VALID.equals(validateTarget.getState())) {
secToken = new SecurityToken(ut.getID());
secToken.setToken(ut.getElement());
int hashCode = tokenId.hashCode();
String identifier = Integer.toString(hashCode);
secToken.setTokenHash(hashCode);
tokenParameters.getTokenStore().add(identifier, secToken);
}
response.setPrincipal(principal);
response.setTokenRealm(null);
validateTarget.setPrincipal(principal);
} catch (WSSecurityException ex) {
LOGGER.debug("Unable to validate token.", ex);
}
if (response.getToken().getState() != STATE.VALID) {
failedLoginDelayer.delay(response.getToken().getPrincipal().getName());
}
return response;
}
use of javax.security.auth.callback.CallbackHandler in project jdk8u_jdk by JetBrains.
the class SunPKCS11 method getCallbackHandler.
private CallbackHandler getCallbackHandler(CallbackHandler handler) {
if (handler != null) {
return handler;
}
if (debug != null) {
debug.println("getting provider callback handler");
}
synchronized (LOCK_HANDLER) {
// see if handler was set via setCallbackHandler
if (pHandler != null) {
return pHandler;
}
try {
if (debug != null) {
debug.println("getting default callback handler");
}
CallbackHandler myHandler = AccessController.doPrivileged(new PrivilegedExceptionAction<CallbackHandler>() {
public CallbackHandler run() throws Exception {
String defaultHandler = java.security.Security.getProperty("auth.login.defaultCallbackHandler");
if (defaultHandler == null || defaultHandler.length() == 0) {
// ok
if (debug != null) {
debug.println("no default handler set");
}
return null;
}
Class<?> c = Class.forName(defaultHandler, true, Thread.currentThread().getContextClassLoader());
return (CallbackHandler) c.newInstance();
}
});
// save it
pHandler = myHandler;
return myHandler;
} catch (PrivilegedActionException pae) {
// ok
if (debug != null) {
debug.println("Unable to load default callback handler");
pae.printStackTrace();
}
}
}
return null;
}
use of javax.security.auth.callback.CallbackHandler in project jdk8u_jdk by JetBrains.
the class GSSUtil method login.
/**
* Authenticate using the login module from the specified
* configuration entry.
*
* @param caller the caller of JAAS Login
* @param mech the mech to be used
* @return the authenticated subject
*/
public static Subject login(GSSCaller caller, Oid mech) throws LoginException {
CallbackHandler cb = null;
if (caller instanceof HttpCaller) {
cb = new sun.net.www.protocol.http.spnego.NegotiateCallbackHandler(((HttpCaller) caller).info());
} else {
String defaultHandler = java.security.Security.getProperty(DEFAULT_HANDLER);
// get the default callback handler
if ((defaultHandler != null) && (defaultHandler.length() != 0)) {
cb = null;
} else {
cb = new TextCallbackHandler();
}
}
// New instance of LoginConfigImpl must be created for each login,
// since the entry name is not passed as the first argument, but
// generated with caller and mech inside LoginConfigImpl
LoginContext lc = new LoginContext("", null, cb, new LoginConfigImpl(caller, mech));
lc.login();
return lc.getSubject();
}
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;
}
Aggregations