diff options
Diffstat (limited to 'eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification')
9 files changed, 833 insertions, 552 deletions
diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/AbstractRequestSignedSecurityPolicyRule.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/AbstractRequestSignedSecurityPolicyRule.java deleted file mode 100644 index f1dd1269..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/AbstractRequestSignedSecurityPolicyRule.java +++ /dev/null @@ -1,195 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.verification; - -import javax.xml.namespace.QName; -import javax.xml.transform.dom.DOMSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; - -import org.apache.commons.lang3.StringUtils; -import org.opensaml.common.SignableSAMLObject; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.security.MetadataCriteria; -import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.ws.message.MessageContext; -import org.opensaml.ws.security.SecurityPolicyException; -import org.opensaml.ws.security.SecurityPolicyRule; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.security.CriteriaSet; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.criteria.EntityIDCriteria; -import org.opensaml.xml.security.criteria.UsageCriteria; -import org.opensaml.xml.signature.SignatureTrustEngine; -import org.opensaml.xml.validation.ValidationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; - -/** - * @author tlenz - * - */ -public abstract class AbstractRequestSignedSecurityPolicyRule implements SecurityPolicyRule { - - private static final Logger log = LoggerFactory.getLogger(AbstractRequestSignedSecurityPolicyRule.class); - - - private SignatureTrustEngine trustEngine = null; - private QName peerEntityRole = null; - /** - * @param peerEntityRole - * - */ - public AbstractRequestSignedSecurityPolicyRule(SignatureTrustEngine trustEngine, QName peerEntityRole) { - this.trustEngine = trustEngine; - this.peerEntityRole = peerEntityRole; - - } - - - /** - * Reload the PVP metadata for a given entity - * - * @param entityID for which the metadata should be refreshed. - * @return true if the refresh was successful, otherwise false - */ - protected abstract boolean refreshMetadataProvider(String entityID); - - - protected abstract SignableSAMLObject getSignedSAMLObject(XMLObject inboundData); - - /* (non-Javadoc) - * @see org.opensaml.ws.security.SecurityPolicyRule#evaluate(org.opensaml.ws.message.MessageContext) - */ - @Override - public void evaluate(MessageContext context) throws SecurityPolicyException { - try { - verifySignature(context); - - } catch (SecurityPolicyException e) { - if (StringUtils.isEmpty(context.getInboundMessageIssuer())) { - throw e; - - } - log.debug("PVP2X message validation FAILED. Reload metadata for entityID: " + context.getInboundMessageIssuer()); - if (!refreshMetadataProvider(context.getInboundMessageIssuer())) - throw e; - - else { - log.trace("PVP2X metadata reload finished. Check validate message again."); - verifySignature(context); - - } - log.trace("Second PVP2X message validation finished"); - - } - - - } - - private void verifySignature(MessageContext context) throws SecurityPolicyException { - SignableSAMLObject samlObj = getSignedSAMLObject(context.getInboundMessage()); - if (samlObj != null && samlObj.getSignature() != null) { - - SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); - performSchemaValidation(samlObj.getDOM()); - - } catch (ValidationException e) { - log.warn("Signature is not conform to SAML signature profile", e); - throw new SecurityPolicyException("Signature is not conform to SAML signature profile"); - - } catch (SchemaValidationException e) { - log.warn("Signature is not conform to SAML signature profile", e); - throw new SecurityPolicyException("Signature is not conform to SAML signature profile"); - - } - - - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(context.getInboundMessageIssuer()) ); - criteriaSet.add( new MetadataCriteria(peerEntityRole, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - - try { - if (!trustEngine.validate(samlObj.getSignature(), criteriaSet)) { - throw new SecurityPolicyException("Signature validation FAILED."); - - } - log.debug("PVP message signature valid."); - - } catch (org.opensaml.xml.security.SecurityException e) { - log.info("PVP2x message signature validation FAILED. Message:" + e.getMessage()); - throw new SecurityPolicyException("Signature validation FAILED."); - - } - - } else { - throw new SecurityPolicyException("PVP Message is not signed."); - - } - - } - - private void performSchemaValidation(Element source) throws SchemaValidationException { - - String err = null; - try { - Schema test = SAMLSchemaBuilder.getSAML11Schema(); - Validator val = test.newValidator(); - val.validate(new DOMSource(source)); - log.debug("Schema validation check done OK"); - return; - - } catch (SAXException e) { - err = e.getMessage(); - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Schema validation FAILED with exception:", e); - else - log.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } catch (Exception e) { - err = e.getMessage(); - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Schema validation FAILED with exception:", e); - else - log.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } - - throw new SchemaValidationException("pvp2.22", new Object[]{err}); - - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/EaafMessageContextInitializationHandler.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/EaafMessageContextInitializationHandler.java new file mode 100644 index 00000000..aba0a68b --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/EaafMessageContextInitializationHandler.java @@ -0,0 +1,64 @@ +package at.gv.egiz.eaaf.modules.pvp2.impl.verification; + +import javax.annotation.Nonnull; + +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.exception.Pvp2InternalErrorException; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; + +import org.opensaml.core.config.ConfigurationService; +import org.opensaml.messaging.context.MessageContext; +import org.opensaml.messaging.handler.AbstractMessageHandler; +import org.opensaml.messaging.handler.MessageHandlerException; +import org.opensaml.saml.common.SAMLObject; +import org.opensaml.saml.common.messaging.context.SAMLMessageInfoContext; +import org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext; +import org.opensaml.xmlsec.SignatureValidationConfiguration; +import org.opensaml.xmlsec.SignatureValidationParameters; +import org.opensaml.xmlsec.context.SecurityParametersContext; +import org.opensaml.xmlsec.signature.support.SignatureTrustEngine; + +import lombok.extern.slf4j.Slf4j; +import net.shibboleth.utilities.java.support.component.ComponentInitializationException; + +@Slf4j +public class EaafMessageContextInitializationHandler extends AbstractMessageHandler<SAMLObject> { + + private final IPvp2MetadataProvider internalMetadataProvider; + private SignatureTrustEngine trustEngine; + + public EaafMessageContextInitializationHandler(@Nonnull IPvp2MetadataProvider metadataProvider) { + internalMetadataProvider = metadataProvider; + } + + @Override + protected void doInitialize() throws ComponentInitializationException { + try { + trustEngine = TrustEngineFactory.getSignatureKnownKeysTrustEngine(internalMetadataProvider); + + } catch (final Pvp2InternalErrorException e) { + throw new ComponentInitializationException("TrustEngine injection FAILED", e); + + } + } + + + @Override + protected void doInvoke(MessageContext<SAMLObject> messageContext) throws MessageHandlerException { + log.trace("Injecting sub-context to SAML2 message ... "); + messageContext.addSubcontext(new SAMLPeerEntityContext()); + messageContext.addSubcontext(new SAMLMessageInfoContext()); + + + final SecurityParametersContext securityParameterContext = new SecurityParametersContext(); + final SignatureValidationParameters sigValParameters = new SignatureValidationParameters(); + securityParameterContext.setSignatureValidationParameters(sigValParameters); + messageContext.addSubcontext(securityParameterContext); + + sigValParameters.setBlacklistedAlgorithms( + ConfigurationService.get(SignatureValidationConfiguration.class) + .getBlacklistedAlgorithms()); + sigValParameters.setSignatureTrustEngine(trustEngine); + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/EaafSaml2HttpRedirectDeflateSignatureSecurityHandler.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/EaafSaml2HttpRedirectDeflateSignatureSecurityHandler.java new file mode 100644 index 00000000..204229ee --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/EaafSaml2HttpRedirectDeflateSignatureSecurityHandler.java @@ -0,0 +1,107 @@ +package at.gv.egiz.eaaf.modules.pvp2.impl.verification; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SamlHttpUtils; + +import org.opensaml.messaging.context.MessageContext; +import org.opensaml.messaging.handler.MessageHandlerException; +import org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext; +import org.opensaml.saml.saml2.binding.security.impl.SAML2HTTPRedirectDeflateSignatureSecurityHandler; + +import com.google.common.base.Strings; +import lombok.extern.slf4j.Slf4j; +import net.shibboleth.utilities.java.support.codec.Base64Support; + +/** + * Always extracts the last http parameter with a specific name from request, if + * more than one with the same name exists. + * + * @author tlenz + * + */ +@Slf4j +public class EaafSaml2HttpRedirectDeflateSignatureSecurityHandler extends + SAML2HTTPRedirectDeflateSignatureSecurityHandler { + + public static final String HTTP_REDIRECT_SIGALG = "SigAlg"; + public static final String HTTP_REDIRECT_SIGNATURE = "Signature"; + + private IRefreshableMetadataProvider refreshableMetadataProvider = null; + + /** + * Signature verification handler that reloads SAML2 metadata if signature + * verification fails. + * + * @param metadataProvider Metadata provider implementation. Refreshing is only + * possible, if that provider implements + * {@link IRefreshableMetadataProvider} + */ + public EaafSaml2HttpRedirectDeflateSignatureSecurityHandler( + @Nullable IPvp2MetadataProvider metadataProvider) { + if (metadataProvider != null) { + if (metadataProvider instanceof IRefreshableMetadataProvider) { + refreshableMetadataProvider = (IRefreshableMetadataProvider) metadataProvider; + + } else { + log.trace("Refreshing is not supported by {} metadata-provider", + metadataProvider.getClass().getSimpleName()); + + } + } + } + + @Override + protected void doInvoke(@Nonnull final MessageContext messageContext) throws MessageHandlerException { + try { + super.doInvoke(messageContext); + + } catch (final MessageHandlerException e) { + if (refreshableMetadataProvider != null) { + + log.debug("Starting metadata refresh process ... "); + if (refreshableMetadataProvider.refreshMetadataProvider( + messageContext.getSubcontext(SAMLPeerEntityContext.class).getEntityId())) { + log.trace("Refreshing successful. Restarting message evaluation ... "); + + try { + super.doInvoke(messageContext); + return; + + } catch (final MessageHandlerException e1) { + log.debug("Signature validation fails twice with second error: {}", e.getMessage()); + + } + } + } + + log.info("Signature validation of SAML message failed. Reason: {}", e.getMessage()); + throw new MessageHandlerException( + new SamlSigningException("internal.pvp.10", new Object[] { e.getMessage() }, e)); + } + } + + @Override + @Nullable + protected byte[] getSignature() throws MessageHandlerException { + final String signature = SamlHttpUtils.getLastParameterFromRequest( + getHttpServletRequest(), HTTP_REDIRECT_SIGNATURE); + + if (Strings.isNullOrEmpty(signature)) { + return null; + + } + return Base64Support.decode(signature); + } + + @Override + @Nullable + protected String getSignatureAlgorithm() throws MessageHandlerException { + return SamlHttpUtils.getLastParameterFromRequest(getHttpServletRequest(), HTTP_REDIRECT_SIGALG); + + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/EaafSamlProtocolMessageXmlSignatureSecurityHandler.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/EaafSamlProtocolMessageXmlSignatureSecurityHandler.java new file mode 100644 index 00000000..9f6bc864 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/EaafSamlProtocolMessageXmlSignatureSecurityHandler.java @@ -0,0 +1,75 @@ +package at.gv.egiz.eaaf.modules.pvp2.impl.verification; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.exception.SamlSigningException; + +import org.opensaml.messaging.context.MessageContext; +import org.opensaml.messaging.handler.MessageHandlerException; +import org.opensaml.saml.common.binding.security.impl.SAMLProtocolMessageXMLSignatureSecurityHandler; +import org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +public class EaafSamlProtocolMessageXmlSignatureSecurityHandler extends + SAMLProtocolMessageXMLSignatureSecurityHandler { + + private IRefreshableMetadataProvider refreshableMetadataProvider = null; + + /** + * Signature verification handler that reloads SAML2 metadata if signature + * verification fails. + * + * @param metadataProvider Metadata provider implementation. Refreshing is only + * possible, if that provider implements + * {@link IRefreshableMetadataProvider} + */ + public EaafSamlProtocolMessageXmlSignatureSecurityHandler( + @Nullable IPvp2MetadataProvider metadataProvider) { + if (metadataProvider != null) { + if (metadataProvider instanceof IRefreshableMetadataProvider) { + refreshableMetadataProvider = (IRefreshableMetadataProvider) metadataProvider; + + } else { + log.trace("Refreshing is not supported by {} metadata-provider", + metadataProvider.getClass().getSimpleName()); + + } + } + } + + @Override + public void doInvoke(@Nonnull final MessageContext messageContext) throws MessageHandlerException { + try { + super.doInvoke(messageContext); + + } catch (final MessageHandlerException e) { + if (refreshableMetadataProvider != null) { + + log.debug("Starting metadata refresh process ... "); + if (refreshableMetadataProvider.refreshMetadataProvider( + messageContext.getSubcontext(SAMLPeerEntityContext.class).getEntityId())) { + log.trace("Refreshing successful. Restarting message evaluation ... "); + + try { + super.doInvoke(messageContext); + return; + + } catch (final MessageHandlerException e1) { + log.debug("Signature validation fails twice with second error: {}", e.getMessage()); + + } + } + } + + log.info("Signature validation of SAML message failed. Reason: {}", e.getMessage()); + throw new MessageHandlerException( + new SamlSigningException("internal.pvp.10", new Object[] { e.getMessage() }, e)); + } + + } +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPAuthRequestSignedRole.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPAuthRequestSignedRole.java deleted file mode 100644 index 6d5fdff8..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPAuthRequestSignedRole.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.verification; - -import java.util.List; - -import org.opensaml.common.binding.SAMLMessageContext; -import org.opensaml.saml2.binding.security.SAML2AuthnRequestsSignedRule; -import org.opensaml.ws.transport.http.HTTPInTransport; -import org.opensaml.xml.util.DatatypeHelper; - -/** - * @author tlenz - * - */ -public class PVPAuthRequestSignedRole extends SAML2AuthnRequestsSignedRule { - - @Override - protected boolean isMessageSigned(SAMLMessageContext messageContext) { - // This handles HTTP-Redirect and HTTP-POST-SimpleSign bindings. - HTTPInTransport inTransport = (HTTPInTransport) messageContext.getInboundMessageTransport(); - - //Check signature parameter exists only once and is not empty - List<String> sigParam = inTransport.getParameterValues("Signature"); - boolean isValidSigned = sigParam.size() == 1 && !DatatypeHelper.isEmpty(sigParam.get(0)); - - //Check signature-algorithm parameter exists only once and is not empty - List<String> sigAlgParam = inTransport.getParameterValues("SigAlg"); - boolean isValidSigAlgExists = sigAlgParam.size() == 1 && !DatatypeHelper.isEmpty(sigAlgParam.get(0)); - - //Check signature-content parameter exists only once and is not empty - List<String> samlReqParam = inTransport.getParameterValues("SAMLRequest"); - List<String> samlRespParam = inTransport.getParameterValues("SAMLResponse"); - boolean isValidContent = ( ( samlReqParam.size() == 1 && !DatatypeHelper.isEmpty(samlReqParam.get(0)) ) - || ( samlRespParam.size() == 1 && !DatatypeHelper.isEmpty(samlRespParam.get(0)) ) - ) && !(samlReqParam.size() == 1 && samlRespParam.size() == 1) - ; - - return isValidSigned && isValidSigAlgExists && isValidContent; - - } -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPSignedRequestPolicyRule.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPSignedRequestPolicyRule.java deleted file mode 100644 index eecaf4f0..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PVPSignedRequestPolicyRule.java +++ /dev/null @@ -1,84 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.verification; - -import javax.xml.namespace.QName; - -import org.opensaml.common.SignableSAMLObject; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.signature.SignatureTrustEngine; - -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; - -/** - * @author tlenz - * - */ -public class PVPSignedRequestPolicyRule extends - AbstractRequestSignedSecurityPolicyRule { - - private IRefreshableMetadataProvider metadataProvider = null; - - /** - * @param metadataProvider - * @param trustEngine - * @param peerEntityRole - */ - public PVPSignedRequestPolicyRule(MetadataProvider metadataProvider, SignatureTrustEngine trustEngine, - QName peerEntityRole) { - super(trustEngine, peerEntityRole); - if (metadataProvider instanceof IRefreshableMetadataProvider) - this.metadataProvider = (IRefreshableMetadataProvider) metadataProvider; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.validation.AbstractRequestSignedSecurityPolicyRule#refreshMetadataProvider(java.lang.String) - */ - @Override - protected boolean refreshMetadataProvider(String entityID) { - if (metadataProvider != null) - return metadataProvider.refreshMetadataProvider(entityID); - - return false; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.validation.AbstractRequestSignedSecurityPolicyRule#getSignedSAMLObject(org.opensaml.xml.XMLObject) - */ - @Override - protected SignableSAMLObject getSignedSAMLObject(XMLObject inboundData) { - if (inboundData instanceof SignableSAMLObject) - return (SignableSAMLObject) inboundData; - - else - return null; - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpSamlMessageHandlerChain.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpSamlMessageHandlerChain.java new file mode 100644 index 00000000..a1365023 --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/PvpSamlMessageHandlerChain.java @@ -0,0 +1,71 @@ +package at.gv.egiz.eaaf.modules.pvp2.impl.verification; + +import java.util.ArrayList; +import java.util.List; + +import org.opensaml.messaging.context.MessageContext; +import org.opensaml.messaging.handler.MessageHandler; +import org.opensaml.messaging.handler.MessageHandlerChain; +import org.opensaml.messaging.handler.MessageHandlerException; +import org.opensaml.saml.common.SAMLObject; + +import lombok.extern.slf4j.Slf4j; +import net.shibboleth.utilities.java.support.component.ComponentInitializationException; + +@Slf4j +public class PvpSamlMessageHandlerChain implements MessageHandlerChain<SAMLObject> { + private final List<MessageHandler<SAMLObject>> handlers = new ArrayList<>(); + private boolean isInitialized = false; + + @Override + public void invoke(MessageContext<SAMLObject> messageContext) throws MessageHandlerException { + if (!isInitialized) { + throw new RuntimeException("Component: " + + PvpSamlMessageHandlerChain.class.getName() + " not initialized"); + + } + + for (final MessageHandler<SAMLObject> handler : getHandlers()) { + log.trace("Initializing SAML message handler: {}", handler.getClass().getName()); + handler.invoke(messageContext); + + } + } + + @Override + public boolean isInitialized() { + return isInitialized; + + } + + @Override + public void initialize() throws ComponentInitializationException { + if (!isInitialized) { + for (final MessageHandler<SAMLObject> handler : getHandlers()) { + log.trace("Initializing SAML message handler: {}", handler.getClass().getName()); + handler.initialize(); + + } + + isInitialized = true; + } + + } + + @Override + public List<MessageHandler<SAMLObject>> getHandlers() { + return handlers; + + } + + public void addHandler(MessageHandler<SAMLObject> handler) { + handlers.add(handler); + + } + + public void addHandlers(List<MessageHandler<SAMLObject>> handlerList) { + handlers.addAll(handlerList); + + } + +} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SAMLVerificationEngine.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SAMLVerificationEngine.java deleted file mode 100644 index 078e4ac0..00000000 --- a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SAMLVerificationEngine.java +++ /dev/null @@ -1,207 +0,0 @@ -/******************************************************************************* - * Copyright 2017 Graz University of Technology - * EAAF-Core Components has been developed in a cooperation between EGIZ, - * A-SIT Plus, A-SIT, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * https://joinup.ec.europa.eu/news/understanding-eupl-v12 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eaaf.modules.pvp2.impl.verification; - -import javax.xml.namespace.QName; -import javax.xml.transform.dom.DOMSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; - -import org.apache.commons.lang3.StringUtils; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.metadata.IDPSSODescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.security.MetadataCriteria; -import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.xml.security.CriteriaSet; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.criteria.EntityIDCriteria; -import org.opensaml.xml.security.criteria.UsageCriteria; -import org.opensaml.xml.signature.SignatureTrustEngine; -import org.opensaml.xml.validation.ValidationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; -import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileResponse; - -@Service("SAMLVerificationEngine") -public class SAMLVerificationEngine { - private static final Logger log = LoggerFactory.getLogger(SAMLVerificationEngine.class); - - - @Autowired(required=true) IPVPMetadataProvider metadataProvider; - - public void verify(InboundMessage msg, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { - try { - if (msg instanceof PVPSProfileRequest && - ((PVPSProfileRequest)msg).getSamlRequest() instanceof RequestAbstractType) - verifyRequest(((RequestAbstractType)((PVPSProfileRequest)msg).getSamlRequest()), sigTrustEngine); - - else - verifyIDPResponse(((PVPSProfileResponse)msg).getResponse(), sigTrustEngine); - - } catch (InvalidProtocolRequestException e) { - if (StringUtils.isEmpty(msg.getEntityID())) { - throw e; - - } - log.debug("PVP2X message validation FAILED. Relead metadata for entityID: " + msg.getEntityID()); - - if (metadataProvider == null || - !(metadataProvider instanceof IRefreshableMetadataProvider) || - !((IRefreshableMetadataProvider)metadataProvider).refreshMetadataProvider(msg.getEntityID())) - throw e; - - else { - log.trace("PVP2X metadata reload finished. Check validate message again."); - - if (msg instanceof PVPSProfileRequest && - ((PVPSProfileRequest)msg).getSamlRequest() instanceof RequestAbstractType) - verifyRequest(((RequestAbstractType)((PVPSProfileRequest)msg).getSamlRequest()), sigTrustEngine); - - else - verifyIDPResponse(((PVPSProfileResponse)msg).getResponse(), sigTrustEngine); - - } - log.trace("Second PVP2X message validation finished"); - } - } - - public void verifySLOResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine ) throws InvalidProtocolRequestException { - verifyResponse(samlObj, sigTrustEngine, SPSSODescriptor.DEFAULT_ELEMENT_NAME); - - } - - public void verifyIDPResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine) throws InvalidProtocolRequestException{ - verifyResponse(samlObj, sigTrustEngine, IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - - } - - private void verifyResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine, QName defaultElementName) throws InvalidProtocolRequestException{ - SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); - performSchemaValidation(samlObj.getDOM()); - - } catch (ValidationException e) { - log.warn("Signature is not conform to SAML signature profile", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SchemaValidationException e) { - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(samlObj.getIssuer().getValue()) ); - criteriaSet.add( new MetadataCriteria(defaultElementName, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - - try { - if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } catch (org.opensaml.xml.security.SecurityException e) { - log.warn("PVP2x message signature validation FAILED.", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } - - private void verifyRequest(RequestAbstractType samlObj, SignatureTrustEngine sigTrustEngine ) throws InvalidProtocolRequestException { - SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); - performSchemaValidation(samlObj.getDOM()); - - } catch (ValidationException e) { - log.warn("Signature is not conform to SAML signature profile", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SchemaValidationException e) { - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(samlObj.getIssuer().getValue()) ); - criteriaSet.add( new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - - try { - if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } catch (org.opensaml.xml.security.SecurityException e) { - log.warn("PVP2x message signature validation FAILED.", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } - - protected void performSchemaValidation(Element source) throws SchemaValidationException { - - String err = null; - try { - Schema test = SAMLSchemaBuilder.getSAML11Schema(); - Validator val = test.newValidator(); - val.validate(new DOMSource(source)); - log.debug("Schema validation check done OK"); - return; - - } catch (SAXException e) { - err = e.getMessage(); - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Schema validation FAILED with exception:", e); - else - log.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } catch (Exception e) { - err = e.getMessage(); - if (log.isDebugEnabled() || log.isTraceEnabled()) - log.warn("Schema validation FAILED with exception:", e); - else - log.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } - - throw new SchemaValidationException("pvp2.22", new Object[]{err}); - - } - -} diff --git a/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SamlVerificationEngine.java b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SamlVerificationEngine.java new file mode 100644 index 00000000..e0a3ab8e --- /dev/null +++ b/eaaf_modules/eaaf_module_pvp2_core/src/main/java/at/gv/egiz/eaaf/modules/pvp2/impl/verification/SamlVerificationEngine.java @@ -0,0 +1,516 @@ +/* + * Copyright 2017 Graz University of Technology EAAF-Core Components has been developed in a + * cooperation between EGIZ, A-SIT Plus, A-SIT, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.2 or - as soon they will be approved by the European + * Commission - subsequent versions of the EUPL (the "Licence"); You may not use this work except in + * compliance with the Licence. You may obtain a copy of the Licence at: + * https://joinup.ec.europa.eu/news/understanding-eupl-v12 + * + * Unless required by applicable law or agreed to in writing, software distributed under the Licence + * is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express + * or implied. See the Licence for the specific language governing permissions and limitations under + * the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text file for details on the + * various modules and licenses. The "NOTICE" text file is part of the distribution. Any derivative + * works that you distribute must include a readable copy of the "NOTICE" text file. +*/ + +package at.gv.egiz.eaaf.modules.pvp2.impl.verification; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.namespace.QName; +import javax.xml.transform.dom.DOMSource; +import javax.xml.validation.Schema; +import javax.xml.validation.Validator; + +import at.gv.egiz.eaaf.core.exceptions.EaafProtocolException; +import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; +import at.gv.egiz.eaaf.modules.pvp2.api.credential.EaafX509Credential; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPvp2MetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IRefreshableMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.exception.SamlAssertionValidationExeption; +import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PvpSProfileResponse; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.opensaml.core.criterion.EntityIdCriterion; +import org.opensaml.saml.common.xml.SAMLConstants; +import org.opensaml.saml.common.xml.SAMLSchemaBuilder; +import org.opensaml.saml.common.xml.SAMLSchemaBuilder.SAML1Version; +import org.opensaml.saml.criterion.EntityRoleCriterion; +import org.opensaml.saml.criterion.ProtocolCriterion; +import org.opensaml.saml.saml2.core.Assertion; +import org.opensaml.saml.saml2.core.Audience; +import org.opensaml.saml.saml2.core.AudienceRestriction; +import org.opensaml.saml.saml2.core.Conditions; +import org.opensaml.saml.saml2.core.EncryptedAssertion; +import org.opensaml.saml.saml2.core.RequestAbstractType; +import org.opensaml.saml.saml2.core.Response; +import org.opensaml.saml.saml2.core.StatusCode; +import org.opensaml.saml.saml2.core.StatusResponseType; +import org.opensaml.saml.saml2.encryption.Decrypter; +import org.opensaml.saml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; +import org.opensaml.saml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml.security.impl.SAMLSignatureProfileValidator; +import org.opensaml.security.credential.UsageType; +import org.opensaml.security.criteria.UsageCriterion; +import org.opensaml.xmlsec.encryption.support.ChainingEncryptedKeyResolver; +import org.opensaml.xmlsec.encryption.support.DecryptionException; +import org.opensaml.xmlsec.encryption.support.EncryptedKeyResolver; +import org.opensaml.xmlsec.encryption.support.InlineEncryptedKeyResolver; +import org.opensaml.xmlsec.encryption.support.SimpleRetrievalMethodEncryptedKeyResolver; +import org.opensaml.xmlsec.keyinfo.impl.StaticKeyInfoCredentialResolver; +import org.opensaml.xmlsec.signature.support.SignatureException; +import org.opensaml.xmlsec.signature.support.SignatureTrustEngine; +import org.springframework.beans.factory.annotation.Autowired; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import lombok.extern.slf4j.Slf4j; +import net.shibboleth.utilities.java.support.net.BasicURLComparator; +import net.shibboleth.utilities.java.support.net.URIException; +import net.shibboleth.utilities.java.support.resolver.CriteriaSet; + +@Slf4j +public class SamlVerificationEngine { + private static SAMLSchemaBuilder schemaBuilder = new SAMLSchemaBuilder(SAML1Version.SAML_11); + + private static final String ERROR_03 = "internal.pvp.03"; + private static final String ERROR_10 = "internal.pvp.10"; + private static final String ERROR_14 = "internal.pvp.14"; + private static final String ERROR_15 = "internal.pvp.15"; + private static final String ERROR_16 = "internal.pvp.16"; + private static final String ERROR_17 = "internal.pvp.17"; + + private static final Object SIG_VAL_ERROR_MSG = "Signature verification return false"; + + /** + * 5 allow 3 minutes time jitter in before validation. + */ + private static final int TIME_JITTER = 3; + + + + + + @Autowired(required = true) + IPvp2MetadataProvider metadataProvider; + + /** + * Verify signature of a signed SAML2 object. + * + *<p>This method only perform signature verification</p> + * + * @param msg SAML2 message + * @param sigTrustEngine TrustEngine + * @throws org.opensaml.xml.security.SecurityException In case of invalid + * signature + * @throws Exception In case of a general + * error + */ + public void verify(final InboundMessage msg, final SignatureTrustEngine sigTrustEngine) + throws SecurityException, Exception { + try { + if (msg instanceof PvpSProfileRequest + && ((PvpSProfileRequest) msg).getSamlRequest() instanceof RequestAbstractType) { + verifyRequest((RequestAbstractType) ((PvpSProfileRequest) msg).getSamlRequest(), + sigTrustEngine); + } else if (msg instanceof PvpSProfileResponse) { + verifyIdpResponse(((PvpSProfileResponse) msg).getResponse(), sigTrustEngine); + + } else { + log.warn("SAML2 message type: {} not supported", msg.getClass().getName()); + throw new EaafProtocolException("internal.pvp.99", null); + + } + + } catch (final InvalidProtocolRequestException e) { + if (StringUtils.isEmpty(msg.getEntityID())) { + throw e; + + } + log.debug("PVP2X message validation FAILED. Relead metadata for entityID: {}", + msg.getEntityID()); + + if (metadataProvider == null || !(metadataProvider instanceof IRefreshableMetadataProvider) + || !((IRefreshableMetadataProvider) metadataProvider) + .refreshMetadataProvider(msg.getEntityID())) { + throw e; + + } else { + log.trace("PVP2X metadata reload finished. Check validate message again."); + + if (msg instanceof PvpSProfileRequest + && ((PvpSProfileRequest) msg).getSamlRequest() instanceof RequestAbstractType) { + verifyRequest((RequestAbstractType) ((PvpSProfileRequest) msg).getSamlRequest(), + sigTrustEngine); + + } else { + verifyIdpResponse(((PvpSProfileResponse) msg).getResponse(), sigTrustEngine); + + } + + } + log.trace("Second PVP2X message validation finished"); + + } + } + + /** + * Verify the signature of a signed SAML2 object from ServiceProvider. + * + * @param samlObj signed Response from ServiceProvider + * @param sigTrustEngine TrustEngie for verification + * @throws InvalidProtocolRequestException In case of a verification error + */ + public void verifySloResponse(final StatusResponseType samlObj, + final SignatureTrustEngine sigTrustEngine) throws InvalidProtocolRequestException { + verifyResponse(samlObj, sigTrustEngine, SPSSODescriptor.DEFAULT_ELEMENT_NAME); + + } + + /** + * Verify the signature of a signed SAML2 object from IDP. + * + * <p>This method only perform signature verification</p> + * + * @param samlObj signed SAML2 message from IDP + * @param sigTrustEngine TrustEngie for verification + * @throws InvalidProtocolRequestException In case of a verification error + */ + public void verifyIdpResponse(final StatusResponseType samlObj, + final SignatureTrustEngine sigTrustEngine) throws InvalidProtocolRequestException { + verifyResponse(samlObj, sigTrustEngine, IDPSSODescriptor.DEFAULT_ELEMENT_NAME); + + } + + /** + * Validate a PVP response and all included assertions. + * + *<p> + * If the SAML2 assertions are encrypted than they will be decrypted afterwards + * </p> + * + *<p>This method <b>DOES NOT</b> verify the <i>Destination</i> attribute in SAML2 Response</p> + * + * @param samlResp SAML2 Response object + * @param assertionDecryption Assertion decryption-credentials to decrypt SAML2 + * assertions + * @param spEntityID EntityId of the SAML2 client + * @param loggerName Name for logging purposes + * @throws SamlAssertionValidationExeption In case of a validation error + */ + public void validateAssertion(Response samlResp, + EaafX509Credential assertionDecryption, String spEntityID, String loggerName) + throws SamlAssertionValidationExeption { + validateAssertion(samlResp, assertionDecryption, spEntityID, loggerName, true); + + } + + /** + * Validate each SAML2 assertions in a SAML2 response. <br> + * <p> + * If the SAML2 assertions are encrypted than they will be decrypted afterwards + * </p> + * + *<p>This method <b>DOES NOT</b> verify the <i>Destination</i> attribute in SAML2 Response</p> + * + * @param samlResp SAML2 Response object + * @param assertionDecryption Assertion decryption-credentials to decrypt SAML2 + * assertions + * @param spEntityID EntityId of the SAML2 client + * @param loggerName Name for logging purposes + * @param validateDateTime <code>true</code> if <i>getIssueInstant</i> + * attribute should be validated, otherwise false + * @throws SamlAssertionValidationExeption In case of a validation error + */ + public void validateAssertion(Response samlResp, EaafX509Credential assertionDecryption, + String spEntityID, String loggerName, boolean validateDateTime) + throws SamlAssertionValidationExeption { + try { + // pre-validate the SAML2 response + assertionPreValidation(samlResp, loggerName, validateDateTime); + + // get Assertion from response and decrypt them if the are encrypted + final List<Assertion> saml2assertions = getOrDecryptAndGetAssertions(samlResp, assertionDecryption); + + // validate each assertion + final List<Assertion> validatedassertions = new ArrayList<>(); + for (final Assertion saml2assertion : saml2assertions) { + if (internalAssertionValidation(saml2assertion, spEntityID, validateDateTime)) { + log.debug("Add valid Assertion:" + saml2assertion.getID()); + validatedassertions.add(saml2assertion); + + } else { + log.warn("Remove non-valid Assertion:" + saml2assertion.getID()); + } + + } + + if (validatedassertions.isEmpty()) { + log.info("No valid PVP 2.1 assertion received."); + throw new SamlAssertionValidationExeption(ERROR_15, new Object[] { loggerName }); + + } + + samlResp.getAssertions().clear(); + samlResp.getEncryptedAssertions().clear(); + samlResp.getAssertions().addAll(validatedassertions); + + } catch (final DecryptionException e) { + log.warn("Assertion decrypt FAILED.", e); + throw new SamlAssertionValidationExeption(ERROR_16, + new Object[] { e.getMessage() }, e); + +// } catch (final ConfigurationException e) { +// throw new AssertionValidationExeption("pvp.12", +// new Object[]{loggerName, e.getMessage()}, e); + } + } + + private boolean internalAssertionValidation(Assertion saml2assertion, String spEntityId, + boolean validateDateTime) { + boolean isAssertionValid = true; + try { + // schema validation + performSchemaValidation(saml2assertion.getDOM()); + + // validate DateTime conditions + final Conditions conditions = saml2assertion.getConditions(); + if (conditions != null) { + final DateTime notbefore = conditions.getNotBefore().minusMinutes(5); + final DateTime notafter = conditions.getNotOnOrAfter(); + if (validateDateTime + && (notbefore.isAfterNow() || notafter.isBeforeNow())) { + isAssertionValid = false; + log.info("Assertion with ID:{} is out of Date. [ Current:{} NotBefore:{} NotAfter:{} ]", + saml2assertion.getID(), new DateTime(), notbefore, notafter); + + } + + // validate audienceRestrictions are valid for this SP + final List<AudienceRestriction> audienceRest = conditions.getAudienceRestrictions(); + if (audienceRest == null || audienceRest.size() == 0) { + log.info("Assertion with ID:{} has not 'AudienceRestriction' element", + saml2assertion.getID()); + isAssertionValid = false; + + } else { + for (final AudienceRestriction el : audienceRest) { + for (final Audience audience : el.getAudiences()) { + if (!urlCompare(spEntityId, audience.getAudienceURI())) { + log.info("Assertion with ID:{} 'AudienceRestriction' is not valid.", + saml2assertion.getID()); + isAssertionValid = false; + + } + } + } + } + + } else { + log.info("Assertion with ID:{} contains not 'Conditions' element", + saml2assertion.getID()); + isAssertionValid = false; + + } + + } catch (final SchemaValidationException e) { + isAssertionValid = false; + log.info("Assertion with ID:{} FAILED Schema validation. Msg: {}", + saml2assertion.getID(), e.getMessage()); + + } catch (final URIException e) { + isAssertionValid = false; + log.info("Assertion with ID:{} FAILED AudienceRestriction validation. Msg:", + saml2assertion.getID(), e.getMessage()); + + } + + return isAssertionValid; + + } + + private List<Assertion> getOrDecryptAndGetAssertions(Response samlResp, + EaafX509Credential assertionDecryption) throws DecryptionException { + final List<Assertion> saml2assertions = new ArrayList<>(); + + // check encrypted Assertions + final List<EncryptedAssertion> encryAssertionList = samlResp.getEncryptedAssertions(); + if (encryAssertionList != null && encryAssertionList.size() > 0) { + // decrypt assertions + log.debug("Found encryped assertion. Start decryption ..."); + final List<EncryptedKeyResolver> listOfKeyResolvers = new ArrayList<>(); + listOfKeyResolvers.add(new InlineEncryptedKeyResolver()); + listOfKeyResolvers.add(new EncryptedElementTypeEncryptedKeyResolver()); + listOfKeyResolvers.add(new SimpleRetrievalMethodEncryptedKeyResolver()); + + final Decrypter samlDecrypter = new Decrypter(null, + new StaticKeyInfoCredentialResolver(assertionDecryption), + new ChainingEncryptedKeyResolver(listOfKeyResolvers)); + + for (final EncryptedAssertion encAssertion : encryAssertionList) { + saml2assertions.add(samlDecrypter.decrypt(encAssertion)); + + } + log.debug("Assertion decryption finished. "); + + } + + saml2assertions.addAll(samlResp.getAssertions()); + + return saml2assertions; + + } + + private void performSchemaValidation(final Element source) throws SchemaValidationException { + + String err = null; + try { + final Schema test = schemaBuilder.getSAMLSchema(); + final Validator val = test.newValidator(); + val.validate(new DOMSource(source)); + log.debug("Schema validation check done OK"); + return; + + } catch (final SAXException e) { + err = e.getMessage(); + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.warn("Schema validation FAILED with exception:", e); + } else { + log.warn("Schema validation FAILED with message: " + e.getMessage()); + } + + } catch (final Exception e) { + err = e.getMessage(); + if (log.isDebugEnabled() || log.isTraceEnabled()) { + log.warn("Schema validation FAILED with exception:", e); + } else { + log.warn("Schema validation FAILED with message: " + e.getMessage()); + } + + } + + throw new SchemaValidationException(ERROR_03, new Object[] { err }); + + } + + private void verifyResponse(final StatusResponseType samlObj, + final SignatureTrustEngine sigTrustEngine, final QName defaultElementName) + throws InvalidProtocolRequestException { + + final SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); + try { + profileValidator.validate(samlObj.getSignature()); + performSchemaValidation(samlObj.getDOM()); + + } catch (final SignatureException e) { + log.warn("Signature is not conform to SAML signature profile", e); + throw new InvalidProtocolRequestException(ERROR_10, new Object[] {e.getMessage() }, e); + + } catch (final SchemaValidationException e) { + throw new InvalidProtocolRequestException(ERROR_03, new Object[] { e.getMessage() }, e); + + } + + final CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIdCriterion(samlObj.getIssuer().getValue())); + criteriaSet.add(new ProtocolCriterion(SAMLConstants.SAML20P_NS)); + criteriaSet.add(new EntityRoleCriterion(defaultElementName)); + criteriaSet.add(new UsageCriterion(UsageType.SIGNING)); + + try { + if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { + throw new InvalidProtocolRequestException(ERROR_10, new Object[] {SIG_VAL_ERROR_MSG}); + + } + + } catch (final org.opensaml.security.SecurityException e) { + log.warn("PVP2x message signature validation FAILED.", e); + throw new InvalidProtocolRequestException(ERROR_10, new Object[] {e.getMessage()}, e); + + } + } + + private void verifyRequest(final RequestAbstractType samlObj, + final SignatureTrustEngine sigTrustEngine) throws InvalidProtocolRequestException { + final SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); + try { + profileValidator.validate(samlObj.getSignature()); + performSchemaValidation(samlObj.getDOM()); + + } catch (final SignatureException e) { + log.warn("Signature is not conform to SAML signature profile", e); + throw new InvalidProtocolRequestException(ERROR_10, new Object[] {e.getMessage()}, e); + + } catch (final SchemaValidationException e) { + throw new InvalidProtocolRequestException(ERROR_03, new Object[] { e.getMessage() }, e); + + } + + final CriteriaSet criteriaSet = new CriteriaSet(); + criteriaSet.add(new EntityIdCriterion(samlObj.getIssuer().getValue())); + criteriaSet.add(new ProtocolCriterion(SAMLConstants.SAML20P_NS)); + criteriaSet.add(new EntityRoleCriterion(SPSSODescriptor.DEFAULT_ELEMENT_NAME)); + criteriaSet.add(new UsageCriterion(UsageType.SIGNING)); + + try { + if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { + throw new InvalidProtocolRequestException(ERROR_10, new Object[] {SIG_VAL_ERROR_MSG}); + + } + } catch (final org.opensaml.security.SecurityException e) { + log.warn("PVP2x message signature validation FAILED.", e); + throw new InvalidProtocolRequestException(ERROR_10, new Object[] {e.getMessage()}, e); + + } + + } + + private void assertionPreValidation(Response samlResp, String loggerName, boolean validateDateTime) + throws SamlAssertionValidationExeption { + if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS)) { + // validate response issueInstant + final DateTime issueInstant = samlResp.getIssueInstant(); + if (issueInstant == null) { + log.warn("PVP response does not include a 'IssueInstant' attribute"); + throw new SamlAssertionValidationExeption(ERROR_14, + new Object[] { loggerName, "'IssueInstant' attribute is not included" }); + + } + if (validateDateTime && issueInstant.minusMinutes(TIME_JITTER).isAfterNow()) { + log.warn("PVP response: IssueInstant DateTime is not valid anymore."); + throw new SamlAssertionValidationExeption(ERROR_14, + new Object[] { loggerName, "'IssueInstant' Time is not valid any more" }); + + } + + } else { + log.info("PVP 2.x assertion includes an error. Receive errorcode " + + samlResp.getStatus().getStatusCode().getValue()); + throw new SamlAssertionValidationExeption(ERROR_17, + new Object[] { loggerName, + samlResp.getIssuer().getValue(), + samlResp.getStatus().getStatusCode().getValue(), + samlResp.getStatus().getStatusMessage() != null + ? samlResp.getStatus().getStatusMessage().getMessage() + : " no status message" }); + + } + } + + private static boolean urlCompare(String url1, String url2) throws URIException { + final BasicURLComparator comparator = new BasicURLComparator(); + comparator.setCaseInsensitive(false); + return comparator.compare(url1, url2); + } + +} |