use of org.apache.wss4j.dom.engine.WSSConfig in project cxf by apache.
the class AbstractSamlInHandler method validateToken.
protected void validateToken(Message message, SamlAssertionWrapper assertion) {
try {
RequestData data = new RequestData();
data.setMsgContext(message);
// Add Audience Restrictions for SAML
configureAudienceRestriction(message, data);
if (assertion.isSigned()) {
WSSConfig cfg = WSSConfig.getNewInstance();
data.setWssConfig(cfg);
data.setCallbackHandler(RSSecurityUtils.getCallbackHandler(message, this.getClass()));
try {
data.setSigVerCrypto(new CryptoLoader().getCrypto(message, SecurityConstants.SIGNATURE_CRYPTO, SecurityConstants.SIGNATURE_PROPERTIES));
} catch (IOException ex) {
throwFault("Crypto can not be loaded", ex);
}
boolean enableRevocation = false;
String enableRevocationStr = (String) org.apache.cxf.rt.security.utils.SecurityUtils.getSecurityPropertyValue(SecurityConstants.ENABLE_REVOCATION, message);
if (enableRevocationStr != null) {
enableRevocation = Boolean.parseBoolean(enableRevocationStr);
}
data.setEnableRevocation(enableRevocation);
Signature sig = assertion.getSignature();
WSDocInfo docInfo = new WSDocInfo(sig.getDOM().getOwnerDocument());
data.setWsDocInfo(docInfo);
SAMLKeyInfo samlKeyInfo = null;
KeyInfo keyInfo = sig.getKeyInfo();
if (keyInfo != null) {
samlKeyInfo = SAMLUtil.getCredentialFromKeyInfo(keyInfo.getDOM(), new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto());
} else if (!keyInfoMustBeAvailable) {
samlKeyInfo = createKeyInfoFromDefaultAlias(data.getSigVerCrypto());
}
assertion.verifySignature(samlKeyInfo);
assertion.parseSubject(new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(), data.getCallbackHandler());
} else if (getTLSCertificates(message) == null) {
throwFault("Assertion must be signed", null);
}
if (samlValidator != null) {
Credential credential = new Credential();
credential.setSamlAssertion(assertion);
samlValidator.validate(credential, data);
}
checkSubjectConfirmationData(message, assertion);
setSecurityContext(message, assertion);
} catch (Exception ex) {
throwFault("Assertion can not be validated", ex);
}
}
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 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
final Element usernameTokenElement;
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;
}
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);
}
}
}
}
Aggregations