From cbdb6946d5af7de63afebf5ad256743303f00935 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 24 Feb 2016 06:21:22 +0100 Subject: refactor PVP protocol implementation to resuse code in other modules --- .../moa/id/auth/MOAIDAuthConstants.java | 4 +- .../id/auth/builder/AuthenticationDataBuilder.java | 50 +- .../id/auth/modules/BKUSelectionModuleImpl.java | 3 +- .../internal/tasks/EvaluateBKUSelectionTask.java | 3 + .../tasks/RestartAuthProzessManagement.java | 10 +- .../moa/id/moduls/AuthenticationManager.java | 12 +- .../id/protocols/pvp2x/AttributQueryAction.java | 5 +- .../id/protocols/pvp2x/AuthenticationAction.java | 12 +- .../moa/id/protocols/pvp2x/MetadataAction.java | 257 +------- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 112 +--- .../moa/id/protocols/pvp2x/binding/IEncoder.java | 24 +- .../id/protocols/pvp2x/binding/PostBinding.java | 35 +- .../protocols/pvp2x/binding/RedirectBinding.java | 43 +- .../id/protocols/pvp2x/binding/SoapBinding.java | 21 +- .../pvp2x/builder/AbstractPVPMetadataBuilder.java | 649 --------------------- .../pvp2x/builder/PVPMetadataBuilder.java | 460 +++++++++++++++ .../pvp2x/builder/SingleLogOutBuilder.java | 3 +- .../pvp2x/config/IDPPVPMetadataConfiguration.java | 288 +++++++++ .../config/IPVPMetadataBuilderConfiguration.java | 217 +++++++ .../pvp2x/verification/SAMLVerificationEngine.java | 236 ++++---- 20 files changed, 1231 insertions(+), 1213 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index d76021bbd..1a9018563 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -174,8 +174,10 @@ public class MOAIDAuthConstants extends MOAIDConstants{ //AuthnRequest IssueInstant validation public static final int TIME_JITTER = 5; //all 5 minutes time jitter - public static final String PROCESSCONTEXT_INTERFEDERATION_ENTITYID = "interfederationIDPEntityID"; + public static final String PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH = "interfederationAuthentication"; public static final String PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION = "requireLocalAuthentication"; + public static final String PROCESSCONTEXT_PERFORM_BKUSELECTION = "performBKUSelection"; + public static final String PROCESSCONTEXT_ISLEGACYREQUEST = "isLegacyRequest"; //General protocol-request data-store keys public static final String AUTHPROCESS_DATA_TARGET = "authProces_Target"; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index dbf95f604..8a9999d85 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -104,7 +104,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; @@ -127,24 +126,13 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; @Autowired protected AuthConfiguration authConfig; @Autowired private AttributQueryBuilder attributQueryBuilder; + @Autowired private SAMLVerificationEngine samlVerificationEngine; public IAuthData buildAuthenticationData(IRequest protocolRequest, - AuthenticationSession session, List reqAttributes) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { - - - String oaID = protocolRequest.getOAURL(); - if (oaID == null) { - throw new WrongParametersException("StartAuthentication", - PARAM_OA, "auth.12"); - } - - // check parameter - if (!ParamValidatorUtils.isValidOA(oaID)) - throw new WrongParametersException("StartAuthentication", - PARAM_OA, "auth.12"); - + AuthenticationSession session, List reqAttributes) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { AuthenticationData authdata = null; + //only needed for SAML1 legacy support try { //check if SAML1 authentication module is in Classpath Class saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); @@ -165,15 +153,14 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { authdata = new AuthenticationData(); } - - + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { authdata = new AuthenticationData(); } - //reuse some parameters if it is a reauthentication - OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, oaID, protocolRequest.requestedModule()); + //reuse some parameters if it is a Service-Provider reauthentication + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, protocolRequest.getOAURL(), protocolRequest.requestedModule()); if (activeOA != null) { authdata.setSessionIndex(activeOA.getAssertionSessionID()); authdata.setNameID(activeOA.getUserNameID()); @@ -193,7 +180,8 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } } - + + //search federated IDP information in MOASession InterfederationSessionStore interfIDP = authenticatedSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); IOAAuthParameters oaParam = null; @@ -201,20 +189,22 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { //get OnlineApplication from MOA-ID-Auth configuration oaParam = protocolRequest.getOnlineApplicationConfiguration(); - //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway + //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway if (oaParam.isSTORKPVPGateway()) oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, protocolRequest); } else { - //build OnlineApplication dynamic from requested attributes + //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) oaParam = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes, interfIDP); } - if (interfIDP != null ) { - //IDP is a chained interfederated IDP and Authentication is requested + if (interfIDP != null ) { + //authentication by using a federated IDP if (oaParam.isInderfederationIDP() && protocolRequest instanceof PVPTargetConfiguration && !(((PVPTargetConfiguration)protocolRequest).getRequest() instanceof AttributeQuery)) { + //IDP is a chained interfederated IDP and Authentication is requested + //only set minimal response attributes authdata.setQAALevel(interfIDP.getQAALevel()); authdata.setBPK(interfIDP.getUserNameID()); @@ -290,12 +280,15 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } + //get SAML2 Response from federated IDP Response intfResp = (Response) req.getGenericData( RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, MOAResponse.class).getResponse(); - AssertionAttributeExtractor extractor = - new AssertionAttributeExtractor(intfResp); - + + //initialize Attribute extractor + AssertionAttributeExtractor extractor = new AssertionAttributeExtractor(intfResp); + + //check if SAML2 Assertion contains already all required attributes if (!extractor.containsAllRequiredAttributes()) { Logger.info("Received assertion does no contain a minimum set of attributes. Starting AttributeQuery process ..."); //collect attributes by using BackChannel communication @@ -323,8 +316,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { //validate PVP 2.1 response try { - SAMLVerificationEngine engine = new SAMLVerificationEngine(); - engine.verifyIDPResponse(intfResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + samlVerificationEngine.verifyIDPResponse(intfResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); //TODO: find better solution //SAMLVerificationEngine.validateAssertion(intfResp, false); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java index 8b02a5bf6..c96167e71 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java @@ -22,6 +22,7 @@ */ package at.gv.egovernment.moa.id.auth.modules; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.process.api.ExecutionContext; /** @@ -44,7 +45,7 @@ public class BKUSelectionModuleImpl implements AuthModule { @Override public String selectProcess(ExecutionContext context) { boolean performBKUSelection = false; - Object performBKUSelectionObj = context.get("performBKUSelection"); + Object performBKUSelectionObj = context.get(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION); if (performBKUSelectionObj != null && performBKUSelectionObj instanceof Boolean) performBKUSelection = (boolean) performBKUSelectionObj; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java index ed88c2aff..bd8dd709f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java @@ -62,6 +62,9 @@ public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { } + //remove BKU-selection flag from context + executionContext.remove(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION); + Logger.info("BKU is selected finished -> Start BKU selection evaluation ..."); } catch (Exception e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java index e0403f242..ddda86ecc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java @@ -64,11 +64,7 @@ public class RestartAuthProzessManagement extends AbstractAuthServletTask { } - //remove BKU selection flag - newec.remove("performBKUSelection"); - - - Logger.debug("Swicht to specific authentication process after BKU is selected"); + Logger.debug("Select new auth.-process and restart restart process-engine ... "); // select and create new process instance String processDefinitionId = ModuleRegistration.getInstance().selectProcess(newec); @@ -91,8 +87,8 @@ public class RestartAuthProzessManagement extends AbstractAuthServletTask { throw new MOAIDException("init.04", new Object[] { pendingReq.getRequestID() }); } - - Logger.info("BKU is selected -> Start BKU communication ..."); + + Logger.info("Restart process-engine with auth.process:" + processDefinitionId); // start process processEngine.start(pendingReq); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 39106dc3b..22561e435 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -99,6 +99,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { @Autowired private MOAReversionLogger revisionsLogger; @Autowired protected AuthConfiguration authConfig; @Autowired private SingleLogOutBuilder sloBuilder; + @Autowired private SAMLVerificationEngine samlVerificationEngine; public void performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { @@ -346,13 +347,15 @@ public class AuthenticationManager extends MOAIDAuthConstants { //create authentication process execution context ExecutionContext executionContext = new ExecutionContextImpl(); - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID, + //set interfederation authentication flag + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH, MiscUtil.isNotEmpty( pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); + //set legacy mode or BKU-selection flags boolean leagacyMode = (legacyallowed && legacyparamavail); - executionContext.put("isLegacyRequest", leagacyMode); - executionContext.put("performBKUSelection", !leagacyMode + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_ISLEGACYREQUEST, leagacyMode); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION, !leagacyMode && MiscUtil.isEmpty(pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); //add leagcy parameters to context @@ -485,8 +488,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { sloContainer.putFailedOA(sloReq.getIssuer().getValue()); } else { - SAMLVerificationEngine engine = new SAMLVerificationEngine(); - engine.verifySLOResponse(sloResp, + samlVerificationEngine.verifySLOResponse(sloResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java index 36145375b..bd6399377 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java @@ -52,6 +52,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; @@ -64,6 +65,7 @@ public class AttributQueryAction implements IAction { @Autowired IAuthenticationSessionStoreage authenticationSessionStorage; @Autowired private AuthenticationDataBuilder authDataBuilder; + @Autowired private IDPCredentialProvider pvpCredentials; private final static List DEFAULTSTORKATTRIBUTES = Arrays.asList( new String[]{PVPConstants.EID_STORK_TOKEN_NAME}); @@ -114,7 +116,8 @@ public class AttributQueryAction implements IAction { try { SoapBinding decoder = new SoapBinding(); - decoder.encodeRespone(httpReq, httpResp, authResponse, null, null); + decoder.encodeRespone(httpReq, httpResp, authResponse, null, null, + pvpCredentials.getIDPAssertionSigningCredential()); return null; } catch (MessageEncodingException e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java index f64aacc6d..21f505bf1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java @@ -35,7 +35,6 @@ import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -51,13 +50,13 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.BindingNotSupportedException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; @Service("PVPAuthenticationRequestAction") public class AuthenticationAction implements IAction { - - @Autowired ApplicationContext context; + @Autowired IDPCredentialProvider pvpCredentials; public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { @@ -88,11 +87,11 @@ public class AuthenticationAction implements IAction { if (consumerService.getBinding().equals( SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = context.getBean(RedirectBinding.class); + binding = new RedirectBinding(); } else if (consumerService.getBinding().equals( SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = context.getBean(PostBinding.class); + binding = new PostBinding(); } @@ -102,7 +101,8 @@ public class AuthenticationAction implements IAction { try { binding.encodeRespone(httpReq, httpResp, authResponse, - consumerService.getLocation(), moaRequest.getRelayState()); + consumerService.getLocation(), moaRequest.getRelayState(), + pvpCredentials.getIDPAssertionSigningCredential()); //set protocol type sloInformation.setProtocolType(req.requestedModule()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java index d48603a7c..15fe1e9d7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java @@ -22,43 +22,33 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x; -import java.util.Arrays; -import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.NameIDType; -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.Organization; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.xml.security.credential.Credential; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPMetadataBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.IDPPVPMetadataConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.logging.Logger; @Service("pvpMetadataService") -public class MetadataAction extends AbstractPVPMetadataBuilder implements IAction { +public class MetadataAction implements IAction { - private static final int VALIDUNTIL_IN_HOURS = 24; + @Autowired private MOAReversionLogger revisionsLogger; @Autowired private IDPCredentialProvider credentialProvider; + @Autowired private PVPMetadataBuilder metadatabuilder; public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { @@ -66,7 +56,10 @@ public class MetadataAction extends AbstractPVPMetadataBuilder implements IActio revisionsLogger.logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_PVP_METADATA); //build metadata - String metadataXML = buildPVPMetadata(req.getAuthURLWithOutSlash()); + IPVPMetadataBuilderConfiguration metadataConfig = + new IDPPVPMetadataConfiguration(req.getAuthURLWithOutSlash(), credentialProvider); + + String metadataXML = metadatabuilder.buildPVPMetadata(metadataConfig); Logger.debug("METADATA: " + metadataXML); httpResp.setContentType("text/xml"); @@ -87,236 +80,12 @@ public class MetadataAction extends AbstractPVPMetadataBuilder implements IActio return false; } - public String getDefaultActionName() { - return (PVP2XProtocol.METADATA); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataValidUntil() - */ - @Override - public int getMetadataValidUntil() { - return VALIDUNTIL_IN_HOURS; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildEntitiesDescriptorAsRootElement() - */ - @Override - public boolean buildEntitiesDescriptorAsRootElement() { - return true; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildIDPSSODescriptor() - */ - @Override - public boolean buildIDPSSODescriptor() { - return true; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildSPSSODescriptor() - */ - @Override - public boolean buildSPSSODescriptor() { - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityID() - */ - @Override - public String getEntityIDPostfix() { - //TODO: maybe change EntityID to Metadata URL - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityFriendlyName() - */ - @Override - public String getEntityFriendlyName() { - try { - return PVPConfiguration.getInstance().getIDPIssuerName(); - - } catch (ConfigurationException e) { - Logger.error("Can not load Metadata entry: EntityID friendlyName.", e); - return null; - - } - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getContactPersonInformation() - */ - @Override - public List getContactPersonInformation() { - try { - return PVPConfiguration.getInstance().getIDPContacts(); - - } catch (ConfigurationException e) { - Logger.warn("Can not load Metadata entry: Contect Person", e); - return null; - - } - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getOrgansiationInformation() - */ - @Override - public Organization getOrgansiationInformation() { - try { - return PVPConfiguration.getInstance().getIDPOrganisation(); - - } catch (ConfigurationException e) { - Logger.warn("Can not load Metadata entry: Organisation", e); - return null; - - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataSigningCredentials() - */ - @Override - public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException { - return credentialProvider.getIDPMetaDataSigningCredential(); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getRequestorResponseSigningCredentials() - */ - @Override - public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException { - return credentialProvider.getIDPAssertionSigningCredential(); - - } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEncryptionCredentials() + * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() */ @Override - public Credential getEncryptionCredentials() throws CredentialsNotAvailableException { - return credentialProvider.getIDPAssertionEncryptionCredential(); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSOPostBindingURL() - */ - @Override - public String getIDPWebSSOPostBindingURL() { - return PVPConfiguration.PVP2_IDP_POST; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSORedirectBindingURL() - */ - @Override - public String getIDPWebSSORedirectBindingURL() { - return PVPConfiguration.PVP2_IDP_REDIRECT; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLOPostBindingURL() - */ - @Override - public String getIDPSLOPostBindingURL() { - return PVPConfiguration.PVP2_IDP_POST; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLORedirectBindingURL() - */ - @Override - public String getIDPSLORedirectBindingURL() { - return PVPConfiguration.PVP2_IDP_REDIRECT; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServicePostBindingURL() - */ - @Override - public String getSPAssertionConsumerServicePostBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServiceRedirectBindingURL() - */ - @Override - public String getSPAssertionConsumerServiceRedirectBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOPostBindingURL() - */ - @Override - public String getSPSLOPostBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLORedirectBindingURL() - */ - @Override - public String getSPSLORedirectBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOSOAPBindingURL() - */ - @Override - public String getSPSLOSOAPBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleAttributes() - */ - @Override - public List getIDPPossibleAttributes() { - return PVPAttributeBuilder.buildSupportedEmptyAttributes(); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleNameITTypes() - */ - @Override - public List getIDPPossibleNameITTypes() { - return Arrays.asList(NameIDType.PERSISTENT, - NameIDType.TRANSIENT, - NameIDType.UNSPECIFIED); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPRequiredAttributes() - */ - @Override - public List getSPRequiredAttributes() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAllowedNameITTypes() - */ - @Override - public List getSPAllowedNameITTypes() { - return null; + public String getDefaultActionName() { + return "IDP - PVP Metadata action"; } - - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java index 88f0e3b74..08d9f67b6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java @@ -48,7 +48,9 @@ import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.ws.security.SecurityPolicyException; import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.x509.X509Credential; import org.opensaml.xml.signature.SignableXMLObject; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -81,6 +83,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SLOException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.CheckMandateAttributes; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.id.protocols.pvp2x.validation.AuthnRequestValidator; @@ -96,6 +99,9 @@ import at.gv.egovernment.moa.util.MiscUtil; @Controller public class PVP2XProtocol extends AbstractAuthProtocolModulController { + @Autowired IDPCredentialProvider pvpCredentials; + @Autowired SAMLVerificationEngine samlVerificationEngine; + public static final String NAME = PVP2XProtocol.class.getName(); public static final String PATH = "id_pvp2x"; @@ -182,8 +188,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); //get POST-Binding decoder implementation - PostBinding coder = applicationContext.getBean(PostBinding.class); - InboundMessage msg = (InboundMessage) coder.decode(req, resp, false); + InboundMessage msg = (InboundMessage) new PostBinding().decode(req, resp, false); pendingReq.setRequest(msg); //preProcess Message @@ -231,8 +236,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); //get POST-Binding decoder implementation - RedirectBinding coder = applicationContext.getBean(RedirectBinding.class); - InboundMessage msg = (InboundMessage) coder.decode(req, resp, false); + InboundMessage msg = (InboundMessage) new RedirectBinding().decode(req, resp, false); pendingReq.setRequest(msg); //preProcess Message @@ -270,8 +274,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { } if(!msg.isVerified()) { - SAMLVerificationEngine engine = new SAMLVerificationEngine(); - engine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + samlVerificationEngine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); msg.setVerified(true); } @@ -301,53 +304,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { pendingReq, MOAIDEventConstants.AUTHPROTOCOL_TYPE, PATH); //switch to session authentication - performAuthentication(request, response, pendingReq); - -// else if (msg instanceof MOAResponse && -// ((MOAResponse)msg).getResponse() instanceof Response) { -// //load service provider AuthRequest from session -// -// IRequest obj = RequestStorage.getPendingRequest(msg.getRelayState()); -// if (obj instanceof RequestImpl) { -// RequestImpl iReqSP = (RequestImpl) obj; -// -// MOAReversionLogger.getInstance().logEvent(iReqSP, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHRESPONSE); -// -// MOAResponse processedMsg = preProcessAuthResponse((MOAResponse) msg); -// -// if ( processedMsg != null ) { -// iReqSP.setInterfederationResponse(processedMsg); -// -// MOAReversionLogger.getInstance().logEvent(iReqSP, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_REVEIVED); -// -// Logger.info("Receive a valid assertion from IDP " + msg.getEntityID() -// + ". Switch to original transaction with ID " + iReqSP.getRequestID()); -// TransactionIDUtils.setTransactionId(iReqSP.getRequestID()); -// TransactionIDUtils.setSessionId(iReqSP.getSessionIdentifier()); -// -// } else { -// Logger.info("Interfederated IDP " + msg.getEntityID() + " has NO valid SSO session." -// +". Switch back local authentication process ..."); -// -// SSOManager ssomanager = SSOManager.getInstance(); -// ssomanager.removeInterfederatedSSOIDP(msg.getEntityID(), request); -// -// iReqSP.setRequestedIDP(null); -// -// } -// -// return iReqSP; -// -// } -// -// Logger.error("Stored PVP21 authrequest from service provider has an unsuppored type."); -// return null; - -// } - - - - + performAuthentication(request, response, pendingReq); } public boolean generateErrorMessage(Throwable e, @@ -424,11 +381,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { encoder = new RedirectBinding(); - - } else if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_ARTIFACT_BINDING_URI)) { - // TODO: not supported YET!! - //binding = new ArtifactBinding(); - + } else if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { encoder = new PostBinding(); @@ -445,8 +398,10 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { if (pvpRequest.getRequest() != null) relayState = pvpRequest.getRequest().getRelayState(); + X509Credential signCred = pvpCredentials.getIDPAssertionSigningCredential(); + encoder.encodeRespone(request, response, samlResponse, pvpRequest.getConsumerURL(), - relayState); + relayState, signCred); return true; } @@ -731,43 +686,4 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHREQUEST); } - -// /** -// * PreProcess AuthResponse and Assertion -// * @param msg -// */ -// private MOAResponse preProcessAuthResponse(MOAResponse msg) { -// Logger.debug("Start PVP21 assertion processing... "); -// Response samlResp = (Response) msg.getResponse(); -// -// try { -// if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { -// -// //validate PVP 2.1 assertion -// SAMLVerificationEngine.validateAssertion(samlResp, true); -// -// msg.setSAMLMessage(SAML2Utils.asDOMDocument(samlResp).getDocumentElement()); -// return msg; -// -// } else { -// Logger.debug("Receive StatusCode " + samlResp.getStatus().getStatusCode().getValue() -// + " from interfederated IDP."); -// -// } -// -// } catch (IOException e) { -// Logger.warn("Interfederation response marshaling FAILED.", e); -// -// } catch (MarshallingException e) { -// Logger.warn("Interfederation response marshaling FAILED.", e); -// -// } catch (TransformerException e) { -// Logger.warn("Interfederation response marshaling FAILED.", e); -// -// } catch (AssertionValidationExeption e) { -// //error is already logged, to nothing -// } -// -// return null; -// } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java index de5548a44..3b2fb3687 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java @@ -29,24 +29,40 @@ import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.StatusResponseType; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.credential.Credential; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; public interface IEncoder { + + /** + * + * @param req The http request + * @param resp The http response + * @param request The SAML2 request object + * @param targetLocation URL, where the request should be transmit + * @param relayState token for session handling + * @param credentials Credential to sign the request object + * @throws MessageEncodingException + * @throws SecurityException + * @throws PVP2Exception + */ public void encodeRequest(HttpServletRequest req, - HttpServletResponse resp, RequestAbstractType request, String targetLocation, String relayState) + HttpServletResponse resp, RequestAbstractType request, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException, PVP2Exception; /** * Encoder SAML Response * @param req The http request * @param resp The http response - * @param response The repsonse object - * @param targetLocation + * @param response The SAML2 repsonse object + * @param targetLocation URL, where the request should be transmit + * @param relayState token for session handling + * @param credentials Credential to sign the response object * @throws MessageEncodingException * @throws SecurityException */ public void encodeRespone(HttpServletRequest req, - HttpServletResponse resp, StatusResponseType response, String targetLocation, String relayState) + HttpServletResponse resp, StatusResponseType response, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException, PVP2Exception; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index 24bdf4c3c..ebb4b2991 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -46,9 +46,7 @@ import org.opensaml.ws.transport.http.HttpServletRequestAdapter; import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.x509.X509Credential; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import org.opensaml.xml.security.credential.Credential; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; @@ -59,8 +57,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.validation.MOAPVPSignedRequestPolicyRule; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.util.HTTPUtils; @@ -68,18 +64,15 @@ import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -@Service("PVPPostBindingCoder") public class PostBinding implements IDecoder, IEncoder { - - @Autowired private IDPCredentialProvider credentialProvider; - + public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState) + RequestAbstractType request, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException { try { - X509Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); +// X509Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -102,9 +95,9 @@ public class PostBinding implements IDecoder, IEncoder { encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); } catch (Exception e) { e.printStackTrace(); throw new SecurityException(e); @@ -112,12 +105,12 @@ public class PostBinding implements IDecoder, IEncoder { } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState) + StatusResponseType response, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException { try { - X509Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); +// X509Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -143,9 +136,9 @@ public class PostBinding implements IDecoder, IEncoder { context.setRelayState(relayState); encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); } catch (Exception e) { e.printStackTrace(); throw new SecurityException(e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 7167d8b7d..0ff18d903 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -47,9 +47,7 @@ import org.opensaml.ws.transport.http.HttpServletRequestAdapter; import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.x509.X509Credential; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import org.opensaml.xml.security.credential.Credential; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; @@ -60,25 +58,20 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -@Service("PVPRedirectBindingCoder") public class RedirectBinding implements IDecoder, IEncoder { - - @Autowired private IDPCredentialProvider credentialProvider; public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState) + RequestAbstractType request, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException { - try { - X509Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); +// try { +// X509Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -100,18 +93,18 @@ public class RedirectBinding implements IDecoder, IEncoder { context.setRelayState(relayState); encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); - } +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); +// } } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState) - throws MessageEncodingException, SecurityException { - try { - X509Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); + StatusResponseType response, String targetLocation, String relayState, + Credential credentials) throws MessageEncodingException, SecurityException { +// try { +// X509Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -133,10 +126,10 @@ public class RedirectBinding implements IDecoder, IEncoder { context.setRelayState(relayState); encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); - } +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); +// } } public InboundMessageInterface decode(HttpServletRequest req, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index bd60b7a13..cc3553551 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -46,7 +46,6 @@ import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.signature.SignableXMLObject; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; @@ -55,12 +54,10 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -@Service("PVPSOAPBindingCoder") public class SoapBinding implements IDecoder, IEncoder { @Autowired private IDPCredentialProvider credentialProvider; @@ -136,17 +133,17 @@ public class SoapBinding implements IDecoder, IEncoder { } public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState) + RequestAbstractType request, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException, PVP2Exception { } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState) + StatusResponseType response, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException, PVP2Exception { - try { - Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); +// try { +// Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -160,10 +157,10 @@ public class SoapBinding implements IDecoder, IEncoder { context.setOutboundMessageTransport(responseAdapter); encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); - } +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); +// } } public String getSAML2BindingName() { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java deleted file mode 100644 index 0212f8f1c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java +++ /dev/null @@ -1,649 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 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: - * http://www.osor.eu/eupl/ - * - * 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.egovernment.moa.id.protocols.pvp2x.builder; - -import java.io.IOException; -import java.io.StringWriter; -import java.security.PrivateKey; -import java.security.interfaces.RSAPrivateKey; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.joda.time.DateTime; -import org.opensaml.Configuration; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.AttributeConsumingService; -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.EntitiesDescriptor; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.IDPSSODescriptor; -import org.opensaml.saml2.metadata.KeyDescriptor; -import org.opensaml.saml2.metadata.LocalizedString; -import org.opensaml.saml2.metadata.NameIDFormat; -import org.opensaml.saml2.metadata.Organization; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.saml2.metadata.RoleDescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.ServiceName; -import org.opensaml.saml2.metadata.SingleLogoutService; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.xml.io.Marshaller; -import org.opensaml.xml.io.MarshallingException; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.SecurityHelper; -import org.opensaml.xml.security.credential.Credential; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; -import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; -import org.opensaml.xml.signature.Signature; -import org.opensaml.xml.signature.SignatureConstants; -import org.opensaml.xml.signature.SignatureException; -import org.opensaml.xml.signature.Signer; -import org.w3c.dom.Document; - -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ - -public abstract class AbstractPVPMetadataBuilder { - - X509KeyInfoGeneratorFactory keyInfoFactory = null; - - /** - * - */ - public AbstractPVPMetadataBuilder() { - keyInfoFactory = new X509KeyInfoGeneratorFactory(); - keyInfoFactory.setEmitEntityIDAsKeyName(true); - keyInfoFactory.setEmitEntityCertificate(true); - - } - - - /** - * Set metadata valid area - * - * @return valid until in hours [h] - */ - public abstract int getMetadataValidUntil(); - - /** - * Build a SAML2 Entities element as metadata root element - * - * @return true, if the metadata should start with entities element - */ - public abstract boolean buildEntitiesDescriptorAsRootElement(); - - /** - * - * - * @return true, if an IDP SSO-descriptor element should be generated - */ - public abstract boolean buildIDPSSODescriptor(); - - /** - * - * - * @return true, if an SP SSO-descriptor element should be generated - */ - public abstract boolean buildSPSSODescriptor(); - - /** - * Set the PVP entityID for this SAML2 metadata. - * The entityID must be a URL and is public-URL prefix of the server, as minimum. - * If this is null or a empty String, the EntityID is the public-url prefix - * - * @return PVP entityID postfix as String - */ - public abstract String getEntityIDPostfix(); - - /** - * Set a friendlyName for this PVP entity - * - * @return - */ - public abstract String getEntityFriendlyName(); - - /** - * Set the contact information for this metadata entity - * - * @return - */ - public abstract List getContactPersonInformation(); - - /** - * Set organisation information for this metadata entity - * - * @return - */ - public abstract Organization getOrgansiationInformation(); - - - /** - * Set the credential for metadata signing - * - * @return - * @throws CredentialsNotAvailableException - */ - public abstract Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException; - - /** - * Set the credential for request/response signing - * IDP metadata: this credential is used for SAML2 response signing - * SP metadata: this credential is used for SAML2 response signing - * - * @return - * @throws CredentialsNotAvailableException - */ - public abstract Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException; - - /** - * Set the credential for response encryption - * - * @return - * @throws CredentialsNotAvailableException - */ - public abstract Credential getEncryptionCredentials() throws CredentialsNotAvailableException; - - /** - * Set the IDP Post-Binding URL-postfix for WebSSO - * - * @return - */ - public abstract String getIDPWebSSOPostBindingURL(); - - /** - * Set the IDP Redirect-Binding URL-postfix for WebSSO - * - * @return - */ - public abstract String getIDPWebSSORedirectBindingURL(); - - /** - * Set the IDP Post-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getIDPSLOPostBindingURL(); - - /** - * Set the IDP Redirect-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getIDPSLORedirectBindingURL(); - - /** - * Set the SP Post-Binding URL-postfix for for the Assertion-Consumer Service - * - * @return - */ - public abstract String getSPAssertionConsumerServicePostBindingURL(); - - /** - * Set the SP Redirect-Binding URL-postfix for the Assertion-Consumer Service - * - * @return - */ - public abstract String getSPAssertionConsumerServiceRedirectBindingURL(); - - /** - * Set the SP Post-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getSPSLOPostBindingURL(); - - /** - * Set the SP Redirect-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getSPSLORedirectBindingURL(); - - /** - * Set the SP SOAP-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getSPSLOSOAPBindingURL(); - - - /** - * Set all SAML2 attributes which could be provided by this IDP - * - * @return - */ - public abstract List getIDPPossibleAttributes(); - - /** - * Set all nameID types which could be provided by this IDP - * - * @return a List of SAML2 nameID types - */ - public abstract List getIDPPossibleNameITTypes(); - - /** - * Set all SAML2 attributes which are required by the SP - * - * @return - */ - public abstract List getSPRequiredAttributes(); - - /** - * Set all nameID types which allowed from the SP - * - * @return a List of SAML2 nameID types - */ - public abstract List getSPAllowedNameITTypes(); - - /** - * - * Build PVP 2.1 conform SAML2 metadata - * - * @param instancePublicURLPrefix - * Public-URL prefix which should be used to generate URLs. - * The URL String must by without trailing / - * - * @return PVP metadata as XML String - * @throws SecurityException - * @throws ConfigurationException - * @throws CredentialsNotAvailableException - * @throws TransformerFactoryConfigurationError - * @throws MarshallingException - * @throws TransformerException - * @throws ParserConfigurationException - * @throws IOException - * @throws SignatureException - */ - public String buildPVPMetadata(String instancePublicURLPrefix) throws CredentialsNotAvailableException, ConfigurationException, SecurityException, TransformerFactoryConfigurationError, MarshallingException, TransformerException, ParserConfigurationException, IOException, SignatureException { - if (MiscUtil.isEmpty(instancePublicURLPrefix)) { - Logger.error("Metadata generation FAILED! --> PublicURL Prefix is null or empty"); - throw new NullPointerException("PublicURL Prefix is null or empty"); - - } - - //remove trailing slash - if (instancePublicURLPrefix.endsWith("/")) - instancePublicURLPrefix.substring(0, instancePublicURLPrefix.length()-1); - - DateTime date = new DateTime(); - EntityDescriptor entityDescriptor = SAML2Utils - .createSAMLObject(EntityDescriptor.class); - - //set entityID - if (MiscUtil.isNotEmpty(getEntityIDPostfix())) - entityDescriptor.setEntityID(instancePublicURLPrefix + getEntityIDPostfix()); - else - entityDescriptor.setEntityID(instancePublicURLPrefix); - - //set contact and organisation information - List contactPersons = getContactPersonInformation(); - if (contactPersons != null) - entityDescriptor.getContactPersons().addAll(contactPersons); - - Organization organisation = getOrgansiationInformation(); - if (organisation != null) - entityDescriptor.setOrganization(organisation); - - //set IDP metadata - if (buildIDPSSODescriptor()) { - RoleDescriptor idpSSODesc = generateIDPMetadata(instancePublicURLPrefix); - if (idpSSODesc != null) - entityDescriptor.getRoleDescriptors().add(idpSSODesc); - - } - - //set SP metadata for interfederation - if (buildSPSSODescriptor()) { - RoleDescriptor spSSODesc = generateSPMetadata(instancePublicURLPrefix); - if (spSSODesc != null) - entityDescriptor.getRoleDescriptors().add(spSSODesc); - - } - - //set metadata signature parameters - Credential metadataSignCred = getMetadataSigningCredentials(); - Signature signature = getIDPSignature(metadataSignCred); - SecurityHelper.prepareSignatureParams(signature, metadataSignCred, null, null); - - - //initialize XML document builder - DocumentBuilder builder; - DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - - builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - - - //build entities descriptor - if (buildEntitiesDescriptorAsRootElement()) { - EntitiesDescriptor entitiesDescriptor = - SAML2Utils.createSAMLObject(EntitiesDescriptor.class); - entitiesDescriptor.setName(getEntityFriendlyName()); - entitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); - entitiesDescriptor.setValidUntil(date.plusHours(getMetadataValidUntil())); - entitiesDescriptor.getEntityDescriptors().add(entityDescriptor); - - entitiesDescriptor.setSignature(signature); - - //marshall document - Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(entitiesDescriptor); - out.marshall(entitiesDescriptor, document); - - } else { - entityDescriptor.setValidUntil(date.plusHours(getMetadataValidUntil())); - - entityDescriptor.setSignature(signature); - - //marshall document - Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(entityDescriptor); - out.marshall(entityDescriptor, document); - - } - - //sign metadata - Signer.signObject(signature); - - //transform metadata object to XML string - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - - StringWriter sw = new StringWriter(); - StreamResult sr = new StreamResult(sw); - DOMSource source = new DOMSource(document); - transformer.transform(source, sr); - sw.close(); - - return sw.toString(); - } - - - private RoleDescriptor generateSPMetadata(String instancePublicURLPrefix) throws CredentialsNotAvailableException, SecurityException, ConfigurationException { - SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); - spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - spSSODescriptor.setAuthnRequestsSigned(true); - spSSODescriptor.setWantAssertionsSigned(false); - - KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - - //Set AuthRequest Signing certificate - Credential authcredential = getRequestorResponseSigningCredentials(); - if (authcredential == null) { - Logger.warn("SP Metadata generation FAILED! --> Builder has NO request signing-credential. "); - return null; - - } else { - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); - spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - } - - //Set assertion encryption credentials - Credential authEncCredential = getEncryptionCredentials(); - - if (authEncCredential != null) { - KeyDescriptor encryKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - encryKeyDescriptor.setUse(UsageType.ENCRYPTION); - encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); - spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); - - } else { - Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); - - } - - //check nameID formates - if (getSPAllowedNameITTypes() == null || getSPAllowedNameITTypes().size() == 0) { - Logger.warn("SP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); - return null; - - } else { - for (String format : getSPAllowedNameITTypes()) { - NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - nameIDFormat.setFormat(format); - spSSODescriptor.getNameIDFormats().add(nameIDFormat); - - } - } - - - //add POST-Binding assertion consumer services - if (MiscUtil.isNotEmpty(getSPAssertionConsumerServicePostBindingURL())) { - AssertionConsumerService postassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - postassertionConsumerService.setIndex(0); - postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - postassertionConsumerService.setLocation(instancePublicURLPrefix + getSPAssertionConsumerServicePostBindingURL()); - postassertionConsumerService.setIsDefault(true); - spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); - - } - - //add POST-Binding assertion consumer services - if (MiscUtil.isNotEmpty(getSPAssertionConsumerServiceRedirectBindingURL())) { - AssertionConsumerService redirectassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - redirectassertionConsumerService.setIndex(1); - redirectassertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - redirectassertionConsumerService.setLocation(instancePublicURLPrefix + getSPAssertionConsumerServiceRedirectBindingURL()); - spSSODescriptor.getAssertionConsumerServices().add(redirectassertionConsumerService); - - } - - //validate WebSSO endpoints - if (spSSODescriptor.getAssertionConsumerServices().size() == 0) { - Logger.warn("SP Metadata generation FAILED! --> NO SAML2 AssertionConsumerService endpoint found. "); - return null; - - } - - //add POST-Binding SLO descriptor - if (MiscUtil.isNotEmpty(getSPSLOPostBindingURL())) { - SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - postSLOService.setLocation(instancePublicURLPrefix + getSPSLOPostBindingURL()); - postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(postSLOService); - - } - - //add POST-Binding SLO descriptor - if (MiscUtil.isNotEmpty(getSPSLORedirectBindingURL())) { - SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(instancePublicURLPrefix + getSPSLORedirectBindingURL()); - redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(redirectSLOService); - - } - - //add POST-Binding SLO descriptor - if (MiscUtil.isNotEmpty(getSPSLOSOAPBindingURL())) { - SingleLogoutService soapSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - soapSLOService.setLocation(instancePublicURLPrefix + getSPSLOSOAPBindingURL()); - soapSLOService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(soapSLOService); - - } - - - //add required attributes - List reqSPAttr = getSPRequiredAttributes(); - AttributeConsumingService attributeService = SAML2Utils.createSAMLObject(AttributeConsumingService.class); - - attributeService.setIndex(0); - attributeService.setIsDefault(true); - ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); - serviceName.setName(new LocalizedString("Default Service", "en")); - attributeService.getNames().add(serviceName); - - if (reqSPAttr != null && reqSPAttr.size() > 0) { - Logger.debug("Add " + reqSPAttr.size() + " attributes to SP metadata"); - attributeService.getRequestAttributes().addAll(reqSPAttr); - - } else { - Logger.debug("SP metadata contains NO requested attributes."); - - } - - spSSODescriptor.getAttributeConsumingServices().add(attributeService); - - return spSSODescriptor; - } - - private IDPSSODescriptor generateIDPMetadata(String instancePublicURLPrefix) throws ConfigurationException, CredentialsNotAvailableException, SecurityException { - //check response signing credential - Credential responseSignCred = getRequestorResponseSigningCredentials(); - if (responseSignCred == null) { - Logger.warn("IDP Metadata generation FAILED! --> Builder has NO Response signing credential. "); - return null; - - } - - //check nameID formates - if (getIDPPossibleNameITTypes() == null || getIDPPossibleNameITTypes().size() == 0) { - Logger.warn("IDP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); - return null; - - } - - // build SAML2 IDP-SSO descriptor element - IDPSSODescriptor idpSSODescriptor = SAML2Utils - .createSAMLObject(IDPSSODescriptor.class); - - idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - - //set ass default value, because PVP 2.x specification defines this feature as MUST - idpSSODescriptor.setWantAuthnRequestsSigned(true); - - // add WebSSO descriptor for POST-Binding - if (MiscUtil.isNotEmpty(getIDPWebSSOPostBindingURL())) { - SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); - postSingleSignOnService.setLocation(instancePublicURLPrefix + getIDPWebSSOPostBindingURL()); - postSingleSignOnService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); - - } - - // add WebSSO descriptor for Redirect-Binding - if (MiscUtil.isNotEmpty(getIDPWebSSORedirectBindingURL())) { - SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); - postSingleSignOnService.setLocation(instancePublicURLPrefix + getIDPWebSSORedirectBindingURL()); - postSingleSignOnService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); - - } - - //add Single LogOut POST-Binding endpoing - if (MiscUtil.isNotEmpty(getIDPSLOPostBindingURL())) { - SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - postSLOService.setLocation(instancePublicURLPrefix + getIDPSLOPostBindingURL()); - postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - idpSSODescriptor.getSingleLogoutServices().add(postSLOService); - - } - - //add Single LogOut Redirect-Binding endpoing - if (MiscUtil.isNotEmpty(getIDPSLORedirectBindingURL())) { - SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(instancePublicURLPrefix + getIDPSLORedirectBindingURL()); - redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleLogoutServices().add(redirectSLOService); - - } - - //validate WebSSO endpoints - if (idpSSODescriptor.getSingleSignOnServices().size() == 0) { - Logger.warn("IDP Metadata generation FAILED! --> NO SAML2 SingleSignOnService endpoint found. "); - return null; - - } - - //set assertion signing key - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(getRequestorResponseSigningCredentials())); - idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - //set IDP attribute set - idpSSODescriptor.getAttributes().addAll(getIDPPossibleAttributes()); - - //set providable nameID formats - for (String format : getIDPPossibleNameITTypes()) { - NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - nameIDFormat.setFormat(format); - idpSSODescriptor.getNameIDFormats().add(nameIDFormat); - - } - - return idpSSODescriptor; - - } - - private Signature getIDPSignature(Credential credentials) { - PrivateKey privatekey = credentials.getPrivateKey(); - Signature signer = SAML2Utils.createSAMLObject(Signature.class); - - if (privatekey instanceof RSAPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); - - } else if (privatekey instanceof iaik.security.ecc.ecdsa.ECPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); - - } else { - Logger.warn("Could NOT evaluate the Private-Key type from " + credentials.getEntityId() + " credential."); - - - } - - signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); - signer.setSigningCredential(credentials); - return signer; - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java new file mode 100644 index 000000000..3418ffb69 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java @@ -0,0 +1,460 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 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: + * http://www.osor.eu/eupl/ + * + * 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.egovernment.moa.id.protocols.pvp2x.builder; + +import java.io.IOException; +import java.io.StringWriter; +import java.security.PrivateKey; +import java.security.interfaces.RSAPrivateKey; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.joda.time.DateTime; +import org.opensaml.Configuration; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.saml2.metadata.SingleLogoutService; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; +import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.signature.SignatureConstants; +import org.opensaml.xml.signature.SignatureException; +import org.opensaml.xml.signature.Signer; +import org.springframework.stereotype.Service; +import org.w3c.dom.Document; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ + +@Service("PVPMetadataBuilder") +public class PVPMetadataBuilder { + + X509KeyInfoGeneratorFactory keyInfoFactory = null; + + /** + * + */ + public PVPMetadataBuilder() { + keyInfoFactory = new X509KeyInfoGeneratorFactory(); + keyInfoFactory.setEmitEntityIDAsKeyName(true); + keyInfoFactory.setEmitEntityCertificate(true); + + } + + + /** + * + * Build PVP 2.1 conform SAML2 metadata + * + * @param config + * PVPMetadataBuilder configuration + * + * @return PVP metadata as XML String + * @throws SecurityException + * @throws ConfigurationException + * @throws CredentialsNotAvailableException + * @throws TransformerFactoryConfigurationError + * @throws MarshallingException + * @throws TransformerException + * @throws ParserConfigurationException + * @throws IOException + * @throws SignatureException + */ + public String buildPVPMetadata(IPVPMetadataBuilderConfiguration config) throws CredentialsNotAvailableException, ConfigurationException, SecurityException, TransformerFactoryConfigurationError, MarshallingException, TransformerException, ParserConfigurationException, IOException, SignatureException { + DateTime date = new DateTime(); + EntityDescriptor entityDescriptor = SAML2Utils + .createSAMLObject(EntityDescriptor.class); + + //set entityID + entityDescriptor.setEntityID(config.getEntityID()); + + //set contact and organisation information + List contactPersons = config.getContactPersonInformation(); + if (contactPersons != null) + entityDescriptor.getContactPersons().addAll(contactPersons); + + Organization organisation = config.getOrgansiationInformation(); + if (organisation != null) + entityDescriptor.setOrganization(organisation); + + //set IDP metadata + if (config.buildIDPSSODescriptor()) { + RoleDescriptor idpSSODesc = generateIDPMetadata(config); + if (idpSSODesc != null) + entityDescriptor.getRoleDescriptors().add(idpSSODesc); + + } + + //set SP metadata for interfederation + if (config.buildSPSSODescriptor()) { + RoleDescriptor spSSODesc = generateSPMetadata(config); + if (spSSODesc != null) + entityDescriptor.getRoleDescriptors().add(spSSODesc); + + } + + //set metadata signature parameters + Credential metadataSignCred = config.getMetadataSigningCredentials(); + Signature signature = getIDPSignature(metadataSignCred); + SecurityHelper.prepareSignatureParams(signature, metadataSignCred, null, null); + + + //initialize XML document builder + DocumentBuilder builder; + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + + builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + + + //build entities descriptor + if (config.buildEntitiesDescriptorAsRootElement()) { + EntitiesDescriptor entitiesDescriptor = + SAML2Utils.createSAMLObject(EntitiesDescriptor.class); + entitiesDescriptor.setName(config.getEntityFriendlyName()); + entitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); + entitiesDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); + entitiesDescriptor.getEntityDescriptors().add(entityDescriptor); + + entitiesDescriptor.setSignature(signature); + + //marshall document + Marshaller out = Configuration.getMarshallerFactory() + .getMarshaller(entitiesDescriptor); + out.marshall(entitiesDescriptor, document); + + } else { + entityDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); + + entityDescriptor.setSignature(signature); + + //marshall document + Marshaller out = Configuration.getMarshallerFactory() + .getMarshaller(entityDescriptor); + out.marshall(entityDescriptor, document); + + } + + //sign metadata + Signer.signObject(signature); + + //transform metadata object to XML string + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); + + StringWriter sw = new StringWriter(); + StreamResult sr = new StreamResult(sw); + DOMSource source = new DOMSource(document); + transformer.transform(source, sr); + sw.close(); + + return sw.toString(); + } + + + private RoleDescriptor generateSPMetadata(IPVPMetadataBuilderConfiguration config) throws CredentialsNotAvailableException, SecurityException, ConfigurationException { + SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); + spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + spSSODescriptor.setAuthnRequestsSigned(true); + spSSODescriptor.setWantAssertionsSigned(false); + + KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); + + //Set AuthRequest Signing certificate + Credential authcredential = config.getRequestorResponseSigningCredentials(); + if (authcredential == null) { + Logger.warn("SP Metadata generation FAILED! --> Builder has NO request signing-credential. "); + return null; + + } else { + KeyDescriptor signKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + signKeyDescriptor.setUse(UsageType.SIGNING); + signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); + spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); + + } + + //Set assertion encryption credentials + Credential authEncCredential = config.getEncryptionCredentials(); + + if (authEncCredential != null) { + KeyDescriptor encryKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + encryKeyDescriptor.setUse(UsageType.ENCRYPTION); + encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); + spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); + + } else { + Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); + + } + + //check nameID formates + if (config.getSPAllowedNameITTypes() == null || config.getSPAllowedNameITTypes().size() == 0) { + Logger.warn("SP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); + return null; + + } else { + for (String format : config.getSPAllowedNameITTypes()) { + NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); + nameIDFormat.setFormat(format); + spSSODescriptor.getNameIDFormats().add(nameIDFormat); + + } + } + + + //add POST-Binding assertion consumer services + if (MiscUtil.isNotEmpty(config.getSPAssertionConsumerServicePostBindingURL())) { + AssertionConsumerService postassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); + postassertionConsumerService.setIndex(0); + postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + postassertionConsumerService.setLocation(config.getSPAssertionConsumerServicePostBindingURL()); + postassertionConsumerService.setIsDefault(true); + spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); + + } + + //add POST-Binding assertion consumer services + if (MiscUtil.isNotEmpty(config.getSPAssertionConsumerServiceRedirectBindingURL())) { + AssertionConsumerService redirectassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); + redirectassertionConsumerService.setIndex(1); + redirectassertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + redirectassertionConsumerService.setLocation(config.getSPAssertionConsumerServiceRedirectBindingURL()); + spSSODescriptor.getAssertionConsumerServices().add(redirectassertionConsumerService); + + } + + //validate WebSSO endpoints + if (spSSODescriptor.getAssertionConsumerServices().size() == 0) { + Logger.warn("SP Metadata generation FAILED! --> NO SAML2 AssertionConsumerService endpoint found. "); + return null; + + } + + //add POST-Binding SLO descriptor + if (MiscUtil.isNotEmpty(config.getSPSLOPostBindingURL())) { + SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + postSLOService.setLocation(config.getSPSLOPostBindingURL()); + postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + spSSODescriptor.getSingleLogoutServices().add(postSLOService); + + } + + //add POST-Binding SLO descriptor + if (MiscUtil.isNotEmpty(config.getSPSLORedirectBindingURL())) { + SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + redirectSLOService.setLocation(config.getSPSLORedirectBindingURL()); + redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + spSSODescriptor.getSingleLogoutServices().add(redirectSLOService); + + } + + //add POST-Binding SLO descriptor + if (MiscUtil.isNotEmpty(config.getSPSLOSOAPBindingURL())) { + SingleLogoutService soapSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + soapSLOService.setLocation(config.getSPSLOSOAPBindingURL()); + soapSLOService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); + spSSODescriptor.getSingleLogoutServices().add(soapSLOService); + + } + + + //add required attributes + List reqSPAttr = config.getSPRequiredAttributes(); + AttributeConsumingService attributeService = SAML2Utils.createSAMLObject(AttributeConsumingService.class); + + attributeService.setIndex(0); + attributeService.setIsDefault(true); + ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); + serviceName.setName(new LocalizedString("Default Service", "en")); + attributeService.getNames().add(serviceName); + + if (reqSPAttr != null && reqSPAttr.size() > 0) { + Logger.debug("Add " + reqSPAttr.size() + " attributes to SP metadata"); + attributeService.getRequestAttributes().addAll(reqSPAttr); + + } else { + Logger.debug("SP metadata contains NO requested attributes."); + + } + + spSSODescriptor.getAttributeConsumingServices().add(attributeService); + + return spSSODescriptor; + } + + private IDPSSODescriptor generateIDPMetadata(IPVPMetadataBuilderConfiguration config) throws ConfigurationException, CredentialsNotAvailableException, SecurityException { + //check response signing credential + Credential responseSignCred = config.getRequestorResponseSigningCredentials(); + if (responseSignCred == null) { + Logger.warn("IDP Metadata generation FAILED! --> Builder has NO Response signing credential. "); + return null; + + } + + //check nameID formates + if (config.getIDPPossibleNameITTypes() == null || config.getIDPPossibleNameITTypes().size() == 0) { + Logger.warn("IDP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); + return null; + + } + + // build SAML2 IDP-SSO descriptor element + IDPSSODescriptor idpSSODescriptor = SAML2Utils + .createSAMLObject(IDPSSODescriptor.class); + + idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + + //set ass default value, because PVP 2.x specification defines this feature as MUST + idpSSODescriptor.setWantAuthnRequestsSigned(true); + + // add WebSSO descriptor for POST-Binding + if (MiscUtil.isNotEmpty(config.getIDPWebSSOPostBindingURL())) { + SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); + postSingleSignOnService.setLocation(config.getIDPWebSSOPostBindingURL()); + postSingleSignOnService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); + + } + + // add WebSSO descriptor for Redirect-Binding + if (MiscUtil.isNotEmpty(config.getIDPWebSSORedirectBindingURL())) { + SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); + postSingleSignOnService.setLocation(config.getIDPWebSSORedirectBindingURL()); + postSingleSignOnService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); + + } + + //add Single LogOut POST-Binding endpoing + if (MiscUtil.isNotEmpty(config.getIDPSLOPostBindingURL())) { + SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + postSLOService.setLocation(config.getIDPSLOPostBindingURL()); + postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + idpSSODescriptor.getSingleLogoutServices().add(postSLOService); + + } + + //add Single LogOut Redirect-Binding endpoing + if (MiscUtil.isNotEmpty(config.getIDPSLORedirectBindingURL())) { + SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + redirectSLOService.setLocation(config.getIDPSLORedirectBindingURL()); + redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + idpSSODescriptor.getSingleLogoutServices().add(redirectSLOService); + + } + + //validate WebSSO endpoints + if (idpSSODescriptor.getSingleSignOnServices().size() == 0) { + Logger.warn("IDP Metadata generation FAILED! --> NO SAML2 SingleSignOnService endpoint found. "); + return null; + + } + + //set assertion signing key + KeyDescriptor signKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + signKeyDescriptor.setUse(UsageType.SIGNING); + KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); + signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(config.getRequestorResponseSigningCredentials())); + idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); + + //set IDP attribute set + idpSSODescriptor.getAttributes().addAll(config.getIDPPossibleAttributes()); + + //set providable nameID formats + for (String format : config.getIDPPossibleNameITTypes()) { + NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); + nameIDFormat.setFormat(format); + idpSSODescriptor.getNameIDFormats().add(nameIDFormat); + + } + + return idpSSODescriptor; + + } + + private Signature getIDPSignature(Credential credentials) { + PrivateKey privatekey = credentials.getPrivateKey(); + Signature signer = SAML2Utils.createSAMLObject(Signature.class); + + if (privatekey instanceof RSAPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); + + } else if (privatekey instanceof iaik.security.ecc.ecdsa.ECPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); + + } else { + Logger.warn("Could NOT evaluate the Private-Key type from " + credentials.getEntityId() + " credential."); + + + } + + signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); + signer.setSigningCredential(credentials); + return signer; + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java index 959fc7d2d..a7fc8295a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java @@ -201,7 +201,8 @@ public class SingleLogOutBuilder { try { binding.encodeRespone(req, resp, sloResp, - consumerService.getLocation(), relayState); + consumerService.getLocation(), relayState, + credentialProvider.getIDPAssertionSigningCredential()); } catch (MessageEncodingException e) { Logger.error("Message Encoding exception", e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java new file mode 100644 index 000000000..e0994ff19 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java @@ -0,0 +1,288 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 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: + * http://www.osor.eu/eupl/ + * + * 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.egovernment.moa.id.protocols.pvp2x.config; + +import java.util.Arrays; +import java.util.List; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.security.credential.Credential; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfiguration { + + private static final int VALIDUNTIL_IN_HOURS = 24; + + private String authURL; + private IDPCredentialProvider credentialProvider; + + public IDPPVPMetadataConfiguration(String authURL, IDPCredentialProvider credentialProvider) { + this.authURL = authURL; + this.credentialProvider = credentialProvider; + + } + + public String getDefaultActionName() { + return (PVP2XProtocol.METADATA); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataValidUntil() + */ + @Override + public int getMetadataValidUntil() { + return VALIDUNTIL_IN_HOURS; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildEntitiesDescriptorAsRootElement() + */ + @Override + public boolean buildEntitiesDescriptorAsRootElement() { + return true; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildIDPSSODescriptor() + */ + @Override + public boolean buildIDPSSODescriptor() { + return true; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildSPSSODescriptor() + */ + @Override + public boolean buildSPSSODescriptor() { + return false; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityID() + */ + @Override + public String getEntityID() { + return authURL; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityFriendlyName() + */ + @Override + public String getEntityFriendlyName() { + try { + return PVPConfiguration.getInstance().getIDPIssuerName(); + + } catch (ConfigurationException e) { + Logger.error("Can not load Metadata entry: EntityID friendlyName.", e); + return null; + + } + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getContactPersonInformation() + */ + @Override + public List getContactPersonInformation() { + try { + return PVPConfiguration.getInstance().getIDPContacts(); + + } catch (ConfigurationException e) { + Logger.warn("Can not load Metadata entry: Contect Person", e); + return null; + + } + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getOrgansiationInformation() + */ + @Override + public Organization getOrgansiationInformation() { + try { + return PVPConfiguration.getInstance().getIDPOrganisation(); + + } catch (ConfigurationException e) { + Logger.warn("Can not load Metadata entry: Organisation", e); + return null; + + } + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataSigningCredentials() + */ + @Override + public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPMetaDataSigningCredential(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getRequestorResponseSigningCredentials() + */ + @Override + public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPAssertionSigningCredential(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEncryptionCredentials() + */ + @Override + public Credential getEncryptionCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPAssertionEncryptionCredential(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSOPostBindingURL() + */ + @Override + public String getIDPWebSSOPostBindingURL() { + return authURL + PVPConfiguration.PVP2_IDP_POST; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSORedirectBindingURL() + */ + @Override + public String getIDPWebSSORedirectBindingURL() { + return authURL + PVPConfiguration.PVP2_IDP_REDIRECT; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLOPostBindingURL() + */ + @Override + public String getIDPSLOPostBindingURL() { + return authURL + PVPConfiguration.PVP2_IDP_POST; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLORedirectBindingURL() + */ + @Override + public String getIDPSLORedirectBindingURL() { + return authURL + PVPConfiguration.PVP2_IDP_REDIRECT; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServicePostBindingURL() + */ + @Override + public String getSPAssertionConsumerServicePostBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServiceRedirectBindingURL() + */ + @Override + public String getSPAssertionConsumerServiceRedirectBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOPostBindingURL() + */ + @Override + public String getSPSLOPostBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLORedirectBindingURL() + */ + @Override + public String getSPSLORedirectBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOSOAPBindingURL() + */ + @Override + public String getSPSLOSOAPBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleAttributes() + */ + @Override + public List getIDPPossibleAttributes() { + return PVPAttributeBuilder.buildSupportedEmptyAttributes(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleNameITTypes() + */ + @Override + public List getIDPPossibleNameITTypes() { + return Arrays.asList(NameIDType.PERSISTENT, + NameIDType.TRANSIENT, + NameIDType.UNSPECIFIED); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPRequiredAttributes() + */ + @Override + public List getSPRequiredAttributes() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAllowedNameITTypes() + */ + @Override + public List getSPAllowedNameITTypes() { + return null; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java new file mode 100644 index 000000000..52096fd19 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java @@ -0,0 +1,217 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 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: + * http://www.osor.eu/eupl/ + * + * 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.egovernment.moa.id.protocols.pvp2x.config; + +import java.util.List; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.security.credential.Credential; + +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; + +/** + * @author tlenz + * + */ +public interface IPVPMetadataBuilderConfiguration { + + + /** + * Set metadata valid area + * + * @return valid until in hours [h] + */ + public int getMetadataValidUntil(); + + /** + * Build a SAML2 Entities element as metadata root element + * + * @return true, if the metadata should start with entities element + */ + public boolean buildEntitiesDescriptorAsRootElement(); + + /** + * + * + * @return true, if an IDP SSO-descriptor element should be generated + */ + public boolean buildIDPSSODescriptor(); + + /** + * + * + * @return true, if an SP SSO-descriptor element should be generated + */ + public boolean buildSPSSODescriptor(); + + /** + * Set the PVP entityID for this SAML2 metadata. + * The entityID must be an URL and must be start with the public-URL prefix of the server + * + * @return PVP entityID postfix as String + */ + public String getEntityID(); + + /** + * Set a friendlyName for this PVP entity + * + * @return + */ + public String getEntityFriendlyName(); + + /** + * Set the contact information for this metadata entity + * + * @return + */ + public List getContactPersonInformation(); + + /** + * Set organisation information for this metadata entity + * + * @return + */ + public Organization getOrgansiationInformation(); + + + /** + * Set the credential for metadata signing + * + * @return + * @throws CredentialsNotAvailableException + */ + public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException; + + /** + * Set the credential for request/response signing + * IDP metadata: this credential is used for SAML2 response signing + * SP metadata: this credential is used for SAML2 response signing + * + * @return + * @throws CredentialsNotAvailableException + */ + public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException; + + /** + * Set the credential for response encryption + * + * @return + * @throws CredentialsNotAvailableException + */ + public Credential getEncryptionCredentials() throws CredentialsNotAvailableException; + + /** + * Set the IDP Post-Binding URL for WebSSO + * + * @return + */ + public String getIDPWebSSOPostBindingURL(); + + /** + * Set the IDP Redirect-Binding URL for WebSSO + * + * @return + */ + public String getIDPWebSSORedirectBindingURL(); + + /** + * Set the IDP Post-Binding URL for Single LogOut + * + * @return + */ + public String getIDPSLOPostBindingURL(); + + /** + * Set the IDP Redirect-Binding URL for Single LogOut + * + * @return + */ + public String getIDPSLORedirectBindingURL(); + + /** + * Set the SP Post-Binding URL for for the Assertion-Consumer Service + * + * @return + */ + public String getSPAssertionConsumerServicePostBindingURL(); + + /** + * Set the SP Redirect-Binding URL for the Assertion-Consumer Service + * + * @return + */ + public String getSPAssertionConsumerServiceRedirectBindingURL(); + + /** + * Set the SP Post-Binding URL for Single LogOut + * + * @return + */ + public String getSPSLOPostBindingURL(); + + /** + * Set the SP Redirect-Binding URL for Single LogOut + * + * @return + */ + public String getSPSLORedirectBindingURL(); + + /** + * Set the SP SOAP-Binding URL for Single LogOut + * + * @return + */ + public String getSPSLOSOAPBindingURL(); + + + /** + * Set all SAML2 attributes which could be provided by this IDP + * + * @return + */ + public List getIDPPossibleAttributes(); + + /** + * Set all nameID types which could be provided by this IDP + * + * @return a List of SAML2 nameID types + */ + public List getIDPPossibleNameITTypes(); + + /** + * Set all SAML2 attributes which are required by the SP + * + * @return + */ + public List getSPRequiredAttributes(); + + /** + * Set all nameID types which allowed from the SP + * + * @return a List of SAML2 nameID types + */ + public List getSPAllowedNameITTypes(); +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index f7e753273..5e44c9057 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -22,29 +22,50 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.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 org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.common.xml.SAMLSchemaBuilder; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.EncryptedAssertion; import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.core.StatusCode; import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.saml2.encryption.Decrypter; +import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; 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.encryption.ChainingEncryptedKeyResolver; +import org.opensaml.xml.encryption.DecryptionException; +import org.opensaml.xml.encryption.InlineEncryptedKeyResolver; +import org.opensaml.xml.encryption.SimpleRetrievalMethodEncryptedKeyResolver; import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.credential.Credential; 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.security.keyinfo.StaticKeyInfoCredentialResolver; import org.opensaml.xml.signature.SignatureTrustEngine; import org.opensaml.xml.validation.ValidationException; +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.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; @@ -53,8 +74,11 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@Service("SAMLVerificationEngine") public class SAMLVerificationEngine { + @Autowired AuthConfiguration authConfig; + public void verify(InboundMessage msg, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { try { if (msg instanceof MOARequest && @@ -158,116 +182,110 @@ public class SAMLVerificationEngine { } } -// public static void validateAssertion(Response samlResp, boolean validateDestination) throws AssertionValidationExeption { -// try { -// if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { -// List saml2assertions = new ArrayList(); -// -// List allowedPublicURLPrefix = -// AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); -// boolean isValidDestination = false; -// for (String allowedPreFix : allowedPublicURLPrefix) { -// if (validateDestination && samlResp.getDestination().startsWith( -// allowedPreFix)) { -// isValidDestination = true; -// break; -// -// } -// } -// if (!isValidDestination && validateDestination) { -// Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); -// throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); -// -// } -// -// //check encrypted Assertion -// List encryAssertionList = samlResp.getEncryptedAssertions(); -// if (encryAssertionList != null && encryAssertionList.size() > 0) { -// //decrypt assertions -// -// Logger.debug("Found encryped assertion. Start decryption ..."); -// -// X509Credential authDecCredential = CredentialProvider.getIDPAssertionEncryptionCredential(); -// -// StaticKeyInfoCredentialResolver skicr = -// new StaticKeyInfoCredentialResolver(authDecCredential); -// -// ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); -// encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); -// encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); -// encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); -// -// Decrypter samlDecrypter = -// new Decrypter(null, skicr, encryptedKeyResolver); -// -// for (EncryptedAssertion encAssertion : encryAssertionList) { -// saml2assertions.add(samlDecrypter.decrypt(encAssertion)); -// -// } -// -// Logger.debug("Assertion decryption finished. "); -// -// } else { -// saml2assertions.addAll(samlResp.getAssertions()); -// -// } -// -// List validatedassertions = new ArrayList(); -// for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { -// -// try { -// performSchemaValidation(saml2assertion.getDOM()); -// -// Conditions conditions = saml2assertion.getConditions(); -// DateTime notbefore = conditions.getNotBefore().minusMinutes(5); -// DateTime notafter = conditions.getNotOnOrAfter(); -// if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { -// Logger.warn("PVP2 Assertion is out of Date. " -// + "{ Current : " + new DateTime() -// + " NotBefore: " + notbefore -// + " NotAfter : " + notafter -// + " }");; -// -// } else { -// validatedassertions.add(saml2assertion); -// -// } -// -// } catch (SchemaValidationException e) { -// -// } -// } -// -// if (validatedassertions.isEmpty()) { -// Logger.info("No valid PVP 2.1 assertion received."); -// throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); -// } -// -// samlResp.getAssertions().clear(); -// samlResp.getEncryptedAssertions().clear(); -// samlResp.getAssertions().addAll(validatedassertions); -// -// } else { -// Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " -// + samlResp.getStatus().getStatusCode().getValue()); -// throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " -// + samlResp.getStatus().getStatusCode().getValue(), null); -// } -// -// } catch (CredentialsNotAvailableException e) { -// Logger.warn("Assertion decrypt FAILED - No Credentials", e); -// throw new AssertionValidationExeption("Assertion decrypt FAILED - No Credentials", null, e); -// -// } catch (DecryptionException e) { -// Logger.warn("Assertion decrypt FAILED.", e); -// throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); -// -// } catch (ConfigurationException e) { -// throw new AssertionValidationExeption("pvp.12", null, e); -// } -// } + public void validateAssertion(Response samlResp, boolean validateDestination, Credential assertionDecryption) throws AssertionValidationExeption { + try { + if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { + List saml2assertions = new ArrayList(); + + //validate destination URL + List allowedPublicURLPrefix = authConfig.getPublicURLPrefix(); + boolean isValidDestination = false; + for (String allowedPreFix : allowedPublicURLPrefix) { + if (validateDestination && samlResp.getDestination().startsWith( + allowedPreFix)) { + isValidDestination = true; + break; + + } + } + if (!isValidDestination && validateDestination) { + Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); + throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); + + } + + //check encrypted Assertion + List encryAssertionList = samlResp.getEncryptedAssertions(); + if (encryAssertionList != null && encryAssertionList.size() > 0) { + //decrypt assertions + + Logger.debug("Found encryped assertion. Start decryption ..."); + + StaticKeyInfoCredentialResolver skicr = + new StaticKeyInfoCredentialResolver(assertionDecryption); + + ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); + encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); + encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); + encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); + + Decrypter samlDecrypter = + new Decrypter(null, skicr, encryptedKeyResolver); + + for (EncryptedAssertion encAssertion : encryAssertionList) { + saml2assertions.add(samlDecrypter.decrypt(encAssertion)); + + } + + Logger.debug("Assertion decryption finished. "); + + } else { + saml2assertions.addAll(samlResp.getAssertions()); + + } + + List validatedassertions = new ArrayList(); + for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { + + try { + performSchemaValidation(saml2assertion.getDOM()); + + Conditions conditions = saml2assertion.getConditions(); + DateTime notbefore = conditions.getNotBefore().minusMinutes(5); + DateTime notafter = conditions.getNotOnOrAfter(); + if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { + Logger.warn("PVP2 Assertion is out of Date. " + + "{ Current : " + new DateTime() + + " NotBefore: " + notbefore + + " NotAfter : " + notafter + + " }");; + + } else { + validatedassertions.add(saml2assertion); + + } + + } catch (SchemaValidationException e) { + + } + } + + if (validatedassertions.isEmpty()) { + Logger.info("No valid PVP 2.1 assertion received."); + throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); + } + + samlResp.getAssertions().clear(); + samlResp.getEncryptedAssertions().clear(); + samlResp.getAssertions().addAll(validatedassertions); + + } else { + Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " + + samlResp.getStatus().getStatusCode().getValue()); + throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " + + samlResp.getStatus().getStatusCode().getValue(), null); + } + + } catch (DecryptionException e) { + Logger.warn("Assertion decrypt FAILED.", e); + throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); + + } catch (ConfigurationException e) { + throw new AssertionValidationExeption("pvp.12", null, e); + } + } - private static void performSchemaValidation(Element source) throws SchemaValidationException { + private void performSchemaValidation(Element source) throws SchemaValidationException { String err = null; try { -- cgit v1.2.3