use of org.apache.wss4j.common.saml.SAMLKeyInfo 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.common.saml.SAMLKeyInfo 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.common.saml.SAMLKeyInfo in project cxf by apache.
the class IssueSamlUnitTest method testIssueSaml2SymmetricKeyTokenEncryptedKey.
/**
* Test to successfully issue a Saml2 SymmetricKey token. Rather than using a Nonce as the Entropy,
* a secret key is supplied by the client instead in an EncryptedKey structure.
*/
@org.junit.Test
public void testIssueSaml2SymmetricKeyTokenEncryptedKey() throws Exception {
TokenIssueOperation issueOperation = new TokenIssueOperation();
// Add Token Provider
issueOperation.setTokenProviders(Collections.singletonList(new SAMLTokenProvider()));
// Add Service
ServiceMBean service = new StaticService();
service.setEndpoints(Collections.singletonList("http://dummy-service.com/dummy"));
issueOperation.setServices(Collections.singletonList(service));
// Add STSProperties object
STSPropertiesMBean stsProperties = new StaticSTSProperties();
Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
stsProperties.setEncryptionCrypto(crypto);
stsProperties.setSignatureCrypto(crypto);
stsProperties.setEncryptionUsername("myservicekey");
stsProperties.setSignatureUsername("mystskey");
stsProperties.setCallbackHandler(new PasswordCallbackHandler());
stsProperties.setIssuer("STS");
issueOperation.setStsProperties(stsProperties);
// Mock up a request
RequestSecurityTokenType request = new RequestSecurityTokenType();
JAXBElement<String> tokenType = new JAXBElement<String>(QNameConstants.TOKEN_TYPE, String.class, WSS4JConstants.WSS_SAML2_TOKEN_TYPE);
request.getAny().add(tokenType);
JAXBElement<String> keyType = new JAXBElement<String>(QNameConstants.KEY_TYPE, String.class, STSConstants.SYMMETRIC_KEY_KEYTYPE);
request.getAny().add(keyType);
request.getAny().add(createAppliesToElement("http://dummy-service.com/dummy"));
// Mock up message context
MessageImpl msg = new MessageImpl();
WrappedMessageContext msgCtx = new WrappedMessageContext(msg);
Principal principal = new CustomTokenPrincipal("alice");
msgCtx.put(SecurityContext.class.getName(), createSecurityContext(principal));
// Now add Entropy
Document doc = DOMUtils.createDocument();
WSSecEncryptedKey builder = new WSSecEncryptedKey(doc);
builder.setUserInfo("mystskey");
builder.setKeyIdentifierType(WSConstants.ISSUER_SERIAL);
builder.setKeyEncAlgo(WSS4JConstants.KEYTRANSPORT_RSAOAEP);
KeyGenerator keyGen = KeyUtils.getKeyGenerator(WSConstants.AES_128);
SecretKey symmetricKey = keyGen.generateKey();
builder.prepare(stsProperties.getSignatureCrypto(), symmetricKey);
Element encryptedKeyElement = builder.getEncryptedKeyElement();
byte[] secret = symmetricKey.getEncoded();
EntropyType entropyType = new EntropyType();
entropyType.getAny().add(encryptedKeyElement);
JAXBElement<EntropyType> entropyJaxbType = new JAXBElement<>(QNameConstants.ENTROPY, EntropyType.class, entropyType);
request.getAny().add(entropyJaxbType);
RequestSecurityTokenResponseCollectionType response = issueOperation.issue(request, principal, msgCtx);
List<RequestSecurityTokenResponseType> securityTokenResponse = response.getRequestSecurityTokenResponse();
assertFalse(securityTokenResponse.isEmpty());
// Test the generated token.
Element assertion = null;
for (Object tokenObject : securityTokenResponse.get(0).getAny()) {
if (tokenObject instanceof JAXBElement<?> && REQUESTED_SECURITY_TOKEN.equals(((JAXBElement<?>) tokenObject).getName())) {
RequestedSecurityTokenType rstType = (RequestedSecurityTokenType) ((JAXBElement<?>) tokenObject).getValue();
assertion = (Element) rstType.getAny();
}
}
assertNotNull(assertion);
String tokenString = DOM2Writer.nodeToString(assertion);
assertTrue(tokenString.contains("AttributeStatement"));
assertTrue(tokenString.contains("alice"));
assertFalse(tokenString.contains(SAML2Constants.CONF_BEARER));
assertTrue(tokenString.contains(SAML2Constants.CONF_HOLDER_KEY));
// Test that the (encrypted) secret sent in Entropy was used in the SAML Subject KeyInfo
SamlAssertionWrapper assertionWrapper = new SamlAssertionWrapper(assertion);
RequestData data = new RequestData();
Properties properties = new Properties();
properties.put("org.apache.wss4j.crypto.provider", "org.apache.wss4j.common.crypto.Merlin");
properties.put("org.apache.wss4j.crypto.merlin.keystore.password", "sspass");
properties.put("org.apache.wss4j.crypto.merlin.keystore.file", "keys/servicestore.jks");
data.setDecCrypto(CryptoFactory.getInstance(properties));
data.setCallbackHandler(new PasswordCallbackHandler());
data.setWssConfig(WSSConfig.getNewInstance());
data.setWsDocInfo(new WSDocInfo(assertion.getOwnerDocument()));
assertionWrapper.parseSubject(new WSSSAMLKeyInfoProcessor(data), data.getSigVerCrypto(), data.getCallbackHandler());
SAMLKeyInfo samlKeyInfo = assertionWrapper.getSubjectKeyInfo();
assertArrayEquals(secret, samlKeyInfo.getSecret());
}
use of org.apache.wss4j.common.saml.SAMLKeyInfo in project cxf by apache.
the class STSRESTTest method testIssuePublicKeySAML2TokenShortKeyType.
@org.junit.Test
public void testIssuePublicKeySAML2TokenShortKeyType() throws Exception {
WebClient client = webClient().path("saml2.0").query("keyType", "PublicKey").accept(MediaType.APPLICATION_XML);
Document assertionDoc = client.get(Document.class);
SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
List<String> methods = assertion.getConfirmationMethods();
String confirmMethod = null;
if (methods != null && !methods.isEmpty()) {
confirmMethod = methods.get(0);
}
assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
assertNotNull(subjectKeyInfo.getCerts());
}
use of org.apache.wss4j.common.saml.SAMLKeyInfo in project cxf by apache.
the class STSRESTTest method testIssuePublicKeySAML2Token.
@org.junit.Test
public void testIssuePublicKeySAML2Token() throws Exception {
WebClient client = webClient().path("saml2.0").query("keyType", STSConstants.PUBLIC_KEY_KEYTYPE).accept(MediaType.APPLICATION_XML);
Document assertionDoc = client.get(Document.class);
SamlAssertionWrapper assertion = validateSAMLToken(assertionDoc);
assertTrue(assertion.getSaml2() != null && assertion.getSaml1() == null);
List<String> methods = assertion.getConfirmationMethods();
String confirmMethod = null;
if (methods != null && !methods.isEmpty()) {
confirmMethod = methods.get(0);
}
assertTrue(OpenSAMLUtil.isMethodHolderOfKey(confirmMethod));
SAMLKeyInfo subjectKeyInfo = assertion.getSubjectKeyInfo();
assertNotNull(subjectKeyInfo.getCerts());
}
Aggregations