From b9937af42fdab6b85aa1121148bda474c70f5e75 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 8 Mar 2016 11:10:19 +0100 Subject: finish first beta-version of ELGA mandate-service client-module --- id/server/auth/pom.xml | 11 +- id/server/idserverlib/pom.xml | 17 +- .../id/advancedlogging/MOAIDEventConstants.java | 6 +- .../moa/id/advancedlogging/StatisticLogger.java | 13 +- .../moa/id/auth/MOAIDAuthConstants.java | 4 + .../moa/id/auth/MOAIDAuthInitializer.java | 166 ++ .../id/auth/builder/AuthenticationDataBuilder.java | 1652 ++++++++++---------- .../moa/id/auth/builder/BPKBuilder.java | 97 +- .../AuthenticationSessionStorageConstants.java | 2 + .../StartAuthentificationParameterParser.java | 24 +- .../moa/id/data/AuthenticationData.java | 76 +- .../at/gv/egovernment/moa/id/data/IAuthData.java | 4 +- .../at/gv/egovernment/moa/id/data/MISMandate.java | 26 +- .../java/at/gv/egovernment/moa/id/data/Trible.java | 51 + .../moa/id/moduls/AuthenticationManager.java | 4 +- .../gv/egovernment/moa/id/moduls/RequestImpl.java | 5 +- .../attributes/BirthdateAttributeBuilder.java | 1 - .../protocols/builder/attributes/EIDSourcePIN.java | 1 - .../MandateFullMandateAttributeBuilder.java | 5 +- ...dateNaturalPersonGivenNameAttributeBuilder.java | 2 +- .../id/protocols/pvp2x/AttributQueryAction.java | 212 ++- .../id/protocols/pvp2x/AuthenticationAction.java | 15 +- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 22 +- .../moa/id/protocols/pvp2x/binding/IDecoder.java | 3 +- .../id/protocols/pvp2x/binding/PostBinding.java | 29 +- .../protocols/pvp2x/binding/RedirectBinding.java | 26 +- .../id/protocols/pvp2x/binding/SoapBinding.java | 3 +- .../pvp2x/builder/AuthResponseBuilder.java | 19 +- .../pvp2x/builder/PVPAttributeBuilder.java | 49 + .../pvp2x/builder/PVPAuthnRequestBuilder.java | 15 +- .../builder/assertion/PVP2AssertionBuilder.java | 167 +- .../IPVPAuthnRequestBuilderConfiguruation.java | 17 + .../protocols/pvp2x/config/PVPConfiguration.java | 21 +- .../metadata/IMOARefreshableMetadataProvider.java | 38 + .../pvp2x/metadata/MOAMetadataProvider.java | 3 +- .../pvp2x/utils/AssertionAttributeExtractor.java | 92 +- .../AbstractRequestSignedSecurityPolicyRule.java | 4 +- .../validation/MOAPVPSignedRequestPolicyRule.java | 17 +- .../pvp2x/verification/SAMLVerificationEngine.java | 129 +- .../verification/SAMLVerificationEngineSP.java | 161 ++ .../storage/DBAuthenticationSessionStoreage.java | 5 - .../resources/properties/id_messages_de.properties | 6 +- .../protocol_response_statuscodes_de.properties | 5 + .../id/commons/db/dao/session/OASessionStore.java | 24 +- .../internal/tasks/CertificateReadRequestTask.java | 2 +- .../tasks/InitializeBKUAuthenticationTask.java | 180 ++- .../internal/tasks/VerifyCertificateTask.java | 2 +- .../id/util/client/mis/simple/MISSimpleClient.java | 2 - .../internal/DefaultAuthentication.process.xml | 2 +- .../moa/id/auth/modules/eidas/Constants.java | 2 - .../eidas/tasks/ReceiveAuthnResponseTask.java | 4 + .../moa/id/protocols/eidas/EIDASProtocol.java | 3 +- .../eidas/eIDASAuthenticationRequest.java | 6 +- .../ELGAMandatesRequestBuilderConfiguration.java | 40 +- .../tasks/ELGAInitializeBKUAuthenticationTask.java | 107 ++ .../tasks/ReceiveElgaMandateResponseTask.java | 65 +- .../elgamandates/tasks/RequestELGAMandateTask.java | 15 +- .../utils/ELGAMandateServiceMetadataProvider.java | 5 +- .../DefaultAuth_with_ELGA_mandates.process.xml | 8 +- .../moaid_elga_mandate_client_auth.beans.xml | 4 + id/server/modules/moa-id-module-openID/pom.xml | 6 - .../data/SSOTransferAuthenticationData.java | 20 +- .../ssotransfer/utils/SSOContainerUtils.java | 4 +- .../src/test/java/at/gv/egiz/tests/Tests.java | 19 +- .../FederatedAuthnRequestBuilderConfiguration.java | 17 +- .../tasks/ReceiveAuthnResponseTask.java | 94 +- .../protocols/saml1/SAML1AuthenticationServer.java | 280 ++-- .../moa/id/protocols/saml1/SAML1Protocol.java | 11 +- .../moa/id/protocols/saml1/SAML1RequestImpl.java | 19 +- id/server/pom.xml | 5 +- 70 files changed, 2516 insertions(+), 1655 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java create mode 100644 id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/ELGAInitializeBKUAuthenticationTask.java (limited to 'id/server') diff --git a/id/server/auth/pom.xml b/id/server/auth/pom.xml index e3e9ee4f0..e88692a14 100644 --- a/id/server/auth/pom.xml +++ b/id/server/auth/pom.xml @@ -128,6 +128,11 @@ + + MOA.id.server + moa-id-spring-initializer + + MOA.id.server.modules @@ -172,11 +177,13 @@ moa-id-modules-federated_authentication - + + + iaik.prod diff --git a/id/server/idserverlib/pom.xml b/id/server/idserverlib/pom.xml index 770230bfc..8cf2603e1 100644 --- a/id/server/idserverlib/pom.xml +++ b/id/server/idserverlib/pom.xml @@ -33,17 +33,12 @@ 6.1.1 test - + + + com.google.guava + guava + 19.0 + at.gv.egiz.components diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java index d5d0a3ab1..eccd63e3d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java @@ -81,7 +81,7 @@ public interface MOAIDEventConstants extends EventConstants { public static final int AUTHPROCESS_PEPS_REQUESTED = 4400; public static final int AUTHPROCESS_PEPS_RECEIVED = 4401; public static final int AUTHPROCESS_PEPS_IDL_RECEIVED = 4402; - + //person information public static final int PERSONAL_INFORMATION_PROF_REPRESENTATIVE_BPK = 5000; public static final int PERSONAL_INFORMATION_PROF_REPRESENTATIVE = 5001; @@ -92,6 +92,10 @@ public interface MOAIDEventConstants extends EventConstants { public static final int PERSONAL_INFORMATION_MANDATE_MANDATOR_HASH = 5102; public static final int PERSONAL_INFORMATION_MANDATE_MANDATOR_BASEID = 5103; + //Attribute Provider [6000 --> 7900] + public static final int AUTHPROCESS_ELGA_MANDATE_SERVICE_REQUESTED = 6000; + public static final int AUTHPROCESS_ELGA_MANDATE_RECEIVED = 6001; + public static final int AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED = 6002; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java index 87b3bc9ca..8efdf6014 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java @@ -54,6 +54,7 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -106,12 +107,14 @@ public class StatisticLogger { boolean isbusinessservice = isBusinessService(dbOA); dblog.setBusinessservice(isbusinessservice); dblog.setOatarget(authData.getBPKType()); - - dblog.setInterfederatedSSOSession(authData.isInterfederatedSSOSession()); + + + boolean isFederatedAuthentication = protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE) != null; + dblog.setInterfederatedSSOSession(isFederatedAuthentication); - if (authData.isInterfederatedSSOSession()) { + if (isFederatedAuthentication) { dblog.setBkutype(IOAAuthParameters.INDERFEDERATEDIDP); - dblog.setBkuurl(authData.getInterfederatedIDP()); + dblog.setBkuurl(protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_ENTITYID, String.class)); } else { dblog.setBkuurl(authData.getBkuURL()); @@ -252,7 +255,7 @@ public class StatisticLogger { dblog.setBkutype(findBKUType(moasession.getBkuURL(), dbOA)); } - dblog.setMandatelogin(moasession.getUseMandate()); + dblog.setMandatelogin(moasession.isMandateUsed()); } } catch (MOADatabaseException e) { 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 c7ef73b47..27c87ccbf 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 @@ -25,6 +25,8 @@ public class MOAIDAuthConstants extends MOAIDConstants{ public static final String PARAM_TARGET = "Target"; /** servlet parameter "useMandate" */ public static final String PARAM_USEMANDATE = "useMandate"; + public static final String PARAM_USEMISMANDATE = "useMISMandate"; + public static final String PARAM_USEELGAMANDATE = "useELGAMandate"; /** servlet parameter "OA" */ public static final String PARAM_OA = "OA"; /** servlet parameter "bkuURI" */ @@ -166,6 +168,8 @@ public class MOAIDAuthConstants extends MOAIDConstants{ } }); + public static final String COUNTRYCODE_AUSTRIA = "AT"; + public static final String REGEX_PATTERN_TARGET = "^[A-Za-z]{2}(-.*)?$"; public static final String MDC_TRANSACTION_ID = "transactionId"; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java new file mode 100644 index 000000000..458f9afe6 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -0,0 +1,166 @@ +/* + * 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.auth; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.Provider; +import java.security.Security; + +import javax.activation.CommandMap; +import javax.activation.MailcapCommandMap; + +import org.springframework.web.context.support.GenericWebApplicationContext; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; +import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.id.util.SSLUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.logging.LoggingContext; +import at.gv.egovernment.moa.logging.LoggingContextManager; +import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; +import at.gv.egovernment.moa.spss.server.iaik.config.IaikConfigurator; +import at.gv.egovernment.moa.util.Constants; +import at.gv.egovernment.moa.util.MiscUtil; +import iaik.pki.PKIException; +import iaik.security.ecc.provider.ECCProvider; +import iaik.security.provider.IAIK; + +/** + * @author tlenz + * + */ +public class MOAIDAuthInitializer { + + /** + * Initializes the web application components which need initialization: + * logging, JSSE, MOA-ID Auth configuration, Axis, session cleaner. + * @param rootContext + */ + public static void initialize(GenericWebApplicationContext rootContext) throws ConfigurationException, + PKIException, IOException, GeneralSecurityException { + Logger.setHierarchy("moa.id.auth"); + Logger.info("Default java file.encoding: " + + System.getProperty("file.encoding")); + + + //JDK bug workaround according to: + // http://jce.iaik.tugraz.at/products/03_cms/faq/index.php#JarVerifier + // register content data handlers for S/MIME types + MailcapCommandMap mc = new MailcapCommandMap(); + CommandMap.setDefaultCommandMap(mc); + + if (MiscUtil.isEmpty(System.getProperty("https.cipherSuites"))) + System.setProperty( + "https.cipherSuites", + "TLS_DH_anon_WITH_AES_128_CBC_SHA" + + ",TLS_DHE_RSA_WITH_AES_128_CBC_SHA" + + ",TLS_DHE_DSS_WITH_AES_128_CBC_SHA" + + ",TLS_RSA_WITH_AES_128_CBC_SHA" + + ",TLS_RSA_WITH_AES_256_CBC_SHA" + + ",SSL_DH_anon_WITH_3DES_EDE_CBC_SHA" + + ",SSL_RSA_WITH_3DES_EDE_CBC_SHA" + ); + + + + // load some jsse classes so that the integrity of the jars can be + // verified + // before the iaik jce is installed as the security provider + // this workaround is only needed when sun jsse is used in conjunction + // with + // iaik-jce (on jdk1.3) + ClassLoader cl = MOAIDAuthInitializer.class.getClassLoader(); + try { + cl.loadClass("javax.security.cert.Certificate"); // from jcert.jar + } catch (ClassNotFoundException e) { + Logger.warn(MOAIDMessageProvider.getInstance().getMessage( + "init.01", null), e); + } + + Logger.info("Loading Java security providers."); + IAIK.addAsProvider(); + ECCProvider.addAsProvider(); + + // Initializes SSLSocketFactory store + SSLUtils.initialize(); + + // Initializes Namespace Map + Constants.nSMap.put(Constants.SAML_PREFIX, Constants.SAML_NS_URI); + Constants.nSMap.put(Constants.ECDSA_PREFIX, + "http://www.w3.org/2001/04/xmldsig-more#"); + Constants.nSMap.put(Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); + + //seed the random number generator + Random.seedRandom(); + Logger.debug("Random-number generator is seeded."); + + // Initialize configuration provider + AuthConfiguration authConf = AuthConfigurationProviderFactory.reload(rootContext); + + //test, if MOA-ID is already configured + authConf.getPublicURLPrefix(); + + + // Initialize MOA-SP + //MOA-SP is only use by API calls since MOA-ID 3.0.0 + try { + LoggingContextManager.getInstance().setLoggingContext( + new LoggingContext("startup")); + ConfigurationProvider config = ConfigurationProvider + .getInstance(); + new IaikConfigurator().configure(config); + + } catch (at.gv.egovernment.moa.spss.server.config.ConfigurationException ex) { + throw new ConfigurationException("config.10", new Object[] { ex + .toString() }, ex); + + } + + + //IAIK.addAsProvider(); + //ECCProvider.addAsProvider(); + + Security.insertProviderAt(IAIK.getInstance(), 0); + Security.addProvider(new ECCProvider()); + + if (Logger.isDebugEnabled()) { + Logger.debug("Loaded Security Provider:"); + Provider[] providerList = Security.getProviders(); + for (int i=0; i reqAttributes, InterfederationSessionStore nextIDPInformation) throws MOAIDException { - AuthenticationData authdata = new AuthenticationData(); + + public IAuthData buildAuthenticationData(IRequest pendingReq, + AuthenticationSession session) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { + return buildAuthenticationData(pendingReq, session, pendingReq.getOnlineApplicationConfiguration()); + } + + public IAuthData buildAuthenticationData(IRequest pendingReq, + AuthenticationSession session, IOAAuthParameters oaParam) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { + AuthenticationData authdata = null; + + //only needed for SAML1 legacy support try { - //mark AttributeQuery as used if it exists - OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); - if (activeOA != null) { - //reuse some parameters if it is a Service-Provider reauthentication - authdata.setSessionIndex(activeOA.getAssertionSessionID()); - authdata.setNameID(activeOA.getUserNameID()); - authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); - - //mark - if ( pendingReq instanceof PVPTargetConfiguration && - ((PVPTargetConfiguration) pendingReq).getRequest() instanceof MOARequest && - ((PVPTargetConfiguration) pendingReq).getRequest().getInboundMessage() instanceof AttributeQuery) { - try { - activeOA.setAttributeQueryUsed(true); - MOASessionDBUtils.saveOrUpdate(activeOA); - - } catch (MOADatabaseException e) { - Logger.error("MOASession interfederation information can not stored to database.", e); + //check if SAML1 authentication module is in Classpath + Class saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); + IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); + if (saml1RequstTemplate != null && + saml1RequstTemplate.isInstance(pendingReq)) { + //request is SAML1 --> invoke SAML1 protocol specific methods + if (session.getExtendedSAMLAttributesOA() == null) { + saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, new ArrayList()); - } + } else { + saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, session.getExtendedSAMLAttributesOA()); } + + authdata = (AuthenticationData) saml1authdata; + + } else { + authdata = new AuthenticationData(); + } + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { + authdata = new AuthenticationData(); - //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) and configuration - IOAAuthParameters spConfig = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes); - - //search federated IDP information for this MOASession - if (nextIDPInformation != null) { - Logger.info("Find active federated IDP information." - + ". --> Request next IDP:" + nextIDPInformation.getIdpurlprefix() - + " for authentication information."); - - //load configuration of next IDP - OAAuthParameter idp = authConfig.getOnlineApplicationParameter(nextIDPInformation.getIdpurlprefix()); - if (idp == null) { - Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() - + "is not loadable."); - throw new MOAIDException("auth.32", new Object[]{nextIDPInformation.getIdpurlprefix()}); - - } - - //check if next IDP config allows inbound messages - if (!idp.isInboundSSOInterfederationAllowed()) { - Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() - + "disallow inbound authentication messages."); - throw new MOAIDException("auth.33", new Object[]{nextIDPInformation.getIdpurlprefix()}); - - } - - //check next IDP service area policy. BusinessService IDPs can only request wbPKs - if (!spConfig.getBusinessService() && !idp.isIDPPublicService()) { - Logger.error("Interfederated IDP " + idp.getPublicURLPrefix() - + " has a BusinessService-IDP but requests PublicService attributes."); - throw new MOAIDException("auth.34", new Object[]{nextIDPInformation.getIdpurlprefix()}); - - } + } - //validation complete --> start AttributeQuery Request - getAuthDataFromInterfederation(authdata, reqAttributes, nextIDPInformation, idp); - - } else { - Logger.debug("Build authData for AttributQuery from local MOASession."); - buildAuthDataFormMOASession(authdata, session, spConfig, pendingReq); + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); + //reuse authentication information in case of service-provider reauthentication + if (activeOA != null) { + authdata.setSessionIndex(activeOA.getAssertionSessionID()); + authdata.setNameID(activeOA.getUserNameID()); + authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); + + } + + //TODO: move to eIDAS-Code in case of ISA1.18 action is enabled for eIDAS + //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway + if (oaParam.isSTORKPVPGateway()) + oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, pendingReq); - } - - return authdata; + Boolean isMinimalFrontChannelResp = pendingReq.getGenericData( + PVPTargetConfiguration.DATAID_INTERFEDERATION_MINIMAL_FRONTCHANNEL_RESP, Boolean.class); + if (isMinimalFrontChannelResp != null && isMinimalFrontChannelResp) { + //only set minimal response attributes + authdata.setQAALevel( + pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_QAALEVEL, String.class)); + authdata.setBPK( + pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_NAMEID, String.class)); - } catch (MOAIDException e) { - throw e; + } else { + //build AuthenticationData from MOASession + buildAuthDataFormMOASession(authdata, session, oaParam, pendingReq); + } + + return authdata; } - - private void getAuthDataFromInterfederation( - AuthenticationData authdata, List reqQueryAttr, - InterfederationSessionStore nextIDPInfo, OAAuthParameter nextIDPConfig ) throws MOAIDException{ - String idpEnityID = nextIDPConfig.getPublicURLPrefix(); + /** + * Get PVP authentication attributes by using a SAML2 AttributeQuery + * + * @param reqQueryAttr List of PVP attributes which are requested + * @param userNameID SAML2 UserNameID of the user for which attributes are requested + * @param idpConfig Configuration of the IDP, which is requested + * @return + * @return PVP attribute DAO, which contains all received information + * @throws MOAIDException + */ + public AssertionAttributeExtractor getAuthDataFromAttributeQuery(List reqQueryAttr, + String userNameID, IOAAuthParameters idpConfig ) throws MOAIDException{ + String idpEnityID = idpConfig.getPublicURLPrefix(); - AssertionAttributeExtractor extractor; try { Logger.debug("Starting AttributeQuery process ..."); //collect attributes by using BackChannel communication - String endpoint = nextIDPConfig.getIDPAttributQueryServiceURL(); + String endpoint = idpConfig.getIDPAttributQueryServiceURL(); if (MiscUtil.isEmpty(endpoint)) { Logger.error("No AttributeQueryURL for interfederationIDP " + idpEnityID); throw new ConfigurationException("config.26", new Object[]{idpEnityID}); @@ -226,7 +202,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } //build attributQuery request - AttributeQuery query = attributQueryBuilder.buildAttributQueryRequest(nextIDPInfo.getUserNameID(), endpoint, reqQueryAttr); + AttributeQuery query = attributQueryBuilder.buildAttributQueryRequest(userNameID, endpoint, reqQueryAttr); //build SOAP request List xmlObjects = MOASAMLSOAPClient.send(endpoint, query); @@ -249,17 +225,8 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { MOAMetadataProvider.getInstance())); //create assertion attribute extractor from AttributeQuery response - extractor = new AssertionAttributeExtractor(intfResp); - - //copy attributes into authData object - Set includedAttrNames = extractor.getAllIncludeAttributeNames(); - for (String el : includedAttrNames) { - authdata.setGenericData(el, extractor.getSingleAttributeValue(el)); - Logger.debug("Add PVP-attribute " + el + " into authData objext"); - - } - - + return new AssertionAttributeExtractor(intfResp); + } catch (Exception e) { Logger.warn("PVP 2.1 assertion validation FAILED.", e); throw new AssertionValidationExeption("auth.27", @@ -272,24 +239,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { new Object[]{idpEnityID, "Receive AttributeQuery response-body include no PVP 2.1 response"}); } - - try { - //mark attribute request as used - if (nextIDPInfo.isStoreSSOInformation()) { - nextIDPInfo.setAttributesRequested(true); - MOASessionDBUtils.saveOrUpdate(nextIDPInfo); - - //delete federated IDP from Session - } else { - MOASessionDBUtils.delete(nextIDPInfo); - - } - - } catch (MOADatabaseException e) { - Logger.error("MOASession interfederation information can not stored to database.", e); - - } - + } catch (SOAPException e) { throw new BuildException("builder.06", null, e); @@ -301,589 +251,588 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } - - - public IAuthData buildAuthenticationData(IRequest pendingReq, - AuthenticationSession session) 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"); - IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); - if (saml1RequstTemplate != null && - saml1RequstTemplate.isInstance(pendingReq)) { - //request is SAML1 --> invoke SAML1 protocol specific methods - if (session.getExtendedSAMLAttributesOA() == null) { - saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, new ArrayList()); + private void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, + IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { + + Collection includedToGenericAuthData = null; + if (session.getGenericSessionDataStorage() != null && + !session.getGenericSessionDataStorage().isEmpty()) + includedToGenericAuthData = session.getGenericSessionDataStorage().keySet(); + else + includedToGenericAuthData = new ArrayList(); + + try { + //#################################################### + //set general authData info's + authData.setIssuer(protocolRequest.getAuthURL()); + authData.setSsoSession(protocolRequest.needSingleSignOnFunctionality()); + authData.setIsBusinessService(oaParam.getBusinessService()); + + + //#################################################### + //parse user info's from identityLink + IdentityLink idlFromPVPAttr = null; + IdentityLink identityLink = session.getIdentityLink(); + if (identityLink != null) { + parseBasicUserInfosFromIDL(authData, identityLink, includedToGenericAuthData); + + } else { + // identityLink is not direct in MOASession + String pvpAttrIDL = session.getGenericDataFromSession(PVPConstants.EID_IDENTITY_LINK_NAME, String.class); + //find PVP-Attr. which contains the IdentityLink + if (MiscUtil.isNotEmpty(pvpAttrIDL)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_IDENTITY_LINK_FRIENDLY_NAME + + " --> Parse basic user info's from that attribute."); + InputStream idlStream = null; + try { + idlStream = Base64Utils.decodeToStream(pvpAttrIDL, false); + idlFromPVPAttr = new IdentityLinkAssertionParser(idlStream).parseIdentityLink(); + parseBasicUserInfosFromIDL(authData, idlFromPVPAttr, includedToGenericAuthData); + + } catch (ParseException e) { + Logger.error("Received IdentityLink is not valid", e); + + } catch (Exception e) { + Logger.error("Received IdentityLink is not valid", e); + + } finally { + try { + includedToGenericAuthData.remove(PVPConstants.EID_IDENTITY_LINK_NAME); + if (idlStream != null) + idlStream.close(); + + } catch (IOException e) { + Logger.fatal("Close InputStream FAILED.", e); + + } + + } - } else { - saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, session.getExtendedSAMLAttributesOA()); } - authdata = (AuthenticationData) saml1authdata; - - } else { - authdata = new AuthenticationData(); - + //if no basic user info's are set yet, parse info's single PVP-Attributes + if (MiscUtil.isEmpty(authData.getFamilyName())) { + Logger.debug("No IdentityLink found or not parseable --> Parse basic user info's from single PVP-Attributes."); + authData.setFamilyName(session.getGenericDataFromSession(PVPConstants.PRINCIPAL_NAME_NAME, String.class)); + authData.setGivenName(session.getGenericDataFromSession(PVPConstants.GIVEN_NAME_NAME, String.class)); + authData.setDateOfBirth(session.getGenericDataFromSession(PVPConstants.BIRTHDATE_NAME, String.class)); + authData.setIdentificationValue(session.getGenericDataFromSession(PVPConstants.EID_SOURCE_PIN_NAME, String.class)); + authData.setIdentificationType(session.getGenericDataFromSession(PVPConstants.EID_SOURCE_PIN_TYPE_NAME, String.class)); + + //remove corresponding keys from genericSessionData if exists + includedToGenericAuthData.remove(PVPConstants.PRINCIPAL_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.GIVEN_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.BIRTHDATE_NAME); + includedToGenericAuthData.remove(PVPConstants.EID_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPConstants.EID_SOURCE_PIN_TYPE_NAME); + } + } - - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { - authdata = new AuthenticationData(); - } + if (authData.getIdentificationType() != null && + !authData.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + Logger.trace("IdentificationType is not a baseID --> clear it. "); + authData.setBPK(authData.getIdentificationValue()); + authData.setBPKType(authData.getIdentificationType()); - OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); - //reuse authentication information in case of service-provider reauthentication - if (activeOA != null) { - authdata.setSessionIndex(activeOA.getAssertionSessionID()); - authdata.setNameID(activeOA.getUserNameID()); - authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); + authData.setIdentificationValue(null); + authData.setIdentificationType(null); + + } + + + //#################################################### + //set BKU URL + includedToGenericAuthData.remove(PVPConstants.EID_CCS_URL_NAME); + if (MiscUtil.isNotEmpty(session.getBkuURL())) + authData.setBkuURL(session.getBkuURL()); + else + authData.setBkuURL(session.getGenericDataFromSession(PVPConstants.EID_CCS_URL_NAME, String.class)); - } - - //get OnlineApplication from MOA-ID-Auth configuration - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - - //TODO: move to eIDAS-Code in case of ISA1.18 action is enabled for eIDAS - //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway - if (oaParam.isSTORKPVPGateway()) - oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, pendingReq); - - //check if minimal response is required - - //TODO check if really required - Boolean isMinimalFrontChannelResp = pendingReq.getGenericData( - PVPTargetConfiguration.DATAID_INTERFEDERATION_MINIMAL_FRONTCHANNEL_RESP, Boolean.class); - if (isMinimalFrontChannelResp != null && isMinimalFrontChannelResp) { - //only set minimal response attributes - authdata.setQAALevel( - pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_QAALEVEL, String.class)); - authdata.setBPK( - pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_NAMEID, String.class)); + + //#################################################### + //set QAA level + includedToGenericAuthData.remove(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME); + if (MiscUtil.isNotEmpty(session.getQAALevel())) + authData.setQAALevel(session.getQAALevel()); + + else { + String qaaLevel = session.getGenericDataFromSession(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME, String.class); + if (MiscUtil.isNotEmpty(qaaLevel)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME + + " --> Parse QAA-Level from that attribute."); - } else { - //build AuthenticationData from MOASession - buildAuthDataFormMOASession(authdata, session, oaParam, pendingReq); + if (qaaLevel.startsWith(PVPConstants.STORK_QAA_PREFIX)) { + authData.setQAALevel(qaaLevel); + + } else { + Logger.debug("Found PVP QAA level. QAA mapping process starts ... "); + String mappedQAA = PVPtoSTORKMapper.getInstance().mapToQAALevel(qaaLevel); + if (MiscUtil.isNotEmpty(mappedQAA)) + authData.setQAALevel(mappedQAA); + + } + } + } - } - - return authdata; - } + //if no QAA level is set in MOASession then set default QAA level + if (MiscUtil.isEmpty(authData.getQAALevel())) { + Logger.info("No QAA level found. Set to default level " + PVPConstants.STORK_QAA_PREFIX + "1"); + authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + "1"); + + } - private void buildAuthDataFormInterfederationResponse( - AuthenticationData authData, - AuthenticationSession session, - AssertionAttributeExtractor extractor, - IOAAuthParameters oaParam, - IRequest req) - throws BuildException, AssertionAttributeExtractorExeption { - - Logger.debug("Build AuthData from assertion starts ...."); - - authData.setIsBusinessService(oaParam.getBusinessService()); - - authData.setFamilyName(extractor.getSingleAttributeValue(PVPConstants.PRINCIPAL_NAME_NAME)); - authData.setGivenName(extractor.getSingleAttributeValue(PVPConstants.GIVEN_NAME_NAME)); - authData.setDateOfBirth(extractor.getSingleAttributeValue(PVPConstants.BIRTHDATE_NAME)); - authData.setCcc(extractor.getSingleAttributeValue(PVPConstants.EID_ISSUING_NATION_NAME)); - authData.setBkuURL(extractor.getSingleAttributeValue(PVPConstants.EID_CCS_URL_NAME)); - authData.setIdentificationValue(extractor.getSingleAttributeValue(PVPConstants.EID_SOURCE_PIN_NAME)); - authData.setIdentificationType(extractor.getSingleAttributeValue(PVPConstants.EID_SOURCE_PIN_TYPE_NAME)); - - - if (extractor.containsAttribute(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME)) { - String bpkType = extractor.getSingleAttributeValue(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME); - if (bpkType.startsWith(Constants.URN_PREFIX_CDID) && - !bpkType.substring(Constants.URN_PREFIX_CDID.length(), - Constants.URN_PREFIX_CDID.length() + 1).equals("+")) { - Logger.warn("Receive uncorrect encoded bBKType attribute " + bpkType + " Starting attribute value correction ... "); - bpkType = Constants.URN_PREFIX_CDID + "+" + bpkType.substring(Constants.URN_PREFIX_CDID.length() + 1); + + //#################################################### + //set signer certificate + includedToGenericAuthData.remove(PVPConstants.EID_SIGNER_CERTIFICATE_NAME); + if (session.getEncodedSignerCertificate() != null) + authData.setSignerCertificate(session.getEncodedSignerCertificate()); + + else { + String pvpAttrSignerCert = session.getGenericDataFromSession(PVPConstants.EID_SIGNER_CERTIFICATE_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrSignerCert)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_SIGNER_CERTIFICATE_FRIENDLY_NAME); + try { + authData.setSignerCertificate(Base64Utils.decode(pvpAttrSignerCert, false)); + + } catch (IOException e) { + Logger.error("SignerCertificate received via federated IDP is NOT valid", e); + + } + } else + Logger.info("NO SignerCertificate in MOASession."); } - - authData.setBPKType(bpkType); - } - - if (extractor.containsAttribute(PVPConstants.BPK_NAME)) { - String pvpbPK = extractor.getSingleAttributeValue(PVPConstants.BPK_NAME); - if (pvpbPK.startsWith("bPK:")) { - Logger.warn("Attribute " + PVPConstants.BPK_NAME - + " contains a not standardize prefix! Staring attribute value correction process ..."); - pvpbPK = pvpbPK.substring("bPK:".length()); + + //#################################################### + //set authBlock + includedToGenericAuthData.remove(PVPConstants.EID_AUTH_BLOCK_NAME); + if (MiscUtil.isNotEmpty(session.getAuthBlock())) { + authData.setAuthBlock(session.getAuthBlock()); + + } else { + String pvpAttrAuthBlock = session.getGenericDataFromSession(PVPConstants.EID_AUTH_BLOCK_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrAuthBlock)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_AUTH_BLOCK_FRIENDLY_NAME); + try { + byte[] authBlock = Base64Utils.decode(pvpAttrAuthBlock, false); + authData.setAuthBlock(new String(authBlock, "UTF-8")); + + } catch (IOException e) { + Logger.error("AuthBlock received via federated IDP is NOT valid", e); + + } + + } else + Logger.info("NO AuthBlock in MOASession."); } - String[] spitted = pvpbPK.split(":"); - authData.setBPK(spitted[1]); - if (MiscUtil.isEmpty(authData.getBPKType())) { - Logger.debug("PVP assertion contains NO bPK/wbPK target attribute. " + - "Starting target extraction from bPK/wbPK prefix ..."); - //exract bPK/wbPK type from bpk attribute value prefix if type is - //not transmitted as single attribute - Pattern pattern = Pattern.compile("[a-zA-Z]{2}(-[a-zA-Z]+)?"); - Matcher matcher = pattern.matcher(spitted[0]); - if (matcher.matches()) { - //find public service bPK - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + spitted[0]); - Logger.debug("Found bPK prefix. Set target to " + authData.getBPKType()); - - } else { - //find business service wbPK - authData.setBPKType(Constants.URN_PREFIX_WBPK+ "+" + spitted[0]); - Logger.debug("Found wbPK prefix. Set target to " + authData.getBPKType()); - - } + + //#################################################### + //set isForeigner flag + //TODO: change to new eIDAS-token attribute identifier + if (session.getGenericDataFromSession(PVPConstants.EID_STORK_TOKEN_NAME) != null) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_STORK_TOKEN_FRIENDLY_NAME + + " --> Set 'isForeigner' flag to TRUE"); + authData.setForeigner(true); + + } else { + authData.setForeigner(session.isForeigner()); + } - } - - boolean foundEncryptedbPKForOA = false; - if (extractor.containsAttribute(PVPConstants.ENC_BPK_LIST_NAME)) { - List encbPKList = Arrays.asList( - extractor.getSingleAttributeValue(PVPConstants.ENC_BPK_LIST_NAME).split(";")); - authData.setEncbPKList(encbPKList); - for (String fullEncbPK : encbPKList) { - int index = fullEncbPK.indexOf("|"); - if (index >= 0) { - String encbPK = fullEncbPK.substring(index+1); - String second = fullEncbPK.substring(0, index); - int secIndex = second.indexOf("+"); - if (secIndex >= 0) { - if (oaParam.getTarget().equals(second.substring(secIndex+1))) { - Logger.debug("Found encrypted bPK for online-application " - + oaParam.getPublicURLPrefix() - + " Start decryption process ..."); - PrivateKey privKey = oaParam.getBPKDecBpkDecryptionKey(); - foundEncryptedbPKForOA = true; - if (privKey != null) { - try { - String bPK = BPKBuilder.decryptBPK(encbPK, oaParam.getTarget(), privKey); - if (MiscUtil.isNotEmpty(bPK)) { - if (MiscUtil.isEmpty(authData.getBPK())) { - authData.setBPK(bPK); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget()); - Logger.info("bPK decryption process finished successfully."); - } - - } else { - Logger.error("bPK decryption FAILED."); - + + + //#################################################### + //set citizen country-code + includedToGenericAuthData.remove(PVPConstants.EID_ISSUING_NATION_NAME); + String pvpCCCAttr = session.getGenericDataFromSession(PVPConstants.EID_ISSUING_NATION_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpCCCAttr)) { + authData.setCcc(pvpCCCAttr); + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_ISSUING_NATION_FRIENDLY_NAME); + + } else { + if (authData.isForeigner()) { + try { + if (authData.getSignerCertificate() != null) { + //TODO: replace with TSL lookup when TSL is ready! + X509Certificate certificate = new X509Certificate(authData.getSignerCertificate()); + if (certificate != null) { + LdapName ln = new LdapName(certificate.getIssuerDN() + .getName()); + for (Rdn rdn : ln.getRdns()) { + if (rdn.getType().equalsIgnoreCase("C")) { + Logger.info("C is: " + rdn.getValue()); + authData.setCcc(rdn.getValue().toString()); + break; } - } catch (BuildException e) { - Logger.error("bPK decryption FAILED.", e); - } - - } else { - Logger.info("bPK decryption FAILED, because no valid decryption key is found."); - - } - - } else { - Logger.info("Found encrypted bPK but " + - "encrypted bPK target does not match to online-application target"); + } - } - } - } - } - } - - if (MiscUtil.isEmpty(authData.getIdentificationValue()) && - MiscUtil.isEmpty(authData.getBPK()) && - !foundEncryptedbPKForOA) { - Logger.info("Federated assertion include no bPK, encrypted bPK or baseID"); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME - + " or " + PVPConstants.ENC_BPK_LIST_NAME); - - } - - //check if received bPK matchs to online application configuration - //and no encrypted bPK is found for this oa - if (!matchsReceivedbPKToOnlineApplication(oaParam, authData) - && !foundEncryptedbPKForOA) { - Logger.info("Received bPK/wbPK does not match to online application"); - - if (MiscUtil.isEmpty(authData.getIdentificationValue())) { - Logger.info("No baseID found. Connect SZR to reveive baseID ..."); - try { - EgovUtilPropertiesConfiguration eGovClientsConfig = authConfig.geteGovUtilsConfig(); - if (eGovClientsConfig != null) { - SZRClient szrclient = new SZRClient(eGovClientsConfig); + } else + Logger.warn("NO PVP-Attr: " + PVPConstants.EID_ISSUING_NATION_NAME + + " and NO SignerCertificate in MOASession -->" + + " Can NOT extract citizen-country of foreign person."); - Logger.debug("Create SZR request to get baseID ... "); - PersonInfoType personInfo = new PersonInfoType(); - at.gv.util.xsd.szr.persondata.PhysicalPersonType person = new at.gv.util.xsd.szr.persondata.PhysicalPersonType(); - personInfo.setPerson(person); - at.gv.util.xsd.szr.persondata.PersonNameType name = new at.gv.util.xsd.szr.persondata.PersonNameType(); - person.setName(name); - at.gv.util.xsd.szr.persondata.IdentificationType idValue = new at.gv.util.xsd.szr.persondata.IdentificationType(); - person.setIdentification(idValue); - //set bPK or wbPK - idValue.setValue(authData.getBPK()); - idValue.setType(authData.getBPKType()); - - //set person information - name.setGivenName(authData.getGivenName()); - name.setFamilyName(authData.getFamilyName()); - if (authData.getDateOfBirth() != null) - person.setDateOfBirth(authData.getFormatedDateOfBirth()); - - //request szr and store baseID - authData.setIdentificationValue(szrclient.getStammzahl(personInfo)); - authData.setIdentificationType(Constants.URN_PREFIX_BASEID); - - } else { - Logger.warn("No SZR clieht configuration found. Interfederation SSO login not possible."); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); + } catch (Exception e) { + Logger.error("Failed to extract country code from certificate with message: " + e.getMessage()); } - - } catch (EgovUtilException e) { - Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); - - } catch (SZRException e) { - Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); + + } else { + authData.setCcc(COUNTRYCODE_AUSTRIA); - } + } } - //build OA specific bPK/wbPK information - buildOAspecificbPK(req, oaParam, authData, - authData.getIdentificationValue(), - authData.getIdentificationType()); - } - - if (MiscUtil.isEmpty(authData.getBPK())) { - Logger.debug("Calcutlate bPK from baseID"); - buildOAspecificbPK(req, oaParam, authData, - authData.getIdentificationValue(), - authData.getIdentificationType()); - - } - - - try { - String qaaLevel = extractor.getQAALevel(); - if (MiscUtil.isNotEmpty(qaaLevel) && - qaaLevel.startsWith(PVPConstants.STORK_QAA_PREFIX)) { - authData.setQAALevel(qaaLevel); - - } else { - Logger.debug("Found PVP QAA level. QAA mapping process starts ... "); - String mappedQAA = PVPtoSTORKMapper.getInstance().mapToQAALevel(qaaLevel); - if (MiscUtil.isNotEmpty(mappedQAA)) - authData.setQAALevel(mappedQAA); + //#################################################### + //set max. SSO session time + includedToGenericAuthData.remove(AuthenticationSessionStorageConstants.FEDERATION_RESPONSE_VALIDE_TO); + Date validToFromFederatedIDP = session.getGenericDataFromSession( + AuthenticationSessionStorageConstants.FEDERATION_RESPONSE_VALIDE_TO, Date.class); + if (validToFromFederatedIDP != null) { + authData.setSsoSessionValidTo(validToFromFederatedIDP); + Logger.debug("Use idToken validTo periode from federated IDP response."); - else - throw new AssertionAttributeExtractorExeption("PVP SecClass not mappable"); + } else { + if (authData.isSsoSession()) { + long maxSSOSessionTime = authConfig.getSSOCreatedTimeOut() * 1000; + Date ssoSessionValidTo = new Date(session.getSessionCreated().getTime() + maxSSOSessionTime); + authData.setSsoSessionValidTo(ssoSessionValidTo); - } - - } catch (AssertionAttributeExtractorExeption e) { - Logger.warn("No QAA level found in element of interfederated assertion. " + - "(ErrorHeader=" + e.getMessage() + ")"); - if (extractor.containsAttribute(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME)) { - authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + - extractor.getSingleAttributeValue(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME)); - - } else { - Logger.info("No QAA level found. Set to default level " + - PVPConstants.STORK_QAA_PREFIX + "1"); - authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + "1"); + } else { + //set valid to 5 min + Date ssoSessionValidTo = new Date(new Date().getTime() + 5 * 60 * 1000); + authData.setSsoSessionValidTo(ssoSessionValidTo); + } } - - } - - if (extractor.containsAttribute(PVPConstants.EID_AUTH_BLOCK_NAME)) { - try { - byte[] authBlock = Base64Utils.decode(extractor.getSingleAttributeValue(PVPConstants.EID_AUTH_BLOCK_NAME), false); - authData.setAuthBlock(new String(authBlock, "UTF-8")); - } catch (IOException e) { - Logger.error("Received AuthBlock is not valid", e); + //mandate functionality + MISMandate misMandate = null; + if (session.isMandateUsed()) { + //#################################################### + //set Mandate reference value + includedToGenericAuthData.remove(PVPConstants.MANDATE_REFERENCE_VALUE_NAME); + if (MiscUtil.isNotEmpty(session.getMandateReferenceValue())) + authData.setMandateReferenceValue(session.getMandateReferenceValue()); - } - } - - if (extractor.containsAttribute(PVPConstants.EID_SIGNER_CERTIFICATE_NAME)) { - try { - authData.setSignerCertificate(Base64Utils.decode( - extractor.getSingleAttributeValue(PVPConstants.EID_SIGNER_CERTIFICATE_NAME), false)); + else { + String pvpMandateRefAttr = session.getGenericDataFromSession(PVPConstants.MANDATE_REFERENCE_VALUE_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpMandateRefAttr)) { + authData.setMandateReferenceValue(pvpMandateRefAttr); + Logger.debug("Find PVP-Attr: " + PVPConstants.MANDATE_REFERENCE_VALUE_FRIENDLY_NAME); + } + } - } catch (IOException e) { - Logger.error("Received SignerCertificate is not valid", e); - } - } + /* TODO: Support SSO Mandate MODE! + * Insert functionality to translate mandates in case of SSO + */ - if (extractor.containsAttribute(PVPConstants.EID_IDENTITY_LINK_NAME)) { - try { - InputStream idlStream = Base64Utils.decodeToStream(extractor.getSingleAttributeValue(PVPConstants.EID_IDENTITY_LINK_NAME), false); - IdentityLink idl = new IdentityLinkAssertionParser(idlStream).parseIdentityLink(); - idlStream.close(); - buildOAspecificIdentityLink(oaParam, authData, idl); + //#################################################### + //set Full-mandate + misMandate = session.getMISMandate(); + if (misMandate != null ) { + //set MIS mandate to authdata + authData.setMISMandate(misMandate); + authData.setUseMandate(session.isMandateUsed()); + + } else { + String pvpFullMandateAttr = session.getGenericDataFromSession( + PVPConstants.MANDATE_FULL_MANDATE_NAME, String.class); + //check if full-mandate is available as PVP attribute + if (MiscUtil.isNotEmpty(pvpFullMandateAttr)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.MANDATE_FULL_MANDATE_FRIENDLY_NAME); + try { + byte[] mandate = Base64Utils.decode(pvpFullMandateAttr, false); + misMandate = new MISMandate(); + misMandate.setMandate(mandate); + + //read Organwalter OID + String pvpRepOIDAttr = session.getGenericDataFromSession(PVPConstants.MANDATE_PROF_REP_OID_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpRepOIDAttr)) { + misMandate.setProfRep(pvpRepOIDAttr); + Logger.debug("Find PVP-Attr: " + PVPConstants.MANDATE_PROF_REP_OID_NAME); - } catch (ParseException e) { - Logger.error("Received IdentityLink is not valid", e); - - } catch (Exception e) { - Logger.error("Received IdentityLink is not valid", e); + } + + //read Organwalter bPK from full-mandate + NodeList mandateElements = misMandate.getMandateDOM().getChildNodes(); + for (int i=0; i Use single PVP attributes for mandate information."); + //check if ELGA mandates exists + String mandateType = session.getGenericDataFromSession(PVPConstants.MANDATE_TYPE_NAME, String.class); + if (MiscUtil.isNotEmpty(mandateType)) { + //switch to mandate-mode for authdata generation, because mandate-information + // is directly included in MOA-Session as PVP attributes + Logger.info("AuthDataBuilder find directly included 'MandateType' PVP-attribute." + + " --> Switch to mandate-mode for authdata generation."); + authData.setUseMandate(true); + + } + } + } + //remove PVP attributes with mandate information, because full-mandate exists + if (authData.getMISMandate() != null) { + includedToGenericAuthData.remove(PVPConstants.MANDATE_FULL_MANDATE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_TYPE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_BPK_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_PROF_REP_DESC_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_PROF_REP_OID_NAME); + } } - } - // set mandate attributes - authData.setMandateReferenceValue(extractor.getSingleAttributeValue(PVPConstants.MANDATE_REFERENCE_VALUE_NAME)); - - if (extractor.containsAttribute(PVPConstants.MANDATE_FULL_MANDATE_NAME)) { - try { - byte[] mandate = Base64Utils.decode( - (extractor.getSingleAttributeValue(PVPConstants.MANDATE_FULL_MANDATE_NAME)), false); + + + + //#################################################### + // set bPK and IdentityLink for Organwalter --> + // Organwalter has a special bPK is received from MIS + if (authData.isUseMandate() && session.isOW() && misMandate != null + && MiscUtil.isNotEmpty(misMandate.getOWbPK())) { + //TODO: if full-mandate is removed in OPB --> OWbPK functionality needs an update!!! + authData.setBPK(misMandate.getOWbPK()); + authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); + Logger.trace("Authenticated User is OW: " + misMandate.getOWbPK()); - if (authData.getMISMandate() == null) - authData.setMISMandate(new MISMandate()); - authData.getMISMandate().setMandate(mandate); - authData.getMISMandate().setFullMandateIncluded(true); - authData.setUseMandate(true); - - } catch (Exception e) { - Logger.error("Received Mandate is not valid", e); - throw new AssertionAttributeExtractorExeption(PVPConstants.MANDATE_FULL_MANDATE_NAME); - } - } - - //TODO: build short mandate if full mandate is no included. - if (authData.getMISMandate() == null && - (extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME) - || extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_BPK_NAME) - || extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME)) ) { - Logger.info("Federated assertion contains no full mandate. Start short mandate generation process ... "); - - MISMandate misMandate = new MISMandate(); - misMandate.setFullMandateIncluded(false); - - Mandate mandateObject = new Mandate(); - Mandator mandator = new Mandator(); - mandateObject.setMandator(mandator); + //TODO: check in case of mandates for business services + if (identityLink != null) + authData.setIdentityLink(identityLink); - //build legal person short mandate - if (extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME)) { - Logger.debug("Build short mandate for legal person ..."); - CorporateBodyType legalperson = new CorporateBodyType(); - IdentificationType legalID = new IdentificationType(); - Value idvalue = new Value(); - legalID.setValue(idvalue ); - legalperson.getIdentification().add(legalID ); - mandator.setCorporateBody(legalperson ); - - legalperson.setFullName(extractor.getSingleAttributeValue(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME)); - legalID.setType(extractor.getSingleAttributeValue(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME)); - idvalue.setValue(extractor.getSingleAttributeValue(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME)); - - //build natural person short mandate - } else if ( (extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME) || - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_BPK_NAME)) && - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME)) { - Logger.debug("Build short mandate for natural person ..."); - PhysicalPersonType physPerson = new PhysicalPersonType(); - PersonNameType persName = new PersonNameType(); - mandator.setPhysicalPerson(physPerson ); - physPerson.setName(persName ); - FamilyName familyName = new FamilyName(); - persName.getFamilyName().add(familyName ); - IdentificationType persID = new IdentificationType(); - physPerson.getIdentification().add(persID ); - Value idValue = new Value(); - persID.setValue(idValue ); - - String[] pvp2GivenName = extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME).split(" "); - for(int i=0; i pvpEncbPKAttr = getEncryptedbPKFromPVPAttribute(session, authData, oaParam); + + //check if a unique ID for this citizen exists + if (MiscUtil.isEmpty(authData.getIdentificationValue()) && + MiscUtil.isEmpty(pvpbPKValue) && MiscUtil.isEmpty(authData.getBPK()) && + pvpEncbPKAttr == null) { + Logger.info("Can not build authData, because moaSession include no bPK, encrypted bPK or baseID"); + throw new MOAIDException("builder.08", new Object[]{"No " + PVPConstants.BPK_FRIENDLY_NAME + + " or " + PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME + + " or " + PVPConstants.ENC_BPK_LIST_FRIENDLY_NAME}); + + } + + // baseID is in MOASesson --> calculate bPK directly + if (MiscUtil.isNotEmpty(authData.getIdentificationValue())) { + Logger.debug("Citizen baseID is in MOASession --> calculate bPK from this."); + Pair result = buildOAspecificbPK(protocolRequest, oaParam, authData); + authData.setBPK(result.getFirst()); + authData.setBPKType(result.getSecond()); + + //check if bPK already added to AuthData matches OA + } else if (MiscUtil.isNotEmpty(authData.getBPK()) + && matchsReceivedbPKToOnlineApplication(oaParam, authData.getBPKType()) ) { + Logger.debug("Correct bPK is already included in AuthData."); + + //check if bPK received by PVP-Attribute matches OA + } else if (MiscUtil.isNotEmpty(pvpbPKValue) && + matchsReceivedbPKToOnlineApplication(oaParam, pvpbPKTypeAttr)) { + Logger.debug("Receive correct bPK from PVP-Attribute"); + authData.setBPK(pvpbPKValue); + authData.setBPKType(pvpbPKTypeAttr); + //check if decrypted bPK exists + } else if (pvpEncbPKAttr != null) { + Logger.debug("Receive bPK as encrypted bPK and decryption was possible."); + authData.setBPK(pvpEncbPKAttr.getFirst()); + authData.setBPKType(pvpEncbPKAttr.getSecond()); + + //ask SZR to get bPK } else { - String[] pvp2bPK = extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_BPK_NAME).split(":"); - if (pvp2bPK.length == 2) { - idValue.setValue(pvp2bPK[1]); + String notValidbPK = authData.getBPK(); + String notValidbPKType = authData.getBPKType(); + if (MiscUtil.isEmpty(notValidbPK) && + MiscUtil.isEmpty(notValidbPKType)) { + notValidbPK = pvpbPKValue; + notValidbPKType = pvpbPKTypeAttr; - Pattern pattern = Pattern.compile(MOAIDAuthConstants.REGEX_PATTERN_TARGET); - Matcher matcher = pattern.matcher(pvp2bPK[0]); - if (matcher.matches()) - persID.setType(Constants.URN_PREFIX_CDID + "+" + pvp2bPK[0]); - else - persID.setType(Constants.URN_PREFIX_WBPK + "+" + pvp2bPK[0]); + if (MiscUtil.isEmpty(notValidbPK) && + MiscUtil.isEmpty(notValidbPKType)) { + Logger.fatal("No bPK in MOASession. THIS error should not occur any more."); + throw new NullPointerException("No bPK in MOASession. THIS error should not occur any more."); + } + } + + Pair baseIDFromSZR = getbaseIDFromSZR(authData, notValidbPK, notValidbPKType); + if (baseIDFromSZR != null) { + Logger.info("Receive citizen baseID from SRZ. Authentication can be completed"); + authData.setIdentificationValue(baseIDFromSZR.getFirst()); + authData.setIdentificationType(baseIDFromSZR.getSecond()); + Pair result = buildOAspecificbPK(protocolRequest, oaParam, authData); + authData.setBPK(result.getFirst()); + authData.setBPKType(result.getSecond()); } else { - Logger.warn("Receive mandator bPK from federation with an unsupported format. " + extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_BPK_NAME)); - throw new AssertionAttributeExtractorExeption("Receive mandator bPK from federation with an unsupported format."); + Logger.warn("Can not build authData, because moaSession include no valid bPK, encrypted bPK or baseID"); + throw new MOAIDException("builder.08", new Object[]{"No valid " + PVPConstants.BPK_FRIENDLY_NAME + + " or " + PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME + + " or " + PVPConstants.ENC_BPK_LIST_FRIENDLY_NAME}); } } - - } else { - Logger.error("Short mandate could not generated. Assertion contains not all attributes which are necessary."); - throw new AssertionAttributeExtractorExeption("Assertion contains not all attributes which are necessary for mandate generation", null); - - } - - try { - JAXBContext jc = JAXBContext.newInstance("at.gv.e_government.reference.namespace.mandates._20040701_"); - Marshaller m = jc.createMarshaller(); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - m.marshal(mandateObject, stream); - misMandate.setMandate(Base64Utils.encode(stream.toByteArray()).getBytes()); - stream.close(); + + //build IdentityLink + if (identityLink != null) + authData.setIdentityLink(buildOAspecificIdentityLink(oaParam, identityLink, authData.getBPK(), authData.getBPKType())); - } catch (JAXBException e) { - Logger.error("Failed to parse short mandate", e); - throw new AssertionAttributeExtractorExeption(); + else if (idlFromPVPAttr != null) { + authData.setIdentityLink(buildOAspecificIdentityLink(oaParam, idlFromPVPAttr, authData.getBPK(), authData.getBPKType())); + Logger.debug("Set IdentityLink received from federated IDP"); - } catch (IOException e) { - Logger.error("Failed to parse short mandate", e); - throw new AssertionAttributeExtractorExeption(); - - } - authData.setUseMandate(true); + } else { + Logger.info("Can NOT set IdentityLink. Msg: No IdentityLink found"); + + } + } - } - - - if (extractor.containsAttribute(PVPConstants.MANDATE_PROF_REP_OID_NAME)) { - if (authData.getMISMandate() == null) - authData.setMISMandate(new MISMandate()); - authData.getMISMandate().setProfRep( - extractor.getSingleAttributeValue(PVPConstants.MANDATE_PROF_REP_OID_NAME)); - } - - //set PVP role attribute - if (extractor.containsAttribute(PVPConstants.ROLES_NAME)) { - String pvpRoles = extractor.getSingleAttributeValue(PVPConstants.ROLES_NAME); - if (MiscUtil.isNotEmpty(pvpRoles)) { - List roles = Arrays.asList(pvpRoles.split(";")); + //################################################################### + //set PVP role attribute (implemented for ISA 1.18 action) + includedToGenericAuthData.remove(PVPConstants.ROLES_NAME); + String pvpAttrRoles = session.getGenericDataFromSession(PVPConstants.ROLES_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrRoles)) { + List roles = Arrays.asList(pvpAttrRoles.split(";")); for (String role : roles) { authData.addAuthenticationRole(AuthenticationRoleFactory.buildFormPVPole(role)); - } - } - } - - //set PVP OU attribute - if (extractor.containsAttribute(PVPConstants.OU_NAME)) { - authData.setPvpAttribute_OU(extractor.getSingleAttributeValue(PVPConstants.OU_NAME)); - Logger.debug("Found PVP 'OU' attribute in response -> " + authData.getPvpAttribute_OU()); - - } - - //set STORK attributes - if (extractor.containsAttribute(PVPConstants.EID_STORK_TOKEN_NAME)) { - try { - authData.setGenericData(AuthenticationSessionStorageConstants.STORK_RESPONSE, - extractor.getSingleAttributeValue(PVPConstants.EID_STORK_TOKEN_NAME)); - authData.setForeigner(true); - } catch (SessionDataStorageException e) { - Logger.warn("STORK Response can not stored into generic authData.", e); + } + } + + + //################################################################### + //set PVP OU attribute (implemented for ISA 1.18 action) + includedToGenericAuthData.remove(PVPConstants.OU_NAME); + String pvpAttrOUName = session.getGenericDataFromSession(PVPConstants.OU_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrOUName)) { + authData.setPvpAttribute_OU(pvpAttrOUName); + Logger.debug("Found PVP 'OU' attribute in response -> " + authData.getPvpAttribute_OU()); - } + } - } - -// if (!extractor.getSTORKAttributes().isEmpty()) { -// authData.setStorkAttributes(extractor.getSTORKAttributes()); -// authData.setForeigner(true); -// -// } + //#################################################################### + //parse AuthBlock signature-verification response + //INFO: this parameters are only required for SAML1 auth. protocol + VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); + if (verifyXMLSigResp != null) { + authData.setQualifiedCertificate(verifyXMLSigResp + .isQualifiedCertificate()); + authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); + authData.setPublicAuthorityCode(verifyXMLSigResp + .getPublicAuthorityCode()); - authData.setSsoSession(true); - authData.setInterfederatedSSOSession(true); - - if (extractor.getFullAssertion().getAuthnStatements() != null - && extractor.getFullAssertion().getAuthnStatements().size() > 0) { - for (AuthnStatement el : extractor.getFullAssertion().getAuthnStatements()) { - if (el.getSessionNotOnOrAfter() != null) { - authData.setSsoSessionValidTo(el.getSessionNotOnOrAfter().toDate()); - break; - } + } else { + //set parameters in respect to QAA level + Logger.info("No authBlock signature-verfication response found. Maybe IDP federation is in use."); + if (PVPConstants.STORK_QAA_1_4.equals(authData.getQAALevel())) + authData.setQualifiedCertificate(true); + else + authData.setQualifiedCertificate(false); + authData.setPublicAuthority(false); + + } + + //#################################################################### + //copy all generic authentication information, which are not processed before to authData + Iterator copyInterator = includedToGenericAuthData.iterator(); + while (copyInterator.hasNext()) { + String elementKey = copyInterator.next(); + try { + authData.setGenericData(elementKey, session.getGenericDataFromSession(elementKey)); + + } catch (SessionDataStorageException e) { + Logger.warn("Can not add generic authData with key:" + elementKey, e); + + } } - } else { - authData.setSsoSessionValidTo(extractor.getFullAssertion().getConditions().getNotOnOrAfter().toDate()); + } catch (BuildException e) { + throw e; - } + } catch (Throwable ex) { + throw new BuildException("builder.00", new Object[]{ + "AuthenticationData", ex.toString()}, ex); + } - //only for SAML1 - if (PVPConstants.STORK_QAA_1_4.equals(authData.getQAALevel())) - authData.setQualifiedCertificate(true); - else - authData.setQualifiedCertificate(false); - authData.setPublicAuthority(false); } - + /** - * @param oaParam - * @param authData - * @return + * Check a bPK-Type against a Service-Provider configuration
+ * If bPK-Type is null the result is false. + * + * @param oaParam Service-Provider configuration, never null + * @param bPKType bPK-Type to check + * @return true, if bPK-Type matchs to Service-Provider configuration, otherwise false */ - private boolean matchsReceivedbPKToOnlineApplication( - IOAAuthParameters oaParam, AuthenticationData authData) { - + private boolean matchsReceivedbPKToOnlineApplication(IOAAuthParameters oaParam, String bPKType) { String oaTarget = null; if (oaParam.getBusinessService()) { - if (oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_WBPK) || - oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_STORK)) - oaTarget = oaParam.getIdentityLinkDomainIdentifier(); - - else { - Logger.warn("BusinessIdentifier can not be clearly assigned, because it starts without a prefix."); - return false; - - } - + oaTarget = oaParam.getIdentityLinkDomainIdentifier(); + } else { oaTarget = Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget(); } - - - if (oaTarget.equals(authData.getBPKType())) + + if (oaTarget.equals(bPKType)) return true; else return false; } - private void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, - IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { - - IdentityLink identityLink = session.getIdentityLink(); - - VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); - - authData.setIssuer(protocolRequest.getAuthURL()); - + private void parseBasicUserInfosFromIDL(AuthenticationData authData, IdentityLink identityLink, Collection includedGenericSessionData) { //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO authData.setIdentificationValue(identityLink.getIdentificationValue()); authData.setIdentificationType(identityLink.getIdentificationType()); @@ -892,173 +841,238 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { authData.setFamilyName(identityLink.getFamilyName()); authData.setDateOfBirth(identityLink.getDateOfBirth()); - if (verifyXMLSigResp != null) { - authData.setQualifiedCertificate(verifyXMLSigResp - .isQualifiedCertificate()); - authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); - authData.setPublicAuthorityCode(verifyXMLSigResp - .getPublicAuthorityCode()); - - } else { - Logger.warn("No signature verfication response found!"); - - } - - authData.setBkuURL(session.getBkuURL()); - - //copy all generic authentication information to authData - if (session.getGenericSessionDataStorage() != null && - !session.getGenericSessionDataStorage().isEmpty()) { - Iterator> copyInterator = session.getGenericSessionDataStorage().entrySet().iterator(); - while (copyInterator.hasNext()) { - Entry element = copyInterator.next(); - try { - authData.setGenericData(element.getKey(), element.getValue()); - - } catch (SessionDataStorageException e) { - Logger.warn("Can not add generic authData with key:" + element.getKey(), e); - - } - } - } - - authData.setSignerCertificate(session.getEncodedSignerCertificate()); - authData.setAuthBlock(session.getAuthBlock()); - - authData.setForeigner(session.isForeigner()); - authData.setQAALevel(session.getQAALevel()); - - authData.setIsBusinessService(oaParam.getBusinessService()); + //remove corresponding keys from genericSessionData if exists + includedGenericSessionData.remove(PVPConstants.PRINCIPAL_NAME_NAME); + includedGenericSessionData.remove(PVPConstants.GIVEN_NAME_NAME); + includedGenericSessionData.remove(PVPConstants.BIRTHDATE_NAME); + includedGenericSessionData.remove(PVPConstants.EID_SOURCE_PIN_NAME); + includedGenericSessionData.remove(PVPConstants.EID_SOURCE_PIN_TYPE_NAME); - if (session.isForeigner()) { - try { - //TODO: replace with TSL lookup when TSL is ready! - X509Certificate certificate = new X509Certificate(authData.getSignerCertificate()); - if (certificate != null) { - LdapName ln = new LdapName(certificate.getIssuerDN() - .getName()); - for (Rdn rdn : ln.getRdns()) { - if (rdn.getType().equalsIgnoreCase("C")) { - Logger.info("C is: " + rdn.getValue()); - authData.setCcc(rdn.getValue().toString()); - break; - } - } - } + } + + /** + * @param authData + * @param notValidbPK + * @param notValidbPKType + * @return + */ + private Pair getbaseIDFromSZR(AuthenticationData authData, String notValidbPK, + String notValidbPKType) { + try { + EgovUtilPropertiesConfiguration eGovClientsConfig = authConfig.geteGovUtilsConfig(); + if (eGovClientsConfig != null) { + Logger.info("bPK in MOASession (bPK-Type:" + notValidbPKType + + " does no match to Service-Provider configuration. --> Request SZR to get correct bPK."); - } catch (Exception e) { - Logger.error("Failed to extract country code from certificate with message: " + e.getMessage()); + SZRClient szrclient = new SZRClient(eGovClientsConfig); - } - - if (MiscUtil.isEmpty(authData.getCcc())) { - String storkCCC = authData.getGenericData( - AuthenticationSessionStorageConstants.STORK_CCC, String.class); + Logger.debug("Create SZR request to get baseID ... "); + PersonInfoType personInfo = new PersonInfoType(); + at.gv.util.xsd.szr.persondata.PhysicalPersonType person = new at.gv.util.xsd.szr.persondata.PhysicalPersonType(); + personInfo.setPerson(person); + at.gv.util.xsd.szr.persondata.PersonNameType name = new at.gv.util.xsd.szr.persondata.PersonNameType(); + person.setName(name); + at.gv.util.xsd.szr.persondata.IdentificationType idValue = new at.gv.util.xsd.szr.persondata.IdentificationType(); + person.setIdentification(idValue); + + //set bPK or wbPK + idValue.setValue(authData.getBPK()); + idValue.setType(authData.getBPKType()); + + //set person information + name.setGivenName(authData.getGivenName()); + name.setFamilyName(authData.getFamilyName()); + if (authData.getDateOfBirth() != null) + person.setDateOfBirth(authData.getFormatedDateOfBirth()); + + //request szr and store baseID + return Pair.newInstance(szrclient.getStammzahl(personInfo), + Constants.URN_PREFIX_BASEID); + + } else { + Logger.debug("No SZR clieht configuration found."); + return null; - if (MiscUtil.isNotEmpty(storkCCC)) { - authData.setCcc(storkCCC); - Logger.info("Can not extract country from certificate -> Use country:" + storkCCC + " from STORK request."); - - } - } + + } catch (SZRException e) { + Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - } else { - authData.setCcc("AT"); + } catch (at.gv.util.ex.EgovUtilException e) { + Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); } - try { - authData.setSsoSession(protocolRequest.needSingleSignOnFunctionality()); + return null; + } + + /** + * Add encrypted bPKs from PVP Attribute 'ENC_BPK_LIST_NAME', which could be exist in + * MOASession as 'GenericData'
session.getGenericDataFromSession(PVPConstants.ENC_BPK_LIST_NAME, String.class)
+ * to authData + * + * @param session MOASession, but never null + * @param authData AuthenticationData DAO + * @param spConfig Service-Provider configuration + * + * @return Pair which was received by PVP-Attribute and could be decrypted for this Service Provider, + * or null if no attribute exists or can not decrypted + */ + private Pair getEncryptedbPKFromPVPAttribute(AuthenticationSession session, + AuthenticationData authData, IOAAuthParameters spConfig) { + //set List of encrypted bPKs to authData DAO + String pvpEncbPKListAttr = session.getGenericDataFromSession(PVPConstants.ENC_BPK_LIST_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpEncbPKListAttr)) { + List encbPKList = Arrays.asList(pvpEncbPKListAttr.split(";")); + authData.setEncbPKList(encbPKList); - //set max. SSO session time - if (authData.isSsoSession()) { - long maxSSOSessionTime = authConfig.getSSOCreatedTimeOut() * 1000; - Date ssoSessionValidTo = new Date(session.getSessionCreated().getTime() + maxSSOSessionTime); - authData.setSsoSessionValidTo(ssoSessionValidTo); - - } else { - //set valid to 5 min - Date ssoSessionValidTo = new Date(new Date().getTime() + 5 * 60 * 1000); - authData.setSsoSessionValidTo(ssoSessionValidTo); - + //check if one of this encrypted bPK could be decrypt for this Service-Provider + for (String fullEncbPK : encbPKList) { + int index = fullEncbPK.indexOf("|"); + if (index >= 0) { + String encbPK = fullEncbPK.substring(index+1); + String second = fullEncbPK.substring(0, index); + int secIndex = second.indexOf("+"); + if (secIndex >= 0) { + if (spConfig.getTarget().equals(second.substring(secIndex+1))) { + Logger.debug("Found encrypted bPK for online-application " + + spConfig.getPublicURLPrefix() + + " Start decryption process ..."); + PrivateKey privKey = spConfig.getBPKDecBpkDecryptionKey(); + if (privKey != null) { + try { + String bPK = BPKBuilder.decryptBPK(encbPK, spConfig.getTarget(), privKey); + if (MiscUtil.isNotEmpty(bPK)) { + Logger.info("bPK decryption process finished successfully."); + return Pair.newInstance(bPK, Constants.URN_PREFIX_CDID + "+" + spConfig.getTarget()); + + } else { + Logger.error("bPK decryption FAILED."); + + } + } catch (BuildException e) { + Logger.error("bPK decryption FAILED.", e); + + } + + } else { + Logger.info("bPK decryption FAILED, because no valid decryption key is found."); + + } + + } else { + Logger.info("Found encrypted bPK but " + + "encrypted bPK target does not match to online-application target"); + + } + } + } } - - - /* TODO: Support SSO Mandate MODE! - * Insert functionality to translate mandates in case of SSO - */ + } + + return null; + } + /** + * Get bPK from PVP Attribute 'BPK_NAME', which could be exist in + * MOASession as 'GenericData'
session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class)
+ * + * @param session MOASession, but never null + * @return bPK, which was received by PVP-Attribute, or null if no attribute exists + */ + private String getbPKValueFromPVPAttribute(AuthenticationSession session) { + String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpbPKValueAttr)) { - MISMandate mandate = session.getMISMandate(); - if (session.getUseMandate() && mandate == null) { - Logger.error("Mandate is requested but NO mandate-data is found!."); - throw new BuildException("builder.00", new Object[]{ - "Mandate", "Mandate is requested but NO mandate-data is found!"}); + //fix a wrong bPK-value prefix, which was used in some PVP Standardportal implementations + if (pvpbPKValueAttr.startsWith("bPK:")) { + Logger.warn("Attribute " + PVPConstants.BPK_NAME + + " contains a not standardize prefix! Staring attribute value correction process ..."); + pvpbPKValueAttr = pvpbPKValueAttr.substring("bPK:".length()); } - authData.setMandateReferenceValue(session.getMandateReferenceValue()); - - if (mandate != null) { - //set MIS mandate to authdata - authData.setMISMandate(mandate); - authData.setUseMandate(session.getUseMandate()); - - } else { - //check if ELGA mandates exists - String mandateType = session.getGenericDataFromSession( - PVPConstants.MANDATE_TYPE_NAME, String.class); - if (MiscUtil.isNotEmpty(mandateType)) { - //switch to mandate-mode for authdata generation, because mandate-information - // is directly included in MOA-Session as PVP attributes - Logger.debug("AuthDataBuilder find directly included 'MandateType' attribute." - + " --> Switch to mandate-mode for authdata generation."); - authData.setUseMandate(true); - - } - + String[] spitted = pvpbPKValueAttr.split(":"); + if (spitted.length != 2) { + Logger.warn("Attribute " + PVPConstants.BPK_NAME + " has a wrong encoding and can NOT be USED!" + + " Value:" + pvpbPKValueAttr); + return null; } - - if (session.getUseMandate() && session.isOW() - && mandate != null && MiscUtil.isNotEmpty(mandate.getOWbPK())) { - authData.setBPK(mandate.getOWbPK()); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); - - //TODO: check in case of mandates for business services - authData.setIdentityLink(identityLink); - Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); - - } else { - buildOAspecificbPK(protocolRequest, oaParam, authData, - identityLink.getIdentificationValue(), - identityLink.getIdentificationType()); - - buildOAspecificIdentityLink(oaParam, authData, identityLink); - - } + Logger.debug("Find PVP-Attr: " + PVPConstants.BPK_FRIENDLY_NAME); + return spitted[1]; - //TODO - } catch (BuildException e) { - throw e; + } + + return null; + } + + /** + * Get bPK-Type from PVP Attribute 'EID_SECTOR_FOR_IDENTIFIER_NAME', which could be exist in + * MOASession as 'GenericData'
session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)
+ * + * @param session MOASession, but never null + * @return bPKType, which was received by PVP-Attribute, or null if no attribute exists + */ + private String getbPKTypeFromPVPAttribute(AuthenticationSession session) { + String pvpbPKTypeAttr = session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpbPKTypeAttr)) { - } catch (Throwable ex) { - throw new BuildException("builder.00", new Object[]{ - "AuthenticationData", ex.toString()}, ex); - } + //fix a wrong bPK-Type encoding, which was used in some PVP Standardportal implementations + if (pvpbPKTypeAttr.startsWith(Constants.URN_PREFIX_CDID) && + !pvpbPKTypeAttr.substring(Constants.URN_PREFIX_CDID.length(), + Constants.URN_PREFIX_CDID.length() + 1).equals("+")) { + Logger.warn("Receive uncorrect encoded bBKType attribute " + pvpbPKTypeAttr + " Starting attribute value correction ... "); + pvpbPKTypeAttr = Constants.URN_PREFIX_CDID + "+" + pvpbPKTypeAttr.substring(Constants.URN_PREFIX_CDID.length() + 1); + + } + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME); + return pvpbPKTypeAttr; + } + + return null; + + + /* + * INFO: This code could be used to extract the bPKType from 'PVPConstants.BPK_NAME', + * because the prefix of BPK_NAME attribute contains the postfix of the bPKType + * + * Now, all PVP Standardportals should be able to send 'EID_SECTOR_FOR_IDENTIFIER' + * PVP attributes + */ +// String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class); +// String[] spitted = pvpbPKValueAttr.split(":"); +// if (MiscUtil.isEmpty(authData.getBPKType())) { +// Logger.debug("PVP assertion contains NO bPK/wbPK target attribute. " + +// "Starting target extraction from bPK/wbPK prefix ..."); +// //exract bPK/wbPK type from bpk attribute value prefix if type is +// //not transmitted as single attribute +// Pattern pattern = Pattern.compile("[a-zA-Z]{2}(-[a-zA-Z]+)?"); +// Matcher matcher = pattern.matcher(spitted[0]); +// if (matcher.matches()) { +// //find public service bPK +// authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + spitted[0]); +// Logger.debug("Found bPK prefix. Set target to " + authData.getBPKType()); +// +// } else { +// //find business service wbPK +// authData.setBPKType(Constants.URN_PREFIX_WBPK+ "+" + spitted[0]); +// Logger.debug("Found wbPK prefix. Set target to " + authData.getBPKType()); +// +// } +// } } - - private void buildOAspecificIdentityLink(IOAAuthParameters oaParam, AuthenticationData authData, IdentityLink idl) throws MOAIDException { + + private IdentityLink buildOAspecificIdentityLink(IOAAuthParameters oaParam, IdentityLink idl, String bPK, String bPKType) throws MOAIDException { if (oaParam.getBusinessService()) { Element idlassertion = idl.getSamlAssertion(); //set bpk/wpbk; Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - prIdentification.getFirstChild().setNodeValue(authData.getBPK()); + prIdentification.getFirstChild().setNodeValue(bPK); //set bkp/wpbk type Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); - prIdentificationType.getFirstChild().setNodeValue(authData.getBPKType()); + prIdentificationType.getFirstChild().setNodeValue(bPKType); IdentityLinkAssertionParser idlparser = new IdentityLinkAssertionParser(idlassertion); IdentityLink businessServiceIdl = idlparser.parseIdentityLink(); @@ -1073,62 +1087,70 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { resignedilAssertion = businessServiceIdl.getSamlAssertion(); } IdentityLinkAssertionParser resignedIDLParser = new IdentityLinkAssertionParser(resignedilAssertion); - IdentityLink resignedIDL = resignedIDLParser.parseIdentityLink(); + return resignedIDLParser.parseIdentityLink(); - authData.setIdentityLink(resignedIDL); - } else - authData.setIdentityLink(idl); + return idl; } - - private void buildOAspecificbPK(IRequest protocolRequest, IOAAuthParameters oaParam, AuthenticationData authData, String baseID, String baseIDType) throws BuildException { - - if (oaParam.getBusinessService()) { - //since we have foreigner, wbPK is not calculated in BKU - if (baseIDType.equals(Constants.URN_PREFIX_BASEID)) { - String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); - authData.setBPK(new BPKBuilder().buildbPKorwbPK(baseID, registerAndOrdNr)); - authData.setBPKType(registerAndOrdNr); - - } else { - authData.setBPK(baseID); - authData.setBPKType(baseIDType); - - } - Logger.trace("Authenticate user with wbPK " + authData.getBPK()); - - } else { - if (baseIDType.equals(Constants.URN_PREFIX_BASEID)) { - // only compute bPK if online application is a public service and we have the Stammzahl - String target = null; - Object saml1Requst = null; - try { - saml1Requst = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl").newInstance(); - - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | java.lang.SecurityException ex) { - - - } - - if (saml1Requst != null && protocolRequest.getClass().isInstance(saml1Requst)) - target = protocolRequest.getGenericData( - MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, String.class); - else - target = oaParam.getTarget(); - - String bpkBase64 = new BPKBuilder().buildBPK(baseID, target); - authData.setBPK(bpkBase64); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + target); - } + private Pair buildOAspecificbPK(IRequest pendingReq, IOAAuthParameters oaParam, AuthenticationData authData) throws BuildException { + + String bPK; + String bPKType; - Logger.trace("Authenticate user with bPK " + authData.getBPK()); - } + String baseID = authData.getIdentificationValue(); + String baseIDType = authData.getIdentificationType(); + + String eIDASOutboundCountry = pendingReq.getGenericData(RequestImpl.eIDAS_GENERIC_REQ_DATA_COUNTRY, String.class); + if (Constants.URN_PREFIX_BASEID.equals(baseIDType)) { + if (MiscUtil.isNotEmpty(eIDASOutboundCountry) && !COUNTRYCODE_AUSTRIA.equals(eIDASOutboundCountry)) { + Pair eIDASID = new BPKBuilder().buildeIDASIdentifer(baseIDType, baseID, + COUNTRYCODE_AUSTRIA, eIDASOutboundCountry); + Logger.trace("Authenticate user with bPK:" + eIDASID.getFirst() + " Type:" + eIDASID.getSecond()); + return eIDASID; + + } else if (oaParam.getBusinessService()) { + //is Austrian private-service application + String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); + bPK = new BPKBuilder().buildbPKorwbPK(baseID, registerAndOrdNr); + bPKType = registerAndOrdNr; + + } else { + // only compute bPK if online application is a public service and we have the Stammzahl + String target = null; + Class saml1RequstTemplate = null; + try { + saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); + if (saml1RequstTemplate != null && + saml1RequstTemplate.isInstance(pendingReq)) { + target = (String) pendingReq.getClass().getMethod("getTarget").invoke(pendingReq); + + } + + } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | java.lang.SecurityException | InvocationTargetException | NoSuchMethodException ex) { } + + if (MiscUtil.isEmpty(target)) + target = oaParam.getTarget(); + + bPK = new BPKBuilder().buildBPK(baseID, target); + bPKType = Constants.URN_PREFIX_CDID + "+" + target; + + } + + } else { + Logger.warn("!!!baseID-element does not include a baseID. This should not be happen any more!!!"); + bPK = baseID; + bPKType = baseIDType; + + } + Logger.trace("Authenticate user with bPK:" + bPK + " Type:" + bPKType); + return Pair.newInstance(bPK, bPKType); + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java index 1cf6929e6..9e4e36fec 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java @@ -46,13 +46,6 @@ package at.gv.egovernment.moa.id.auth.builder; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Base64Utils; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.MiscUtil; - import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -66,6 +59,13 @@ import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; +import at.gv.egovernment.moa.id.auth.exception.BuildException; +import at.gv.egovernment.moa.id.data.Pair; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.Base64Utils; +import at.gv.egovernment.moa.util.Constants; +import at.gv.egovernment.moa.util.MiscUtil; + /** * Builder for the bPK, as defined in * "Ableitung f¨r die bereichsspezifische Personenkennzeichnung" @@ -203,73 +203,42 @@ public class BPKBuilder { /** * Builds the storkeid from the given parameters. * - * @param identityLink identity link - * @param destinationCountry destination country code (2 chars) - * @return storkid in a BASE64 encoding - * @throws BuildException if an error occurs on building the wbPK - */ - public String buildStorkeIdentifier(IdentityLink identityLink, String destinationCountry) - throws BuildException { - return buildStorkbPK(identityLink.getIdentificationValue(), - identityLink.getIdentificationType(), "AT", destinationCountry); - } - - /** - * Builds the storkeid from the given parameters. - * - * @param identityLink identity link - * @param destinationCountry destination country code (2 chars) - * @return storkid in a BASE64 encoding - * @throws BuildException if an error occurs on building the wbPK - */ - public String buildStorkeIdentifier(String identificationType, String identificationValue, String destinationCountry) - throws BuildException { - return buildStorkbPK(identificationValue, identificationType, "AT", destinationCountry); - } - - /** - * Builds the storkeid from the given parameters. - * - * @param identityLink identity link - * @param sourceCountry source country code (2 chars) - * @param destinationCountry destination country code (2 chars) - * @return storkid in a BASE64 encoding + * @param baseID baseID of the citizen + * @param baseIDType Type of the baseID + * @param sourceCountry CountryCode of that country, which build the eIDAs ID + * @param destinationCountry CountryCode of that country, which receives the eIDAs ID + * + * @return Pair in a BASE64 encoding * @throws BuildException if an error occurs on building the wbPK */ - public String buildStorkbPK(String baseID, String baseIDType, String sourceCountry, String destinationCountry) - throws BuildException { - String identificationValue = null; - + public Pair buildeIDASIdentifer(String baseID, String baseIDType, String sourceCountry, String destinationCountry) + throws BuildException { + String bPK = null; + String bPKType = null; + // check if we have been called by public sector application - if (baseIDType.startsWith(Constants.URN_PREFIX_BASEID)) { - identificationValue = calculateStorkeIdentifierBase(baseID, sourceCountry, destinationCountry); + if (baseIDType.startsWith(Constants.URN_PREFIX_BASEID)) { + bPKType = Constants.URN_PREFIX_EIDAS + "+" + sourceCountry + "+" + destinationCountry; + Logger.debug("Building eIDAS identification from: [identValue]+" + bPKType); + bPK = calculatebPKwbPK(baseID + "+" + bPKType); } else { // if not, sector identification value is already calculated by BKU - Logger.debug("STORK eIdentifier already provided by BKU"); - identificationValue = baseID; + Logger.debug("eIDAS eIdentifier already provided by BKU"); + bPK = baseID; } - if ((identificationValue == null || - identificationValue.length() == 0 || - destinationCountry == null || - destinationCountry.length() == 0 || - sourceCountry == null || - sourceCountry.length() == 0)) { + if ((MiscUtil.isEmpty(bPK) || + MiscUtil.isEmpty(sourceCountry) || + MiscUtil.isEmpty(destinationCountry))) { throw new BuildException("builder.00", - new Object[]{"storkid", "Unvollständige Parameterangaben: identificationValue=" + - identificationValue + ", Zielland=" + destinationCountry + ", Ursprungsland=" + sourceCountry}); + new Object[]{"eIDAS-ID", "Unvollständige Parameterangaben: identificationValue=" + + bPK + ", Zielland=" + destinationCountry + ", Ursprungsland=" + sourceCountry}); } - Logger.info("Building STORK identification from: " + sourceCountry+"/"+destinationCountry+"/" + "[identValue]"); - String eIdentifier = sourceCountry+"/"+destinationCountry+"/"+identificationValue; - - return eIdentifier; - } - - private String calculateStorkeIdentifierBase(String baseID, String sourceCountry, String destinationCountry) throws BuildException { - String basisbegriff = baseID + "+" + Constants.URN_PREFIX_STORK + "+" + sourceCountry + "+" + destinationCountry; - Logger.debug("Building STORK identification from: [identValue]+" + Constants.URN_PREFIX_STORK + "+" + sourceCountry + "+" + destinationCountry); - return calculatebPKwbPK(basisbegriff); + Logger.debug("Building eIDAS identification from: " + sourceCountry+"/"+destinationCountry+"/" + "[identValue]"); + String eIdentifier = sourceCountry + "/" + destinationCountry + "/" + bPK; + + return Pair.newInstance(eIdentifier, baseIDType); } private String calculatebPKwbPK(String basisbegriff) throws BuildException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java index 648dcf6f1..4a764e362 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java @@ -38,5 +38,7 @@ public class AuthenticationSessionStorageConstants { public static final String eIDAS_ATTRIBUTELIST = PREFIX_eIDAS + "attributeList"; public static final String eIDAS_RESPONSE = PREFIX_eIDAS + "response"; + + public static final String FEDERATION_RESPONSE_VALIDE_TO = "federationRespValidTo"; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java index b7e95785b..a4abbbcfa 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java @@ -78,20 +78,20 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ //check UseMandate flag - String useMandateString = null; - boolean useMandateBoolean = false; + String useMISMandateString = null; + boolean useMISMandateBoolean = false; if ((useMandate != null) && (useMandate.compareTo("") != 0)) { - useMandateString = useMandate; + useMISMandateString = useMandate; } else { - useMandateString = "false"; + useMISMandateString = "false"; } - if (useMandateString.compareToIgnoreCase("true") == 0) - useMandateBoolean = true; + if (useMISMandateString.compareToIgnoreCase("true") == 0) + useMISMandateBoolean = true; else - useMandateBoolean = false; + useMISMandateBoolean = false; - moasession.setUseMandate(useMandateString); + moasession.setUseMandate(useMISMandateString); //load OnlineApplication configuration @@ -155,7 +155,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ } else { Logger.debug("Service-Provider is of type 'PrivateService' with DomainIdentifier:" + oaParam.getIdentityLinkDomainIdentifier()); - if (useMandateBoolean) { + if (useMISMandateBoolean) { Logger.error("Online-Mandate Mode for business application not supported."); throw new AuthenticationException("auth.17", null); } @@ -213,6 +213,12 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ protocolReq.setNeedSingleSignOnFunctionality(false); } + if (protocolReq.needSingleSignOnFunctionality() && useMISMandateBoolean) { + Logger.info("Usage of MIS-MandateService does not allow Single Sign-On. --> SSO is disabled for this request."); + protocolReq.setNeedSingleSignOnFunctionality(false); + + } + } public void parse(ExecutionContext ec, HttpServletRequest req, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java index 53be0881b..aa9a0824d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java @@ -147,8 +147,8 @@ public class AuthenticationData implements IAuthData, Serializable { private boolean ssoSession = false; private Date ssoSessionValidTo = null; - private boolean interfederatedSSOSession = false; - private String interfederatedIDP = null; +// private boolean interfederatedSSOSession = false; +// private String interfederatedIDP = null; private String sessionIndex = null; private String nameID = null; @@ -255,16 +255,18 @@ public class AuthenticationData implements IAuthData, Serializable { } /** - * Returns the identificationValue. - * @return String + * Holds the baseID of a citizen + * + * @return baseID */ public String getIdentificationValue() { return identificationValue; } /** - * Returns the identificationType - * @return String + * Holds the type of the baseID + * + * @return baseID-Type */ public String getIdentificationType() { return identificationType; @@ -439,6 +441,10 @@ public class AuthenticationData implements IAuthData, Serializable { } public Element getMandate() { + if (mandate == null) + return null; + + //parse Element from mandate XML try { byte[] byteMandate = mandate.getMandate(); String stringMandate = new String(byteMandate); @@ -579,7 +585,9 @@ public class AuthenticationData implements IAuthData, Serializable { } /** - * @return the ccc + * CountryCode of the citizen which is identified and authenticated + * + * @return the CountryCode
like. AT, SI, ...
*/ public String getCcc() { return ccc; @@ -635,33 +643,33 @@ public class AuthenticationData implements IAuthData, Serializable { this.nameIDFormat = nameIDFormat; } - /** - * @return the interfederatedSSOSession - */ - public boolean isInterfederatedSSOSession() { - return interfederatedSSOSession; - } - - /** - * @param interfederatedSSOSession the interfederatedSSOSession to set - */ - public void setInterfederatedSSOSession(boolean interfederatedSSOSession) { - this.interfederatedSSOSession = interfederatedSSOSession; - } - - /** - * @return the interfederatedIDP - */ - public String getInterfederatedIDP() { - return interfederatedIDP; - } - - /** - * @param interfederatedIDP the interfederatedIDP to set - */ - public void setInterfederatedIDP(String interfederatedIDP) { - this.interfederatedIDP = interfederatedIDP; - } +// /** +// * @return the interfederatedSSOSession +// */ +// public boolean isInterfederatedSSOSession() { +// return interfederatedSSOSession; +// } +// +// /** +// * @param interfederatedSSOSession the interfederatedSSOSession to set +// */ +// public void setInterfederatedSSOSession(boolean interfederatedSSOSession) { +// this.interfederatedSSOSession = interfederatedSSOSession; +// } +// +// /** +// * @return the interfederatedIDP +// */ +// public String getInterfederatedIDP() { +// return interfederatedIDP; +// } +// +// /** +// * @param interfederatedIDP the interfederatedIDP to set +// */ +// public void setInterfederatedIDP(String interfederatedIDP) { +// this.interfederatedIDP = interfederatedIDP; +// } /** * @return the ssoSessionValidTo diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java index 91d40fcc3..c32564679 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java @@ -40,7 +40,7 @@ public interface IAuthData { boolean isBusinessService(); boolean isSsoSession(); - boolean isInterfederatedSSOSession(); + //boolean isInterfederatedSSOSession(); boolean isUseMandate(); String getFamilyName(); @@ -53,7 +53,7 @@ public interface IAuthData { Date getSsoSessionValidTo(); - String getInterfederatedIDP(); + //String getInterfederatedIDP(); String getIdentificationValue(); String getIdentificationType(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java index 12fe3c948..81157994e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java @@ -79,7 +79,7 @@ public class MISMandate implements Serializable{ private String oid = null; private byte[] mandate = null; private String owBPK = null; - private boolean isFullMandateIncluded = false; +// private boolean isFullMandateIncluded = false; public String getProfRep() { return oid; @@ -144,18 +144,18 @@ public class MISMandate implements Serializable{ } } - /** - * @return the isFullMandateIncluded - */ - public boolean isFullMandateIncluded() { - return isFullMandateIncluded; - } - /** - * @param isFullMandateIncluded the isFullMandateIncluded to set - */ - public void setFullMandateIncluded(boolean isFullMandateIncluded) { - this.isFullMandateIncluded = isFullMandateIncluded; - } +// /** +// * @return the isFullMandateIncluded +// */ +// public boolean isFullMandateIncluded() { +// return isFullMandateIncluded; +// } +// /** +// * @param isFullMandateIncluded the isFullMandateIncluded to set +// */ +// public void setFullMandateIncluded(boolean isFullMandateIncluded) { +// this.isFullMandateIncluded = isFullMandateIncluded; +// } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java new file mode 100644 index 000000000..78e8be452 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * 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.data; + +public class Trible { + private final P1 first; + private final P2 second; + private final P3 third; + + private Trible(final P1 newFirst, final P2 newSecond, final P3 newThird) { + this.first = newFirst; + this.second = newSecond; + this.third = newThird; + } + + public P1 getFirst() { + return this.first; + } + + public P2 getSecond() { + return this.second; + } + + public P3 getThird() { + return this.third; + } + + public static Trible newInstance(final P1 newFirst, final P2 newSecond, final P3 newThird) { + return new Trible(newFirst, newSecond, newThird); + } +} 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 21ef38732..f065bbc56 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 @@ -72,7 +72,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder; 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.utils.MOASAMLSOAPClient; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.storage.ITransactionStorage; @@ -100,7 +100,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { @Autowired private MOAReversionLogger revisionsLogger; @Autowired protected AuthConfiguration authConfig; @Autowired private SingleLogOutBuilder sloBuilder; - @Autowired private SAMLVerificationEngine samlVerificationEngine; + @Autowired private SAMLVerificationEngineSP samlVerificationEngine; public void performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index e05bedac8..aec5ad124 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -48,7 +48,10 @@ public abstract class RequestImpl implements IRequest, Serializable{ public static final String DATAID_INTERFEDERATIOIDP_URL = "interIDPURL"; public static final String DATAID_INTERFEDERATIOIDP_RESPONSE = "interIDPResponse"; - public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; + public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; + public static final String DATAID_INTERFEDERATIOIDP_ENTITYID = "interIDPEntityID"; + + public static final String eIDAS_GENERIC_REQ_DATA_COUNTRY = "country"; private static final long serialVersionUID = 1L; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java index 7cbdeca66..0e6dc1838 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java @@ -26,7 +26,6 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java index 0437cd687..69f0c3088 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java @@ -23,7 +23,6 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributePolicyException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java index 27d3845ff..ca66700a2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java @@ -26,10 +26,7 @@ import java.io.IOException; import javax.xml.transform.TransformerException; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; @@ -48,7 +45,7 @@ public class MandateFullMandateAttributeBuilder implements IPVPAttributeBuilder if (authData.isUseMandate()) { //only provide full mandate if it is included. //In case of federation only a short mandate could be include - if (authData.getMandate() != null && authData.getMISMandate().isFullMandateIncluded()) { + if (authData.getMandate() != null) { String fullMandate; try { fullMandate = DOMUtils.serializeNode(authData diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java index 8948f1227..55c864335 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java @@ -46,7 +46,7 @@ public class MandateNaturalPersonGivenNameAttributeBuilder implements IPVPAttrib IAttributeGenerator g) throws AttributeException { if (authData.isUseMandate()) { //get PVP attribute directly, if exists - String givenName = authData.getGenericData(MANDATE_NAT_PER_BPK_NAME, String.class); + String givenName = authData.getGenericData(MANDATE_NAT_PER_GIVEN_NAME_NAME, String.class); if (MiscUtil.isEmpty(givenName)) { Element mandate = authData.getMandate(); 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 042eeeed8..142810d45 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 @@ -25,6 +25,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x; import java.util.ArrayList; import java.util.Arrays; +import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; @@ -44,23 +45,28 @@ import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; import at.gv.egovernment.moa.id.auth.builder.DynamicOAAuthParameterBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.FederatedAuthenticatenContainer; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; +import at.gv.egovernment.moa.id.data.Trible; import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.SoapBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; 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.IDPCredentialProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -72,7 +78,7 @@ public class AttributQueryAction implements IAction { @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; @Autowired private AuthenticationDataBuilder authDataBuilder; @Autowired private IDPCredentialProvider pvpCredentials; - @Autowired private ITransactionStorage transactionStorage; + @Autowired private AuthConfiguration authConfig; private final static List DEFAULTSTORKATTRIBUTES = Arrays.asList( new String[]{PVPConstants.EID_STORK_TOKEN_NAME}); @@ -98,34 +104,44 @@ public class AttributQueryAction implements IAction { //set time reference DateTime date = new DateTime(); - //get Single Sign-On information for the Service-Provider - // which sends the Attribute-Query request - AuthenticationSession moaSession = authenticationSessionStorage.getSession(pendingReq.getMOASessionIdentifier()); - if (moaSession == null) { - Logger.warn("No MOASession with ID:" + pendingReq.getMOASessionIdentifier() + " FOUND."); - throw new MOAIDException("auth.02", new Object[]{pendingReq.getMOASessionIdentifier()}); - } - - InterfederationSessionStore nextIDPInformation = - authenticationSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(moaSession.getSessionID()); - - AttributeQuery attrQuery = - (AttributeQuery)((MOARequest)((PVPTargetConfiguration) pendingReq).getRequest()).getSamlRequest(); + try { + //get Single Sign-On information for the Service-Provider + // which sends the Attribute-Query request + AuthenticationSession moaSession = authenticationSessionStorage.getSession(pendingReq.getMOASessionIdentifier()); + if (moaSession == null) { + Logger.warn("No MOASession with ID:" + pendingReq.getMOASessionIdentifier() + " FOUND."); + throw new MOAIDException("auth.02", new Object[]{pendingReq.getMOASessionIdentifier()}); + } - //generate authData for AttributQueryRequest - authData = authDataBuilder.buildAuthenticationDataForAttributQuery(pendingReq, moaSession, attrQuery.getAttributes(), nextIDPInformation); - + InterfederationSessionStore nextIDPInformation = + authenticationSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(moaSession.getSessionID()); - //add default attributes in case of mandates or STORK is in use - List attrList = addDefaultAttributes(attrQuery, authData); + AttributeQuery attrQuery = + (AttributeQuery)((MOARequest)((PVPTargetConfiguration) pendingReq).getRequest()).getSamlRequest(); + + //build PVP 2.1 response-attribute information for this AttributQueryRequest + Trible, Date, String> responseInfo = + buildResponseInformationForAttributQuery(pendingReq, moaSession, attrQuery.getAttributes(), nextIDPInformation); - //build PVP 2.1 assertion - Assertion assertion = PVP2AssertionBuilder.buildAssertion(req, attrQuery, attrList, authData, date, authData.getSessionIndex()); - - //build PVP 2.1 response - Response authResponse = AuthResponseBuilder.buildResponse(req.getAuthURL(), attrQuery, date, assertion); - - try { + Logger.debug("AttributQuery return " + responseInfo.getFirst().size() + + " attributes with QAA-Level:" + responseInfo.getThird() + + " validTo:" + responseInfo.getSecond().toString()); + + //build PVP 2.1 assertion + + String issuerEntityID = pendingReq.getAuthURL(); + if (issuerEntityID.endsWith("/")) + issuerEntityID = issuerEntityID.substring(0, issuerEntityID.length()-1); + + Assertion assertion = PVP2AssertionBuilder.buildAssertion(issuerEntityID, + attrQuery, responseInfo.getFirst(), date, new DateTime(responseInfo.getSecond().getTime()), + responseInfo.getThird(), authData.getSessionIndex()); + + //build PVP 2.1 response + Response authResponse = AuthResponseBuilder.buildResponse( + MOAMetadataProvider.getInstance(), issuerEntityID, attrQuery, date, + assertion, authConfig.isPVP2AssertionEncryptionActive()); + SoapBinding decoder = new SoapBinding(); decoder.encodeRespone(httpReq, httpResp, authResponse, null, null, pvpCredentials.getIDPAssertionSigningCredential()); @@ -139,6 +155,11 @@ public class AttributQueryAction implements IAction { Logger.error("Security exception", e); throw new MOAIDException("pvp2.01", null, e); + } catch (MOADatabaseException e) { + Logger.error("MOASession with SessionID=" + pendingReq.getMOASessionIdentifier() + + " is not found in Database", e); + throw new MOAIDException("init.04", new Object[] { pendingReq.getMOASessionIdentifier() }); + } } else { @@ -164,32 +185,143 @@ public class AttributQueryAction implements IAction { public String getDefaultActionName() { return PVP2XProtocol.ATTRIBUTEQUERY; } + + private Trible, Date, String> buildResponseInformationForAttributQuery(IRequest pendingReq, + AuthenticationSession session, List reqAttributes, InterfederationSessionStore nextIDPInformation) throws MOAIDException { + try { + //mark AttributeQuery as used if it exists + OASessionStore activeOA = authenticationSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); + if (activeOA != null) { + //mark + if ( pendingReq instanceof PVPTargetConfiguration && + ((PVPTargetConfiguration) pendingReq).getRequest() instanceof MOARequest && + ((PVPTargetConfiguration) pendingReq).getRequest().getInboundMessage() instanceof AttributeQuery) { + try { + activeOA.setAttributeQueryUsed(true); + MOASessionDBUtils.saveOrUpdate(activeOA); + + } catch (MOADatabaseException e) { + Logger.error("MOASession interfederation information can not stored to database.", e); + + } + } + } + + //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) and configuration + IOAAuthParameters spConfig = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes); + + //search federated IDP information for this MOASession + if (nextIDPInformation != null) { + Logger.info("Find active federated IDP information." + + ". --> Request next IDP:" + nextIDPInformation.getIdpurlprefix() + + " for authentication information."); + + //load configuration of next IDP + OAAuthParameter idp = authConfig.getOnlineApplicationParameter(nextIDPInformation.getIdpurlprefix()); + if (idp == null) { + Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() + + "is not loadable."); + throw new MOAIDException("auth.32", new Object[]{nextIDPInformation.getIdpurlprefix()}); + + } + + //check if next IDP config allows inbound messages + if (!idp.isInboundSSOInterfederationAllowed()) { + Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() + + "disallow inbound authentication messages."); + throw new MOAIDException("auth.33", new Object[]{nextIDPInformation.getIdpurlprefix()}); + + } + + //check next IDP service area policy. BusinessService IDPs can only request wbPKs + if (!spConfig.getBusinessService() && !idp.isIDPPublicService()) { + Logger.error("Interfederated IDP " + idp.getPublicURLPrefix() + + " has a BusinessService-IDP but requests PublicService attributes."); + throw new MOAIDException("auth.34", new Object[]{nextIDPInformation.getIdpurlprefix()}); + + } + + //validation complete --> start AttributeQuery Request + AssertionAttributeExtractor extractor = authDataBuilder.getAuthDataFromAttributeQuery(reqAttributes, + nextIDPInformation.getUserNameID(), idp); + + try { + //mark attribute request as used + if (nextIDPInformation.isStoreSSOInformation()) { + nextIDPInformation.setAttributesRequested(true); + MOASessionDBUtils.saveOrUpdate(nextIDPInformation); - private List addDefaultAttributes(AttributeQuery query, IAuthData authData) { + //delete federated IDP from Session + } else { + MOASessionDBUtils.delete(nextIDPInformation); + + } + + } catch (MOADatabaseException e) { + Logger.error("MOASession interfederation information can not stored to database.", e); + + } + + return Trible.newInstance( + extractor.getAllResponseAttributesFromFirstAttributeStatement(), + extractor.getAssertionNotOnOrAfter(), + extractor.getQAALevel()); + + } else { + Logger.debug("Build authData for AttributQuery from local MOASession."); + IAuthData authData = authDataBuilder.buildAuthenticationData(pendingReq, session, spConfig); + + //add default attributes in case of mandates or STORK is in use + List attrList = addDefaultAttributes(reqAttributes, authData); + + //build Set of response attributes + List respAttr = PVPAttributeBuilder.buildSetOfResponseAttributes(authData, attrList); + + return Trible.newInstance(respAttr, authData.getSsoSessionValidTo(), authData.getQAALevel()); + + } + + } catch (MOAIDException e) { + throw e; + } + } + + /** + * Add additional PVP Attribute-Names in respect to current MOASession. + *

+ *
As example: if current MOASession includes mandates but mandate attributes are not requested, 
+	 * this method a a minimum set of mandate attribute-names
+ * + * @param reqAttr From Service Provider requested attributes + * @param authData AuthenticationData + * @return List of PVP attribute-names + */ + private List addDefaultAttributes(List reqAttr, IAuthData authData) { - List reqAttributs = new ArrayList(); + List reqAttributeNames = new ArrayList(); - for (Attribute attr : query.getAttributes()) { - reqAttributs.add(attr.getName()); + for (Attribute attr : reqAttr) { + reqAttributeNames.add(attr.getName()); } //add default STORK attributes if it is a STORK authentication - if (authData.isForeigner() && !reqAttributs.containsAll(DEFAULTSTORKATTRIBUTES)) { + if (authData.isForeigner() && !reqAttributeNames.containsAll(DEFAULTSTORKATTRIBUTES)) { for (String el : DEFAULTSTORKATTRIBUTES) { - if (!reqAttributs.contains(el)) - reqAttributs.add(el); + if (!reqAttributeNames.contains(el)) + reqAttributeNames.add(el); } } //add default mandate attributes if it is a authentication with mandates - if (authData.isUseMandate() && !reqAttributs.containsAll(DEFAULTMANDATEATTRIBUTES)) { + if (authData.isUseMandate() && !reqAttributeNames.containsAll(DEFAULTMANDATEATTRIBUTES)) { for (String el : DEFAULTMANDATEATTRIBUTES) { - if (!reqAttributs.contains(el)) - reqAttributs.add(el); + if (!reqAttributeNames.contains(el)) + reqAttributeNames.add(el); } } - return reqAttributs; + return reqAttributeNames; } + } 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 2882f20e1..a214dad9d 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 @@ -38,6 +38,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationImpl; import at.gv.egovernment.moa.id.data.SLOInformationInterface; @@ -50,6 +51,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.BindingNotSupportedException; 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.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; @@ -57,6 +59,7 @@ import at.gv.egovernment.moa.logging.Logger; @Service("PVPAuthenticationRequestAction") public class AuthenticationAction implements IAction { @Autowired IDPCredentialProvider pvpCredentials; + @Autowired AuthConfiguration authConfig; public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { @@ -77,12 +80,18 @@ public class AuthenticationAction implements IAction { SLOInformationImpl sloInformation = new SLOInformationImpl(); - + //change to entity value from entity name to IDP EntityID (URL) + String issuerEntityID = pvpRequest.getAuthURL(); + if (issuerEntityID.endsWith("/")) + issuerEntityID = issuerEntityID.substring(0, issuerEntityID.length()-1); + //build Assertion - Assertion assertion = PVP2AssertionBuilder.buildAssertion(pvpRequest, authnRequest, authData, + Assertion assertion = PVP2AssertionBuilder.buildAssertion(issuerEntityID, pvpRequest, authnRequest, authData, peerEntity, date, consumerService, sloInformation); - Response authResponse = AuthResponseBuilder.buildResponse(pvpRequest.getAuthURL(), authnRequest, date, assertion); + Response authResponse = AuthResponseBuilder.buildResponse( + MOAMetadataProvider.getInstance(), issuerEntityID, authnRequest, + date, assertion, authConfig.isPVP2AssertionEncryptionActive()); IEncoder binding = null; 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 4dbc35041..8065af1a6 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 @@ -57,20 +57,18 @@ import org.springframework.web.bind.annotation.RequestMethod; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.DynamicOAAuthParameterBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.MOAURICompare; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.SoapBinding; @@ -92,7 +90,7 @@ 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; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.util.ErrorResponseUtils; import at.gv.egovernment.moa.id.util.HTTPUtils; @@ -105,7 +103,7 @@ import at.gv.egovernment.moa.util.MiscUtil; public class PVP2XProtocol extends AbstractAuthProtocolModulController { @Autowired IDPCredentialProvider pvpCredentials; - @Autowired SAMLVerificationEngine samlVerificationEngine; + @Autowired SAMLVerificationEngineSP samlVerificationEngine; public static final String NAME = PVP2XProtocol.class.getName(); public static final String PATH = "id_pvp2x"; @@ -193,9 +191,11 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); //get POST-Binding decoder implementation - InboundMessage msg = (InboundMessage) new PostBinding().decode(req, resp, MOAMetadataProvider.getInstance(), false); + InboundMessage msg = (InboundMessage) new PostBinding().decode( + req, resp, MOAMetadataProvider.getInstance(), false, + new MOAURICompare(PVPConfiguration.getInstance().getIDPSSOPostService(pendingReq.getAuthURL()))); pendingReq.setRequest(msg); - + //preProcess Message preProcess(req, resp, pendingReq); @@ -241,7 +241,9 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); //get POST-Binding decoder implementation - InboundMessage msg = (InboundMessage) new RedirectBinding().decode(req, resp, MOAMetadataProvider.getInstance(), false); + InboundMessage msg = (InboundMessage) new RedirectBinding().decode( + req, resp, MOAMetadataProvider.getInstance(), false, + new MOAURICompare(PVPConfiguration.getInstance().getIDPSSOPostService(pendingReq.getAuthURL()))); pendingReq.setRequest(msg); //preProcess Message @@ -290,7 +292,9 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); //get POST-Binding decoder implementation - InboundMessage msg = (InboundMessage) new SoapBinding().decode(req, resp, MOAMetadataProvider.getInstance(), false); + InboundMessage msg = (InboundMessage) new SoapBinding().decode( + req, resp, MOAMetadataProvider.getInstance(), false, + new MOAURICompare(PVPConfiguration.getInstance().getIDPSSOPostService(pendingReq.getAuthURL()))); pendingReq.setRequest(msg); //preProcess Message diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java index 86b31f1eb..71c5a46a4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java @@ -25,6 +25,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.binding; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.opensaml.common.binding.decoding.URIComparator; import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.ws.message.decoder.MessageDecodingException; import org.opensaml.xml.security.SecurityException; @@ -34,7 +35,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface public interface IDecoder { public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint) + HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, SecurityException, PVP2Exception; public boolean handleDecode(String action, HttpServletRequest req); 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 6d376faa0..46381fcc2 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 @@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.velocity.app.VelocityEngine; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.binding.decoding.URIComparator; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.decoding.HTTPPostDecoder; import org.opensaml.saml2.binding.encoding.HTTPPostEncoder; @@ -49,17 +50,14 @@ import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; 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.config.MOADefaultBootstrap; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; 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.validation.MOAPVPSignedRequestPolicyRule; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -146,26 +144,21 @@ public class PostBinding implements IDecoder, IEncoder { } public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint) throws MessageDecodingException, + HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, SecurityException { HTTPPostDecoder decode = new HTTPPostDecoder(new BasicParserPool()); BasicSAMLMessageContext messageContext = new BasicSAMLMessageContext(); messageContext .setInboundMessageTransport(new HttpServletRequestAdapter(req)); - try { - //set metadata descriptor type - if (isSPEndPoint) { - messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(new MOAURICompare(PVPConfiguration.getInstance().getSPSSOPostService(HTTPUtils.extractAuthURLFromRequest(req)))); - - } else { - messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(new MOAURICompare(PVPConfiguration.getInstance().getIDPSSOPostService(HTTPUtils.extractAuthURLFromRequest(req)))); - } - - } catch (ConfigurationException e) { - throw new SecurityException(e); + //set metadata descriptor type + if (isSPEndPoint) { + messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); + decode.setURIComparator(comparator); + + } else { + messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); + decode.setURIComparator(comparator); } messageContext.setMetadataProvider(metadataProvider); @@ -173,7 +166,7 @@ public class PostBinding implements IDecoder, IEncoder { //set security policy context BasicSecurityPolicy policy = new BasicSecurityPolicy(); policy.getPolicyRules().add( - new MOAPVPSignedRequestPolicyRule( + new MOAPVPSignedRequestPolicyRule(metadataProvider, TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider), messageContext.getPeerEntityRole())); SecurityPolicyResolver secResolver = new StaticSecurityPolicyResolver(policy); 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 683a72e67..1d13cbd07 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 @@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletResponse; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.binding.decoding.URIComparator; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.decoding.HTTPRedirectDeflateDecoder; import org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder; @@ -50,17 +51,14 @@ import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; 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.config.MOADefaultBootstrap; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; 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.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -134,7 +132,7 @@ public class RedirectBinding implements IDecoder, IEncoder { } public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint) throws MessageDecodingException, + HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, SecurityException { HTTPRedirectDeflateDecoder decode = new HTTPRedirectDeflateDecoder( @@ -144,20 +142,14 @@ public class RedirectBinding implements IDecoder, IEncoder { messageContext .setInboundMessageTransport(new HttpServletRequestAdapter(req)); - try { - //set metadata descriptor type - if (isSPEndPoint) { - messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(new MOAURICompare(PVPConfiguration.getInstance().getSPSSORedirectService(HTTPUtils.extractAuthURLFromRequest(req)))); - - } else { - messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(new MOAURICompare(PVPConfiguration.getInstance().getIDPSSORedirectService(HTTPUtils.extractAuthURLFromRequest(req)))); - } - - } catch (ConfigurationException e) { - throw new SecurityException(e); + //set metadata descriptor type + if (isSPEndPoint) { + messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); + decode.setURIComparator(comparator); + } else { + messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); + decode.setURIComparator(comparator); } messageContext.setMetadataProvider(metadataProvider); 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 12b571ed1..25b22f0ad 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 @@ -29,6 +29,7 @@ import javax.servlet.http.HttpServletResponse; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.binding.decoding.URIComparator; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.encoding.HTTPSOAP11Encoder; import org.opensaml.saml2.core.RequestAbstractType; @@ -64,7 +65,7 @@ public class SoapBinding implements IDecoder, IEncoder { @Autowired private IDPCredentialProvider credentialProvider; public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint) throws MessageDecodingException, + HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, SecurityException, PVP2Exception { HTTPSOAP11Decoder soapDecoder = new HTTPSOAP11Decoder(new BasicParserPool()); BasicSAMLMessageContext messageContext = diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java index 24c2626e3..aea3c2ee7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java @@ -23,7 +23,6 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder; import java.util.ArrayList; -import java.util.Date; import java.util.List; import org.joda.time.DateTime; @@ -38,6 +37,7 @@ import org.opensaml.saml2.core.Response; import org.opensaml.saml2.encryption.Encrypter; import org.opensaml.saml2.encryption.Encrypter.KeyPlacement; import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.security.MetadataCredentialResolver; import org.opensaml.security.MetadataCriteria; import org.opensaml.xml.encryption.EncryptionException; @@ -52,11 +52,8 @@ import org.opensaml.xml.security.keyinfo.KeyInfoGeneratorFactory; import org.opensaml.xml.security.x509.X509Credential; import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidAssertionEncryptionException; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; @@ -66,15 +63,12 @@ import at.gv.egovernment.moa.logging.Logger; */ public class AuthResponseBuilder { - public static Response buildResponse(String authURL, RequestAbstractType req, DateTime date, Assertion assertion) throws InvalidAssertionEncryptionException, ConfigurationException { + public static Response buildResponse(MetadataProvider metadataProvider, String issuerEntityID, RequestAbstractType req, DateTime date, Assertion assertion, boolean enableEncryption) throws InvalidAssertionEncryptionException, ConfigurationException { Response authResponse = SAML2Utils.createSAMLObject(Response.class); Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); - //change to entity value from entity name to IDP EntityID (URL) - if (authURL.endsWith("/")) - authURL = authURL.substring(0, authURL.length()-1); - nissuer.setValue(authURL); + nissuer.setValue(issuerEntityID); nissuer.setFormat(NameID.ENTITY); authResponse.setIssuer(nissuer); authResponse.setInResponseTo(req.getID()); @@ -91,7 +85,7 @@ public class AuthResponseBuilder { //check, if metadata includes an encryption key MetadataCredentialResolver mdCredResolver = - new MetadataCredentialResolver(MOAMetadataProvider.getInstance()); + new MetadataCredentialResolver(metadataProvider); CriteriaSet criteriaSet = new CriteriaSet(); criteriaSet.add( new EntityIDCriteria(req.getIssuer().getValue()) ); @@ -107,9 +101,8 @@ public class AuthResponseBuilder { throw new InvalidAssertionEncryptionException(); } - - boolean isEncryptionActive = AuthConfigurationProviderFactory.getInstance().isPVP2AssertionEncryptionActive(); - if (encryptionCredentials != null && isEncryptionActive) { + + if (encryptionCredentials != null && enableEncryption) { //encrypt SAML2 assertion try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java index 164583f77..c48caed29 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java @@ -23,6 +23,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder; import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -155,4 +156,52 @@ public class PVPAttributeBuilder { return attribute; } + /** + * Build a set of PVP Response-Attributes + *

+ * INFO: If a specific attribute can not be build, a info is logged, but no execpetion is thrown. + * Therefore, the return List must not include all requested attributes. + * + * @param authData AuthenticationData IAuthData which is used to build the attribute values, but never null + * @param reqAttributenName List of PVP attribute names which are requested, but never null + * @return List of PVP attributes, but never null + */ + public static List buildSetOfResponseAttributes(IAuthData authData, + Collection reqAttributenName) { + List attrList = new ArrayList(); + if (reqAttributenName != null) { + Iterator it = reqAttributenName.iterator(); + while (it.hasNext()) { + String reqAttributName = it.next(); + try { + Attribute attr = PVPAttributeBuilder.buildAttribute( + reqAttributName, null, authData); + if (attr == null) { + Logger.info( + "Attribute generation failed! for " + + reqAttributName); + + } else { + attrList.add(attr); + + } + + } catch (PVP2Exception e) { + Logger.info( + "Attribute generation failed! for " + + reqAttributName); + + } catch (Exception e) { + Logger.warn( + "General Attribute generation failed! for " + + reqAttributName, e); + + } + } + } + + return attrList; + } + + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java index 0a0be2a2c..d5d84dd51 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java @@ -108,8 +108,16 @@ public class PVPAuthnRequestBuilder { //set basic AuthnRequest information - SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); - authReq.setID(gen.generateIdentifier()); + String reqID = config.getRequestID(); + if (MiscUtil.isNotEmpty(reqID)) + authReq.setID(reqID); + + else { + SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); + authReq.setID(gen.generateIdentifier()); + + } + authReq.setIssueInstant(new DateTime()); //set isPassive flag @@ -158,6 +166,9 @@ public class PVPAuthnRequestBuilder { NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); subjectNameID.setValue(config.getSubjectNameID()); + if (MiscUtil.isNotEmpty(config.getSubjectNameIDQualifier())) + subjectNameID.setNameQualifier(config.getSubjectNameIDQualifier()); + if (MiscUtil.isNotEmpty(config.getSubjectNameIDFormat())) subjectNameID.setFormat(config.getSubjectNameIDFormat()); else diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index 03cfe27d7..7a7044ebf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -66,7 +66,6 @@ import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationImpl; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; @@ -86,45 +85,24 @@ import at.gv.egovernment.moa.util.MiscUtil; public class PVP2AssertionBuilder implements PVPConstants { - public static Assertion buildAssertion(IRequest pendingReq, AttributeQuery attrQuery, - List reqAttributes, IAuthData authData, DateTime date, String sessionIndex) throws ConfigurationException { - - + /** + * Build a PVP assertion as response for a SAML2 AttributeQuery request + * + * @param issuerEntityID EnitiyID, which should be used for this IDP response + * @param attrQuery AttributeQuery request from Service-Provider + * @param attrList List of PVP response attributes + * @param now Current time + * @param validTo ValidTo time of the assertion + * @param qaaLevel QAA level of the authentication + * @param sessionIndex SAML2 SessionIndex, which should be included * + * @return PVP 2.1 Assertion + * @throws ConfigurationException + */ + public static Assertion buildAssertion(String issuerEntityID, AttributeQuery attrQuery, + List attrList, DateTime now, DateTime validTo, String qaaLevel, String sessionIndex) throws ConfigurationException { + AuthnContextClassRef authnContextClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - authnContextClassRef.setAuthnContextClassRef(authData.getQAALevel()); - - List attrList = new ArrayList(); - if (reqAttributes != null) { - Iterator it = reqAttributes.iterator(); - while (it.hasNext()) { - String reqAttributName = it.next(); - try { - Attribute attr = PVPAttributeBuilder.buildAttribute( - reqAttributName, null, authData); - if (attr == null) { - Logger.error( - "Attribute generation failed! for " - + reqAttributName); - - } else { - attrList.add(attr); - - } - - } catch (PVP2Exception e) { - Logger.error( - "Attribute generation failed! for " - + reqAttributName); - - } catch (Exception e) { - Logger.error( - "General Attribute generation failed! for " - + reqAttributName, e); - - } - } - } - + authnContextClassRef.setAuthnContextClassRef(qaaLevel); NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); subjectNameID.setFormat(attrQuery.getSubject().getNameID().getFormat()); @@ -132,17 +110,31 @@ public class PVP2AssertionBuilder implements PVPConstants { SubjectConfirmationData subjectConfirmationData = null; - return buildGenericAssertion(pendingReq.getAuthURL(), attrQuery.getIssuer().getValue(), date, + return buildGenericAssertion(issuerEntityID, attrQuery.getIssuer().getValue(), now, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, - new DateTime(authData.getSsoSessionValidTo().getTime())); + validTo); } - - public static Assertion buildAssertion(PVPTargetConfiguration pendingReq, AuthnRequest authnRequest, + + + /** + * Build a PVP 2.1 assertion as response of a SAML2 AuthnRequest + * + * @param issuerEntityID EnitiyID, which should be used for this IDP response + * @param pendingReq Current processed pendingRequest DAO + * @param authnRequest Current processed PVP AuthnRequest + * @param authData AuthenticationData of the user, which is already authenticated + * @param peerEntity SAML2 EntityDescriptor of the service-provider, which receives the response + * @param date TimeStamp + * @param assertionConsumerService SAML2 endpoint of the service-provider, which should be used + * @param sloInformation Single LogOut information DAO + * @return + * @throws MOAIDException + */ + public static Assertion buildAssertion(String issuerEntityID, PVPTargetConfiguration pendingReq, AuthnRequest authnRequest, IAuthData authData, EntityDescriptor peerEntity, DateTime date, AssertionConsumerService assertionConsumerService, SLOInformationImpl sloInformation) throws MOAIDException { - RequestedAuthnContext reqAuthnContext = authnRequest .getRequestedAuthnContext(); @@ -282,37 +274,74 @@ public class PVP2AssertionBuilder implements PVPConstants { } NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); - + //build nameID and nameID Format from moasession //TODO: nameID generation if (authData.isUseMandate()) { - Element mandate = authData.getMandate(); - if(mandate == null) { - throw new NoMandateDataAvailableException(); - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAvailableException(); - } - CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); - PhysicalPersonType pysicalperson = mandateObject.getMandator().getPhysicalPerson(); + String bpktype = null; + String bpk = null; - IdentificationType id; - if(corporation != null && corporation.getIdentification().size() > 0) - id = corporation.getIdentification().get(0); - + Element mandate = authData.getMandate(); + if(mandate != null) { + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); + PhysicalPersonType pysicalperson = mandateObject.getMandator().getPhysicalPerson(); - else if (pysicalperson != null && pysicalperson.getIdentification().size() > 0) - id = pysicalperson.getIdentification().get(0); + IdentificationType id; + if(corporation != null && corporation.getIdentification().size() > 0) + id = corporation.getIdentification().get(0); + + + else if (pysicalperson != null && pysicalperson.getIdentification().size() > 0) + id = pysicalperson.getIdentification().get(0); + + else { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAvailableException(); + } + + bpktype = id.getType(); + bpk = id.getValue().getValue(); + + } else { + Logger.debug("Read mandatpr bPK|baseID from PVP attributes ... "); + bpk = authData.getGenericData(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME, String.class); + bpktype = authData.getGenericData(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME, String.class); - else { - Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); + if (MiscUtil.isEmpty(bpk)) { + //no sourcePin is included --> search for bPK + bpk = authData.getGenericData(PVPConstants.MANDATE_NAT_PER_BPK_NAME, String.class); + + //set bPK-Type from configuration, because it MUST be equal to service-provider type + if (oaParam.getBusinessService()) { + if (oaParam.getIdentityLinkDomainIdentifier().startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) + bpktype = oaParam.getIdentityLinkDomainIdentifier(); + else + bpktype = Constants.URN_PREFIX_WBPK + "+" + oaParam.getIdentityLinkDomainIdentifier(); + + } else { + if (oaParam.getTarget().startsWith(Constants.URN_PREFIX_CDID + "+")) + bpktype = oaParam.getTarget(); + else + bpktype = Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget(); + + } + + } else { + //sourcePin is include --> check sourcePinType + if (MiscUtil.isEmpty(bpktype)) + bpktype = Constants.URN_PREFIX_BASEID; + + } } - - String bpktype = id.getType(); - String bpk = id.getValue().getValue(); + if (MiscUtil.isEmpty(bpk) || MiscUtil.isEmpty(bpktype)) { + throw new NoMandateDataAvailableException(); + + } if (bpktype.equals(Constants.URN_PREFIX_BASEID)) { if (oaParam.getBusinessService()) { @@ -335,7 +364,7 @@ public class PVP2AssertionBuilder implements PVPConstants { subjectNameID.setNameQualifier(bpktype); subjectNameID.setValue(bpk); } - + } else { subjectNameID.setNameQualifier(authData.getBPKType()); subjectNameID.setValue(authData.getBPK()); @@ -414,7 +443,7 @@ public class PVP2AssertionBuilder implements PVPConstants { sloInformation.setNameIDFormat(subjectNameID.getFormat()); sloInformation.setSessionIndex(sessionIndex); - return buildGenericAssertion(pendingReq.getAuthURL(), peerEntity.getEntityID(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, subjectConfirmationData.getNotOnOrAfter()); + return buildGenericAssertion(issuerEntityID, peerEntity.getEntityID(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, subjectConfirmationData.getNotOnOrAfter()); } /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java index e209d0bc5..6e1798ed1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java @@ -118,6 +118,15 @@ public interface IPVPAuthnRequestBuilderConfiguruation { */ public String getSubjectNameID(); + /** + * Define the qualifier of the SubjectNameID + *

+ * Like: 'urn:publicid:gv.at:cdid+BF' + * + * @return qualifier, or null if no qualifier should be set + */ + public String getSubjectNameIDQualifier(); + /** * Define the format of the subjectNameID, which is included in authn-request * @@ -125,5 +134,13 @@ public interface IPVPAuthnRequestBuilderConfiguruation { * @return nameIDFormat, of SAML2 'transient' if nothing is defined */ public String getSubjectNameIDFormat(); + + /** + * Define a SP specific SAMK2 requestID + * + * @return requestID, or null if the requestID should be generated automatically + */ + public String getRequestID(); + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java index bbf395a6f..58210a72c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java @@ -28,7 +28,6 @@ import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.Manifest; @@ -92,18 +91,18 @@ public class PVPConfiguration { private static String moaIDVersion = null; //PVP2 generalpvpconfigdb; - Properties props; - String rootDir = null; + //Properties props; + //String rootDir = null; private PVPConfiguration() { - try { - //generalpvpconfigdb = AuthConfigurationProvider.getInstance().getGeneralPVP2DBConfig(); - props = AuthConfigurationProviderFactory.getInstance().getGeneralPVP2ProperiesConfig(); - rootDir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); - - } catch (ConfigurationException e) { - e.printStackTrace(); - } +// try { +// //generalpvpconfigdb = AuthConfigurationProvider.getInstance().getGeneralPVP2DBConfig(); +// //props = AuthConfigurationProviderFactory.getInstance().getGeneralPVP2ProperiesConfig(); +// //rootDir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); +// +// } catch (ConfigurationException e) { +// e.printStackTrace(); +// } } public List getIDPPublicPath() throws ConfigurationException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java new file mode 100644 index 000000000..3da4dc18a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java @@ -0,0 +1,38 @@ +/* + * 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.metadata; + +/** + * @author tlenz + * + */ +public interface IMOARefreshableMetadataProvider { + + /** + * Refresh a entity or load a entity in a metadata provider + * + * @param entityID + * @return true, if refresh is success, otherwise false + */ + public boolean refreshMetadataProvider(String entityID); +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java index 6e87abb06..618346485 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java @@ -59,7 +59,7 @@ import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; public class MOAMetadataProvider extends SimpleMOAMetadataProvider - implements ObservableMetadataProvider, IGarbageCollectorProcessing { + implements ObservableMetadataProvider, IGarbageCollectorProcessing, IMOARefreshableMetadataProvider { private static MOAMetadataProvider instance = null; private static Object mutex = new Object(); @@ -118,6 +118,7 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider MetadataProvider internalProvider; + @Override public boolean refreshMetadataProvider(String entityID) { try { OAAuthParameter oaParam = diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java index 8787df82d..106be8a09 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java @@ -25,6 +25,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -53,9 +54,18 @@ public class AssertionAttributeExtractor { private final List minimalAttributeNameList = Arrays.asList( PVPConstants.PRINCIPAL_NAME_NAME, - PVPConstants.GIVEN_NAME_NAME); - - + PVPConstants.GIVEN_NAME_NAME, + PVPConstants.ENC_BPK_LIST_NAME, + PVPConstants.BPK_NAME); + + /** + * Parse the SAML2 Response element and extracts included information + *

+ * INFO: Actually, only the first SAML2 Assertion of the SAML2 Response is used! + * + * @param samlResponse SAML2 Response + * @throws AssertionAttributeExtractorExeption + */ public AssertionAttributeExtractor(StatusResponseType samlResponse) throws AssertionAttributeExtractorExeption { if (samlResponse != null && samlResponse instanceof Response) { List assertions = ((Response) samlResponse).getAssertions(); @@ -96,6 +106,27 @@ public class AssertionAttributeExtractor { throw new AssertionAttributeExtractorExeption(); } + /** + * Get all SAML2 attributes from first SAML2 AttributeStatement element + * + * @return List of SAML2 Attributes + */ + public List getAllResponseAttributesFromFirstAttributeStatement() { + return assertion.getAttributeStatements().get(0).getAttributes(); + + } + + /** + * Get all SAML2 attributes of specific SAML2 AttributeStatement element + * + * @param attrStatementID List ID of the AttributeStatement element + * @return List of SAML2 Attributes + */ + public List getAllResponseAttributes(int attrStatementID) { + return assertion.getAttributeStatements().get(attrStatementID).getAttributes(); + + } + /** * check attributes from assertion with minimal required attribute list * @return @@ -107,7 +138,7 @@ public class AssertionAttributeExtractor { /** * check attributes from assertion with attributeNameList - * bPK or enc_bPK is always needed + * bPK or enc_bPK are always needed * * @param List of attributes which are required * @@ -116,24 +147,24 @@ public class AssertionAttributeExtractor { public boolean containsAllRequiredAttributes(Collection attributeNameList) { //first check if a bPK or an encrypted bPK is available - if (attributs.containsKey(PVPConstants.ENC_BPK_LIST_NAME) || - (attributs.containsKey(PVPConstants.BPK_NAME))) { - boolean flag = true; - for (String attr : attributeNameList) { - if (!attributs.containsKey(attr)) { - flag = false; - Logger.debug("Assertion contains no Attribute " + attr); - - } - + boolean flag = true; + for (String attr : attributeNameList) { + if (!attributs.containsKey(attr)) { + flag = false; + Logger.debug("Assertion contains no Attribute " + attr); + } - - return flag; - + } - Logger.debug("Assertion contains no bPK or encryptedbPK."); - return false; + if (flag) + return flag; + + else { + Logger.debug("Assertion contains no bPK or encryptedbPK."); + return false; + + } } public boolean containsAttribute(String attributeName) { @@ -218,6 +249,29 @@ public class AssertionAttributeExtractor { return assertion; } + + /** + * Get the Assertion validTo period + * + * Primarily, the 'SessionNotOnOrAfter' attribute in the SAML2 'AuthnStatment' element is used. + * If this is empty, this method returns value of SAML 'Conditions' element. + * + * @return Date, until this SAML2 assertion is valid + */ + public Date getAssertionNotOnOrAfter() { + if (getFullAssertion().getAuthnStatements() != null + && getFullAssertion().getAuthnStatements().size() > 0) { + for (AuthnStatement el : getFullAssertion().getAuthnStatements()) { + if (el.getSessionNotOnOrAfter() != null) + return (el.getSessionNotOnOrAfter().toDate()); + } + + } + + return getFullAssertion().getConditions().getNotOnOrAfter().toDate(); + + } + private AuthnStatement getAuthnStatement() throws AssertionAttributeExtractorExeption { List authnList = assertion.getAuthnStatements(); if (authnList.size() == 0) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java index f62410656..86ca591ee 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java @@ -139,7 +139,7 @@ public abstract class AbstractRequestSignedSecurityPolicyRule implements Securit throw new SecurityPolicyException("Signature validation FAILED."); } - Logger.debug("PVP AuthnRequest signature valid."); + Logger.debug("PVP message signature valid."); } catch (org.opensaml.xml.security.SecurityException e) { Logger.info("PVP2x message signature validation FAILED. Message:" + e.getMessage()); @@ -148,7 +148,7 @@ public abstract class AbstractRequestSignedSecurityPolicyRule implements Securit } } else { - throw new SecurityPolicyException("Request is not signed."); + throw new SecurityPolicyException("PVP Message is not signed."); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java index 932f3b818..7b3f890e9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java @@ -25,10 +25,12 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.validation; import javax.xml.namespace.QName; import org.opensaml.common.SignableSAMLObject; +import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.xml.XMLObject; import org.opensaml.xml.signature.SignatureTrustEngine; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IMOARefreshableMetadataProvider; +import at.gv.egovernment.moa.logging.Logger; /** * @author tlenz @@ -37,13 +39,19 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; public class MOAPVPSignedRequestPolicyRule extends AbstractRequestSignedSecurityPolicyRule { + private IMOARefreshableMetadataProvider metadataProvider = null; + /** + * @param metadataProvider * @param trustEngine * @param peerEntityRole */ - public MOAPVPSignedRequestPolicyRule(SignatureTrustEngine trustEngine, + public MOAPVPSignedRequestPolicyRule(MetadataProvider metadataProvider, SignatureTrustEngine trustEngine, QName peerEntityRole) { super(trustEngine, peerEntityRole); + if (metadataProvider instanceof IMOARefreshableMetadataProvider) + this.metadataProvider = (IMOARefreshableMetadataProvider) metadataProvider; + } /* (non-Javadoc) @@ -51,7 +59,10 @@ public class MOAPVPSignedRequestPolicyRule extends */ @Override protected boolean refreshMetadataProvider(String entityID) { - return MOAMetadataProvider.getInstance().refreshMetadataProvider(entityID); + if (metadataProvider != null) + return metadataProvider.refreshMetadataProvider(entityID); + + return false; } 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 5e44c9057..f384dd511 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,50 +22,30 @@ *******************************************************************************/ 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; @@ -77,8 +57,6 @@ 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 && @@ -181,111 +159,8 @@ public class SAMLVerificationEngine { throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); } } - - 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 void performSchemaValidation(Element source) throws SchemaValidationException { + + protected void performSchemaValidation(Element source) throws SchemaValidationException { String err = null; try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java new file mode 100644 index 000000000..cd80d8c24 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java @@ -0,0 +1,161 @@ +/* + * 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.verification; + +import java.util.ArrayList; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.EncryptedAssertion; +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.saml2.encryption.Decrypter; +import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; +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.credential.Credential; +import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +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.logging.Logger; + +/** + * @author tlenz + * + */ +@Service("SAMLVerificationEngineSP") +public class SAMLVerificationEngineSP extends SAMLVerificationEngine { + + @Autowired AuthConfiguration authConfig; + + 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); + } + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java index 316ca2177..10594d6fc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java @@ -53,7 +53,6 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.EncryptedData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.util.Random; @@ -440,10 +439,6 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } - //set additional information for AttributeQuery - activeOA.setAttQueryContainerID(protocolRequest.getGenericData( - PVPTargetConfiguration.DATAID_INTERFEDERATION_ATTRQUERYCONTAINERID, String.class)); - List activeOAs = dbsession.getActiveOAsessions(); activeOAs.add(activeOA); dbsession.setActiveOAsessions(activeOAs); diff --git a/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties b/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties index cf2e9d6d5..a53d7e920 100644 --- a/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties +++ b/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties @@ -105,6 +105,7 @@ builder.04=Die Personenbindung konnte nicht neu signiert werden und wird aus die builder.05=Beim resignieren der Personenbindung ist ein allgemeiner Fehler aufgetreten und wird aus diesem Grund nicht ausgeliefert. builder.06=Fehler beim generieren der Anmeldedaten aus SSO IDP Interfederation Informationen. builder.07=Fehlerhaftes SecurityLayer Template. +builder.08=Authentication process could NOT completed. Reason: {0} service.00=Fehler beim Aufruf des Web Service: {0} service.01=Fehler beim Aufruf des Web Service: kein Endpoint @@ -220,6 +221,8 @@ validator.70=Das einmale Tokken im signierten AuthBlock ({0}) stimmt nicht mit d validator.71=Das Signaturzertifikat ist nicht qualifiziert. validator.72=Das Signaturzertifikat ist nicht qualifiziert und es wurde keine OID f\u00FCr Test Identit\u00E4ten gefunden. +validator.73=Das MIS-Vollmachtenservice und das ELGA-Vollmachtenservice k\u00f6nnen nicht in einem Anmeldevorgang verwendet werden. + ssl.01=Validierung des SSL-Server-Endzertifikates hat fehlgeschlagen stork.00=STORK SAML AuthnRequest konnte nicht signiert werden @@ -284,10 +287,11 @@ sp.pvp2.01=Can not build PVP AuthnRequest for {0} {0}. IDP is not allowed for fe sp.pvp2.02=Can not build PVP AuthnRequest for {0} {0}. IDP has no (valid) metadata. sp.pvp2.03=Receive PVP Response from {0} with unsupported Binding. sp.pvp2.04=Receive invalid PVP Response from {0}. No PVP metadata found. -sp.pvp2.05=Receive invalid PVP Response from {0} {1}. StatusCode {2}. +sp.pvp2.05=Receive invalid PVP Response from {0} {1}. StatusCode:{2} Msg:{3}. sp.pvp2.06=Receive invalid PVP Response from {0}. Assertion does not contain all required attributes. sp.pvp2.07=Receive invalid PVP Response from {0}. Attribute {1} is not valid. sp.pvp2.08=Receive invalid PVP Response from {0}. Response issuer {1} is not valid or allowed. +sp.pvp2.09=Receive invalid PVP Response from {0} {1}. StatusCodes:{2} {3} Msg:{4} oauth20.01=Fehlerhafte redirect url oauth20.02=Fehlender oder ung\u00FCltiger Parameter "{0}" diff --git a/id/server/idserverlib/src/main/resources/resources/properties/protocol_response_statuscodes_de.properties b/id/server/idserverlib/src/main/resources/resources/properties/protocol_response_statuscodes_de.properties index 2aed7d47d..a81540e2b 100644 --- a/id/server/idserverlib/src/main/resources/resources/properties/protocol_response_statuscodes_de.properties +++ b/id/server/idserverlib/src/main/resources/resources/properties/protocol_response_statuscodes_de.properties @@ -85,6 +85,7 @@ builder.04=Die Personenbindung konnte nicht neu signiert werden und wird aus die builder.05=Beim resignieren der Personenbindung ist ein allgemeiner Fehler aufgetreten und wird aus diesem Grund nicht ausgeliefert. builder.06=4400 builder.07=9002 +builder.08=TODO service.00=4300 service.03=4300 @@ -109,6 +110,7 @@ sp.pvp2.05=TODO sp.pvp2.06=TODO sp.pvp2.07=TODO sp.pvp2.08=TODO +sp.pvp2.09=TODO validator.00=1102 validator.01=1102 @@ -178,6 +180,9 @@ validator.69=1106 validator.70=1106 validator.71=1105 +validator.72=TODO +validator.73=TODO + ssl.01=1107 stork.00=1200 diff --git a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java index bead2f593..44ae43115 100644 --- a/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java +++ b/id/server/moa-id-commons/src/main/java/at/gv/egovernment/moa/id/commons/db/dao/session/OASessionStore.java @@ -70,10 +70,7 @@ public class OASessionStore implements Serializable{ @Column(name = "attributequeryused", unique=false, nullable=false) private boolean attributeQueryUsed = false; - - @Column(name = "attQueryContainerID", unique=false, nullable=true) - private String attQueryContainerID = null; - + @Column(name = "created", updatable=false, nullable=false) // @Temporal(TemporalType.TIMESTAMP) private Date created; @@ -203,24 +200,5 @@ public class OASessionStore implements Serializable{ this.authURL = authURL; } - /** - * @return the attQueryContainerID - */ - public String getAttQueryContainerID() { - return attQueryContainerID; - } - - /** - * @param attQueryContainerID the attQueryContainerID to set - */ - public void setAttQueryContainerID(String attQueryContainerID) { - this.attQueryContainerID = attQueryContainerID; - } - - - - - - } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java index e3afc713b..aff6b1ca6 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java @@ -54,7 +54,7 @@ public class CertificateReadRequestTask extends AbstractAuthServletTask { //execute default task initialization defaultTaskInitialization(req, executionContext); - boolean useMandate = moasession.getUseMandate(); + boolean useMandate = moasession.isMandateUsed(); boolean identityLinkAvailable = BooleanUtils.isTrue((Boolean) executionContext.get("identityLinkAvailable")); if (!identityLinkAvailable && useMandate) { Logger.error("Online-Mandate Mode for foreign citizencs not supported."); diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java index 54db1d8ff..b1b87f68d 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java @@ -34,6 +34,7 @@ import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser; @@ -62,91 +63,8 @@ public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask { throws TaskExecutionException { try { - Logger.info("BKU is selected -> Start BKU communication ..."); - defaultTaskInitialization(request, executionContext); - - boolean isLegacyRequest = false; - Object isLegacyRequestObj = executionContext.get("isLegacyRequest"); - if (isLegacyRequestObj != null && isLegacyRequestObj instanceof Boolean) - isLegacyRequest = (boolean) isLegacyRequestObj; - - if (isLegacyRequest) { - //parse request parameter into MOASession - Logger.info("Start Authentication Module: " + pendingReq.requestedModule() - + " Action: " + pendingReq.requestedAction()); - - authInitialisationParser.parse(executionContext, request, moasession, pendingReq); - - } else { - String bkuid = (String) executionContext.get(MOAIDAuthConstants.PARAM_BKU); - String useMandate = (String) executionContext.get(MOAIDAuthConstants.PARAM_USEMANDATE); - String ccc = (String) executionContext.get(MOAIDAuthConstants.PARAM_CCC); - - if (MiscUtil.isEmpty(bkuid)) { - Logger.warn("BKU-type is empty. Maybe an old BKU-selection template is in use."); - throw new MOAIDException("auth.23", new Object[] {}); - } - - //load OA Config - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - - if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[] { pendingReq.getOAURL() }); - - else { - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUTYPE_SELECTED, bkuid); - - //get Target from config or from request in case of SAML 1 - String target = null; - if (MiscUtil.isNotEmpty(pendingReq.getGenericData("target", String.class)) && - pendingReq.requestedModule().equals("at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol")) - target = pendingReq.getGenericData("target", String.class); - else - target = oaParam.getTarget(); - - String bkuURL = oaParam.getBKUURL(bkuid); - if (MiscUtil.isEmpty(bkuURL)) { - Logger.info("No OA specific BKU defined. Use BKU from default configuration"); - bkuURL = authConfig.getDefaultBKUURL(bkuid); - } - - //search for OA specific template - String templateURL = null; - List oaTemplateURLList = oaParam.getTemplateURL(); - if ( oaTemplateURLList != null && oaTemplateURLList.size() > 0 - && MiscUtil.isNotEmpty(oaTemplateURLList.get(0)) ) { - templateURL = oaTemplateURLList.get(0); - - } else { - templateURL = authConfig.getSLRequestTemplates(bkuid); - } - - //make url absolut if it is a local url - if (MiscUtil.isNotEmpty(templateURL)) - templateURL = FileUtils.makeAbsoluteURL(templateURL, - authConfig.getRootConfigFileDir()); - - if (oaParam.isOnlyMandateAllowed()) - useMandate = "true"; - - if (!oaParam.isShowMandateCheckBox()) - useMandate = "false"; - - //parse all OA parameters i - authInitialisationParser.parse( moasession, - target, - pendingReq.getOAURL(), - bkuURL, - templateURL, - useMandate, - ccc, - request, - pendingReq); - } - } - - executionContext.put(MOAIDAuthConstants.PARAM_USEMANDATE, moasession.getUseMandate()); + // + internalInitializeWithoutPersist(executionContext, request, response); // make sure MOASession and Pending-Request has been persisted before running the process try { @@ -171,5 +89,97 @@ public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask { } } + + protected void internalInitializeWithoutPersist(ExecutionContext executionContext, + HttpServletRequest request, HttpServletResponse response) throws WrongParametersException, MOAIDException, MOADatabaseException { + + Logger.info("BKU is selected -> Start BKU communication ..."); + defaultTaskInitialization(request, executionContext); + + boolean isLegacyRequest = false; + Object isLegacyRequestObj = executionContext.get("isLegacyRequest"); + if (isLegacyRequestObj != null && isLegacyRequestObj instanceof Boolean) + isLegacyRequest = (boolean) isLegacyRequestObj; + + if (isLegacyRequest) { + //parse request parameter into MOASession + Logger.info("Start Authentication Module: " + pendingReq.requestedModule() + + " Action: " + pendingReq.requestedAction()); + + authInitialisationParser.parse(executionContext, request, moasession, pendingReq); + + } else { + String bkuid = (String) executionContext.get(MOAIDAuthConstants.PARAM_BKU); + String useMandate = (String) executionContext.get(MOAIDAuthConstants.PARAM_USEMANDATE); + String ccc = (String) executionContext.get(MOAIDAuthConstants.PARAM_CCC); + + if (MiscUtil.isEmpty(bkuid)) { + Logger.warn("BKU-type is empty. Maybe an old BKU-selection template is in use."); + throw new MOAIDException("auth.23", new Object[] {}); + } + + //load OA Config + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + + if (oaParam == null) + throw new AuthenticationException("auth.00", new Object[] { pendingReq.getOAURL() }); + + else { + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUTYPE_SELECTED, bkuid); + + //get Target from config or from request in case of SAML 1 + String target = null; + if (MiscUtil.isNotEmpty(pendingReq.getGenericData("target", String.class)) && + pendingReq.requestedModule().equals("at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol")) + target = pendingReq.getGenericData("target", String.class); + else + target = oaParam.getTarget(); + + String bkuURL = oaParam.getBKUURL(bkuid); + if (MiscUtil.isEmpty(bkuURL)) { + Logger.info("No OA specific BKU defined. Use BKU from default configuration"); + bkuURL = authConfig.getDefaultBKUURL(bkuid); + } + + //search for OA specific template + String templateURL = null; + List oaTemplateURLList = oaParam.getTemplateURL(); + if ( oaTemplateURLList != null && oaTemplateURLList.size() > 0 + && MiscUtil.isNotEmpty(oaTemplateURLList.get(0)) ) { + templateURL = oaTemplateURLList.get(0); + + } else { + templateURL = authConfig.getSLRequestTemplates(bkuid); + } + + //make url absolut if it is a local url + if (MiscUtil.isNotEmpty(templateURL)) + templateURL = FileUtils.makeAbsoluteURL(templateURL, + authConfig.getRootConfigFileDir()); + + if (oaParam.isOnlyMandateAllowed()) + useMandate = "true"; + + if (!oaParam.isShowMandateCheckBox()) + useMandate = "false"; + + //parse all OA parameters i + authInitialisationParser.parse( moasession, + target, + pendingReq.getOAURL(), + bkuURL, + templateURL, + useMandate, + ccc, + request, + pendingReq); + } + } + + executionContext.put(MOAIDAuthConstants.PARAM_USEMANDATE, moasession.isMandateUsed()); + executionContext.put(MOAIDAuthConstants.PARAM_USEMISMANDATE, moasession.isMandateUsed()); + + } } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java index 464c1f3a1..cd444f7c8 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java @@ -89,7 +89,7 @@ public class VerifyCertificateTask extends AbstractAuthServletTask { throw new AuthenticationException("auth.14", null); } - if (moasession.getUseMandate()) { + if (moasession.isMandateUsed()) { // verify certificate for OrganWalter authServer.verifyCertificate(moasession, cert, pendingReq); diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java index e346c8bee..7b5a7b9c0 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java @@ -56,7 +56,6 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.codec.binary.Base64; -import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; @@ -148,7 +147,6 @@ public class MISSimpleClient { //misMandate.setMandate(Base64.decodeBase64(DOMUtils.getText(mandate))); misMandate.setMandate(Base64.decodeBase64(DOMUtils.getText(mandate).getBytes())); - misMandate.setFullMandateIncluded(true); foundMandates.add(misMandate); } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml index 74792ed72..afa3fe2ad 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml @@ -38,7 +38,7 @@ - + diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/Constants.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/Constants.java index 909b29fab..8471439e2 100644 --- a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/Constants.java +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/Constants.java @@ -79,6 +79,4 @@ public class Constants { public static final int eIDAS_REVERSIONSLOG_SP_AUTHREQUEST= 3403; public static final int eIDAS_REVERSIONSLOG_SP_AUTHRESPONSE= 3404; - public static final String eIDAS_GENERIC_REQ_DATA_COUNTRY = "country"; - } diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/ReceiveAuthnResponseTask.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/ReceiveAuthnResponseTask.java index dea9e675e..9858d6004 100644 --- a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/ReceiveAuthnResponseTask.java +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/ReceiveAuthnResponseTask.java @@ -15,6 +15,7 @@ import at.gv.egovernment.moa.id.auth.modules.eidas.utils.MOAPersonalAttributeLis import at.gv.egovernment.moa.id.auth.modules.eidas.utils.SAMLEngineUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import eu.eidas.auth.commons.EIDASAuthnResponse; @@ -72,6 +73,9 @@ public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { AuthenticationSessionStorageConstants.eIDAS_RESPONSE, decSamlToken); + //set issuer nation as PVP attribute into MOASession + moasession.setGenericDataToSession(PVPConstants.EID_ISSUING_NATION_NAME, samlResp.getCountry()); + //store MOA-session to database authenticatedSessionStorage.storeSession(moasession); diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASProtocol.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASProtocol.java index 4caa6700a..1e3b0f507 100644 --- a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASProtocol.java +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASProtocol.java @@ -39,6 +39,7 @@ import at.gv.egovernment.moa.id.auth.modules.eidas.utils.SAMLEngineUtils; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -153,7 +154,7 @@ public class EIDASProtocol extends AbstractAuthProtocolModulController { // - memorize country code of target country pendingReq.setGenericDataToSession( - Constants.eIDAS_GENERIC_REQ_DATA_COUNTRY, samlReq.getCountry()); + RequestImpl.eIDAS_GENERIC_REQ_DATA_COUNTRY, samlReq.getCountry()); // - memorize requested attributes pendingReq.setEidasRequestedAttributes(new MOAPersonalAttributeList(samlReq.getPersonalAttributeList())); diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/eIDASAuthenticationRequest.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/eIDASAuthenticationRequest.java index d75d4b1b9..5f3f89aee 100644 --- a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/eIDASAuthenticationRequest.java +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/eIDASAuthenticationRequest.java @@ -37,7 +37,6 @@ import org.springframework.http.MediaType; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; import at.gv.egovernment.moa.id.auth.modules.eidas.engine.MOAeIDASChainingMetadataProvider; @@ -90,8 +89,9 @@ public class eIDASAuthenticationRequest implements IAction { case Constants.eIDAS_ATTR_DATEOFBIRTH: newValue = new SimpleDateFormat("YYYY-MM-dd").format(authData.getDateOfBirth()); break; case Constants.eIDAS_ATTR_CURRENTFAMILYNAME: newValue = authData.getFamilyName();break; case Constants.eIDAS_ATTR_CURRENTGIVENNAME: newValue = authData.getGivenName();break; - case Constants.eIDAS_ATTR_PERSONALIDENTIFIER: newValue = new BPKBuilder().buildStorkeIdentifier(authData.getIdentificationType(), authData.getIdentificationValue(), - eidasRequest.getGenericData(Constants.eIDAS_GENERIC_REQ_DATA_COUNTRY, String.class)); break; + + //TODO: change bPK builder !!!!!! + case Constants.eIDAS_ATTR_PERSONALIDENTIFIER: newValue = authData.getBPK(); break; } if("".equals(newValue)) diff --git a/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/config/ELGAMandatesRequestBuilderConfiguration.java b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/config/ELGAMandatesRequestBuilderConfiguration.java index b521116d3..320c4fdc6 100644 --- a/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/config/ELGAMandatesRequestBuilderConfiguration.java +++ b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/config/ELGAMandatesRequestBuilderConfiguration.java @@ -42,6 +42,8 @@ public class ELGAMandatesRequestBuilderConfiguration implements IPVPAuthnRequest private EntityDescriptor idpEntity; private Credential signCred; private String subjectNameID; + private String subjectNameIDQualifier; + private String requestID; /* (non-Javadoc) @@ -73,7 +75,7 @@ public class ELGAMandatesRequestBuilderConfiguration implements IPVPAuthnRequest */ @Override public String getNameIDPolicyFormat() { - return NameID.TRANSIENT; + return NameID.PERSISTENT; } /* (non-Javadoc) @@ -81,7 +83,7 @@ public class ELGAMandatesRequestBuilderConfiguration implements IPVPAuthnRequest */ @Override public boolean getNameIDPolicyAllowCreation() { - return true; + return false; } /* (non-Javadoc) @@ -143,6 +145,15 @@ public class ELGAMandatesRequestBuilderConfiguration implements IPVPAuthnRequest this.subjectNameID = subjectNameID; } + + + /** + * @param requestID the requestID to set + */ + public void setRequestID(String requestID) { + this.requestID = requestID; + } + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getAuthnRequestSigningCredential() */ @@ -183,5 +194,30 @@ public class ELGAMandatesRequestBuilderConfiguration implements IPVPAuthnRequest return NameID.PERSISTENT; } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getRequestID() + */ + @Override + public String getRequestID() { + return this.requestID; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getSubjectNameIDQualifier() + */ + @Override + public String getSubjectNameIDQualifier() { + return this.subjectNameIDQualifier; + } + + /** + * @param subjectNameIDQualifier the subjectNameIDQualifier to set + */ + public void setSubjectNameIDQualifier(String subjectNameIDQualifier) { + this.subjectNameIDQualifier = subjectNameIDQualifier; + } + + + } diff --git a/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/ELGAInitializeBKUAuthenticationTask.java b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/ELGAInitializeBKUAuthenticationTask.java new file mode 100644 index 000000000..50bac3eab --- /dev/null +++ b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/ELGAInitializeBKUAuthenticationTask.java @@ -0,0 +1,107 @@ +/* + * 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.auth.modules.elgamandates.tasks; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Component; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.auth.modules.internal.tasks.InitializeBKUAuthenticationTask; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +@Component("ELGAInitializeBKUAuthenticationTask") +public class ELGAInitializeBKUAuthenticationTask extends InitializeBKUAuthenticationTask { + + @Override + public void execute(ExecutionContext executionContext, + HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + + try { + //perform Default-BKU authentication initialization + internalInitializeWithoutPersist(executionContext, request, response); + + //perform ELGA Mandate-Service specific parts + Logger.debug("Perfom ELGA-Mandate specific parts of initialisation."); + Boolean misMandateUsed = (Boolean) executionContext.get(MOAIDAuthConstants.PARAM_USEMISMANDATE); + + boolean elgaMandateUsed = false; + Object elgaMandateUsedObj = executionContext.get(MOAIDAuthConstants.PARAM_USEELGAMANDATE); + if (elgaMandateUsedObj == null || + !(elgaMandateUsedObj instanceof String || elgaMandateUsedObj instanceof Boolean)) { + Logger.error("Use ELGA-MandateService flag has a wrong type."); + throw new MOAIDException("auth.12", new Object[]{"Start-BKU Authentication","useELGAMandate"}); + + } else { + if (elgaMandateUsedObj instanceof String) + elgaMandateUsed = Boolean.parseBoolean((String) elgaMandateUsedObj); + else + elgaMandateUsed = (boolean) elgaMandateUsedObj; + + } + + + //check if both mandate Services are requested + if ( (misMandateUsed != null && misMandateUsed) && + elgaMandateUsed ) { + Logger.error("Can not use MIS-MandateService and ELGA-MandateService twince"); + throw new MOAIDException("validator.73", null); + + } + + //remove MIS-Mandate flag and set useMandate flag to MOASession + if (elgaMandateUsed) { + Logger.debug("Authentication process select ELGA-MandateService."); + executionContext.remove(MOAIDAuthConstants.PARAM_USEMISMANDATE); + moasession.setUseMandates(elgaMandateUsed); + } + + //disable SSO if it is requested + if (pendingReq.needSingleSignOnFunctionality() && moasession.isMandateUsed()) { + Logger.info("ELGA-MandateService does not allow Single Sign-On. SSO get disabled for this request."); + pendingReq.setNeedSingleSignOnFunctionality(false); + + + } + + //store MOASession and pendingRequest + requestStoreage.storePendingRequest(pendingReq); + authenticatedSessionStorage.storeSession(moasession); + + } catch (MOADatabaseException | MOAIDException e) { + Logger.info("Initialize BKUAuthentication with ELGA Mandates FAILED. Reason:" + e.getMessage()); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + } +} diff --git a/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/ReceiveElgaMandateResponseTask.java b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/ReceiveElgaMandateResponseTask.java index 13e17e03e..a5e316f10 100644 --- a/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/ReceiveElgaMandateResponseTask.java +++ b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/ReceiveElgaMandateResponseTask.java @@ -37,6 +37,7 @@ import org.opensaml.xml.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; @@ -46,6 +47,7 @@ import at.gv.egovernment.moa.id.auth.modules.elgamandates.utils.ELGAMandatesCred import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IDecoder; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.MOAURICompare; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; @@ -55,7 +57,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -67,7 +69,7 @@ import at.gv.egovernment.moa.util.MiscUtil; @Component("ReceiveElgaMandateResponseTask") public class ReceiveElgaMandateResponseTask extends AbstractAuthServletTask { - @Autowired SAMLVerificationEngine samlVerificationEngine; + @Autowired SAMLVerificationEngineSP samlVerificationEngine; @Autowired ELGAMandatesCredentialProvider credentialProvider; @Autowired ELGAMandateServiceMetadataProvider metadataProvider; @@ -81,13 +83,18 @@ public class ReceiveElgaMandateResponseTask extends AbstractAuthServletTask { try { IDecoder decoder = null; + MOAURICompare comperator = null; //select Response Binding if (request.getMethod().equalsIgnoreCase("POST")) { decoder = new PostBinding(); + comperator = new MOAURICompare(pendingReq.getAuthURL() + + ELGAMandatesAuthConstants.ENDPOINT_POST); Logger.debug("Receive PVP Response from ELGA mandate-service, by using POST-Binding."); } else if (request.getMethod().equalsIgnoreCase("GET")) { decoder = new RedirectBinding(); + comperator = new MOAURICompare(pendingReq.getAuthURL() + + ELGAMandatesAuthConstants.ENDPOINT_REDIRECT); Logger.debug("Receive PVP Response from ELGA mandate-service, by using Redirect-Binding."); } else { @@ -99,7 +106,8 @@ public class ReceiveElgaMandateResponseTask extends AbstractAuthServletTask { } //decode PVP response object - msg = (InboundMessage) decoder.decode(request, response, metadataProvider, true); + msg = (InboundMessage) decoder.decode(request, response, metadataProvider, true, + comperator); if (MiscUtil.isEmpty(msg.getEntityID())) { throw new InvalidProtocolRequestException("sp.pvp2.04", @@ -138,7 +146,7 @@ public class ReceiveElgaMandateResponseTask extends AbstractAuthServletTask { //validate receive mandate reference-value String responseRefValue = extractor.getSingleAttributeValue(PVPConstants.MANDATE_REFERENCE_VALUE_NAME); if (!moasession.getMandateReferenceValue().equals(responseRefValue)) { - Logger.warn("PVP Response from ELGA mandate-service contains not all requested attributes."); + Logger.warn("PVP Response from ELGA mandate-service contains a not valid MandateReferenceValue."); throw new AssertionValidationExeption("sp.pvp2.07", new Object[]{ELGAMandatesAuthConstants.MODULE_NAME_FOR_LOGGING, PVPConstants.MANDATE_REFERENCE_VALUE_FRIENDLY_NAME}); @@ -157,30 +165,35 @@ public class ReceiveElgaMandateResponseTask extends AbstractAuthServletTask { //store MOASession authenticatedSessionStorage.storeSession(moasession); - //TODO write log entries - //revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_REVEIVED); + //write revisions log entry + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_RECEIVED); Logger.info("Receive a valid assertion from ELGA mandate-service " + msg.getEntityID()); } catch (MessageDecodingException | SecurityException e) { String samlRequest = request.getParameter("SAMLRequest"); Logger.warn("Receive INVALID PVP Response from ELGA mandate-service: " + samlRequest, e); + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED); throw new TaskExecutionException(pendingReq, "Receive INVALID PVP Response from ELGA mandate-service", e); } catch (IOException | MarshallingException | TransformerException e) { Logger.warn("Processing PVP response from ELGA mandate-service FAILED.", e); + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED); throw new TaskExecutionException(pendingReq, "Processing PVP response from ELGA mandate-service FAILED.", e); } catch (CredentialsNotAvailableException e) { Logger.error("ELGA mandate-service: PVP response decrytion FAILED. No credential found.", e); + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED); throw new TaskExecutionException(pendingReq, "ELGA mandate-service: PVP response decrytion FAILED. No credential found.", e); } catch (AssertionValidationExeption | AuthnResponseValidationException e) { - Logger.info("ELGA mandate-service: PVP response validation FAILED. Msg:" + e.getMessage()); + Logger.info("ELGA mandate-service: PVP response validation FAILED. Msg:" + e.getMessage()); + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED, e.getMessageId()); throw new TaskExecutionException(pendingReq, "ELGA mandate-service: PVP response validation FAILED.", e); } catch (Exception e) { - Logger.info("ELGA mandate-service: General Exception. Msg:" + e.getMessage()); + Logger.info("ELGA mandate-service: General Exception. Msg:" + e.getMessage()); + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED); throw new TaskExecutionException(pendingReq, "ELGA mandate-service: General Exception.", e); } @@ -210,12 +223,36 @@ public class ReceiveElgaMandateResponseTask extends AbstractAuthServletTask { return msg; } else { - Logger.info("Receive StatusCode " + samlResp.getStatus().getStatusCode().getValue() - + " from federated IDP."); - throw new AuthnResponseValidationException("sp.pvp2.04", - new Object[]{ELGAMandatesAuthConstants.MODULE_NAME_FOR_LOGGING, - samlResp.getIssuer().getValue(), - samlResp.getStatus().getStatusCode().getValue()}); + String errorMsg = "No error message"; + StatusCode firstCode = samlResp.getStatus().getStatusCode(); + + //get errormessage from response + if (samlResp.getStatus().getStatusMessage() != null && + MiscUtil.isNotEmpty(samlResp.getStatus().getStatusMessage().getMessage())) + errorMsg = samlResp.getStatus().getStatusMessage().getMessage(); + + //extract response status-codes + if (firstCode.getStatusCode() == null) { + Logger.info("Receive StatusCode:" + firstCode.getValue() + " | Msg:" + errorMsg + + " from federated IDP."); + throw new AuthnResponseValidationException("sp.pvp2.05", + new Object[]{ELGAMandatesAuthConstants.MODULE_NAME_FOR_LOGGING, + samlResp.getIssuer().getValue(), + firstCode.getValue(), + samlResp.getStatus().getStatusMessage().getMessage()}); + + } else { + StatusCode secondCode = firstCode.getStatusCode(); + Logger.info("Receive StatusCode:" + firstCode.getValue() + " -> StatusCode:" + secondCode.getValue() + + " | Msg:" + errorMsg + " from federated IDP."); + throw new AuthnResponseValidationException("sp.pvp2.09", + new Object[]{ELGAMandatesAuthConstants.MODULE_NAME_FOR_LOGGING, + samlResp.getIssuer().getValue(), + firstCode.getValue(), + secondCode.getValue(), + samlResp.getStatus().getStatusMessage().getMessage()}); + + } } diff --git a/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/RequestELGAMandateTask.java b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/RequestELGAMandateTask.java index bcd8076bc..2a3e72640 100644 --- a/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/RequestELGAMandateTask.java +++ b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/tasks/RequestELGAMandateTask.java @@ -34,6 +34,7 @@ import org.opensaml.xml.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; @@ -92,7 +93,7 @@ public class RequestELGAMandateTask extends AbstractAuthServletTask { authnReqConfig.setPassive(false); authnReqConfig.setSignCred(credential.getIDPAssertionSigningCredential()); authnReqConfig.setSPEntityID(pendingReq.getAuthURL() + ELGAMandatesAuthConstants.ENDPOINT_METADATA); - + //set bPK of representative String representativeBPK = null; @@ -129,15 +130,19 @@ public class RequestELGAMandateTask extends AbstractAuthServletTask { } } - - //TODO: check subjectNameID: as per PVP S-Profile specification, - // subjectNameID starts with target postfix (like. GH:xxxxxxxxxxxxx) + + //set bPK of representative as SAML2 subjectNameID authnReqConfig.setSubjectNameID(representativeBPK ); + authnReqConfig.setSubjectNameIDQualifier(configTarget); + + //set MandateReferenceValue as RequestID + authnReqConfig.setRequestID(moasession.getMandateReferenceValue()); //build and transmit AuthnRequest authnReqBuilder.buildAuthnRequest(pendingReq, authnReqConfig , response); - //TODO: TODO: add revisionslog entries + //write revisions log entry + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_SERVICE_REQUESTED, moasession.getMandateReferenceValue()); } catch (MetadataProviderException e) { throw new TaskExecutionException(pendingReq, "ELGA Mandate-Service metadata problem", new ELGAMetadataException("service.10", diff --git a/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/utils/ELGAMandateServiceMetadataProvider.java b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/utils/ELGAMandateServiceMetadataProvider.java index 6deb8eb2b..49f131983 100644 --- a/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/utils/ELGAMandateServiceMetadataProvider.java +++ b/id/server/modules/moa-id-module-elga_mandate_service/src/main/java/at/gv/egovernment/moa/id/auth/modules/elgamandates/utils/ELGAMandateServiceMetadataProvider.java @@ -197,13 +197,12 @@ public class ELGAMandateServiceMetadataProvider extends SimpleMOAMetadataProvide filter, ELGAMandatesAuthConstants.MODULE_NAME_FOR_LOGGING); - metadataProvider.setRequireValidMetadata(true); - - if (metadataProvider == null) { Logger.error("Create ELGA Mandate-Service Client FAILED."); throw new MetadataProviderException("Can not initialize ELGA Mandate-Service metadaa provider."); } + + metadataProvider.setRequireValidMetadata(true); } } diff --git a/id/server/modules/moa-id-module-elga_mandate_service/src/main/resources/at/gv/egovernment/moa/id/auth/modules/elgamandates/DefaultAuth_with_ELGA_mandates.process.xml b/id/server/modules/moa-id-module-elga_mandate_service/src/main/resources/at/gv/egovernment/moa/id/auth/modules/elgamandates/DefaultAuth_with_ELGA_mandates.process.xml index b648e4d27..8cd08d226 100644 --- a/id/server/modules/moa-id-module-elga_mandate_service/src/main/resources/at/gv/egovernment/moa/id/auth/modules/elgamandates/DefaultAuth_with_ELGA_mandates.process.xml +++ b/id/server/modules/moa-id-module-elga_mandate_service/src/main/resources/at/gv/egovernment/moa/id/auth/modules/elgamandates/DefaultAuth_with_ELGA_mandates.process.xml @@ -5,7 +5,7 @@ - National authentication with Austrian Citizen Card and mobile signature with our without mandate. - Legacy authentication for foreign citizens using MOCCA supported signature cards. --> - + @@ -25,9 +25,9 @@ - + - + @@ -43,7 +43,7 @@ - + diff --git a/id/server/modules/moa-id-module-elga_mandate_service/src/main/resources/moaid_elga_mandate_client_auth.beans.xml b/id/server/modules/moa-id-module-elga_mandate_service/src/main/resources/moaid_elga_mandate_client_auth.beans.xml index 6e567a42c..c1abe78df 100644 --- a/id/server/modules/moa-id-module-elga_mandate_service/src/main/resources/moaid_elga_mandate_client_auth.beans.xml +++ b/id/server/modules/moa-id-module-elga_mandate_service/src/main/resources/moaid_elga_mandate_client_auth.beans.xml @@ -27,6 +27,10 @@ class="at.gv.egovernment.moa.id.auth.modules.elgamandates.controller.ELGAMandateSignalController"/> + + diff --git a/id/server/modules/moa-id-module-openID/pom.xml b/id/server/modules/moa-id-module-openID/pom.xml index 030cd32a0..4684c8032 100644 --- a/id/server/modules/moa-id-module-openID/pom.xml +++ b/id/server/modules/moa-id-module-openID/pom.xml @@ -78,12 +78,6 @@ guava 19.0
- - diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferAuthenticationData.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferAuthenticationData.java index 17e88e381..103a03063 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferAuthenticationData.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferAuthenticationData.java @@ -89,21 +89,12 @@ public class SSOTransferAuthenticationData implements IAuthData { return true; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.IAuthData#isInterfederatedSSOSession() - */ - @Override - public boolean isInterfederatedSSOSession() { - // TODO Auto-generated method stub - return false; - } - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.data.IAuthData#isUseMandate() */ @Override public boolean isUseMandate() { - return this.authSession.getUseMandate(); + return this.authSession.isMandateUsed(); } /* (non-Javadoc) @@ -167,15 +158,6 @@ public class SSOTransferAuthenticationData implements IAuthData { return null; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.IAuthData#getInterfederatedIDP() - */ - @Override - public String getInterfederatedIDP() { - // TODO Auto-generated method stub - return null; - } - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.data.IAuthData#getIdentificationValue() */ diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/SSOContainerUtils.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/SSOContainerUtils.java index 4d41ff652..dea538f75 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/SSOContainerUtils.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/SSOContainerUtils.java @@ -105,7 +105,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableEx import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; @@ -139,7 +139,7 @@ public class SSOContainerUtils { } @Autowired IDPCredentialProvider credentials; - @Autowired SAMLVerificationEngine samlVerificationEngine; + @Autowired SAMLVerificationEngineSP samlVerificationEngine; @Autowired AuthConfiguration authConfig; public void parseSSOContainerToMOASessionDataObject(IRequest pendingReq, AuthenticationSession moasession, Response ssoInformation) throws AssertionAttributeExtractorExeption, ConfigurationException { diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/test/java/at/gv/egiz/tests/Tests.java b/id/server/modules/moa-id-module-ssoTransfer/src/test/java/at/gv/egiz/tests/Tests.java index 1beab574a..57f4d11ad 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/test/java/at/gv/egiz/tests/Tests.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/test/java/at/gv/egiz/tests/Tests.java @@ -22,17 +22,6 @@ */ package at.gv.egiz.tests; -import java.io.IOException; - -import org.hibernate.mapping.Map; - -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParser; - /** * @author tlenz * @@ -65,10 +54,10 @@ public class Tests { - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } +// } catch (IOException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthnRequestBuilderConfiguration.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthnRequestBuilderConfiguration.java index 4ae162f5a..19eae06d7 100644 --- a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthnRequestBuilderConfiguration.java +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthnRequestBuilderConfiguration.java @@ -171,7 +171,22 @@ public class FederatedAuthnRequestBuilderConfiguration implements IPVPAuthnReque */ @Override public String getSubjectNameIDFormat() { - // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getRequestID() + */ + @Override + public String getRequestID() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getSubjectNameIDQualifier() + */ + @Override + public String getSubjectNameIDQualifier() { return null; } diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/ReceiveAuthnResponseTask.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/ReceiveAuthnResponseTask.java index a07a87c2b..d5c5354c0 100644 --- a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/ReceiveAuthnResponseTask.java +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/ReceiveAuthnResponseTask.java @@ -32,12 +32,9 @@ import javax.servlet.http.HttpServletResponse; import javax.xml.transform.TransformerException; import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeQuery; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.StatusCode; import org.opensaml.ws.message.decoder.MessageDecodingException; -import org.opensaml.ws.soap.common.SOAPException; -import org.opensaml.xml.XMLObject; import org.opensaml.xml.io.MarshallingException; import org.opensaml.xml.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; @@ -45,8 +42,11 @@ import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; @@ -55,12 +55,12 @@ import at.gv.egovernment.moa.id.auth.modules.federatedauth.utils.FederatedAuthCr import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.FederatedAuthenticatenContainer; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.moduls.SSOManager; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IDecoder; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.MOAURICompare; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; @@ -73,11 +73,9 @@ 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.utils.AssertionAttributeExtractor; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -88,11 +86,12 @@ import at.gv.egovernment.moa.util.MiscUtil; @Component("ReceiveFederatedAuthnResponseTask") public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { - @Autowired private SAMLVerificationEngine samlVerificationEngine; + @Autowired private SAMLVerificationEngineSP samlVerificationEngine; @Autowired private FederatedAuthCredentialProvider credentialProvider; @Autowired private SSOManager ssoManager; @Autowired private AttributQueryBuilder attributQueryBuilder; - @Autowired private ITransactionStorage transactionStorage; + @Autowired private AuthenticationDataBuilder authDataBuilder; + /* (non-Javadoc) @@ -106,13 +105,16 @@ public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { try { IDecoder decoder = null; + MOAURICompare comperator = null; //select Response Binding if (request.getMethod().equalsIgnoreCase("POST")) { decoder = new PostBinding(); + comperator = new MOAURICompare(pendingReq.getAuthURL() + FederatedAuthConstants.ENDPOINT_POST); Logger.trace("Receive PVP Response from federated IDP, by using POST-Binding."); } else if (request.getMethod().equalsIgnoreCase("GET")) { decoder = new RedirectBinding(); + comperator = new MOAURICompare(pendingReq.getAuthURL() + FederatedAuthConstants.ENDPOINT_REDIRECT); Logger.trace("Receive PVP Response from federated IDP, by using Redirect-Binding."); } else { @@ -123,7 +125,9 @@ public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { } //decode PVP response object - msg = (InboundMessage) decoder.decode(request, response, MOAMetadataProvider.getInstance(), true); + msg = (InboundMessage) decoder.decode( + request, response, MOAMetadataProvider.getInstance(), true, + comperator); if (MiscUtil.isEmpty(msg.getEntityID())) { throw new InvalidProtocolRequestException("sp.pvp2.04", new Object[] {FederatedAuthConstants.MODULE_NAME_FOR_LOGGING}); @@ -179,8 +183,7 @@ public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { } else { //SP is real Service-Provider --> check attributes in response // and start Attribute-Query if required - - //get authenticationData and store it into MOASession + getAuthDataFromInterfederation(extractor, pendingReq.getOnlineApplicationConfiguration(), idpConfig); @@ -197,7 +200,8 @@ public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { //store valid assertion into pending-request pendingReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, processedMsg); - + pendingReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_ENTITYID, processedMsg.getEntityID()); + //store pending-request requestStoreage.storePendingRequest(pendingReq); @@ -245,55 +249,17 @@ public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { try { Logger.debug("Service Provider is no federated IDP --> start Attribute validation or requesting ... "); Collection requestedAttr = pendingReq.getRequestedAttributes(); - + //check if SAML2 Assertion contains a minimal set of 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 - String endpoint = idpConfig.getIDPAttributQueryServiceURL(); - if (MiscUtil.isEmpty(endpoint)) { - Logger.error("No AttributeQueryURL for interfederationIDP " + idpConfig.getPublicURLPrefix()); - throw new ConfigurationException("config.26", new Object[]{idpConfig.getPublicURLPrefix()}); - - } - + Logger.info("Received assertion does no contain a minimum set of attributes. Starting AttributeQuery process ..."); + //build attributQuery request List attributs = attributQueryBuilder.buildSAML2AttributeList(spConfig, requestedAttr.iterator()); - AttributeQuery query = - attributQueryBuilder.buildAttributQueryRequest(extractor.getNameID(), endpoint, attributs); - - //build SOAP request - List xmlObjects = MOASAMLSOAPClient.send(endpoint, query); - if (xmlObjects.size() == 0) { - Logger.error("Receive emptry AttributeQuery response-body."); - throw new AttributQueryException("Receive emptry AttributeQuery response-body.", null); - - } - - if (xmlObjects.get(0) instanceof Response) { - Response intfResp = (Response) xmlObjects.get(0); - - //validate PVP 2.1 response - try { - samlVerificationEngine.verifyIDPResponse(intfResp, - TrustEngineFactory.getSignatureKnownKeysTrustEngine( - MOAMetadataProvider.getInstance())); - - //create assertion attribute extractor from AttributeQuery response - extractor = new AssertionAttributeExtractor(intfResp); - - } catch (Exception e) { - Logger.warn("PVP 2.1 assertion validation FAILED.", e); - throw new AssertionValidationExeption("PVP 2.1 assertion validation FAILED.", null, e); - } - - } else { - Logger.error("Receive AttributeQuery response-body include no PVP 2.1 response"); - throw new AttributQueryException("Receive AttributeQuery response-body include no PVP 2.1 response.", null); - - } + //request IDP to get additional attributes + extractor = authDataBuilder.getAuthDataFromAttributeQuery(attributs, extractor.getNameID(), idpConfig); } else { Logger.info("Interfedation response include a minimal set of attributes with are required. Skip AttributQuery request step. "); @@ -314,14 +280,13 @@ public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { moasession.setGenericDataToSession(el, extractor.getSingleAttributeValue(el)); Logger.debug("Add PVP-attribute " + el + " into MOASession"); - } - - } catch (SOAPException e) { - throw new BuildException("builder.06", null, e); - - } catch (SecurityException e) { - throw new BuildException("builder.06", null, e); + } + //set validTo from this federated IDP response + moasession.setGenericDataToSession( + AuthenticationSessionStorageConstants.FEDERATION_RESPONSE_VALIDE_TO, + extractor.getAssertionNotOnOrAfter()); + } catch (AttributQueryException e) { throw new BuildException("builder.06", null, e); @@ -334,6 +299,9 @@ public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { } catch (AssertionAttributeExtractorExeption e) { throw new BuildException("builder.06", null, e); + } catch (MOAIDException e) { + throw new BuildException("builder.06", null, e); + } } diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java index 5eb39880e..9d0dac0f8 100644 --- a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java +++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java @@ -26,9 +26,12 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.namespace.QName; import javax.xml.parsers.ParserConfigurationException; @@ -40,7 +43,10 @@ import org.springframework.stereotype.Service; import org.w3c.dom.Element; import org.xml.sax.SAXException; +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandator; import at.gv.egovernment.moa.id.auth.AuthenticationServer; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataAssertionBuilder; import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.builder.PersonDataBuilder; @@ -48,7 +54,6 @@ import at.gv.egovernment.moa.id.auth.builder.SAMLArtifactBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttributeImpl; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.auth.exception.ParseException; @@ -61,7 +66,9 @@ import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters; import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; @@ -262,15 +269,20 @@ public class SAML1AuthenticationServer extends AuthenticationServer { person.getIdentification().add(id ); Value value = new Value(); id.setValue(value ); - - id.setType(authData.getIdentificationType()); - //add baseID if it is requested and available - if ( MiscUtil.isNotEmpty(authData.getIdentificationValue()) && - saml1parameter.isProvideIdentityLink() ) + + if ( MiscUtil.isNotEmpty(authData.getIdentificationValue()) && + saml1parameter.isProvideIdentityLink() && !authData.isBusinessService()) { + //add baseID if it is requested and available and SP is publicService value.setValue(authData.getIdentificationValue()); - else - value.setValue(""); - + id.setType(authData.getIdentificationType()); + + } else { + //otherwise add bPK + value.setValue(authData.getBPK()); + id.setType(authData.getBPKType()); + + } + familyName.setValue(authData.getFamilyName()); familyName.setPrimary("undefined"); name.getGivenName().add(authData.getGivenName()); @@ -310,14 +322,15 @@ public class SAML1AuthenticationServer extends AuthenticationServer { } - String samlAssertion; + String samlAssertion; + + //add mandate info's if (authData.isUseMandate()) { List oaAttributes = authData.getExtendedSAMLAttributesOA(); - //only provide full mandate if it is included. - //In case of federation only a short mandate could be include + //only provide full mandate if it is included. if (saml1parameter.isProvideFullMandatorData() - && authData.getMISMandate().isFullMandateIncluded()) { + && authData.getMISMandate() != null) { try { @@ -442,33 +455,36 @@ public class SAML1AuthenticationServer extends AuthenticationServer { throw new AuthenticationException("auth.10", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID }); - IdentityLink tempIdentityLink = null; - + Element prPerson = null; + String identificationType = ""; + String identificationValue = ""; + Element mandate = authData.getMandate(); + if (mandate == null) { + //no full-mandate include + Logger.info("AuthData contains no full-mandate. Starting 'mandateDate' generation from PVP attributes ..."); + mandate = generateMandateDateFromPVPMandateAttributes(authData); + + } - if (authData.isUseMandate()) { - tempIdentityLink = new IdentityLink(); + if (mandate != null) { Element mandator = ParepUtils.extractMandator(mandate); String dateOfBirth = ""; - Element prPerson = null; String familyName = ""; String givenName = ""; - String identificationType = ""; - String identificationValue = ""; if (mandator != null) { boolean physical = ParepUtils.isPhysicalPerson(mandator); if (physical) { - familyName = ParepUtils.extractText(mandator, - "descendant-or-self::pr:Name/pr:FamilyName/text()"); - givenName = ParepUtils.extractText(mandator, - "descendant-or-self::pr:Name/pr:GivenName/text()"); - dateOfBirth = ParepUtils - .extractMandatorDateOfBirth(mandator); + familyName = ParepUtils.extractText(mandator, "descendant-or-self::pr:Name/pr:FamilyName/text()"); + givenName = ParepUtils.extractText(mandator, "descendant-or-self::pr:Name/pr:GivenName/text()"); + dateOfBirth = ParepUtils.extractMandatorDateOfBirth(mandator); + } else { familyName = ParepUtils.extractMandatorFullName(mandator); + } - identificationType = ParepUtils.getIdentification(mandator, - "Type"); + + identificationType = ParepUtils.getIdentification(mandator, "Type"); identificationValue = ParepUtils.extractMandatorWbpk(mandator); prPerson = ParepUtils.extractPrPersonOfMandate(mandate); @@ -495,33 +511,19 @@ public class SAML1AuthenticationServer extends AuthenticationServer { ParepUtils .HideStammZahlen(prPerson, true, null, null, true); } - - tempIdentityLink.setDateOfBirth(dateOfBirth); - tempIdentityLink.setFamilyName(familyName); - tempIdentityLink.setGivenName(givenName); - tempIdentityLink.setIdentificationType(identificationType); - tempIdentityLink.setIdentificationValue(identificationValue); - tempIdentityLink.setPrPerson(prPerson); - try { - tempIdentityLink.setSamlAssertion(authData.getIdentityLink() - .getSamlAssertion()); - } catch (Exception e) { - throw new ValidateException("validator.64", null); - } - } - + } - - Element mandatePerson = tempIdentityLink.getPrPerson(); - - String mandateData = null; - try { + + if (prPerson == null) { + Logger.warn("Mandates are enabled, but no mandate-information is found in authData."); + throw new AuthenticationException("auth.16", new Object[] { "Mandates are enabled, but no mandate information is included" }); + } + + try { boolean provideStammzahl = oaParam.getSAML1Parameter().isProvideStammzahl(); - - String oatargetType; - + String oatargetType; if(oaParam.getBusinessService()) { if (oaParam.getIdentityLinkDomainIdentifier().startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) oatargetType = oaParam.getIdentityLinkDomainIdentifier(); @@ -530,64 +532,166 @@ public class SAML1AuthenticationServer extends AuthenticationServer { } else { oatargetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); + } - Element prIdentification = (Element) mandatePerson - .getElementsByTagNameNS(Constants.PD_NS_URI, - "Identification").item(0); + Element prIdentification = (Element) prPerson. + getElementsByTagNameNS(Constants.PD_NS_URI,"Identification").item(0); - if (!oatargetType.equals(tempIdentityLink.getIdentificationType())) { - - String isPrPerson = mandatePerson.getAttribute("xsi:type"); + if (!oatargetType.equals(identificationType)) { + String isPrPerson = prPerson.getAttribute("xsi:type"); if (!StringUtils.isEmpty(isPrPerson)) { if (isPrPerson.equalsIgnoreCase("pr:PhysicalPerson")) { - String baseid = getBaseId(mandatePerson); - Element identificationBpK = createIdentificationBPK(mandatePerson, - baseid, oaParam.getTarget()); - - if (!provideStammzahl) { - prIdentification.getFirstChild().setTextContent(""); + + String baseid = getBaseId(prPerson); + Element identificationBpK; + if (MiscUtil.isNotEmpty(baseid)) { + identificationBpK = createIdentificationBPK(prPerson, baseid, oaParam.getTarget()); + + if (!provideStammzahl) { + prIdentification.getFirstChild().setTextContent(""); + } + + prPerson.insertBefore(identificationBpK, + prIdentification); + + } else { + Logger.info("No baseID included. --> Build 'MandateDate' without baseID"); + } + + - mandatePerson.insertBefore(identificationBpK, - prIdentification); + } } } else { - -// Element identificationBpK = mandatePerson.getOwnerDocument() -// .createElementNS(Constants.PD_NS_URI, "Identification"); -// Element valueBpK = mandatePerson.getOwnerDocument().createElementNS( -// Constants.PD_NS_URI, "Value"); -// -// valueBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( -// tempIdentityLink.getIdentificationValue())); -// Element typeBpK = mandatePerson.getOwnerDocument().createElementNS( -// Constants.PD_NS_URI, "Type"); -// typeBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( -// "urn:publicid:gv.at:cdid+bpk")); -// identificationBpK.appendChild(valueBpK); -// identificationBpK.appendChild(typeBpK); -// -// mandatePerson.insertBefore(identificationBpK, prIdentification); + ; } - - mandateData = DOMUtils.serializeNode(mandatePerson); + return DOMUtils.serializeNode(prPerson); } catch (TransformerException e1) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }); + throw new AuthenticationException("auth.16", new Object[] { GET_MIS_SESSIONID }); } catch (IOException e1) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }); + throw new AuthenticationException("auth.16", new Object[] { GET_MIS_SESSIONID }); } - return mandateData; } + private Element generateMandateDateFromPVPMandateAttributes(IAuthData authdata) throws BuildException { + String legalSourcePin = authdata.getGenericData(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME, String.class); + String legalSourceType = authdata.getGenericData(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, String.class); + String legalCommonName = authdata.getGenericData(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME, String.class); + + String natSourcePin = authdata.getGenericData(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME, String.class); + String natSourcePinType = authdata.getGenericData(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME, String.class); + String natbPK = authdata.getGenericData(PVPConstants.MANDATE_NAT_PER_BPK_NAME, String.class); + + String natGivenName = authdata.getGenericData(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME, String.class); + String natFamilyName = authdata.getGenericData(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_NAME, String.class); + String natDateOfBirth = authdata.getGenericData(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_NAME, String.class); + + Mandate mandateObject = new Mandate(); + Mandator mandator = new Mandator(); + mandateObject.setMandator(mandator); + + if (MiscUtil.isNotEmpty(legalCommonName) && MiscUtil.isNotEmpty(legalSourceType) + && MiscUtil.isNotEmpty(legalSourcePin)) { + Logger.debug("Build 'mandateDate' element for legal person ..."); + at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType legalperson = + new at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType(); + at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType legalID = + new at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType(); + at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType.Value idvalue = + new at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType.Value(); + + legalID.setValue(idvalue ); + legalperson.getIdentification().add(legalID ); + mandator.setCorporateBody(legalperson); + legalperson.setFullName(legalCommonName); + legalID.setType(legalSourceType); + idvalue.setValue(legalSourcePin); + + } else if (MiscUtil.isNotEmpty(natFamilyName) && MiscUtil.isNotEmpty(natGivenName) && MiscUtil.isNotEmpty(natDateOfBirth) + && (MiscUtil.isNotEmpty(natSourcePin) || MiscUtil.isNotEmpty(natbPK))){ + Logger.debug("Build 'mandateDate' element for natural person ..."); + at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType physPerson = + new at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType(); + at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType persName = + new at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType(); + at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType.FamilyName familyName = + new at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType.FamilyName(); + at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType persID = + new at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType(); + at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType.Value idValue = + new at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType.Value(); + + physPerson.setName(persName ); + persName.getFamilyName().add(familyName ); + physPerson.getIdentification().add(persID ); + persID.setValue(idValue ); + mandator.setPhysicalPerson(physPerson); + + String[] pvp2GivenName = natGivenName.split(" "); + for(int i=0; i idserverlib - - auth moa-id-commons modules + moa-id-spring-initializer + + auth -- cgit v1.2.3