use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.
the class UsernameTokenInterceptor method addUsernameToken.
protected WSSecUsernameToken addUsernameToken(SoapMessage message, Document doc, UsernameToken token) {
String userName = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.USERNAME, message);
WSSConfig wssConfig = (WSSConfig) message.getContextualProperty(WSSConfig.class.getName());
if (wssConfig == null) {
wssConfig = WSSConfig.getNewInstance();
}
if (!StringUtils.isEmpty(userName)) {
// If NoPassword property is set we don't need to set the password
if (token.getPasswordType() == UsernameToken.PasswordType.NoPassword) {
WSSecUsernameToken utBuilder = new WSSecUsernameToken(doc);
utBuilder.setIdAllocator(wssConfig.getIdAllocator());
utBuilder.setWsTimeSource(wssConfig.getCurrentTime());
utBuilder.setUserInfo(userName, null);
utBuilder.setPasswordType(null);
return utBuilder;
}
String password = (String) SecurityUtils.getSecurityPropertyValue(SecurityConstants.PASSWORD, message);
if (StringUtils.isEmpty(password)) {
password = getPassword(userName, token, WSPasswordCallback.USERNAME_TOKEN, message);
}
if (!StringUtils.isEmpty(password)) {
// If the password is available then build the token
WSSecUsernameToken utBuilder = new WSSecUsernameToken(doc);
utBuilder.setIdAllocator(wssConfig.getIdAllocator());
utBuilder.setWsTimeSource(wssConfig.getCurrentTime());
if (token.getPasswordType() == UsernameToken.PasswordType.HashPassword) {
utBuilder.setPasswordType(WSS4JConstants.PASSWORD_DIGEST);
} else {
utBuilder.setPasswordType(WSS4JConstants.PASSWORD_TEXT);
}
if (token.isCreated()) {
utBuilder.addCreated();
}
if (token.isNonce()) {
utBuilder.addNonce();
}
utBuilder.setUserInfo(userName, password);
return utBuilder;
}
policyNotAsserted(token, "No username available", message);
} else {
policyNotAsserted(token, "No username available", message);
}
return null;
}
use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.
the class WSS4JInInterceptor method handleMessageInternal.
@SuppressWarnings("deprecation")
private void handleMessageInternal(SoapMessage msg) throws Fault {
boolean utWithCallbacks = MessageUtils.getContextualBoolean(msg, SecurityConstants.VALIDATE_TOKEN, true);
translateProperties(msg);
RequestData reqData = new CXFRequestData();
WSSConfig config = (WSSConfig) msg.getContextualProperty(WSSConfig.class.getName());
WSSecurityEngine engine;
if (config != null) {
engine = new WSSecurityEngine();
engine.setWssConfig(config);
} else {
engine = getSecurityEngine(utWithCallbacks);
if (engine == null) {
engine = new WSSecurityEngine();
}
config = engine.getWssConfig();
}
reqData.setWssConfig(config);
reqData.setEncryptionSerializer(new StaxSerializer());
// Add Audience Restrictions for SAML
reqData.setAudienceRestrictions(SAMLUtils.getAudienceRestrictions(msg, true));
SOAPMessage doc = getSOAPMessage(msg);
boolean doDebug = LOG.isLoggable(Level.FINE);
SoapVersion version = msg.getVersion();
if (doDebug) {
LOG.fine("WSS4JInInterceptor: enter handleMessage()");
}
/*
* The overall try, just to have a finally at the end to perform some
* housekeeping.
*/
try {
reqData.setMsgContext(msg);
reqData.setAttachmentCallbackHandler(new AttachmentCallbackHandler(msg));
setAlgorithmSuites(msg, reqData);
reqData.setCallbackHandler(getCallback(reqData, utWithCallbacks));
computeAction(msg, reqData);
String action = getAction(msg, version);
List<Integer> actions = WSSecurityUtil.decodeAction(action);
String actor = (String) getOption(ConfigurationConstants.ACTOR);
if (actor == null) {
actor = (String) msg.getContextualProperty(SecurityConstants.ACTOR);
}
reqData.setActor(actor);
// Configure replay caching
configureReplayCaches(reqData, actions, msg);
TLSSessionInfo tlsInfo = msg.get(TLSSessionInfo.class);
if (tlsInfo != null) {
Certificate[] tlsCerts = tlsInfo.getPeerCertificates();
reqData.setTlsCerts(tlsCerts);
}
/*
* Get and check the Signature specific parameters first because
* they may be used for encryption too.
*/
doReceiverAction(actions, reqData);
// explicitly specified by the user)
if (getString(ConfigurationConstants.EXPAND_XOP_INCLUDE_FOR_SIGNATURE, msg) == null && getString(ConfigurationConstants.EXPAND_XOP_INCLUDE, msg) == null) {
reqData.setExpandXopInclude(AttachmentUtil.isMtomEnabled(msg));
}
/*get chance to check msg context enableRevocation setting
*when use policy based ws-security where the WSHandler configuration
*isn't available
*/
boolean enableRevocation = reqData.isRevocationEnabled() || MessageUtils.isTrue(SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENABLE_REVOCATION, msg));
reqData.setEnableRevocation(enableRevocation);
Element soapBody = SAAJUtils.getBody(doc);
if (soapBody != null) {
engine.setCallbackLookup(new CXFCallbackLookup(soapBody.getOwnerDocument(), soapBody));
}
Element elem = WSSecurityUtil.getSecurityHeader(doc.getSOAPHeader(), actor, version.getVersion() != 1.1);
elem = (Element) DOMUtils.getDomElement(elem);
Node originalNode = null;
if (elem != null) {
originalNode = elem.cloneNode(true);
}
WSHandlerResult wsResult = engine.processSecurityHeader(elem, reqData);
importNewDomToSAAJ(doc, elem, originalNode, wsResult);
Element header = SAAJUtils.getHeader(doc);
Element body = SAAJUtils.getBody(doc);
header = (Element) DOMUtils.getDomElement(header);
body = (Element) DOMUtils.getDomElement(body);
if (!(wsResult.getResults() == null || wsResult.getResults().isEmpty())) {
// security header found
if (reqData.isEnableSignatureConfirmation()) {
checkSignatureConfirmation(reqData, wsResult);
}
checkActions(msg, reqData, wsResult.getResults(), actions, SAAJUtils.getBody(doc));
doResults(msg, actor, header, body, wsResult, utWithCallbacks);
} else {
// no security header found
if (doc.getSOAPPart().getEnvelope().getBody().hasFault() && isRequestor(msg)) {
LOG.warning("The request is a SOAP Fault, but it is not secured");
// We allow lax action matching here for backwards compatibility
// with manually configured WSS4JInInterceptors that previously
// allowed faults to pass through even if their actions aren't
// a strict match against those configured. In the WS-SP case,
// we will want to still call doResults as it handles asserting
// certain assertions that do not require a WS-S header such as
// a sp:TransportBinding assertion. In the case of WS-SP,
// the unasserted assertions will provide confirmation that
// security was not sufficient.
// checkActions(msg, reqData, wsResult, actions);
doResults(msg, actor, header, body, wsResult, utWithCallbacks);
} else {
checkActions(msg, reqData, wsResult.getResults(), actions, SAAJUtils.getBody(doc));
doResults(msg, actor, header, body, wsResult, utWithCallbacks);
}
}
if (SAAJUtils.getBody(doc) != null) {
advanceBody(msg, body);
}
SAAJInInterceptor.replaceHeaders(doc, msg);
if (doDebug) {
LOG.fine("WSS4JInInterceptor: exit handleMessage()");
}
msg.put(SECURITY_PROCESSED, Boolean.TRUE);
} catch (WSSecurityException e) {
throw WSS4JUtils.createSoapFault(msg, version, e);
} catch (XMLStreamException e) {
throw new SoapFault(new Message("STAX_EX", LOG), e, version.getSender());
} catch (SOAPException e) {
throw new SoapFault(new Message("SAAJ_EX", LOG), e, version.getSender());
} finally {
reqData = null;
}
}
use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.
the class SCTProvider method createToken.
/**
* Create a token given a TokenProviderParameters
*/
public TokenProviderResponse createToken(TokenProviderParameters tokenParameters) {
TokenRequirements tokenRequirements = tokenParameters.getTokenRequirements();
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Handling token of type: " + tokenRequirements.getTokenType());
}
if (tokenParameters.getTokenStore() == null) {
LOG.log(Level.FINE, "A cache must be configured to use the SCTProvider");
throw new STSException("Can't serialize SCT", STSException.REQUEST_FAILED);
}
SymmetricKeyHandler keyHandler = new SymmetricKeyHandler(tokenParameters);
keyHandler.createSymmetricKey();
try {
Document doc = DOMUtils.getEmptyDocument();
SecurityContextToken sct = new SecurityContextToken(getWSCVersion(tokenRequirements.getTokenType()), doc);
WSSConfig wssConfig = WSSConfig.getNewInstance();
sct.setID(wssConfig.getIdAllocator().createId("sctId-", sct));
TokenProviderResponse response = new TokenProviderResponse();
response.setTokenId(sct.getIdentifier());
if (returnEntropy) {
response.setEntropy(keyHandler.getEntropyBytes());
}
long keySize = keyHandler.getKeySize();
response.setKeySize(keySize);
response.setComputedKey(keyHandler.isComputedKey());
// putting the secret key into the cache
Instant created = Instant.now();
response.setCreated(created);
Instant expires = null;
if (lifetime > 0) {
expires = created.plusSeconds(lifetime);
response.setExpires(expires);
}
SecurityToken token = new SecurityToken(sct.getIdentifier(), created, expires);
token.setSecret(keyHandler.getSecret());
token.setPrincipal(tokenParameters.getPrincipal());
Map<String, Object> props = token.getProperties();
if (props == null) {
props = new HashMap<>();
}
token.setProperties(props);
if (tokenParameters.getRealm() != null) {
props.put(STSConstants.TOKEN_REALM, tokenParameters.getRealm());
}
// Handle Renewing logic
Renewing renewing = tokenParameters.getTokenRequirements().getRenewing();
if (renewing != null) {
props.put(STSConstants.TOKEN_RENEWING_ALLOW, String.valueOf(renewing.isAllowRenewing()));
props.put(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY, String.valueOf(renewing.isAllowRenewingAfterExpiry()));
} else {
props.put(STSConstants.TOKEN_RENEWING_ALLOW, "true");
props.put(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY, "false");
}
tokenParameters.getTokenStore().add(token);
if (tokenParameters.isEncryptToken()) {
Element el = TokenProviderUtils.encryptToken(sct.getElement(), response.getTokenId(), tokenParameters.getStsProperties(), tokenParameters.getEncryptionProperties(), tokenParameters.getKeyRequirements(), tokenParameters.getMessageContext());
response.setToken(el);
} else {
response.setToken(sct.getElement());
}
// Create the references
TokenReference attachedReference = new TokenReference();
attachedReference.setIdentifier(sct.getID());
attachedReference.setUseDirectReference(true);
attachedReference.setWsseValueType(tokenRequirements.getTokenType());
response.setAttachedReference(attachedReference);
TokenReference unAttachedReference = new TokenReference();
unAttachedReference.setIdentifier(sct.getIdentifier());
unAttachedReference.setUseDirectReference(true);
unAttachedReference.setWsseValueType(tokenRequirements.getTokenType());
response.setUnattachedReference(unAttachedReference);
LOG.fine("SecurityContextToken successfully created");
return response;
} catch (Exception e) {
LOG.log(Level.WARNING, "", e);
throw new STSException("Can't serialize SCT", e, STSException.REQUEST_FAILED);
}
}
use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.
the class SAMLTokenRenewer method validateAssertion.
private void validateAssertion(SamlAssertionWrapper assertion, ReceivedToken tokenToRenew, SecurityToken token, TokenRenewerParameters tokenParameters) throws WSSecurityException {
// Check the cached renewal properties
Map<String, Object> props = token.getProperties();
if (props == null) {
LOG.log(Level.WARNING, "Error in getting properties from cached token");
throw new STSException("Error in getting properties from cached token", STSException.REQUEST_FAILED);
}
String isAllowRenewal = (String) props.get(STSConstants.TOKEN_RENEWING_ALLOW);
String isAllowRenewalAfterExpiry = (String) props.get(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY);
if (isAllowRenewal == null || !Boolean.valueOf(isAllowRenewal)) {
LOG.log(Level.WARNING, "The token is not allowed to be renewed");
throw new STSException("The token is not allowed to be renewed", STSException.REQUEST_FAILED);
}
// Check to see whether the token has expired greater than the configured max expiry time
if (tokenToRenew.getState() == STATE.EXPIRED) {
if (!allowRenewalAfterExpiry || isAllowRenewalAfterExpiry == null || !Boolean.valueOf(isAllowRenewalAfterExpiry)) {
LOG.log(Level.WARNING, "Renewal after expiry is not allowed");
throw new STSException("Renewal after expiry is not allowed", STSException.REQUEST_FAILED);
}
DateTime expiryDate = getExpiryDate(assertion);
DateTime currentDate = new DateTime();
if ((currentDate.getMillis() - expiryDate.getMillis()) > (maxExpiry * 1000L)) {
LOG.log(Level.WARNING, "The token expired too long ago to be renewed");
throw new STSException("The token expired too long ago to be renewed", STSException.REQUEST_FAILED);
}
}
// Verify Proof of Possession
ProofOfPossessionValidator popValidator = new ProofOfPossessionValidator();
if (verifyProofOfPossession) {
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);
WSDocInfo docInfo = new WSDocInfo(((Element) tokenToRenew.getToken()).getOwnerDocument());
requestData.setWsDocInfo(docInfo);
// Parse the HOK subject if it exists
assertion.parseSubject(new WSSSAMLKeyInfoProcessor(requestData), sigCrypto, callbackHandler);
SAMLKeyInfo keyInfo = assertion.getSubjectKeyInfo();
if (keyInfo == null) {
keyInfo = new SAMLKeyInfo((byte[]) null);
}
if (!popValidator.checkProofOfPossession(tokenParameters, keyInfo)) {
throw new STSException("Failed to verify the proof of possession of the key associated with the " + "saml token. No matching key found in the request.", STSException.INVALID_REQUEST);
}
}
// Check the AppliesTo address
String appliesToAddress = tokenParameters.getAppliesToAddress();
if (appliesToAddress != null) {
if (assertion.getSaml1() != null) {
List<AudienceRestrictionCondition> restrConditions = assertion.getSaml1().getConditions().getAudienceRestrictionConditions();
if (!matchSaml1AudienceRestriction(appliesToAddress, restrConditions)) {
LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
throw new STSException("The AppliesTo address does not match the Audience Restriction", STSException.INVALID_REQUEST);
}
} else {
List<AudienceRestriction> audienceRestrs = assertion.getSaml2().getConditions().getAudienceRestrictions();
if (!matchSaml2AudienceRestriction(appliesToAddress, audienceRestrs)) {
LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
throw new STSException("The AppliesTo address does not match the Audience Restriction", STSException.INVALID_REQUEST);
}
}
}
}
use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.
the class UsernameTokenValidator method validateToken.
/**
* Validate a Token using the given TokenValidatorParameters.
*/
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
LOG.fine("Validating UsernameToken");
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);
requestData.setMsgContext(tokenParameters.getMessageContext());
TokenValidatorResponse response = new TokenValidatorResponse();
ReceivedToken validateTarget = tokenParameters.getToken();
validateTarget.setState(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();
// Marshall the received JAXB object into a DOM Element
Element usernameTokenElement = null;
try {
Set<Class<?>> classes = new HashSet<>();
classes.add(ObjectFactory.class);
classes.add(org.apache.cxf.ws.security.sts.provider.model.wstrust14.ObjectFactory.class);
CachedContextAndSchemas cache = JAXBContextCache.getCachedContextAndSchemas(classes, null, null, null, false);
JAXBContext jaxbContext = cache.getContext();
Marshaller marshaller = jaxbContext.createMarshaller();
Document doc = DOMUtils.getEmptyDocument();
Element rootElement = doc.createElement("root-element");
JAXBElement<UsernameTokenType> tokenType = new JAXBElement<UsernameTokenType>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
marshaller.marshal(tokenType, rootElement);
usernameTokenElement = (Element) rootElement.getFirstChild();
} catch (JAXBException ex) {
LOG.log(Level.WARNING, "", 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) {
return response;
}
// See if the UsernameToken is stored in the cache
int hash = ut.hashCode();
SecurityToken secToken = null;
if (tokenParameters.getTokenStore() != null) {
secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
if (secToken != null && (secToken.getTokenHash() != hash || secToken.isExpired())) {
secToken = null;
}
}
Principal principal = null;
if (secToken == null) {
Credential credential = new Credential();
credential.setUsernametoken(ut);
credential = validator.validate(credential, requestData);
principal = credential.getPrincipal();
if (credential.getSubject() != null && roleParser != null) {
// Parse roles from the validated token
Set<Principal> roles = roleParser.parseRolesFromSubject(principal, credential.getSubject());
response.setRoles(roles);
}
}
if (principal == null) {
principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
}
// Get the realm of the UsernameToken
String tokenRealm = null;
if (usernameTokenRealmCodec != null) {
tokenRealm = usernameTokenRealmCodec.getRealmFromToken(ut);
// verify the realm against the cached token
if (secToken != null) {
Map<String, Object> props = secToken.getProperties();
if (props != null) {
String cachedRealm = (String) props.get(STSConstants.TOKEN_REALM);
if (!tokenRealm.equals(cachedRealm)) {
return response;
}
}
}
}
// Store the successfully validated token in the cache
if (tokenParameters.getTokenStore() != null && secToken == null) {
secToken = new SecurityToken(ut.getID());
secToken.setToken(ut.getElement());
int hashCode = ut.hashCode();
String identifier = Integer.toString(hashCode);
secToken.setTokenHash(hashCode);
tokenParameters.getTokenStore().add(identifier, secToken);
}
response.setPrincipal(principal);
response.setTokenRealm(tokenRealm);
validateTarget.setState(STATE.VALID);
LOG.fine("Username Token successfully validated");
} catch (WSSecurityException ex) {
LOG.log(Level.WARNING, "", ex);
}
return response;
}
Aggregations