From 6d09f43225ba2e0f6d7b0583f843c858a1015807 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 26 Jul 2018 10:30:14 +0200 Subject: namespace refactoring --- connector/pom.xml | 8 +- .../MSSpecificeIDASNodeSpringResourceProvider.java | 29 ++ .../specific/connector/SpringInitializer.java | 172 ++++++++++ .../connector/auth/AuthenticationManager.java | 38 +++ .../builder/AuthenticationDataBuilder.java | 77 +++++ .../connector/builder/PVPSubjectNameGenerator.java | 18 + .../connector/config/PVPEndPointConfiguration.java | 66 ++++ .../connector/config/PVPMetadataConfiguration.java | 240 +++++++++++++ .../connector/controller/PVP2SProfileEndpoint.java | 59 ++++ .../controller/ProcessEngineSignalController.java | 30 ++ .../specific/connector/logger/RevisionLogger.java | 69 ++++ .../specific/connector/logger/StatisticLogger.java | 116 +++++++ .../specific/connector/mapper/LoALevelMapper.java | 34 ++ .../processes/CountrySelectionProcessImpl.java | 42 +++ .../tasks/EvaluateCountrySelectionTask.java | 67 ++++ .../tasks/GenerateCountrySelectionFrameTask.java | 62 ++++ .../provider/PVPEndPointCredentialProvider.java | 94 +++++ .../provider/PVPMetadataConfigurationFactory.java | 28 ++ .../connector/provider/PVPMetadataProvider.java | 124 +++++++ .../connector/provider/StatusMessageProvider.java | 104 ++++++ .../connector/storage/CacheWitheIDASBackend.java | 33 ++ .../storage/SimpleInMemoryTransactionStorage.java | 141 ++++++++ .../connector/storage/TransactionStoreElement.java | 36 ++ .../eIDASCacheTransactionStoreDecorator.java | 124 +++++++ .../verification/AuthnRequestValidator.java | 203 +++++++++++ .../MetadataSignatureVerificationFilter.java | 142 ++++++++ .../MSSpecificeIDASNodeSpringResourceProvider.java | 29 -- .../specific/connector/SpringInitializer.java | 172 ---------- .../connector/auth/AuthenticationManager.java | 38 --- .../builder/AuthenticationDataBuilder.java | 77 ----- .../connector/builder/PVPSubjectNameGenerator.java | 18 - .../connector/config/PVPEndPointConfiguration.java | 66 ---- .../connector/config/PVPMetadataConfiguration.java | 240 ------------- .../connector/controller/PVP2SProfileEndpoint.java | 59 ---- .../controller/ProcessEngineSignalController.java | 29 -- .../specific/connector/logger/RevisionLogger.java | 69 ---- .../specific/connector/logger/StatisticLogger.java | 116 ------- .../specific/connector/mapper/LoALevelMapper.java | 34 -- .../processes/CountrySelectionProcessImpl.java | 42 --- .../tasks/EvaluateCountrySelectionTask.java | 67 ---- .../tasks/GenerateCountrySelectionFrameTask.java | 62 ---- .../provider/PVPEndPointCredentialProvider.java | 94 ----- .../provider/PVPMetadataConfigurationFactory.java | 28 -- .../connector/provider/PVPMetadataProvider.java | 124 ------- .../connector/provider/StatusMessageProvider.java | 104 ------ .../connector/storage/CacheWitheIDASBackend.java | 33 -- .../storage/SimpleInMemoryTransactionStorage.java | 141 -------- .../connector/storage/TransactionStoreElement.java | 36 -- .../eIDASCacheTransactionStoreDecorator.java | 124 ------- .../verification/AuthnRequestValidator.java | 203 ----------- .../MetadataSignatureVerificationFilter.java | 142 -------- ...iz.components.spring.api.SpringResourceProvider | 2 +- ....egiz.eaaf.core.api.idp.auth.modules.AuthModule | 2 +- .../src/main/resources/applicationContext.xml | 2 +- .../resources/specific_eIDAS_connector.beans.xml | 36 +- .../specific_eIDAS_connector.storage.beans.xml | 6 +- connector_lib/pom.xml | 4 +- .../specific/connector/MSConnectorEventCodes.java | 18 + .../specific/connector/MSeIDASNodeConstants.java | 85 +++++ .../config/BasicConfigurationProvider.java | 122 +++++++ .../config/ServiceProviderConfiguration.java | 140 ++++++++ .../connector/gui/DefaultGUIBuilderImpl.java | 43 +++ .../gui/GUIBuilderConfigurationFactory.java | 32 ++ .../gui/StaticGuiBuilderConfiguration.java | 105 ++++++ .../specific/connector/MSConnectorEventCodes.java | 18 - .../specific/connector/MSeIDASNodeConstants.java | 85 ----- .../config/BasicConfigurationProvider.java | 122 ------- .../config/ServiceProviderConfiguration.java | 140 -------- .../connector/gui/DefaultGUIBuilderImpl.java | 43 --- .../gui/GUIBuilderConfigurationFactory.java | 32 -- .../gui/StaticGuiBuilderConfiguration.java | 105 ------ eidas_modules/authmodule-eIDAS-v2/pom.xml | 6 +- .../modules/authmodule_eIDASv2/Constants.java | 110 ++++++ .../eIDASAuthenticationModulImpl.java | 53 +++ .../eIDASAuthenticationSpringResourceProvider.java | 30 ++ .../authmodule_eIDASv2/eIDASSignalServlet.java | 131 +++++++ .../exception/SZRCommunicationException.java | 15 + .../exception/eIDASAttributeException.java | 15 + .../exception/eIDASAuthenticationException.java | 20 ++ .../exception/eIDASValidationException.java | 14 + .../service/eIDASAttributeRegistry.java | 115 +++++++ .../modules/authmodule_eIDASv2/szr/SZRClient.java | 372 ++++++++++++++++++++ .../modules/authmodule_eIDASv2/szr/SZRService.java | 139 ++++++++ .../tasks/CreateIdentityLinkTask.java | 380 +++++++++++++++++++++ .../tasks/GenerateAuthnRequestTask.java | 306 +++++++++++++++++ .../tasks/ReceiveAuthnResponseTask.java | 97 ++++++ .../authmodule_eIDASv2/utils/LoggingHandler.java | 52 +++ .../utils/eIDASResponseUtils.java | 98 ++++++ .../validator/eIDASResponseValidator.java | 135 ++++++++ .../modules/authmodule_eIDASv2/Constants.java | 110 ------ .../eIDASAuthenticationModulImpl.java | 53 --- .../eIDASAuthenticationSpringResourceProvider.java | 30 -- .../authmodule_eIDASv2/eIDASSignalServlet.java | 131 ------- .../exception/SZRCommunicationException.java | 15 - .../exception/eIDASAttributeException.java | 15 - .../exception/eIDASAuthenticationException.java | 20 -- .../exception/eIDASValidationException.java | 14 - .../service/eIDASAttributeRegistry.java | 115 ------- .../modules/authmodule_eIDASv2/szr/SZRClient.java | 372 -------------------- .../modules/authmodule_eIDASv2/szr/SZRService.java | 139 -------- .../tasks/CreateIdentityLinkTask.java | 380 --------------------- .../tasks/GenerateAuthnRequestTask.java | 306 ----------------- .../tasks/ReceiveAuthnResponseTask.java | 97 ------ .../authmodule_eIDASv2/utils/LoggingHandler.java | 52 --- .../utils/eIDASResponseUtils.java | 98 ------ .../validator/eIDASResponseValidator.java | 135 -------- ...iz.components.spring.api.SpringResourceProvider | 2 +- .../src/main/resources/eidas_v2_auth.beans.xml | 14 +- .../modules/authmodule_eIDASv2/SZRClientTest.java | 172 ++++++++++ .../modules/authmodule_eIDASv2/SZRClientTest.java | 172 ---------- .../resources/SpringTest-context_basic_test.xml | 4 +- eidas_modules/pom.xml | 4 +- pom.xml | 8 +- 113 files changed, 4996 insertions(+), 4995 deletions(-) create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/MSSpecificeIDASNodeSpringResourceProvider.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/SpringInitializer.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/auth/AuthenticationManager.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/builder/PVPSubjectNameGenerator.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/config/PVPEndPointConfiguration.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/config/PVPMetadataConfiguration.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/controller/PVP2SProfileEndpoint.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/controller/ProcessEngineSignalController.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/logger/RevisionLogger.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/logger/StatisticLogger.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/mapper/LoALevelMapper.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/processes/CountrySelectionProcessImpl.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/processes/tasks/EvaluateCountrySelectionTask.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/processes/tasks/GenerateCountrySelectionFrameTask.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPEndPointCredentialProvider.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPMetadataConfigurationFactory.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPMetadataProvider.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/provider/StatusMessageProvider.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/storage/CacheWitheIDASBackend.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/storage/SimpleInMemoryTransactionStorage.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/storage/TransactionStoreElement.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/storage/eIDASCacheTransactionStoreDecorator.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/verification/AuthnRequestValidator.java create mode 100644 connector/src/main/java/at/asitplus/eidas/specific/connector/verification/MetadataSignatureVerificationFilter.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/MSSpecificeIDASNodeSpringResourceProvider.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/SpringInitializer.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/auth/AuthenticationManager.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/builder/AuthenticationDataBuilder.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/builder/PVPSubjectNameGenerator.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/config/PVPEndPointConfiguration.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/config/PVPMetadataConfiguration.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/controller/PVP2SProfileEndpoint.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/controller/ProcessEngineSignalController.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/logger/RevisionLogger.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/logger/StatisticLogger.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/mapper/LoALevelMapper.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/CountrySelectionProcessImpl.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/tasks/EvaluateCountrySelectionTask.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/tasks/GenerateCountrySelectionFrameTask.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPEndPointCredentialProvider.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPMetadataConfigurationFactory.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPMetadataProvider.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/StatusMessageProvider.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/CacheWitheIDASBackend.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/SimpleInMemoryTransactionStorage.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/TransactionStoreElement.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/eIDASCacheTransactionStoreDecorator.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/verification/AuthnRequestValidator.java delete mode 100644 connector/src/main/java/at/gv/egiz/eidas/specific/connector/verification/MetadataSignatureVerificationFilter.java create mode 100644 connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MSConnectorEventCodes.java create mode 100644 connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MSeIDASNodeConstants.java create mode 100644 connector_lib/src/main/java/at/asitplus/eidas/specific/connector/config/BasicConfigurationProvider.java create mode 100644 connector_lib/src/main/java/at/asitplus/eidas/specific/connector/config/ServiceProviderConfiguration.java create mode 100644 connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/DefaultGUIBuilderImpl.java create mode 100644 connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/GUIBuilderConfigurationFactory.java create mode 100644 connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/StaticGuiBuilderConfiguration.java delete mode 100644 connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/MSConnectorEventCodes.java delete mode 100644 connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/MSeIDASNodeConstants.java delete mode 100644 connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/config/BasicConfigurationProvider.java delete mode 100644 connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/config/ServiceProviderConfiguration.java delete mode 100644 connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/DefaultGUIBuilderImpl.java delete mode 100644 connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/GUIBuilderConfigurationFactory.java delete mode 100644 connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/StaticGuiBuilderConfiguration.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/Constants.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationModulImpl.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationSpringResourceProvider.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASSignalServlet.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/SZRCommunicationException.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAttributeException.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAuthenticationException.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASValidationException.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/service/eIDASAttributeRegistry.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/szr/SZRClient.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/szr/SZRService.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/CreateIdentityLinkTask.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/GenerateAuthnRequestTask.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/ReceiveAuthnResponseTask.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/utils/LoggingHandler.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/utils/eIDASResponseUtils.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/validator/eIDASResponseValidator.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/Constants.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationModulImpl.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationSpringResourceProvider.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASSignalServlet.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/SZRCommunicationException.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAttributeException.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAuthenticationException.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASValidationException.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/service/eIDASAttributeRegistry.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/szr/SZRClient.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/szr/SZRService.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/CreateIdentityLinkTask.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/GenerateAuthnRequestTask.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/ReceiveAuthnResponseTask.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/utils/LoggingHandler.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/utils/eIDASResponseUtils.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/validator/eIDASResponseValidator.java create mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/test/eidas/specific/modules/authmodule_eIDASv2/SZRClientTest.java delete mode 100644 eidas_modules/authmodule-eIDAS-v2/src/test/java/at/gv/egiz/test/eidas/specific/modules/authmodule_eIDASv2/SZRClientTest.java diff --git a/connector/pom.xml b/connector/pom.xml index 9f1e6c50..f6b12537 100644 --- a/connector/pom.xml +++ b/connector/pom.xml @@ -2,12 +2,12 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 - at.gv.egiz.eidas + at.asitplus.eidas ms_specific 1.x - at.gv.egiz.eidas.ms_specific + at.asitplus.eidas.ms_specific ms_specific_connector ${egiz.eidas.version} war @@ -40,11 +40,11 @@ - at.gv.egiz.eidas.ms_specific + at.asitplus.eidas.ms_specific connector_lib - at.gv.egiz.eidas.ms_specific.modules + at.asitplus.eidas.ms_specific.modules authmodule-eIDAS-v2 diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/MSSpecificeIDASNodeSpringResourceProvider.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/MSSpecificeIDASNodeSpringResourceProvider.java new file mode 100644 index 00000000..aa1a71e4 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/MSSpecificeIDASNodeSpringResourceProvider.java @@ -0,0 +1,29 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import at.gv.egiz.components.spring.api.SpringResourceProvider; + +public class MSSpecificeIDASNodeSpringResourceProvider implements SpringResourceProvider { + + @Override + public Resource[] getResourcesToLoad() { + ClassPathResource mseIDASNode = new ClassPathResource("/specific_eIDAS_connector.beans.xml", MSSpecificeIDASNodeSpringResourceProvider.class); + ClassPathResource mseIDASNodeStorage = new ClassPathResource("/specific_eIDAS_connector.storage.beans.xml", MSSpecificeIDASNodeSpringResourceProvider.class); + return new Resource[] {mseIDASNode, mseIDASNodeStorage}; + } + + @Override + public String[] getPackagesToScan() { + return null; + } + + @Override + public String getName() { + return "MS-specific eIDAS Node SpringResourceProvider"; + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/SpringInitializer.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/SpringInitializer.java new file mode 100644 index 00000000..2f77f9be --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/SpringInitializer.java @@ -0,0 +1,172 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector; + +import java.util.Arrays; + +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.core.io.ClassPathResource; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.request.RequestContextListener; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.context.support.ServletContextResource; +import org.springframework.web.servlet.DispatcherServlet; + +import at.gv.egiz.components.spring.api.SpringLoader; +import at.gv.egiz.eaaf.core.api.IStatusMessenger; +import at.gv.egiz.eaaf.core.impl.logging.LogMessageProviderFactory; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EAAFDefaultSAML2Bootstrap; + +/** + * Web application initializer + * + * @author Thomas Lenz + */ +public class SpringInitializer implements WebApplicationInitializer { + + private static final Logger log = LoggerFactory.getLogger(SpringInitializer.class); + + private String[] rootServletContexts = null; + private String[] servletContexts = null; + private String[] activeProfiles = null; + + public SpringInitializer() { + this.rootServletContexts = null; + this.servletContexts = new String[] { + "/applicationContext.xml", + + }; + this.activeProfiles = null; + } + + + /* (non-Javadoc) + * @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext) + */ + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + try { + log.info("=============== Loading Config Root Context! ==============="); + ApplicationContext cfgRootContext = + new ClassPathXmlApplicationContext(new String[] { + "/applicationContext.xml" + }); + + + log.info("=============== Loading Root Context! ==============="); + GenericWebApplicationContext rootContext = new GenericWebApplicationContext(); + rootContext.setServletContext(servletContext); + rootContext.setParent(cfgRootContext); + +// log.info("=============== Setting active profiles! ==============="); +// if (this.activeProfiles != null) { +// for (String profile : this.activeProfiles) { +// rootContext.getEnvironment().addActiveProfile(profile); +// } +// } + + log.info("Spring-context was initialized with active profiles: " + + Arrays.asList(rootContext.getEnvironment().getActiveProfiles())); + + log.info("=============== Loading Local Contexts! ==============="); + XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader( + rootContext); + if (rootServletContexts != null) { + for (String rootServletContext : rootServletContexts) { + log.debug("Loading: "+ rootServletContext); + xmlReader.loadBeanDefinitions(new ServletContextResource( + servletContext, rootServletContext)); + } + } + // Manage the lifecycle of the root application context + servletContext.addListener(new ContextLoaderListener(rootContext)); + + // log.debug("Beans after logAMQP in {}", rootContext); + // dumpBeanDefinitions(rootContext); + + log.info("=============== Loading SPI Context! ==============="); + if (rootContext instanceof BeanDefinitionRegistry) { + log.debug("Loading modules and components"); + SpringLoader.loadSpringServices(rootContext); + + } else + log.warn("Failed to load external Spring since no BeanDefinitionRegistry"); + + log.trace("Beans after SPI in "+ rootContext); + dumpBeanDefinitions(rootContext); + + log.debug("Loading servlet config in "+ rootContext); + if (servletContexts != null) { + for (String servletContextString : servletContexts) + xmlReader.loadBeanDefinitions(new ClassPathResource(servletContextString, SpringInitializer.class)); + + } + + log.debug("Refreshing context "+ rootContext); + rootContext.refresh(); + + log.info("=============== Register Dispatcher Servlet! ==============="); + + log.trace("Final Beans in "+ rootContext); + dumpBeanDefinitions(rootContext); + + log.info("Registering dispatcher configuration"); + ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext)); + if (dispatcher != null) { + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/"); + dispatcher.setAsyncSupported(true); + + } else + log.error("Failed to register dispatcher server in servlet context!"); + + + log.info("=============== Register RequestContextListener! ==============="); + servletContext.addListener(new RequestContextListener()); + + //initialize status messenger + LogMessageProviderFactory.setStatusMessager(rootContext.getBean(IStatusMessenger.class)); + + log.info("Bootstrap openSAML .... "); + EAAFDefaultSAML2Bootstrap.bootstrap(); + + log.info("Seed random number generator ... "); + Random.seedRandom(); + + log.info("Initialization of MS-specific eIDAS-connector finished."); + + + } catch (Throwable e) { + log.error("MS-specific eIDAS-connector initialization FAILED!", e); + + } + + } + + private void dumpBeanDefinitions(GenericApplicationContext context) { + log.trace("Registered Bean in context " + context.toString()); + + String[] registeredBeans = context.getBeanDefinitionNames(); + for (String registeredBean : registeredBeans) { + BeanDefinition beanDefinition = context + .getBeanDefinition(registeredBean); + log.trace(registeredBean + " -> " + beanDefinition.getBeanClassName()); + + } + + log.trace("Registered Bean in context --"+ context); + } +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/auth/AuthenticationManager.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/auth/AuthenticationManager.java new file mode 100644 index 00000000..7eee2388 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/auth/AuthenticationManager.java @@ -0,0 +1,38 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.auth; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.idp.auth.AbstractAuthenticationManager; +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; + +@Service("AuthenticationManager") +public class AuthenticationManager extends AbstractAuthenticationManager { + private static final Logger log = LoggerFactory.getLogger(AuthenticationManager.class); + + @Override + public ISLOInformationContainer performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, + IRequest pendingReq, String internalSSOId) throws EAAFException { + throw new RuntimeException("Single LogOut is NOT supported by this implementation"); + + } + + @Override + protected void populateExecutionContext(ExecutionContext executionContext, + RequestImpl pendingReq, HttpServletRequest httpReq) + throws EAAFException { + log.trace("No implementation-specific population of execution-context required ... "); + + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java new file mode 100644 index 00000000..35f0cc0e --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/AuthenticationDataBuilder.java @@ -0,0 +1,77 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.builder; + +import java.util.Date; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; +import org.w3c.dom.DOMException; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IAuthProcessDataContainer; +import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFBuilderException; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFParserException; +import at.gv.egiz.eaaf.core.exceptions.XPathException; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; +import at.gv.egiz.eaaf.core.impl.idp.auth.builder.AbstractAuthenticationDataBuilder; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; + +@Service("AuthenticationDataBuilder") +public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder { + private static final Logger log = LoggerFactory.getLogger(AuthenticationDataBuilder.class); + + @Override + public IAuthData buildAuthenticationData(IRequest pendingReq) throws EAAFAuthenticationException { + + IAuthProcessDataContainer authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + AuthenticationData authData = new AuthenticationData(); + + try { + generateBasicAuthData(authData, pendingReq, authProcessData); + + //set specific informations + authData.setSsoSessionValidTo(new Date(new Date().getTime() + + MSeIDASNodeConstants.DEFAULT_PVP_ASSERTION_VALIDITY * 60 * 1000)); + + } catch (EAAFBuilderException | EAAFParserException | EAAFConfigurationException + | XPathException | DOMException e) { + log.warn("Can not build authentication data from auth. process information"); + throw new EAAFAuthenticationException("builder.11", new Object[]{e.getMessage()}, e); + + } + + return authData; + + } + + @Override + protected Pair buildOAspecificbPK(IRequest pendingReq, AuthenticationData authData) throws EAAFBuilderException { + //TODO: check if bPK already exists + + + return super.buildOAspecificbPK(pendingReq, authData); + + } + + @Override + protected Pair getEncryptedbPKFromPVPAttribute(IAuthProcessDataContainer arg0, + AuthenticationData arg1, ISPConfiguration arg2) throws EAAFBuilderException { + return null; + + } + + @Override + protected Pair getbaseIDFromSZR(AuthenticationData arg0, String arg1, String arg2) { + return null; + + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/PVPSubjectNameGenerator.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/PVPSubjectNameGenerator.java new file mode 100644 index 00000000..9fe80f67 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/builder/PVPSubjectNameGenerator.java @@ -0,0 +1,18 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.builder; + +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +import at.gv.egiz.eaaf.modules.pvp2.idp.api.builder.ISubjectNameIdGenerator; + +public class PVPSubjectNameGenerator implements ISubjectNameIdGenerator { + + @Override + public Pair generateSubjectNameId(IAuthData authData, ISPConfiguration spConfig) throws PVP2Exception { + return Pair.newInstance(authData.getBPK(), authData.getBPKType()); + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/config/PVPEndPointConfiguration.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/config/PVPEndPointConfiguration.java new file mode 100644 index 00000000..35e5669d --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/config/PVPEndPointConfiguration.java @@ -0,0 +1,66 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.config; + +import java.util.List; + +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.Organization; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; + +@Service("PVPEndPointConfiguration") +public class PVPEndPointConfiguration implements IPVP2BasicConfiguration { + private static final Logger log = LoggerFactory.getLogger(PVPEndPointConfiguration.class); + + @Autowired(required=true) IConfiguration basicConfiguration; + + @Override + public String getIDPEntityId(String authURL) throws EAAFException { + return removePostFix(authURL) + MSeIDASNodeConstants.ENDPOINT_PVP_METADATA; + + } + + @Override + public String getIDPSSOPostService(String authURL) throws EAAFException { + return removePostFix(authURL) + MSeIDASNodeConstants.ENDPOINT_PVP_POST; + + } + + @Override + public String getIDPSSORedirectService(String authURL) throws EAAFException { + return removePostFix(authURL) + MSeIDASNodeConstants.ENDPOINT_PVP_REDIRECT; + + } + + @Override + public Object getIDPSSOSOAPService(String extractAuthURLFromRequest) throws EAAFException { + log.warn("PVP S-Profile End-Point does NOT support SOAP Binding"); + return null; + + } + + @Override + public List getIDPContacts() throws EAAFException { + return null; + } + + @Override + public Organization getIDPOrganisation() throws EAAFException { + return null; + } + + private String removePostFix(String url) { + if (url != null && url.endsWith("/")) + return url.substring(0, url.length() - 1); + else + return url; + } +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/config/PVPMetadataConfiguration.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/config/PVPMetadataConfiguration.java new file mode 100644 index 00000000..a1d534cf --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/config/PVPMetadataConfiguration.java @@ -0,0 +1,240 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.config; + +import java.util.Arrays; +import java.util.List; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.security.credential.Credential; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataBuilderConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PVPAttributeBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; + +public class PVPMetadataConfiguration implements IPVPMetadataBuilderConfiguration{ + private static final Logger log = LoggerFactory.getLogger(PVPMetadataConfiguration.class); + + private IConfiguration basicConfig; + private String authUrl; + private AbstractCredentialProvider pvpIDPCredentials; + private IPVP2BasicConfiguration pvpBasicConfig; + + public PVPMetadataConfiguration(IConfiguration basicConfig, String authURL, IPVP2BasicConfiguration pvpBasicConfig, AbstractCredentialProvider pvpIDPCredentials) { + this.authUrl = authURL; + this.pvpIDPCredentials = pvpIDPCredentials; + this.basicConfig = basicConfig; + this.pvpBasicConfig = pvpBasicConfig; + + } + + @Override + public String getSPNameForLogging() { + return "PVP2 S-Profile IDP"; + } + + @Override + public int getMetadataValidUntil() { + return Integer.valueOf(basicConfig.getBasicConfiguration( + MSeIDASNodeConstants.PROP_CONFIG_PVP2_METADATA_VALIDITY, + String.valueOf(MSeIDASNodeConstants.DEFAULT_PVP_METADATA_VALIDITY))); + + } + + @Override + public boolean buildEntitiesDescriptorAsRootElement() { + return false; + + } + + @Override + public boolean buildIDPSSODescriptor() { + return true; + + } + + @Override + public boolean buildSPSSODescriptor() { + return false; + + } + + @Override + public String getEntityID() { + try { + return pvpBasicConfig.getIDPEntityId(authUrl); + + } catch (EAAFException e) { + log.error("Can NOT build PVP metadata configuration.", e); + throw new RuntimeException("Can NOT build PVP metadata configuration."); + + } + + } + + @Override + public String getEntityFriendlyName() { + return null; + + } + + @Override + public List getContactPersonInformation() { + try { + return pvpBasicConfig.getIDPContacts(); + + } catch (EAAFException e) { + log.error("Can NOT build PVP metadata configuration.", e); + throw new RuntimeException("Can NOT build PVP metadata configuration."); + + } + + } + + @Override + public Organization getOrgansiationInformation() { + try { + return pvpBasicConfig.getIDPOrganisation(); + + } catch (EAAFException e) { + log.error("Can NOT build PVP metadata configuration.", e); + throw new RuntimeException("Can NOT build PVP metadata configuration."); + + } + } + + @Override + public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException { + return pvpIDPCredentials.getIDPMetaDataSigningCredential(); + + } + + @Override + public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException { + return pvpIDPCredentials.getIDPAssertionSigningCredential(); + + } + + @Override + public Credential getEncryptionCredentials() throws CredentialsNotAvailableException { + return null; + + + } + + @Override + public String getIDPWebSSOPostBindingURL() { + try { + return pvpBasicConfig.getIDPSSOPostService(authUrl); + + } catch (EAAFException e) { + log.error("Can NOT build PVP metadata configuration.", e); + throw new RuntimeException("Can NOT build PVP metadata configuration."); + + } + + } + + @Override + public String getIDPWebSSORedirectBindingURL() { + try { + return pvpBasicConfig.getIDPSSORedirectService(authUrl); + + } catch (EAAFException e) { + log.error("Can NOT build PVP metadata configuration.", e); + throw new RuntimeException("Can NOT build PVP metadata configuration."); + + } + } + + @Override + public String getIDPSLOPostBindingURL() { + return null; + + } + + @Override + public String getIDPSLORedirectBindingURL() { + return null; + + } + + @Override + public String getSPAssertionConsumerServicePostBindingURL() { + return null; + + } + + @Override + public String getSPAssertionConsumerServiceRedirectBindingURL() { + return null; + + } + + @Override + public String getSPSLOPostBindingURL() { + return null; + + } + + @Override + public String getSPSLORedirectBindingURL() { + return null; + + } + + @Override + public String getSPSLOSOAPBindingURL() { + return null; + + } + + @Override + public List getIDPPossibleAttributes() { + return PVPAttributeBuilder.buildSupportedEmptyAttributes(); + + } + + @Override + public List getIDPPossibleNameITTypes() { + return Arrays.asList(NameIDType.PERSISTENT, + NameIDType.TRANSIENT, + NameIDType.UNSPECIFIED); + } + + @Override + public List getSPRequiredAttributes() { + return null; + + } + + @Override + public List getSPAllowedNameITTypes() { + return null; + + } + + @Override + public boolean wantAssertionSigned() { + return false; + + } + + @Override + public boolean wantAuthnRequestSigned() { + return true; + + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/controller/PVP2SProfileEndpoint.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/controller/PVP2SProfileEndpoint.java new file mode 100644 index 00000000..8a6fcb3d --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/controller/PVP2SProfileEndpoint.java @@ -0,0 +1,59 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.AbstractPVP2XProtocol; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; + +@Controller +public class PVP2SProfileEndpoint extends AbstractPVP2XProtocol{ + + public static final String NAME = PVP2SProfileEndpoint.class.getName(); + public static final String PROTOCOL_ID = "pvp2-s"; + + @RequestMapping(value = MSeIDASNodeConstants.ENDPOINT_PVP_METADATA, method = {RequestMethod.POST, RequestMethod.GET}) + public void PVPMetadataRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { + super.pvpMetadataRequest(req, resp); + + } + + @RequestMapping(value = MSeIDASNodeConstants.ENDPOINT_PVP_POST, method = {RequestMethod.POST}) + public void PVPIDPPostRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { + super.PVPIDPPostRequest(req, resp); + + } + + @RequestMapping(value = MSeIDASNodeConstants.ENDPOINT_PVP_REDIRECT, method = {RequestMethod.GET}) + public void PVPIDPRedirecttRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { + super.PVPIDPRedirecttRequest(req, resp); + + } + + + @Override + public String getAuthProtocolIdentifier() { + return PROTOCOL_ID; + } + + @Override + public String getName() { + return NAME; + } + + @Override + protected boolean childPreProcess(HttpServletRequest arg0, HttpServletResponse arg1, PVPSProfilePendingRequest arg2) + throws Throwable { + return false; + } + + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/controller/ProcessEngineSignalController.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/controller/ProcessEngineSignalController.java new file mode 100644 index 00000000..febdbcce --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/controller/ProcessEngineSignalController.java @@ -0,0 +1,30 @@ +package at.asitplus.eidas.specific.connector.controller; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.impl.idp.controller.AbstractProcessEngineSignalController; + +/** + * @author tlenz + * + */ +@Controller +public class ProcessEngineSignalController extends AbstractProcessEngineSignalController { + + @RequestMapping(value = {MSeIDASNodeConstants.ENDPOINT_COUNTRYSELECTION + }, + method = {RequestMethod.POST, RequestMethod.GET}) + public void performGenericAuthenticationProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException { + signalProcessManagement(req, resp); + + } +} + \ No newline at end of file diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/logger/RevisionLogger.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/logger/RevisionLogger.java new file mode 100644 index 00000000..1d29d96b --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/logger/RevisionLogger.java @@ -0,0 +1,69 @@ +package at.asitplus.eidas.specific.connector.logger; + +import java.util.Date; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.gv.egiz.components.eventlog.api.Event; +import at.gv.egiz.components.eventlog.api.EventLogFactory; +import at.gv.egiz.components.eventlog.api.EventLoggingException; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; + +public class RevisionLogger extends EventLogFactory implements IRevisionLogger { + private static final Logger log = LoggerFactory.getLogger(RevisionLogger.class); + + @Override + public void logEvent(ISPConfiguration oaConfig, int eventCode, String message) { + logEvent(createNewEvent(new Date().getTime(), eventCode, message)); + + } + + @Override + public void logEvent(IRequest pendingRequest, int eventCode) { + logEvent(createNewEvent(new Date().getTime(), eventCode, + pendingRequest.getUniqueSessionIdentifier(), pendingRequest.getUniqueTransactionIdentifier())); + + } + + @Override + public void logEvent(IRequest pendingRequest, int eventCode, String message) { + logEvent(createNewEvent(new Date().getTime(), eventCode, message, + pendingRequest.getUniqueSessionIdentifier(), pendingRequest.getUniqueTransactionIdentifier())); + + } + + @Override + public void logEvent(int eventCode, String message) { + logEvent(createNewEvent(new Date().getTime(), eventCode, message)); + + } + + @Override + public void logEvent(String sessionID, String transactionID, int eventCode, String message) { + logEvent(createNewEvent(new Date().getTime(), eventCode, message, sessionID, transactionID)); + + } + + @Override + public void logEvent(String sessionID, String transactionID, int eventCode) { + logEvent(createNewEvent(new Date().getTime(), eventCode, sessionID, transactionID)); + + } + + private void logEvent(Event event) { + try { + if (event.getEventCode() >= 1100) + getEventLog().logEvent(event); + else + log.trace("Ignore Event: " + event.getEventCode() + " because session functionallity is not implemented"); + + } catch (EventLoggingException e) { + log.warn("Event logging FAILED! Reason: " + e.getMessage()); + + } + + } +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/logger/StatisticLogger.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/logger/StatisticLogger.java new file mode 100644 index 00000000..6ff92b53 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/logger/StatisticLogger.java @@ -0,0 +1,116 @@ +package at.asitplus.eidas.specific.connector.logger; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; + +public class StatisticLogger implements IStatisticLogger { + + private static final Logger log = LoggerFactory.getLogger(StatisticLogger.class); + + private static final String DATEFORMATER = "yyyy.MM.dd-HH:mm:ss+z"; + private static final String STATUS_SUCCESS = "success"; + private static final String STATUS_ERROR = "error"; + + @Override + public void logSuccessOperation(IRequest protocolRequest, IAuthData authData, boolean isSSOSession) { + log.info(buildLogMessage( + protocolRequest.getUniqueTransactionIdentifier(), + protocolRequest.getSPEntityId(), + protocolRequest.getRawData(MSeIDASNodeConstants.DATA_REQUESTERID), + protocolRequest.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), + authData.getCiticenCountryCode(), + STATUS_SUCCESS , + StringUtils.EMPTY, + StringUtils.EMPTY)); + + + } + + @Override + public void logErrorOperation(Throwable throwable) { + String errorId = "TODO"; + if (throwable instanceof EAAFException) + errorId = ((EAAFException) throwable).getErrorId(); + + log.info(buildLogMessage( + StringUtils.EMPTY, + StringUtils.EMPTY, + StringUtils.EMPTY, + StringUtils.EMPTY, + StringUtils.EMPTY, + STATUS_ERROR, + errorId, + throwable.getMessage())); + + + } + + @Override + public void logErrorOperation(Throwable throwable, IRequest errorRequest) { + String errorId = "TODO"; + if (throwable instanceof EAAFException) + errorId = ((EAAFException) throwable).getErrorId(); + + if (errorRequest != null) + log.info(buildLogMessage( + errorRequest.getUniqueTransactionIdentifier(), + errorRequest.getSPEntityId(), + errorRequest.getRawData(MSeIDASNodeConstants.DATA_REQUESTERID), + errorRequest.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), + StringUtils.EMPTY, + STATUS_ERROR, + errorId, + throwable.getMessage())); + + else + log.info(buildLogMessage( + StringUtils.EMPTY, + StringUtils.EMPTY, + StringUtils.EMPTY, + StringUtils.EMPTY, + StringUtils.EMPTY, + STATUS_ERROR, + errorId, + throwable.getMessage())); + + } + + @Override + public void internalTesting() throws Exception { + log.trace("Not implemented for a File-based logger"); + + } + + private String buildLogMessage(String tId, String moaIDEntityId, Object requesterId, String target, String cc, + String status, String errorCode, String errorMsg) { + String logMsg = StringUtils.EMPTY; + + //data,tId,MOAID-Id,SP-Id,bPKTarget,CC,status,error-code,error-msg + + logMsg += DateTime.now().toString(DATEFORMATER ) + ","; + logMsg += tId + ","; + logMsg += moaIDEntityId + ","; + + if (requesterId instanceof String && StringUtils.isNotEmpty((String)requesterId)) + logMsg += (String)requesterId + ","; + else + logMsg += StringUtils.EMPTY + ","; + + logMsg += target + ","; + logMsg += cc + ","; + + logMsg += status + ","; + logMsg += errorCode + ","; + logMsg += errorMsg; + + return logMsg; + } +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/mapper/LoALevelMapper.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/mapper/LoALevelMapper.java new file mode 100644 index 00000000..2eae0126 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/mapper/LoALevelMapper.java @@ -0,0 +1,34 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.mapper; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.data.ILoALevelMapper; + +@Service("LoALevelMapper") +public class LoALevelMapper implements ILoALevelMapper{ + private static final Logger log = LoggerFactory.getLogger(LoALevelMapper.class); + + @Override + public String mapToSecClass(String LoA) { + log.info("Mapping to PVP SecClass is NOT supported"); + return null; + } + + @Override + public String mapToeIDASLoA(String LoA) { + if (LoA.startsWith(EAAFConstants.EIDAS_LOA_PREFIX)) + return LoA; + + else + log.info("Can NOT map '" + LoA + "' to eIDAS LoA"); + + return null; + + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/processes/CountrySelectionProcessImpl.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/processes/CountrySelectionProcessImpl.java new file mode 100644 index 00000000..2ab5df03 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/processes/CountrySelectionProcessImpl.java @@ -0,0 +1,42 @@ +package at.asitplus.eidas.specific.connector.processes; + +import org.apache.commons.lang3.StringUtils; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; + +/** + * @author tlenz + * + */ +public class CountrySelectionProcessImpl implements AuthModule { + + @Override + public int getPriority() { + return 0; + + } + + @Override + public String selectProcess(ExecutionContext context) { + Object selectedCountryObj = context.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_COUNTRY); + if (selectedCountryObj != null && selectedCountryObj instanceof String) { + String selectedCountry = (String) selectedCountryObj; + if (StringUtils.isNotEmpty(selectedCountry)) + return null; + + } + + return "CountrySelectionProcess"; + + + } + + @Override + public String[] getProcessDefinitions() { + return new String[] { "classpath:processes/CountrySelection.process.xml" }; + + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/processes/tasks/EvaluateCountrySelectionTask.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/processes/tasks/EvaluateCountrySelectionTask.java new file mode 100644 index 00000000..0f73aded --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/processes/tasks/EvaluateCountrySelectionTask.java @@ -0,0 +1,67 @@ +package at.asitplus.eidas.specific.connector.processes.tasks; + +import java.util.Enumeration; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +import at.asitplus.eidas.specific.connector.MSConnectorEventCodes; +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; + +/** + * @author tlenz + * + */ +@Component("EvaluateCountrySelectionTask") +public class EvaluateCountrySelectionTask extends AbstractAuthServletTask { + private static final Logger log = LoggerFactory.getLogger(EvaluateCountrySelectionTask.class); + + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try { + + String stopAuthFlag = request.getParameter(MSeIDASNodeConstants.REQ_PARAM_STOP_PROCESS); + if (StringUtils.isNotEmpty(stopAuthFlag) && Boolean.parseBoolean(stopAuthFlag)) { + log.info("Authentication process WAS stopped by entity. Stopping auth. process ... "); + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.PROCESS_STOPPED_BY_USER); + pendingReq.setAbortedByUser(true); + pendingReq.setAuthenticated(false); + + } else { + // set parameter execution context + Enumeration reqParamNames = request.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (StringUtils.isNotEmpty(paramName) && + !EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID.equalsIgnoreCase(paramName)) { + for (String el : MSeIDASNodeConstants.COUNTRY_SELECTION_PARAM_WHITELIST) { + if (el.equalsIgnoreCase(paramName)) + executionContext.put(paramName, + StringEscapeUtils.escapeHtml(request.getParameter(paramName))); + } + } + } + log.info("Country selection finished. Starting auth. process for country ... "); + + } + + } catch (Exception e) { + log.warn("EvaluateBKUSelectionTask has an internal error", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/processes/tasks/GenerateCountrySelectionFrameTask.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/processes/tasks/GenerateCountrySelectionFrameTask.java new file mode 100644 index 00000000..fb1f7f53 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/processes/tasks/GenerateCountrySelectionFrameTask.java @@ -0,0 +1,62 @@ +package at.asitplus.eidas.specific.connector.processes.tasks; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import at.asitplus.eidas.specific.connector.MSConnectorEventCodes; +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.asitplus.eidas.specific.connector.gui.StaticGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; + +/** + * @author tlenz + * + */ +@Component("GenerateCountrySelectionFrameTask") +public class GenerateCountrySelectionFrameTask extends AbstractAuthServletTask { + private static final Logger log = LoggerFactory.getLogger(GenerateCountrySelectionFrameTask.class); + + @Autowired IGUIFormBuilder guiBuilder; + @Autowired IConfiguration basicConfig; + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try { + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.STARTING_COUNTRY_SELECTION); + + IGUIBuilderConfiguration config = new StaticGuiBuilderConfiguration( + basicConfig, + pendingReq, + MSeIDASNodeConstants.TEMPLATE_HTML_COUNTRYSELECTION, + MSeIDASNodeConstants.ENDPOINT_COUNTRYSELECTION); + + guiBuilder.build(response, config, "BKU-Selection form"); + + } catch (GUIBuildException e) { + log.warn("Can not build GUI:'BKU-Selection'. Msg:" + e.getMessage()); + throw new TaskExecutionException(pendingReq, + "Can not build GUI. Msg:" + e.getMessage(), + new EAAFException("gui.00", new Object[]{e.getMessage()}, e)); + + } catch (Exception e) { + log.warn("FinalizeAuthenticationTask has an internal error", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPEndPointCredentialProvider.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPEndPointCredentialProvider.java new file mode 100644 index 00000000..47279aff --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPEndPointCredentialProvider.java @@ -0,0 +1,94 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.provider; + +import java.net.MalformedURLException; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; + +public class PVPEndPointCredentialProvider extends AbstractCredentialProvider { + private static final Logger log = LoggerFactory.getLogger(PVPEndPointCredentialProvider.class); + + @Autowired(required=true) IConfiguration basicConfiguration; + + @Override + public String getFriendlyName() { + return "PVP2 S-Profile EndPoint"; + } + + @Override + public String getKeyStoreFilePath() throws EAAFException { + try { + String path = basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEYSTORE_PATH); + if (StringUtils.isEmpty(path)) { + log.error(getFriendlyName() + " | Path to keyStore is NULL or EMPTY"); + throw new EAAFConfigurationException("config.27", + new Object[] {getFriendlyName() + " | Path to keyStore is NULL or EMPTY"}); + + } + + return FileUtils.makeAbsoluteURL( + path, + basicConfiguration.getConfigurationRootDirectory()); + + } catch (MalformedURLException e) { + log.error(getFriendlyName() + " | Path to keyStore NOT valid.", e); + throw new EAAFConfigurationException("config.27", + new Object[] {getFriendlyName() + " | Path to keyStore NOT valid."}, e); + + } + + } + + @Override + public String getKeyStorePassword() { + return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEYSTORE_PASSWORD); + + } + + @Override + public String getMetadataKeyAlias() { + return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEY_METADATA_ALIAS); + } + + @Override + public String getMetadataKeyPassword() { + return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEY_METADATA_PASSWORD); + + } + + @Override + public String getSignatureKeyAlias() { + return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEY_SIGNING_ALIAS); + + } + + @Override + public String getSignatureKeyPassword() { + return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEY_SIGNING_PASSWORD); + + } + + @Override + public String getEncryptionKeyAlias() { + return null; + + } + + @Override + public String getEncryptionKeyPassword() { + return null; + + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPMetadataConfigurationFactory.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPMetadataConfigurationFactory.java new file mode 100644 index 00000000..c6200b31 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPMetadataConfigurationFactory.java @@ -0,0 +1,28 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.provider; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.asitplus.eidas.specific.connector.config.PVPMetadataConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataBuilderConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataConfigurationFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; + +@Service("PVPMetadataConfigurationFactory") +public class PVPMetadataConfigurationFactory implements IPVPMetadataConfigurationFactory { + + @Autowired private IConfiguration basicConfig; + @Autowired private IPVP2BasicConfiguration pvpBasicConfig; + + @Override + public IPVPMetadataBuilderConfiguration generateMetadataBuilderConfiguration(String authURL, + AbstractCredentialProvider pvpIDPCredentials) { + return new PVPMetadataConfiguration(basicConfig, authURL, pvpBasicConfig, pvpIDPCredentials); + + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPMetadataProvider.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPMetadataProvider.java new file mode 100644 index 00000000..ce16da49 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/PVPMetadataProvider.java @@ -0,0 +1,124 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.provider; + +import java.io.IOException; +import java.security.cert.CertificateException; +import java.util.List; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.params.HttpClientParams; +import org.apache.commons.lang3.StringUtils; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.xml.parse.BasicParserPool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.asitplus.eidas.specific.connector.verification.MetadataSignatureVerificationFilter; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2MetadataException; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.AbstractChainingMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.MetadataFilterChain; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.PVPEntityCategoryFilter; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.SchemaValidationFilter; + +@Service("PVPMetadataProvider") +public class PVPMetadataProvider extends AbstractChainingMetadataProvider{ + private static final Logger log = LoggerFactory.getLogger(PVPMetadataProvider.class); + + @Autowired(required=true) IConfiguration basicConfig; + + @Override + protected String getMetadataURL(String entityId) throws EAAFConfigurationException { + ISPConfiguration spConfig = basicConfig.getServiceProviderConfiguration(entityId); + if (spConfig != null) { + String metadataURL = entityId; + + String metadataURLFromConfig = spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_PVP2_METADATA_URL); + if (StringUtils.isNotEmpty(metadataURLFromConfig)) { + log.debug("Use metdataURL from configuration for EntityId: " + entityId); + metadataURL = metadataURLFromConfig; + + } + + return metadataURL; + + } else + log.info("No ServiceProvider with entityId: " + entityId + " in configuration."); + + return null; + } + + @Override + protected MetadataProvider createNewMetadataProvider(String entityId) + throws EAAFConfigurationException, IOException, CertificateException { + ISPConfiguration spConfig = basicConfig.getServiceProviderConfiguration(entityId); + if (spConfig != null) { + try { + String metadataURL = spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_PVP2_METADATA_URL); + if (StringUtils.isEmpty(metadataURL)) { + log.debug("Use EntityId: " + entityId + " instead of explicite metadataURL ... "); + metadataURL = entityId; + + } + String trustStoreUrl = FileUtils.makeAbsoluteURL( + spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE), + authConfig.getConfigurationRootDirectory()); + String trustStorePassword = spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE_PASSWORD); + + return createNewSimpleMetadataProvider(metadataURL, + buildMetadataFilterChain(spConfig, metadataURL, trustStoreUrl, trustStorePassword), + spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_UNIQUEIDENTIFIER), + getTimer(), + new BasicParserPool(), + createHttpClient(metadataURL)); + + } catch (PVP2MetadataException e) { + log.info("Can NOT initialize Metadata signature-verification filter. Reason: " + e.getMessage()); + throw new EAAFConfigurationException("config.27", + new Object[] {"Can NOT initialize Metadata signature-verification filter. Reason: " + e.getMessage()}, e); + + } + + } else + log.info("No ServiceProvider with entityId: " + entityId + " in configuration."); + + return null; + } + + @Override + protected List getAllMetadataURLsFromConfiguration() throws EAAFConfigurationException { + // TODO Auto-generated method stub + return null; + } + + private HttpClient createHttpClient(String metadataURL) { + HttpClient httpClient = new HttpClient(); + HttpClientParams httpClientParams = new HttpClientParams(); + httpClientParams.setSoTimeout(MSeIDASNodeConstants.METADATA_SOCKED_TIMEOUT); + httpClient.setParams(httpClientParams); + return httpClient; + + } + + private MetadataFilterChain buildMetadataFilterChain(ISPConfiguration oaParam, String metadataURL, String trustStoreUrl, String trustStorePassword) throws CertificateException, PVP2MetadataException{ + MetadataFilterChain filterChain = new MetadataFilterChain(); + filterChain.getFilters().add(new SchemaValidationFilter( + basicConfig.getBasicMOAIDConfigurationBoolean(MSeIDASNodeConstants.PROP_CONFIG_PVP_SCHEME_VALIDATION, true))); + + filterChain.getFilters().add( + new MetadataSignatureVerificationFilter( + trustStoreUrl, trustStorePassword, metadataURL)); + + filterChain.getFilters().add(new PVPEntityCategoryFilter( + basicConfig.getBasicMOAIDConfigurationBoolean(MSeIDASNodeConstants.PROP_CONFIG_PVP_ENABLE_ENTITYCATEGORIES, true))); + + return filterChain; + } +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/StatusMessageProvider.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/StatusMessageProvider.java new file mode 100644 index 00000000..5f359ea1 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/provider/StatusMessageProvider.java @@ -0,0 +1,104 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.provider; + +import java.text.MessageFormat; +import java.util.Locale; +import java.util.MissingResourceException; +import java.util.PropertyResourceBundle; +import java.util.ResourceBundle; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import at.gv.egiz.eaaf.core.api.IStatusMessenger; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; + +@Service("StatusMessageProvider") +public class StatusMessageProvider implements IStatusMessenger { + private static final Logger log = LoggerFactory.getLogger(StatusMessageProvider.class); + + private static final String ERROR_MESSAGES_UNAVAILABLE = "Error messages can NOT be load from application. Only errorCode: {0} is availabe" ; + private static final String ERROR_NO_MESSAGE = "No errormesseage for error with number.={0}"; + + private static final String ERROR_EXTERNALERROR_CODES_UNAVAILABLE = "External error-codes can NOT be load from application. Only internal errorCode: {0} is availabe" ; + private static final String ERROR_NO_EXTERNALERROR_CODE = "No external error for internal error with number.={0}"; + + //internal messanges + private static final String DEFAULT_MESSAGE_RESOURCES = "properties/status_messages_en"; + private static final Locale DEFAULT_MESSAGE_LOCALES = new Locale("en", "GB"); + private ResourceBundle messages; + + //external error codes + private static final String DEFAULT_EXTERNALERROR_RESOURCES = "properties/external_statuscodes_map"; + private static final Locale DEFAULT_EXTERNALERROR_LOCALES = new Locale("en", "GB"); + private ResourceBundle externalError = null; + + @Override + public String getMessage(String messageId, Object[] parameters) { + // initialize messages + if (messages == null) { + this.messages = PropertyResourceBundle.getBundle( + DEFAULT_MESSAGE_RESOURCES, + DEFAULT_MESSAGE_LOCALES); + + } + + // create the message + if (messages == null) { + return MessageFormat.format(ERROR_MESSAGES_UNAVAILABLE, new Object[] { messageId }); + + } else { + try { + String rawMessage = messages.getString(messageId); + return MessageFormat.format(rawMessage, parameters); + + } catch (MissingResourceException e2) { + return MessageFormat.format(ERROR_NO_MESSAGE, new Object[] { messageId }); + + } + } + } + + @Override + public String getResponseErrorCode(Throwable throwable) { + String errorCode = IStatusMessenger.CODES_EXTERNAL_ERROR_GENERIC; + if (throwable instanceof EAAFException) { + errorCode = ((EAAFException) throwable).getErrorId(); + + } + //TODO: maybe more internal switches are required + + return errorCode; + + } + + @Override + public String mapInternalErrorToExternalError(String intErrorCode) { + // initialize messages + if (externalError == null) { + this.externalError = PropertyResourceBundle.getBundle( + DEFAULT_EXTERNALERROR_RESOURCES, + DEFAULT_EXTERNALERROR_LOCALES); + + } + + // create the message + if (externalError == null) { + log.warn(MessageFormat.format(ERROR_EXTERNALERROR_CODES_UNAVAILABLE, new Object[] { intErrorCode })); + return IStatusMessenger.CODES_EXTERNAL_ERROR_GENERIC; + + } else { + try { + return externalError.getString(intErrorCode); + + } catch (MissingResourceException e2) { + log.info(MessageFormat.format(ERROR_NO_EXTERNALERROR_CODE, new Object[] { intErrorCode })); + return IStatusMessenger.CODES_EXTERNAL_ERROR_GENERIC; + + } + } + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/CacheWitheIDASBackend.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/CacheWitheIDASBackend.java new file mode 100644 index 00000000..ac0abda0 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/CacheWitheIDASBackend.java @@ -0,0 +1,33 @@ +package at.asitplus.eidas.specific.connector.storage; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import eu.eidas.auth.commons.cache.ConcurrentMapService; +import eu.eidas.auth.commons.tx.AbstractCorrelationMap; + +public class CacheWitheIDASBackend extends AbstractCorrelationMap { + + protected CacheWitheIDASBackend(ConcurrentMapService concurrentMapService) { + super(concurrentMapService); + } + + public List clean(Date now, long dataTimeOut) { + List result = new ArrayList(); + Iterator iterator = map.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + if (map.containsKey(key)) { + TransactionStoreElement element = map.get(key); + if (now.getTime() - element.getCreated().getTime() > dataTimeOut) + result.add(key); + } + } + + return result; + + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/SimpleInMemoryTransactionStorage.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/SimpleInMemoryTransactionStorage.java new file mode 100644 index 00000000..80b0e965 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/SimpleInMemoryTransactionStorage.java @@ -0,0 +1,141 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.storage; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; + +@Service("SimpleInMemoryTransactionStorage") +public class SimpleInMemoryTransactionStorage implements ITransactionStorage{ + private static final Logger log = LoggerFactory.getLogger(SimpleInMemoryTransactionStorage.class); + + private Map storage = new ConcurrentHashMap(); + + @Override + public void changeKey(String oldKey, String newKey, Object value) throws EAAFException { + if (containsKey(oldKey)) { + TransactionStoreElement el = storage.get(oldKey); + el.setKey(newKey); + storage.put(newKey, el); + storage.remove(oldKey); + + } else + throw new EAAFStorageException("No element in TransactionStorage with key: " + oldKey); + + } + + @Override + public List clean(Date now, long dataTimeOut) { + List result = new ArrayList(); + Iterator iterator = storage.keySet().iterator(); + while (iterator.hasNext()) { + String key = iterator.next(); + synchronized (storage) { + if (storage.containsKey(key)) { + TransactionStoreElement element = storage.get(key); + if (now.getTime() - element.getCreated().getTime() > dataTimeOut) + result.add(key); + } + } + } + + return result; + + } + + @Override + public boolean containsKey(String key) { + if (key != null) + return storage.containsKey(key); + else + return false; + + } + + @Override + public Object get(String key) throws EAAFException { + if (key != null && containsKey(key)) { + TransactionStoreElement element = storage.get(key); + return element.getData(); + + } else + return null; + } + + @Override + public T get(String key, Class type) throws EAAFException { + return get(key, type, -1); + + } + + @Override + public T get(String key, Class type, long dataTimeOut) throws EAAFException { + if (key != null && containsKey(key)) { + TransactionStoreElement value = storage.get(key); + + if (dataTimeOut > -1) { + long now = new Date().getTime(); + if (now - value.getCreated().getTime() > dataTimeOut) { + log.info("Transaction-Data with key: " + key + " is out of time."); + throw new EAAFStorageException("Transaction-Data with key: " + key + " is out of time."); + + } + } + + if (type.isAssignableFrom(value.getData().getClass())) { + return (T) value.getData(); + + } else + log.warn("Can NOT cast '" + value.getClass() + "' to '" + type + "'"); + + } + + return null; + } + + @Override + public Object getRaw(String key) throws EAAFException { + return storage.get(key); + + } + + @Override + public void put(String key, Object value, int dataTimeOut) throws EAAFException { + TransactionStoreElement element = new TransactionStoreElement(); + element.setKey(key); + element.setData(value); + storage.put(key, element); + + } + + @Override + public void putRaw(String key, Object value) throws EAAFException { + if (value instanceof TransactionStoreElement) + storage.put(((TransactionStoreElement) value).getKey(), (TransactionStoreElement) value); + else + log.info(value.getClass().getName() + " is NOT a RAW element of " + ITransactionStorage.class.getName()); + + } + + @Override + public void remove(String key) { + if (containsKey(key)) { + log.debug("Remove element with key: " + key + " from " + ITransactionStorage.class.getName()); + storage.remove(key); + + } + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/TransactionStoreElement.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/TransactionStoreElement.java new file mode 100644 index 00000000..b9012376 --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/TransactionStoreElement.java @@ -0,0 +1,36 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.storage; + +import java.io.Serializable; +import java.util.Date; + +public class TransactionStoreElement implements Serializable{ + + private static final long serialVersionUID = 1L; + private String key = null; + private Object data = null; + private Date created; + + public String getKey() { + return key; + } + public void setKey(String key) { + this.key = key; + } + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } + public Date getCreated() { + return created; + } + public void setCreated(Date created) { + this.created = created; + } + + + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/eIDASCacheTransactionStoreDecorator.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/eIDASCacheTransactionStoreDecorator.java new file mode 100644 index 00000000..f1ffba6f --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/storage/eIDASCacheTransactionStoreDecorator.java @@ -0,0 +1,124 @@ +package at.asitplus.eidas.specific.connector.storage; + +import java.util.Date; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; + +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; + +public class eIDASCacheTransactionStoreDecorator implements ITransactionStorage{ + private static final Logger log = LoggerFactory.getLogger(eIDASCacheTransactionStoreDecorator.class); + + @Autowired(required=true) private CacheWitheIDASBackend storage; + + @Override + public void changeKey(String oldKey, String newKey, Object value) throws EAAFException { + if (containsKey(oldKey)) { + TransactionStoreElement el = storage.get(oldKey); + el.setKey(newKey); + storage.put(newKey, el); + storage.remove(oldKey); + + } else + throw new EAAFStorageException("No element in TransactionStorage with key: " + oldKey); + + } + + @Override + public List clean(Date now, long dataTimeOut) { + return storage.clean(now, dataTimeOut); + + } + + @Override + public boolean containsKey(String key) { + if (key != null) { + if (storage.get(key) != null) + return true; + + } + + return false; + + } + + @Override + public Object get(String key) throws EAAFException { + if (key != null && containsKey(key)) { + TransactionStoreElement element = storage.get(key); + return element.getData(); + + } else + return null; + } + + @Override + public T get(String key, Class type) throws EAAFException { + return get(key, type, -1); + + } + + @Override + public T get(String key, Class type, long dataTimeOut) throws EAAFException { + if (key != null && containsKey(key)) { + TransactionStoreElement value = storage.get(key); + + if (dataTimeOut > -1) { + long now = new Date().getTime(); + if (now - value.getCreated().getTime() > dataTimeOut) { + log.info("Transaction-Data with key: " + key + " is out of time."); + throw new EAAFStorageException("Transaction-Data with key: " + key + " is out of time."); + + } + } + + if (type.isAssignableFrom(value.getData().getClass())) { + return (T) value.getData(); + + } else + log.warn("Can NOT cast '" + value.getClass() + "' to '" + type + "'"); + + } + + return null; + } + + @Override + public Object getRaw(String key) throws EAAFException { + return storage.get(key); + + } + + @Override + public void put(String key, Object value, int dataTimeOut) throws EAAFException { + TransactionStoreElement element = new TransactionStoreElement(); + element.setKey(key); + element.setData(value); + storage.put(key, element); + + } + + @Override + public void putRaw(String key, Object value) throws EAAFException { + if (value instanceof TransactionStoreElement) + storage.put(((TransactionStoreElement) value).getKey(), (TransactionStoreElement) value); + else + log.info(value.getClass().getName() + " is NOT a RAW element of " + ITransactionStorage.class.getName()); + + } + + @Override + public void remove(String key) { + if (containsKey(key)) { + log.debug("Remove element with key: " + key + " from " + ITransactionStorage.class.getName()); + storage.remove(key); + + } + } + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/AuthnRequestValidator.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/AuthnRequestValidator.java new file mode 100644 index 00000000..607f42df --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/AuthnRequestValidator.java @@ -0,0 +1,203 @@ +package at.asitplus.eidas.specific.connector.verification; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; + +import org.apache.commons.lang3.StringUtils; +import org.opensaml.saml2.core.AuthnContextClassRef; +import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.saml2.core.RequestedAuthnContext; +import org.opensaml.saml2.core.Scoping; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.xml.XMLObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.asitplus.eidas.specific.connector.config.ServiceProviderConfiguration; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; +import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; +import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttributes; +import at.gv.egiz.eaaf.modules.pvp2.api.validation.IAuthnRequestValidator; +import at.gv.egiz.eaaf.modules.pvp2.exception.NameIDFormatNotSupportedException; + +public class AuthnRequestValidator implements IAuthnRequestValidator { + + private static final Logger log = LoggerFactory.getLogger(AuthnRequestValidator.class); + + @Override + public void validate(HttpServletRequest httpReq, IRequest pendingReq, AuthnRequest authnReq, + SPSSODescriptor spSSODescriptor) throws AuthnRequestValidatorException { + try { + //validate NameIDPolicy + NameIDPolicy nameIDPolicy = authnReq.getNameIDPolicy(); + if (nameIDPolicy != null) { + String nameIDFormat = nameIDPolicy.getFormat(); + if (nameIDFormat != null) { + if ( !(NameID.TRANSIENT.equals(nameIDFormat) || + NameID.PERSISTENT.equals(nameIDFormat)) ) { + + throw new NameIDFormatNotSupportedException(nameIDFormat); + + } + + } else + log.trace("Find NameIDPolicy, but NameIDFormat is 'null'"); + } else + log.trace("AuthnRequest includes no 'NameIDPolicy'"); + + + //post-process RequesterId + String spEntityId = extractScopeRequsterId(authnReq); + if (StringUtils.isEmpty(spEntityId)) { + log.info("NO service-provider entityID in Authn. request. Stop authn. process ... "); + throw new AuthnRequestValidatorException("pvp2.22", + new Object[] {"NO relaying-party entityID in Authn. request"}, pendingReq); + + } else + pendingReq.setRawDataToTransaction(MSeIDASNodeConstants.DATA_REQUESTERID, spEntityId); + + + //post-process ProviderName + String providerName = authnReq.getProviderName(); + if (StringUtils.isEmpty(providerName)) + log.info("Authn. request contains NO SP friendlyName"); + else + pendingReq.setRawDataToTransaction(MSeIDASNodeConstants.DATA_PROVIDERNAME, spEntityId); + + //post-process requested LoA + List reqLoA = extractLoA(authnReq); + pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class).setRequiredLoA(reqLoA); + + //post-process requested LoA comparison-level + String reqLoAComperison = extractComparisonLevel(authnReq); + pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class).setLoAMachtingMode(reqLoAComperison); + + //validate and process requested attributes + boolean sectorDetected = false; + List requestedAttributes = authnReq.getExtensions().getUnknownXMLObjects(); + for (XMLObject reqAttrObj : requestedAttributes) { + if (reqAttrObj instanceof EAAFRequestedAttributes) { + EAAFRequestedAttributes reqAttr = (EAAFRequestedAttributes)reqAttrObj; + if (reqAttr.getAttributes() != null && reqAttr.getAttributes().size() != 0 ) { + for (EAAFRequestedAttribute el : reqAttr.getAttributes()) { + log.trace("Processing req. attribute '" + el.getName() + "' ... "); + if (el.getName().equals(PVPAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME)) { + if (el.getAttributeValues() != null && el.getAttributeValues().size() == 1) { + String sectorId = el.getAttributeValues().get(0).getDOM().getTextContent(); + ServiceProviderConfiguration spConfig = pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class); + + try { + spConfig.setbPKTargetIdentifier(sectorId); + sectorDetected = true; + + } catch (EAAFException e) { + log.info("Requested sector: " + sectorId + " DOES NOT match to allowed sectors for SP: " + spConfig.getUniqueIdentifier()); + } + + } else + log.info("Req. attribute '" + el.getName() + "' contains NO or MORE THEN ONE attribute-values. Ignore full req. attribute"); + + } else + log.debug("Ignore req. attribute: " + el.getName()); + + } + + } else + log.debug("No requested Attributes in Authn. Request"); + + } else + log.info("Ignore unknown requested attribute: " + reqAttrObj.getElementQName().toString()); + + } + + if (!sectorDetected) { + log.info("Authn.Req validation FAILED. Reason: Contains NO or NO VALID target-sector information."); + throw new AuthnRequestValidatorException("pvp2.22", new Object[] {"NO or NO VALID target-sector information"}); + + } + + } catch (EAAFStorageException e) { + log.info("Can NOT store Authn. Req. data into pendingRequest." , e); + throw new AuthnRequestValidatorException("internal.02", null, e); + + } + + } + + private String extractComparisonLevel(AuthnRequest authnReq) { + if (authnReq.getRequestedAuthnContext() != null) { + RequestedAuthnContext authContext = authnReq.getRequestedAuthnContext(); + return authContext.getComparison().toString(); + + } + + return null; + } + + private List extractLoA(AuthnRequest authnReq) throws AuthnRequestValidatorException { + List result = new ArrayList(); + if (authnReq.getRequestedAuthnContext() != null) { + RequestedAuthnContext authContext = authnReq.getRequestedAuthnContext(); + if (authContext.getComparison().equals(AuthnContextComparisonTypeEnumeration.MINIMUM)) { + if (authContext.getAuthnContextClassRefs().isEmpty()) { + log.debug("Authn. Req. contains no requested LoA"); + + } else if (authContext.getAuthnContextClassRefs().size() > 1) { + log.info("Authn. Req. contains MORE THAN ONE requested LoA, but " + + AuthnContextComparisonTypeEnumeration.MINIMUM + " allows only one" ); + throw new AuthnRequestValidatorException("pvp2.22", + new Object[] {"Authn. Req. contains MORE THAN ONE requested LoA, but " + + AuthnContextComparisonTypeEnumeration.MINIMUM + " allows only one"}); + + } else + result.add(authContext.getAuthnContextClassRefs().get(0).getAuthnContextClassRef()); + + } else if (authContext.getComparison().equals(AuthnContextComparisonTypeEnumeration.EXACT)) { + for (AuthnContextClassRef el : authContext.getAuthnContextClassRefs()) + result.add(el.getAuthnContextClassRef()); + + } else { + log.info("Currently only '" + AuthnContextComparisonTypeEnumeration.MINIMUM + "' and '" + + AuthnContextComparisonTypeEnumeration.EXACT + "' are supported"); + throw new AuthnRequestValidatorException("pvp2.22", + new Object[] {"Currently only '" + AuthnContextComparisonTypeEnumeration.MINIMUM + "' and '" + + AuthnContextComparisonTypeEnumeration.EXACT + "' are supported"}); + + } + + } + + return result; + } + + private String extractScopeRequsterId(AuthnRequest authnReq) { + if (authnReq.getScoping() != null) { + Scoping scoping = authnReq.getScoping(); + if (scoping.getRequesterIDs() != null && + scoping.getRequesterIDs().size() > 0) { + if (scoping.getRequesterIDs().size() == 1) + return scoping.getRequesterIDs().get(0).getRequesterID(); + + else { + log.info("Authn. request contains more than on RequesterIDs! Only use first one"); + return scoping.getRequesterIDs().get(0).getRequesterID(); + + } + } + } + + return null; + } + + +} diff --git a/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/MetadataSignatureVerificationFilter.java b/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/MetadataSignatureVerificationFilter.java new file mode 100644 index 00000000..67d2d59b --- /dev/null +++ b/connector/src/main/java/at/asitplus/eidas/specific/connector/verification/MetadataSignatureVerificationFilter.java @@ -0,0 +1,142 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.verification; + +import java.io.IOException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + +import org.opensaml.common.SignableSAMLObject; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.security.SAMLSignatureProfileValidator; +import org.opensaml.xml.security.x509.BasicX509Credential; +import org.opensaml.xml.signature.SignatureValidator; +import org.opensaml.xml.validation.ValidationException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2MetadataException; +import at.gv.egiz.eaaf.modules.pvp2.idp.exception.SAMLRequestNotSignedException; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.AbstractMetadataSignatureFilter; + +public class MetadataSignatureVerificationFilter extends AbstractMetadataSignatureFilter{ + private static final Logger log = LoggerFactory.getLogger(MetadataSignatureVerificationFilter.class); + + private String metadataURL; + private List trustedCredential = new ArrayList(); + + public MetadataSignatureVerificationFilter(String trustStorePath, String trustStorePassword, String metadataURL) + throws PVP2MetadataException { + this.metadataURL = metadataURL; + + log.trace("Initialize metadata signature-verification filter with truststore: " + trustStorePath + " ... "); + try { + KeyStore keyStore = KeyStoreUtils.loadKeyStore(trustStorePath, trustStorePassword); + if (keyStore != null) { + //load trusted certificates + Enumeration aliases = keyStore.aliases(); + while(aliases.hasMoreElements()) { + String el = aliases.nextElement(); + log.trace("Process TrustStoreEntry: " + el); + if (keyStore.isCertificateEntry(el)) { + Certificate cert = keyStore.getCertificate(el); + if (cert != null && cert instanceof X509Certificate) { + BasicX509Credential trustedCert = new BasicX509Credential(); + trustedCert.setEntityCertificate((X509Certificate) cert); + this.trustedCredential.add(trustedCert); + log.debug("Add cert: " + ((X509Certificate) cert).getSubjectDN() + " as trusted for metadata: " + metadataURL); + + } else + log.info("Can not process entry: " + el + ". Reason: " + cert.toString()); + + } + } + + + } else + throw new PVP2MetadataException("pvp2.26", + new Object[] {"Can not open trustStore: " + trustStorePath + " for metadata: " + metadataURL}); + + } catch (KeyStoreException | IOException e) { + log.warn("Can not open trustStore: " + trustStorePath + " for metadata: " + metadataURL + " Reason: " + e.getMessage(), e); + throw new PVP2MetadataException("pvp2.26", + new Object[] {"Can not open trustStore: " + trustStorePath + " for metadata"}, e); + + } + + + } + + + @Override + protected void verify(EntityDescriptor desc) throws PVP2MetadataException { + try { + internalVerify(desc); + + } catch (EAAFException e) { + log.info("Metadata verification FAILED for: " + metadataURL + " Reason: " +e.getMessage()); + throw new PVP2MetadataException("pvp2.26", + new Object[] {"Metadata verification FAILED for: " + metadataURL + " Reason: " +e.getMessage()}, e); + + } + } + + @Override + protected void verify(EntitiesDescriptor desc) throws PVP2MetadataException { + throw new PVP2MetadataException("pvp2.26", + new Object[] {"EntitiesDescritors are NOT supported"}); + + } + + @Override + protected void verify(EntityDescriptor entity, EntitiesDescriptor desc) throws PVP2MetadataException { + throw new PVP2MetadataException("pvp2.26", + new Object[] {"EntitiesDescritors are NOT supported"}); + + } + + private void internalVerify(SignableSAMLObject signedElement) + throws EAAFException { + if (signedElement.getSignature() == null) { + throw new SAMLRequestNotSignedException(); + } + + try { + SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator(); + sigValidator.validate(signedElement.getSignature()); + } catch (ValidationException e) { + log.error("Failed to validate Signature", e); + throw new SAMLRequestNotSignedException(e); + } + + boolean isTrusted = false; + for (BasicX509Credential cred : trustedCredential) { + SignatureValidator sigValidator = new SignatureValidator(cred); + try { + sigValidator.validate(signedElement.getSignature()); + isTrusted = true; + + } catch (ValidationException e) { + log.info("Failed to verfiy Signature with cert: " + cred.getEntityCertificate().getSubjectDN() + + " Reason: " + e.getMessage()); + + } + } + + if (!isTrusted) { + log.warn("PVP2 metadata: " + metadataURL + " are NOT trusted!"); + throw new SAMLRequestNotSignedException(); + + } + + } + +} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/MSSpecificeIDASNodeSpringResourceProvider.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/MSSpecificeIDASNodeSpringResourceProvider.java deleted file mode 100644 index 6dacc33b..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/MSSpecificeIDASNodeSpringResourceProvider.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import at.gv.egiz.components.spring.api.SpringResourceProvider; - -public class MSSpecificeIDASNodeSpringResourceProvider implements SpringResourceProvider { - - @Override - public Resource[] getResourcesToLoad() { - ClassPathResource mseIDASNode = new ClassPathResource("/specific_eIDAS_connector.beans.xml", MSSpecificeIDASNodeSpringResourceProvider.class); - ClassPathResource mseIDASNodeStorage = new ClassPathResource("/specific_eIDAS_connector.storage.beans.xml", MSSpecificeIDASNodeSpringResourceProvider.class); - return new Resource[] {mseIDASNode, mseIDASNodeStorage}; - } - - @Override - public String[] getPackagesToScan() { - return null; - } - - @Override - public String getName() { - return "MS-specific eIDAS Node SpringResourceProvider"; - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/SpringInitializer.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/SpringInitializer.java deleted file mode 100644 index 0e115ad0..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/SpringInitializer.java +++ /dev/null @@ -1,172 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector; - -import java.util.Arrays; - -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.core.io.ClassPathResource; -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.request.RequestContextListener; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.context.support.ServletContextResource; -import org.springframework.web.servlet.DispatcherServlet; - -import at.gv.egiz.components.spring.api.SpringLoader; -import at.gv.egiz.eaaf.core.api.IStatusMessenger; -import at.gv.egiz.eaaf.core.impl.logging.LogMessageProviderFactory; -import at.gv.egiz.eaaf.core.impl.utils.Random; -import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EAAFDefaultSAML2Bootstrap; - -/** - * Web application initializer - * - * @author Thomas Lenz - */ -public class SpringInitializer implements WebApplicationInitializer { - - private static final Logger log = LoggerFactory.getLogger(SpringInitializer.class); - - private String[] rootServletContexts = null; - private String[] servletContexts = null; - private String[] activeProfiles = null; - - public SpringInitializer() { - this.rootServletContexts = null; - this.servletContexts = new String[] { - "/applicationContext.xml", - - }; - this.activeProfiles = null; - } - - - /* (non-Javadoc) - * @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext) - */ - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - try { - log.info("=============== Loading Config Root Context! ==============="); - ApplicationContext cfgRootContext = - new ClassPathXmlApplicationContext(new String[] { - "/applicationContext.xml" - }); - - - log.info("=============== Loading Root Context! ==============="); - GenericWebApplicationContext rootContext = new GenericWebApplicationContext(); - rootContext.setServletContext(servletContext); - rootContext.setParent(cfgRootContext); - -// log.info("=============== Setting active profiles! ==============="); -// if (this.activeProfiles != null) { -// for (String profile : this.activeProfiles) { -// rootContext.getEnvironment().addActiveProfile(profile); -// } -// } - - log.info("Spring-context was initialized with active profiles: " + - Arrays.asList(rootContext.getEnvironment().getActiveProfiles())); - - log.info("=============== Loading Local Contexts! ==============="); - XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader( - rootContext); - if (rootServletContexts != null) { - for (String rootServletContext : rootServletContexts) { - log.debug("Loading: "+ rootServletContext); - xmlReader.loadBeanDefinitions(new ServletContextResource( - servletContext, rootServletContext)); - } - } - // Manage the lifecycle of the root application context - servletContext.addListener(new ContextLoaderListener(rootContext)); - - // log.debug("Beans after logAMQP in {}", rootContext); - // dumpBeanDefinitions(rootContext); - - log.info("=============== Loading SPI Context! ==============="); - if (rootContext instanceof BeanDefinitionRegistry) { - log.debug("Loading modules and components"); - SpringLoader.loadSpringServices(rootContext); - - } else - log.warn("Failed to load external Spring since no BeanDefinitionRegistry"); - - log.trace("Beans after SPI in "+ rootContext); - dumpBeanDefinitions(rootContext); - - log.debug("Loading servlet config in "+ rootContext); - if (servletContexts != null) { - for (String servletContextString : servletContexts) - xmlReader.loadBeanDefinitions(new ClassPathResource(servletContextString, SpringInitializer.class)); - - } - - log.debug("Refreshing context "+ rootContext); - rootContext.refresh(); - - log.info("=============== Register Dispatcher Servlet! ==============="); - - log.trace("Final Beans in "+ rootContext); - dumpBeanDefinitions(rootContext); - - log.info("Registering dispatcher configuration"); - ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext)); - if (dispatcher != null) { - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/"); - dispatcher.setAsyncSupported(true); - - } else - log.error("Failed to register dispatcher server in servlet context!"); - - - log.info("=============== Register RequestContextListener! ==============="); - servletContext.addListener(new RequestContextListener()); - - //initialize status messenger - LogMessageProviderFactory.setStatusMessager(rootContext.getBean(IStatusMessenger.class)); - - log.info("Bootstrap openSAML .... "); - EAAFDefaultSAML2Bootstrap.bootstrap(); - - log.info("Seed random number generator ... "); - Random.seedRandom(); - - log.info("Initialization of MS-specific eIDAS-connector finished."); - - - } catch (Throwable e) { - log.error("MS-specific eIDAS-connector initialization FAILED!", e); - - } - - } - - private void dumpBeanDefinitions(GenericApplicationContext context) { - log.trace("Registered Bean in context " + context.toString()); - - String[] registeredBeans = context.getBeanDefinitionNames(); - for (String registeredBean : registeredBeans) { - BeanDefinition beanDefinition = context - .getBeanDefinition(registeredBean); - log.trace(registeredBean + " -> " + beanDefinition.getBeanClassName()); - - } - - log.trace("Registered Bean in context --"+ context); - } -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/auth/AuthenticationManager.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/auth/AuthenticationManager.java deleted file mode 100644 index e41bad28..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/auth/AuthenticationManager.java +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.auth; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.impl.idp.auth.AbstractAuthenticationManager; -import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; - -@Service("AuthenticationManager") -public class AuthenticationManager extends AbstractAuthenticationManager { - private static final Logger log = LoggerFactory.getLogger(AuthenticationManager.class); - - @Override - public ISLOInformationContainer performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, - IRequest pendingReq, String internalSSOId) throws EAAFException { - throw new RuntimeException("Single LogOut is NOT supported by this implementation"); - - } - - @Override - protected void populateExecutionContext(ExecutionContext executionContext, - RequestImpl pendingReq, HttpServletRequest httpReq) - throws EAAFException { - log.trace("No implementation-specific population of execution-context required ... "); - - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/builder/AuthenticationDataBuilder.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/builder/AuthenticationDataBuilder.java deleted file mode 100644 index 34f964fb..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/builder/AuthenticationDataBuilder.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.builder; - -import java.util.Date; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; -import org.w3c.dom.DOMException; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.api.idp.auth.data.IAuthProcessDataContainer; -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFBuilderException; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFParserException; -import at.gv.egiz.eaaf.core.exceptions.XPathException; -import at.gv.egiz.eaaf.core.impl.data.Pair; -import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; -import at.gv.egiz.eaaf.core.impl.idp.auth.builder.AbstractAuthenticationDataBuilder; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -@Service("AuthenticationDataBuilder") -public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder { - private static final Logger log = LoggerFactory.getLogger(AuthenticationDataBuilder.class); - - @Override - public IAuthData buildAuthenticationData(IRequest pendingReq) throws EAAFAuthenticationException { - - IAuthProcessDataContainer authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - AuthenticationData authData = new AuthenticationData(); - - try { - generateBasicAuthData(authData, pendingReq, authProcessData); - - //set specific informations - authData.setSsoSessionValidTo(new Date(new Date().getTime() - + MSeIDASNodeConstants.DEFAULT_PVP_ASSERTION_VALIDITY * 60 * 1000)); - - } catch (EAAFBuilderException | EAAFParserException | EAAFConfigurationException - | XPathException | DOMException e) { - log.warn("Can not build authentication data from auth. process information"); - throw new EAAFAuthenticationException("builder.11", new Object[]{e.getMessage()}, e); - - } - - return authData; - - } - - @Override - protected Pair buildOAspecificbPK(IRequest pendingReq, AuthenticationData authData) throws EAAFBuilderException { - //TODO: check if bPK already exists - - - return super.buildOAspecificbPK(pendingReq, authData); - - } - - @Override - protected Pair getEncryptedbPKFromPVPAttribute(IAuthProcessDataContainer arg0, - AuthenticationData arg1, ISPConfiguration arg2) throws EAAFBuilderException { - return null; - - } - - @Override - protected Pair getbaseIDFromSZR(AuthenticationData arg0, String arg1, String arg2) { - return null; - - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/builder/PVPSubjectNameGenerator.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/builder/PVPSubjectNameGenerator.java deleted file mode 100644 index 1435dd96..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/builder/PVPSubjectNameGenerator.java +++ /dev/null @@ -1,18 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.builder; - -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.impl.data.Pair; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; -import at.gv.egiz.eaaf.modules.pvp2.idp.api.builder.ISubjectNameIdGenerator; - -public class PVPSubjectNameGenerator implements ISubjectNameIdGenerator { - - @Override - public Pair generateSubjectNameId(IAuthData authData, ISPConfiguration spConfig) throws PVP2Exception { - return Pair.newInstance(authData.getBPK(), authData.getBPKType()); - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/config/PVPEndPointConfiguration.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/config/PVPEndPointConfiguration.java deleted file mode 100644 index 3a7bf379..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/config/PVPEndPointConfiguration.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.config; - -import java.util.List; - -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.Organization; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -@Service("PVPEndPointConfiguration") -public class PVPEndPointConfiguration implements IPVP2BasicConfiguration { - private static final Logger log = LoggerFactory.getLogger(PVPEndPointConfiguration.class); - - @Autowired(required=true) IConfiguration basicConfiguration; - - @Override - public String getIDPEntityId(String authURL) throws EAAFException { - return removePostFix(authURL) + MSeIDASNodeConstants.ENDPOINT_PVP_METADATA; - - } - - @Override - public String getIDPSSOPostService(String authURL) throws EAAFException { - return removePostFix(authURL) + MSeIDASNodeConstants.ENDPOINT_PVP_POST; - - } - - @Override - public String getIDPSSORedirectService(String authURL) throws EAAFException { - return removePostFix(authURL) + MSeIDASNodeConstants.ENDPOINT_PVP_REDIRECT; - - } - - @Override - public Object getIDPSSOSOAPService(String extractAuthURLFromRequest) throws EAAFException { - log.warn("PVP S-Profile End-Point does NOT support SOAP Binding"); - return null; - - } - - @Override - public List getIDPContacts() throws EAAFException { - return null; - } - - @Override - public Organization getIDPOrganisation() throws EAAFException { - return null; - } - - private String removePostFix(String url) { - if (url != null && url.endsWith("/")) - return url.substring(0, url.length() - 1); - else - return url; - } -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/config/PVPMetadataConfiguration.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/config/PVPMetadataConfiguration.java deleted file mode 100644 index 7d17baa1..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/config/PVPMetadataConfiguration.java +++ /dev/null @@ -1,240 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.config; - -import java.util.Arrays; -import java.util.List; - -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.NameIDType; -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.Organization; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.xml.security.credential.Credential; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataBuilderConfiguration; -import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; -import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PVPAttributeBuilder; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -public class PVPMetadataConfiguration implements IPVPMetadataBuilderConfiguration{ - private static final Logger log = LoggerFactory.getLogger(PVPMetadataConfiguration.class); - - private IConfiguration basicConfig; - private String authUrl; - private AbstractCredentialProvider pvpIDPCredentials; - private IPVP2BasicConfiguration pvpBasicConfig; - - public PVPMetadataConfiguration(IConfiguration basicConfig, String authURL, IPVP2BasicConfiguration pvpBasicConfig, AbstractCredentialProvider pvpIDPCredentials) { - this.authUrl = authURL; - this.pvpIDPCredentials = pvpIDPCredentials; - this.basicConfig = basicConfig; - this.pvpBasicConfig = pvpBasicConfig; - - } - - @Override - public String getSPNameForLogging() { - return "PVP2 S-Profile IDP"; - } - - @Override - public int getMetadataValidUntil() { - return Integer.valueOf(basicConfig.getBasicConfiguration( - MSeIDASNodeConstants.PROP_CONFIG_PVP2_METADATA_VALIDITY, - String.valueOf(MSeIDASNodeConstants.DEFAULT_PVP_METADATA_VALIDITY))); - - } - - @Override - public boolean buildEntitiesDescriptorAsRootElement() { - return false; - - } - - @Override - public boolean buildIDPSSODescriptor() { - return true; - - } - - @Override - public boolean buildSPSSODescriptor() { - return false; - - } - - @Override - public String getEntityID() { - try { - return pvpBasicConfig.getIDPEntityId(authUrl); - - } catch (EAAFException e) { - log.error("Can NOT build PVP metadata configuration.", e); - throw new RuntimeException("Can NOT build PVP metadata configuration."); - - } - - } - - @Override - public String getEntityFriendlyName() { - return null; - - } - - @Override - public List getContactPersonInformation() { - try { - return pvpBasicConfig.getIDPContacts(); - - } catch (EAAFException e) { - log.error("Can NOT build PVP metadata configuration.", e); - throw new RuntimeException("Can NOT build PVP metadata configuration."); - - } - - } - - @Override - public Organization getOrgansiationInformation() { - try { - return pvpBasicConfig.getIDPOrganisation(); - - } catch (EAAFException e) { - log.error("Can NOT build PVP metadata configuration.", e); - throw new RuntimeException("Can NOT build PVP metadata configuration."); - - } - } - - @Override - public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException { - return pvpIDPCredentials.getIDPMetaDataSigningCredential(); - - } - - @Override - public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException { - return pvpIDPCredentials.getIDPAssertionSigningCredential(); - - } - - @Override - public Credential getEncryptionCredentials() throws CredentialsNotAvailableException { - return null; - - - } - - @Override - public String getIDPWebSSOPostBindingURL() { - try { - return pvpBasicConfig.getIDPSSOPostService(authUrl); - - } catch (EAAFException e) { - log.error("Can NOT build PVP metadata configuration.", e); - throw new RuntimeException("Can NOT build PVP metadata configuration."); - - } - - } - - @Override - public String getIDPWebSSORedirectBindingURL() { - try { - return pvpBasicConfig.getIDPSSORedirectService(authUrl); - - } catch (EAAFException e) { - log.error("Can NOT build PVP metadata configuration.", e); - throw new RuntimeException("Can NOT build PVP metadata configuration."); - - } - } - - @Override - public String getIDPSLOPostBindingURL() { - return null; - - } - - @Override - public String getIDPSLORedirectBindingURL() { - return null; - - } - - @Override - public String getSPAssertionConsumerServicePostBindingURL() { - return null; - - } - - @Override - public String getSPAssertionConsumerServiceRedirectBindingURL() { - return null; - - } - - @Override - public String getSPSLOPostBindingURL() { - return null; - - } - - @Override - public String getSPSLORedirectBindingURL() { - return null; - - } - - @Override - public String getSPSLOSOAPBindingURL() { - return null; - - } - - @Override - public List getIDPPossibleAttributes() { - return PVPAttributeBuilder.buildSupportedEmptyAttributes(); - - } - - @Override - public List getIDPPossibleNameITTypes() { - return Arrays.asList(NameIDType.PERSISTENT, - NameIDType.TRANSIENT, - NameIDType.UNSPECIFIED); - } - - @Override - public List getSPRequiredAttributes() { - return null; - - } - - @Override - public List getSPAllowedNameITTypes() { - return null; - - } - - @Override - public boolean wantAssertionSigned() { - return false; - - } - - @Override - public boolean wantAuthnRequestSigned() { - return true; - - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/controller/PVP2SProfileEndpoint.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/controller/PVP2SProfileEndpoint.java deleted file mode 100644 index 62092675..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/controller/PVP2SProfileEndpoint.java +++ /dev/null @@ -1,59 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.controller; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.modules.pvp2.idp.impl.AbstractPVP2XProtocol; -import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -@Controller -public class PVP2SProfileEndpoint extends AbstractPVP2XProtocol{ - - public static final String NAME = PVP2SProfileEndpoint.class.getName(); - public static final String PROTOCOL_ID = "pvp2-s"; - - @RequestMapping(value = MSeIDASNodeConstants.ENDPOINT_PVP_METADATA, method = {RequestMethod.POST, RequestMethod.GET}) - public void PVPMetadataRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { - super.pvpMetadataRequest(req, resp); - - } - - @RequestMapping(value = MSeIDASNodeConstants.ENDPOINT_PVP_POST, method = {RequestMethod.POST}) - public void PVPIDPPostRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { - super.PVPIDPPostRequest(req, resp); - - } - - @RequestMapping(value = MSeIDASNodeConstants.ENDPOINT_PVP_REDIRECT, method = {RequestMethod.GET}) - public void PVPIDPRedirecttRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { - super.PVPIDPRedirecttRequest(req, resp); - - } - - - @Override - public String getAuthProtocolIdentifier() { - return PROTOCOL_ID; - } - - @Override - public String getName() { - return NAME; - } - - @Override - protected boolean childPreProcess(HttpServletRequest arg0, HttpServletResponse arg1, PVPSProfilePendingRequest arg2) - throws Throwable { - return false; - } - - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/controller/ProcessEngineSignalController.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/controller/ProcessEngineSignalController.java deleted file mode 100644 index 070e8c1c..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/controller/ProcessEngineSignalController.java +++ /dev/null @@ -1,29 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.controller; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import at.gv.egiz.eaaf.core.impl.idp.controller.AbstractProcessEngineSignalController; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -/** - * @author tlenz - * - */ -@Controller -public class ProcessEngineSignalController extends AbstractProcessEngineSignalController { - - @RequestMapping(value = {MSeIDASNodeConstants.ENDPOINT_COUNTRYSELECTION - }, - method = {RequestMethod.POST, RequestMethod.GET}) - public void performGenericAuthenticationProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException { - signalProcessManagement(req, resp); - - } -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/logger/RevisionLogger.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/logger/RevisionLogger.java deleted file mode 100644 index 4b8d7669..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/logger/RevisionLogger.java +++ /dev/null @@ -1,69 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.logger; - -import java.util.Date; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.components.eventlog.api.Event; -import at.gv.egiz.components.eventlog.api.EventLogFactory; -import at.gv.egiz.components.eventlog.api.EventLoggingException; -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; - -public class RevisionLogger extends EventLogFactory implements IRevisionLogger { - private static final Logger log = LoggerFactory.getLogger(RevisionLogger.class); - - @Override - public void logEvent(ISPConfiguration oaConfig, int eventCode, String message) { - logEvent(createNewEvent(new Date().getTime(), eventCode, message)); - - } - - @Override - public void logEvent(IRequest pendingRequest, int eventCode) { - logEvent(createNewEvent(new Date().getTime(), eventCode, - pendingRequest.getUniqueSessionIdentifier(), pendingRequest.getUniqueTransactionIdentifier())); - - } - - @Override - public void logEvent(IRequest pendingRequest, int eventCode, String message) { - logEvent(createNewEvent(new Date().getTime(), eventCode, message, - pendingRequest.getUniqueSessionIdentifier(), pendingRequest.getUniqueTransactionIdentifier())); - - } - - @Override - public void logEvent(int eventCode, String message) { - logEvent(createNewEvent(new Date().getTime(), eventCode, message)); - - } - - @Override - public void logEvent(String sessionID, String transactionID, int eventCode, String message) { - logEvent(createNewEvent(new Date().getTime(), eventCode, message, sessionID, transactionID)); - - } - - @Override - public void logEvent(String sessionID, String transactionID, int eventCode) { - logEvent(createNewEvent(new Date().getTime(), eventCode, sessionID, transactionID)); - - } - - private void logEvent(Event event) { - try { - if (event.getEventCode() >= 1100) - getEventLog().logEvent(event); - else - log.trace("Ignore Event: " + event.getEventCode() + " because session functionallity is not implemented"); - - } catch (EventLoggingException e) { - log.warn("Event logging FAILED! Reason: " + e.getMessage()); - - } - - } -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/logger/StatisticLogger.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/logger/StatisticLogger.java deleted file mode 100644 index ac4bca73..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/logger/StatisticLogger.java +++ /dev/null @@ -1,116 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.logger; - -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.idp.IAuthData; -import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -public class StatisticLogger implements IStatisticLogger { - - private static final Logger log = LoggerFactory.getLogger(StatisticLogger.class); - - private static final String DATEFORMATER = "yyyy.MM.dd-HH:mm:ss+z"; - private static final String STATUS_SUCCESS = "success"; - private static final String STATUS_ERROR = "error"; - - @Override - public void logSuccessOperation(IRequest protocolRequest, IAuthData authData, boolean isSSOSession) { - log.info(buildLogMessage( - protocolRequest.getUniqueTransactionIdentifier(), - protocolRequest.getSPEntityId(), - protocolRequest.getRawData(MSeIDASNodeConstants.DATA_REQUESTERID), - protocolRequest.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), - authData.getCiticenCountryCode(), - STATUS_SUCCESS , - StringUtils.EMPTY, - StringUtils.EMPTY)); - - - } - - @Override - public void logErrorOperation(Throwable throwable) { - String errorId = "TODO"; - if (throwable instanceof EAAFException) - errorId = ((EAAFException) throwable).getErrorId(); - - log.info(buildLogMessage( - StringUtils.EMPTY, - StringUtils.EMPTY, - StringUtils.EMPTY, - StringUtils.EMPTY, - StringUtils.EMPTY, - STATUS_ERROR, - errorId, - throwable.getMessage())); - - - } - - @Override - public void logErrorOperation(Throwable throwable, IRequest errorRequest) { - String errorId = "TODO"; - if (throwable instanceof EAAFException) - errorId = ((EAAFException) throwable).getErrorId(); - - if (errorRequest != null) - log.info(buildLogMessage( - errorRequest.getUniqueTransactionIdentifier(), - errorRequest.getSPEntityId(), - errorRequest.getRawData(MSeIDASNodeConstants.DATA_REQUESTERID), - errorRequest.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), - StringUtils.EMPTY, - STATUS_ERROR, - errorId, - throwable.getMessage())); - - else - log.info(buildLogMessage( - StringUtils.EMPTY, - StringUtils.EMPTY, - StringUtils.EMPTY, - StringUtils.EMPTY, - StringUtils.EMPTY, - STATUS_ERROR, - errorId, - throwable.getMessage())); - - } - - @Override - public void internalTesting() throws Exception { - log.trace("Not implemented for a File-based logger"); - - } - - private String buildLogMessage(String tId, String moaIDEntityId, Object requesterId, String target, String cc, - String status, String errorCode, String errorMsg) { - String logMsg = StringUtils.EMPTY; - - //data,tId,MOAID-Id,SP-Id,bPKTarget,CC,status,error-code,error-msg - - logMsg += DateTime.now().toString(DATEFORMATER ) + ","; - logMsg += tId + ","; - logMsg += moaIDEntityId + ","; - - if (requesterId instanceof String && StringUtils.isNotEmpty((String)requesterId)) - logMsg += (String)requesterId + ","; - else - logMsg += StringUtils.EMPTY + ","; - - logMsg += target + ","; - logMsg += cc + ","; - - logMsg += status + ","; - logMsg += errorCode + ","; - logMsg += errorMsg; - - return logMsg; - } -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/mapper/LoALevelMapper.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/mapper/LoALevelMapper.java deleted file mode 100644 index 80cb6e20..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/mapper/LoALevelMapper.java +++ /dev/null @@ -1,34 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.mapper; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.data.ILoALevelMapper; - -@Service("LoALevelMapper") -public class LoALevelMapper implements ILoALevelMapper{ - private static final Logger log = LoggerFactory.getLogger(LoALevelMapper.class); - - @Override - public String mapToSecClass(String LoA) { - log.info("Mapping to PVP SecClass is NOT supported"); - return null; - } - - @Override - public String mapToeIDASLoA(String LoA) { - if (LoA.startsWith(EAAFConstants.EIDAS_LOA_PREFIX)) - return LoA; - - else - log.info("Can NOT map '" + LoA + "' to eIDAS LoA"); - - return null; - - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/CountrySelectionProcessImpl.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/CountrySelectionProcessImpl.java deleted file mode 100644 index ac99f29d..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/CountrySelectionProcessImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.processes; - -import org.apache.commons.lang3.StringUtils; - -import at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -/** - * @author tlenz - * - */ -public class CountrySelectionProcessImpl implements AuthModule { - - @Override - public int getPriority() { - return 0; - - } - - @Override - public String selectProcess(ExecutionContext context) { - Object selectedCountryObj = context.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_COUNTRY); - if (selectedCountryObj != null && selectedCountryObj instanceof String) { - String selectedCountry = (String) selectedCountryObj; - if (StringUtils.isNotEmpty(selectedCountry)) - return null; - - } - - return "CountrySelectionProcess"; - - - } - - @Override - public String[] getProcessDefinitions() { - return new String[] { "classpath:processes/CountrySelection.process.xml" }; - - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/tasks/EvaluateCountrySelectionTask.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/tasks/EvaluateCountrySelectionTask.java deleted file mode 100644 index 4ae97acf..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/tasks/EvaluateCountrySelectionTask.java +++ /dev/null @@ -1,67 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.processes.tasks; - -import java.util.Enumeration; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; -import at.gv.egiz.eidas.specific.connector.MSConnectorEventCodes; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -/** - * @author tlenz - * - */ -@Component("EvaluateCountrySelectionTask") -public class EvaluateCountrySelectionTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(EvaluateCountrySelectionTask.class); - - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - try { - - String stopAuthFlag = request.getParameter(MSeIDASNodeConstants.REQ_PARAM_STOP_PROCESS); - if (StringUtils.isNotEmpty(stopAuthFlag) && Boolean.parseBoolean(stopAuthFlag)) { - log.info("Authentication process WAS stopped by entity. Stopping auth. process ... "); - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.PROCESS_STOPPED_BY_USER); - pendingReq.setAbortedByUser(true); - pendingReq.setAuthenticated(false); - - } else { - // set parameter execution context - Enumeration reqParamNames = request.getParameterNames(); - while(reqParamNames.hasMoreElements()) { - String paramName = reqParamNames.nextElement(); - if (StringUtils.isNotEmpty(paramName) && - !EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID.equalsIgnoreCase(paramName)) { - for (String el : MSeIDASNodeConstants.COUNTRY_SELECTION_PARAM_WHITELIST) { - if (el.equalsIgnoreCase(paramName)) - executionContext.put(paramName, - StringEscapeUtils.escapeHtml(request.getParameter(paramName))); - } - } - } - log.info("Country selection finished. Starting auth. process for country ... "); - - } - - } catch (Exception e) { - log.warn("EvaluateBKUSelectionTask has an internal error", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/tasks/GenerateCountrySelectionFrameTask.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/tasks/GenerateCountrySelectionFrameTask.java deleted file mode 100644 index 9218a9b5..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/processes/tasks/GenerateCountrySelectionFrameTask.java +++ /dev/null @@ -1,62 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.processes.tasks; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; -import at.gv.egiz.eidas.specific.connector.MSConnectorEventCodes; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; -import at.gv.egiz.eidas.specific.connector.gui.StaticGuiBuilderConfiguration; - -/** - * @author tlenz - * - */ -@Component("GenerateCountrySelectionFrameTask") -public class GenerateCountrySelectionFrameTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(GenerateCountrySelectionFrameTask.class); - - @Autowired IGUIFormBuilder guiBuilder; - @Autowired IConfiguration basicConfig; - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - try { - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.STARTING_COUNTRY_SELECTION); - - IGUIBuilderConfiguration config = new StaticGuiBuilderConfiguration( - basicConfig, - pendingReq, - MSeIDASNodeConstants.TEMPLATE_HTML_COUNTRYSELECTION, - MSeIDASNodeConstants.ENDPOINT_COUNTRYSELECTION); - - guiBuilder.build(response, config, "BKU-Selection form"); - - } catch (GUIBuildException e) { - log.warn("Can not build GUI:'BKU-Selection'. Msg:" + e.getMessage()); - throw new TaskExecutionException(pendingReq, - "Can not build GUI. Msg:" + e.getMessage(), - new EAAFException("gui.00", new Object[]{e.getMessage()}, e)); - - } catch (Exception e) { - log.warn("FinalizeAuthenticationTask has an internal error", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } - - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPEndPointCredentialProvider.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPEndPointCredentialProvider.java deleted file mode 100644 index f515ee5a..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPEndPointCredentialProvider.java +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.provider; - -import java.net.MalformedURLException; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.impl.utils.FileUtils; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -public class PVPEndPointCredentialProvider extends AbstractCredentialProvider { - private static final Logger log = LoggerFactory.getLogger(PVPEndPointCredentialProvider.class); - - @Autowired(required=true) IConfiguration basicConfiguration; - - @Override - public String getFriendlyName() { - return "PVP2 S-Profile EndPoint"; - } - - @Override - public String getKeyStoreFilePath() throws EAAFException { - try { - String path = basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEYSTORE_PATH); - if (StringUtils.isEmpty(path)) { - log.error(getFriendlyName() + " | Path to keyStore is NULL or EMPTY"); - throw new EAAFConfigurationException("config.27", - new Object[] {getFriendlyName() + " | Path to keyStore is NULL or EMPTY"}); - - } - - return FileUtils.makeAbsoluteURL( - path, - basicConfiguration.getConfigurationRootDirectory()); - - } catch (MalformedURLException e) { - log.error(getFriendlyName() + " | Path to keyStore NOT valid.", e); - throw new EAAFConfigurationException("config.27", - new Object[] {getFriendlyName() + " | Path to keyStore NOT valid."}, e); - - } - - } - - @Override - public String getKeyStorePassword() { - return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEYSTORE_PASSWORD); - - } - - @Override - public String getMetadataKeyAlias() { - return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEY_METADATA_ALIAS); - } - - @Override - public String getMetadataKeyPassword() { - return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEY_METADATA_PASSWORD); - - } - - @Override - public String getSignatureKeyAlias() { - return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEY_SIGNING_ALIAS); - - } - - @Override - public String getSignatureKeyPassword() { - return basicConfiguration.getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_PVP2_KEY_SIGNING_PASSWORD); - - } - - @Override - public String getEncryptionKeyAlias() { - return null; - - } - - @Override - public String getEncryptionKeyPassword() { - return null; - - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPMetadataConfigurationFactory.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPMetadataConfigurationFactory.java deleted file mode 100644 index c5d2f29c..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPMetadataConfigurationFactory.java +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.provider; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataBuilderConfiguration; -import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataConfigurationFactory; -import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; -import at.gv.egiz.eidas.specific.connector.config.PVPMetadataConfiguration; - -@Service("PVPMetadataConfigurationFactory") -public class PVPMetadataConfigurationFactory implements IPVPMetadataConfigurationFactory { - - @Autowired private IConfiguration basicConfig; - @Autowired private IPVP2BasicConfiguration pvpBasicConfig; - - @Override - public IPVPMetadataBuilderConfiguration generateMetadataBuilderConfiguration(String authURL, - AbstractCredentialProvider pvpIDPCredentials) { - return new PVPMetadataConfiguration(basicConfig, authURL, pvpBasicConfig, pvpIDPCredentials); - - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPMetadataProvider.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPMetadataProvider.java deleted file mode 100644 index 41a44dba..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/PVPMetadataProvider.java +++ /dev/null @@ -1,124 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.provider; - -import java.io.IOException; -import java.security.cert.CertificateException; -import java.util.List; - -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.params.HttpClientParams; -import org.apache.commons.lang3.StringUtils; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.xml.parse.BasicParserPool; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.impl.utils.FileUtils; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2MetadataException; -import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.AbstractChainingMetadataProvider; -import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.MetadataFilterChain; -import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.PVPEntityCategoryFilter; -import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.SchemaValidationFilter; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; -import at.gv.egiz.eidas.specific.connector.verification.MetadataSignatureVerificationFilter; - -@Service("PVPMetadataProvider") -public class PVPMetadataProvider extends AbstractChainingMetadataProvider{ - private static final Logger log = LoggerFactory.getLogger(PVPMetadataProvider.class); - - @Autowired(required=true) IConfiguration basicConfig; - - @Override - protected String getMetadataURL(String entityId) throws EAAFConfigurationException { - ISPConfiguration spConfig = basicConfig.getServiceProviderConfiguration(entityId); - if (spConfig != null) { - String metadataURL = entityId; - - String metadataURLFromConfig = spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_PVP2_METADATA_URL); - if (StringUtils.isNotEmpty(metadataURLFromConfig)) { - log.debug("Use metdataURL from configuration for EntityId: " + entityId); - metadataURL = metadataURLFromConfig; - - } - - return metadataURL; - - } else - log.info("No ServiceProvider with entityId: " + entityId + " in configuration."); - - return null; - } - - @Override - protected MetadataProvider createNewMetadataProvider(String entityId) - throws EAAFConfigurationException, IOException, CertificateException { - ISPConfiguration spConfig = basicConfig.getServiceProviderConfiguration(entityId); - if (spConfig != null) { - try { - String metadataURL = spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_PVP2_METADATA_URL); - if (StringUtils.isEmpty(metadataURL)) { - log.debug("Use EntityId: " + entityId + " instead of explicite metadataURL ... "); - metadataURL = entityId; - - } - String trustStoreUrl = FileUtils.makeAbsoluteURL( - spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE), - authConfig.getConfigurationRootDirectory()); - String trustStorePassword = spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE_PASSWORD); - - return createNewSimpleMetadataProvider(metadataURL, - buildMetadataFilterChain(spConfig, metadataURL, trustStoreUrl, trustStorePassword), - spConfig.getConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_UNIQUEIDENTIFIER), - getTimer(), - new BasicParserPool(), - createHttpClient(metadataURL)); - - } catch (PVP2MetadataException e) { - log.info("Can NOT initialize Metadata signature-verification filter. Reason: " + e.getMessage()); - throw new EAAFConfigurationException("config.27", - new Object[] {"Can NOT initialize Metadata signature-verification filter. Reason: " + e.getMessage()}, e); - - } - - } else - log.info("No ServiceProvider with entityId: " + entityId + " in configuration."); - - return null; - } - - @Override - protected List getAllMetadataURLsFromConfiguration() throws EAAFConfigurationException { - // TODO Auto-generated method stub - return null; - } - - private HttpClient createHttpClient(String metadataURL) { - HttpClient httpClient = new HttpClient(); - HttpClientParams httpClientParams = new HttpClientParams(); - httpClientParams.setSoTimeout(MSeIDASNodeConstants.METADATA_SOCKED_TIMEOUT); - httpClient.setParams(httpClientParams); - return httpClient; - - } - - private MetadataFilterChain buildMetadataFilterChain(ISPConfiguration oaParam, String metadataURL, String trustStoreUrl, String trustStorePassword) throws CertificateException, PVP2MetadataException{ - MetadataFilterChain filterChain = new MetadataFilterChain(); - filterChain.getFilters().add(new SchemaValidationFilter( - basicConfig.getBasicMOAIDConfigurationBoolean(MSeIDASNodeConstants.PROP_CONFIG_PVP_SCHEME_VALIDATION, true))); - - filterChain.getFilters().add( - new MetadataSignatureVerificationFilter( - trustStoreUrl, trustStorePassword, metadataURL)); - - filterChain.getFilters().add(new PVPEntityCategoryFilter( - basicConfig.getBasicMOAIDConfigurationBoolean(MSeIDASNodeConstants.PROP_CONFIG_PVP_ENABLE_ENTITYCATEGORIES, true))); - - return filterChain; - } -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/StatusMessageProvider.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/StatusMessageProvider.java deleted file mode 100644 index d1787e7d..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/provider/StatusMessageProvider.java +++ /dev/null @@ -1,104 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.provider; - -import java.text.MessageFormat; -import java.util.Locale; -import java.util.MissingResourceException; -import java.util.PropertyResourceBundle; -import java.util.ResourceBundle; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.IStatusMessenger; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; - -@Service("StatusMessageProvider") -public class StatusMessageProvider implements IStatusMessenger { - private static final Logger log = LoggerFactory.getLogger(StatusMessageProvider.class); - - private static final String ERROR_MESSAGES_UNAVAILABLE = "Error messages can NOT be load from application. Only errorCode: {0} is availabe" ; - private static final String ERROR_NO_MESSAGE = "No errormesseage for error with number.={0}"; - - private static final String ERROR_EXTERNALERROR_CODES_UNAVAILABLE = "External error-codes can NOT be load from application. Only internal errorCode: {0} is availabe" ; - private static final String ERROR_NO_EXTERNALERROR_CODE = "No external error for internal error with number.={0}"; - - //internal messanges - private static final String DEFAULT_MESSAGE_RESOURCES = "properties/status_messages_en"; - private static final Locale DEFAULT_MESSAGE_LOCALES = new Locale("en", "GB"); - private ResourceBundle messages; - - //external error codes - private static final String DEFAULT_EXTERNALERROR_RESOURCES = "properties/external_statuscodes_map"; - private static final Locale DEFAULT_EXTERNALERROR_LOCALES = new Locale("en", "GB"); - private ResourceBundle externalError = null; - - @Override - public String getMessage(String messageId, Object[] parameters) { - // initialize messages - if (messages == null) { - this.messages = PropertyResourceBundle.getBundle( - DEFAULT_MESSAGE_RESOURCES, - DEFAULT_MESSAGE_LOCALES); - - } - - // create the message - if (messages == null) { - return MessageFormat.format(ERROR_MESSAGES_UNAVAILABLE, new Object[] { messageId }); - - } else { - try { - String rawMessage = messages.getString(messageId); - return MessageFormat.format(rawMessage, parameters); - - } catch (MissingResourceException e2) { - return MessageFormat.format(ERROR_NO_MESSAGE, new Object[] { messageId }); - - } - } - } - - @Override - public String getResponseErrorCode(Throwable throwable) { - String errorCode = IStatusMessenger.CODES_EXTERNAL_ERROR_GENERIC; - if (throwable instanceof EAAFException) { - errorCode = ((EAAFException) throwable).getErrorId(); - - } - //TODO: maybe more internal switches are required - - return errorCode; - - } - - @Override - public String mapInternalErrorToExternalError(String intErrorCode) { - // initialize messages - if (externalError == null) { - this.externalError = PropertyResourceBundle.getBundle( - DEFAULT_EXTERNALERROR_RESOURCES, - DEFAULT_EXTERNALERROR_LOCALES); - - } - - // create the message - if (externalError == null) { - log.warn(MessageFormat.format(ERROR_EXTERNALERROR_CODES_UNAVAILABLE, new Object[] { intErrorCode })); - return IStatusMessenger.CODES_EXTERNAL_ERROR_GENERIC; - - } else { - try { - return externalError.getString(intErrorCode); - - } catch (MissingResourceException e2) { - log.info(MessageFormat.format(ERROR_NO_EXTERNALERROR_CODE, new Object[] { intErrorCode })); - return IStatusMessenger.CODES_EXTERNAL_ERROR_GENERIC; - - } - } - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/CacheWitheIDASBackend.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/CacheWitheIDASBackend.java deleted file mode 100644 index 7a62eca4..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/CacheWitheIDASBackend.java +++ /dev/null @@ -1,33 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.storage; - -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import eu.eidas.auth.commons.cache.ConcurrentMapService; -import eu.eidas.auth.commons.tx.AbstractCorrelationMap; - -public class CacheWitheIDASBackend extends AbstractCorrelationMap { - - protected CacheWitheIDASBackend(ConcurrentMapService concurrentMapService) { - super(concurrentMapService); - } - - public List clean(Date now, long dataTimeOut) { - List result = new ArrayList(); - Iterator iterator = map.keySet().iterator(); - while (iterator.hasNext()) { - String key = iterator.next(); - if (map.containsKey(key)) { - TransactionStoreElement element = map.get(key); - if (now.getTime() - element.getCreated().getTime() > dataTimeOut) - result.add(key); - } - } - - return result; - - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/SimpleInMemoryTransactionStorage.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/SimpleInMemoryTransactionStorage.java deleted file mode 100644 index 57697ef8..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/SimpleInMemoryTransactionStorage.java +++ /dev/null @@ -1,141 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.storage; - -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; - -@Service("SimpleInMemoryTransactionStorage") -public class SimpleInMemoryTransactionStorage implements ITransactionStorage{ - private static final Logger log = LoggerFactory.getLogger(SimpleInMemoryTransactionStorage.class); - - private Map storage = new ConcurrentHashMap(); - - @Override - public void changeKey(String oldKey, String newKey, Object value) throws EAAFException { - if (containsKey(oldKey)) { - TransactionStoreElement el = storage.get(oldKey); - el.setKey(newKey); - storage.put(newKey, el); - storage.remove(oldKey); - - } else - throw new EAAFStorageException("No element in TransactionStorage with key: " + oldKey); - - } - - @Override - public List clean(Date now, long dataTimeOut) { - List result = new ArrayList(); - Iterator iterator = storage.keySet().iterator(); - while (iterator.hasNext()) { - String key = iterator.next(); - synchronized (storage) { - if (storage.containsKey(key)) { - TransactionStoreElement element = storage.get(key); - if (now.getTime() - element.getCreated().getTime() > dataTimeOut) - result.add(key); - } - } - } - - return result; - - } - - @Override - public boolean containsKey(String key) { - if (key != null) - return storage.containsKey(key); - else - return false; - - } - - @Override - public Object get(String key) throws EAAFException { - if (key != null && containsKey(key)) { - TransactionStoreElement element = storage.get(key); - return element.getData(); - - } else - return null; - } - - @Override - public T get(String key, Class type) throws EAAFException { - return get(key, type, -1); - - } - - @Override - public T get(String key, Class type, long dataTimeOut) throws EAAFException { - if (key != null && containsKey(key)) { - TransactionStoreElement value = storage.get(key); - - if (dataTimeOut > -1) { - long now = new Date().getTime(); - if (now - value.getCreated().getTime() > dataTimeOut) { - log.info("Transaction-Data with key: " + key + " is out of time."); - throw new EAAFStorageException("Transaction-Data with key: " + key + " is out of time."); - - } - } - - if (type.isAssignableFrom(value.getData().getClass())) { - return (T) value.getData(); - - } else - log.warn("Can NOT cast '" + value.getClass() + "' to '" + type + "'"); - - } - - return null; - } - - @Override - public Object getRaw(String key) throws EAAFException { - return storage.get(key); - - } - - @Override - public void put(String key, Object value, int dataTimeOut) throws EAAFException { - TransactionStoreElement element = new TransactionStoreElement(); - element.setKey(key); - element.setData(value); - storage.put(key, element); - - } - - @Override - public void putRaw(String key, Object value) throws EAAFException { - if (value instanceof TransactionStoreElement) - storage.put(((TransactionStoreElement) value).getKey(), (TransactionStoreElement) value); - else - log.info(value.getClass().getName() + " is NOT a RAW element of " + ITransactionStorage.class.getName()); - - } - - @Override - public void remove(String key) { - if (containsKey(key)) { - log.debug("Remove element with key: " + key + " from " + ITransactionStorage.class.getName()); - storage.remove(key); - - } - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/TransactionStoreElement.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/TransactionStoreElement.java deleted file mode 100644 index 25180292..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/TransactionStoreElement.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.storage; - -import java.io.Serializable; -import java.util.Date; - -public class TransactionStoreElement implements Serializable{ - - private static final long serialVersionUID = 1L; - private String key = null; - private Object data = null; - private Date created; - - public String getKey() { - return key; - } - public void setKey(String key) { - this.key = key; - } - public Object getData() { - return data; - } - public void setData(Object data) { - this.data = data; - } - public Date getCreated() { - return created; - } - public void setCreated(Date created) { - this.created = created; - } - - - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/eIDASCacheTransactionStoreDecorator.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/eIDASCacheTransactionStoreDecorator.java deleted file mode 100644 index 6bc23073..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/storage/eIDASCacheTransactionStoreDecorator.java +++ /dev/null @@ -1,124 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.storage; - -import java.util.Date; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; - -public class eIDASCacheTransactionStoreDecorator implements ITransactionStorage{ - private static final Logger log = LoggerFactory.getLogger(eIDASCacheTransactionStoreDecorator.class); - - @Autowired(required=true) private CacheWitheIDASBackend storage; - - @Override - public void changeKey(String oldKey, String newKey, Object value) throws EAAFException { - if (containsKey(oldKey)) { - TransactionStoreElement el = storage.get(oldKey); - el.setKey(newKey); - storage.put(newKey, el); - storage.remove(oldKey); - - } else - throw new EAAFStorageException("No element in TransactionStorage with key: " + oldKey); - - } - - @Override - public List clean(Date now, long dataTimeOut) { - return storage.clean(now, dataTimeOut); - - } - - @Override - public boolean containsKey(String key) { - if (key != null) { - if (storage.get(key) != null) - return true; - - } - - return false; - - } - - @Override - public Object get(String key) throws EAAFException { - if (key != null && containsKey(key)) { - TransactionStoreElement element = storage.get(key); - return element.getData(); - - } else - return null; - } - - @Override - public T get(String key, Class type) throws EAAFException { - return get(key, type, -1); - - } - - @Override - public T get(String key, Class type, long dataTimeOut) throws EAAFException { - if (key != null && containsKey(key)) { - TransactionStoreElement value = storage.get(key); - - if (dataTimeOut > -1) { - long now = new Date().getTime(); - if (now - value.getCreated().getTime() > dataTimeOut) { - log.info("Transaction-Data with key: " + key + " is out of time."); - throw new EAAFStorageException("Transaction-Data with key: " + key + " is out of time."); - - } - } - - if (type.isAssignableFrom(value.getData().getClass())) { - return (T) value.getData(); - - } else - log.warn("Can NOT cast '" + value.getClass() + "' to '" + type + "'"); - - } - - return null; - } - - @Override - public Object getRaw(String key) throws EAAFException { - return storage.get(key); - - } - - @Override - public void put(String key, Object value, int dataTimeOut) throws EAAFException { - TransactionStoreElement element = new TransactionStoreElement(); - element.setKey(key); - element.setData(value); - storage.put(key, element); - - } - - @Override - public void putRaw(String key, Object value) throws EAAFException { - if (value instanceof TransactionStoreElement) - storage.put(((TransactionStoreElement) value).getKey(), (TransactionStoreElement) value); - else - log.info(value.getClass().getName() + " is NOT a RAW element of " + ITransactionStorage.class.getName()); - - } - - @Override - public void remove(String key) { - if (containsKey(key)) { - log.debug("Remove element with key: " + key + " from " + ITransactionStorage.class.getName()); - storage.remove(key); - - } - } - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/verification/AuthnRequestValidator.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/verification/AuthnRequestValidator.java deleted file mode 100644 index 0217eec4..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/verification/AuthnRequestValidator.java +++ /dev/null @@ -1,203 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.verification; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.StringUtils; -import org.opensaml.saml2.core.AuthnContextClassRef; -import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.NameIDPolicy; -import org.opensaml.saml2.core.RequestedAuthnContext; -import org.opensaml.saml2.core.Scoping; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.xml.XMLObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; -import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttribute; -import at.gv.egiz.eaaf.modules.pvp2.api.reqattr.EAAFRequestedAttributes; -import at.gv.egiz.eaaf.modules.pvp2.api.validation.IAuthnRequestValidator; -import at.gv.egiz.eaaf.modules.pvp2.exception.NameIDFormatNotSupportedException; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; -import at.gv.egiz.eidas.specific.connector.config.ServiceProviderConfiguration; - -public class AuthnRequestValidator implements IAuthnRequestValidator { - - private static final Logger log = LoggerFactory.getLogger(AuthnRequestValidator.class); - - @Override - public void validate(HttpServletRequest httpReq, IRequest pendingReq, AuthnRequest authnReq, - SPSSODescriptor spSSODescriptor) throws AuthnRequestValidatorException { - try { - //validate NameIDPolicy - NameIDPolicy nameIDPolicy = authnReq.getNameIDPolicy(); - if (nameIDPolicy != null) { - String nameIDFormat = nameIDPolicy.getFormat(); - if (nameIDFormat != null) { - if ( !(NameID.TRANSIENT.equals(nameIDFormat) || - NameID.PERSISTENT.equals(nameIDFormat)) ) { - - throw new NameIDFormatNotSupportedException(nameIDFormat); - - } - - } else - log.trace("Find NameIDPolicy, but NameIDFormat is 'null'"); - } else - log.trace("AuthnRequest includes no 'NameIDPolicy'"); - - - //post-process RequesterId - String spEntityId = extractScopeRequsterId(authnReq); - if (StringUtils.isEmpty(spEntityId)) { - log.info("NO service-provider entityID in Authn. request. Stop authn. process ... "); - throw new AuthnRequestValidatorException("pvp2.22", - new Object[] {"NO relaying-party entityID in Authn. request"}, pendingReq); - - } else - pendingReq.setRawDataToTransaction(MSeIDASNodeConstants.DATA_REQUESTERID, spEntityId); - - - //post-process ProviderName - String providerName = authnReq.getProviderName(); - if (StringUtils.isEmpty(providerName)) - log.info("Authn. request contains NO SP friendlyName"); - else - pendingReq.setRawDataToTransaction(MSeIDASNodeConstants.DATA_PROVIDERNAME, spEntityId); - - //post-process requested LoA - List reqLoA = extractLoA(authnReq); - pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class).setRequiredLoA(reqLoA); - - //post-process requested LoA comparison-level - String reqLoAComperison = extractComparisonLevel(authnReq); - pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class).setLoAMachtingMode(reqLoAComperison); - - //validate and process requested attributes - boolean sectorDetected = false; - List requestedAttributes = authnReq.getExtensions().getUnknownXMLObjects(); - for (XMLObject reqAttrObj : requestedAttributes) { - if (reqAttrObj instanceof EAAFRequestedAttributes) { - EAAFRequestedAttributes reqAttr = (EAAFRequestedAttributes)reqAttrObj; - if (reqAttr.getAttributes() != null && reqAttr.getAttributes().size() != 0 ) { - for (EAAFRequestedAttribute el : reqAttr.getAttributes()) { - log.trace("Processing req. attribute '" + el.getName() + "' ... "); - if (el.getName().equals(PVPAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME)) { - if (el.getAttributeValues() != null && el.getAttributeValues().size() == 1) { - String sectorId = el.getAttributeValues().get(0).getDOM().getTextContent(); - ServiceProviderConfiguration spConfig = pendingReq.getServiceProviderConfiguration(ServiceProviderConfiguration.class); - - try { - spConfig.setbPKTargetIdentifier(sectorId); - sectorDetected = true; - - } catch (EAAFException e) { - log.info("Requested sector: " + sectorId + " DOES NOT match to allowed sectors for SP: " + spConfig.getUniqueIdentifier()); - } - - } else - log.info("Req. attribute '" + el.getName() + "' contains NO or MORE THEN ONE attribute-values. Ignore full req. attribute"); - - } else - log.debug("Ignore req. attribute: " + el.getName()); - - } - - } else - log.debug("No requested Attributes in Authn. Request"); - - } else - log.info("Ignore unknown requested attribute: " + reqAttrObj.getElementQName().toString()); - - } - - if (!sectorDetected) { - log.info("Authn.Req validation FAILED. Reason: Contains NO or NO VALID target-sector information."); - throw new AuthnRequestValidatorException("pvp2.22", new Object[] {"NO or NO VALID target-sector information"}); - - } - - } catch (EAAFStorageException e) { - log.info("Can NOT store Authn. Req. data into pendingRequest." , e); - throw new AuthnRequestValidatorException("internal.02", null, e); - - } - - } - - private String extractComparisonLevel(AuthnRequest authnReq) { - if (authnReq.getRequestedAuthnContext() != null) { - RequestedAuthnContext authContext = authnReq.getRequestedAuthnContext(); - return authContext.getComparison().toString(); - - } - - return null; - } - - private List extractLoA(AuthnRequest authnReq) throws AuthnRequestValidatorException { - List result = new ArrayList(); - if (authnReq.getRequestedAuthnContext() != null) { - RequestedAuthnContext authContext = authnReq.getRequestedAuthnContext(); - if (authContext.getComparison().equals(AuthnContextComparisonTypeEnumeration.MINIMUM)) { - if (authContext.getAuthnContextClassRefs().isEmpty()) { - log.debug("Authn. Req. contains no requested LoA"); - - } else if (authContext.getAuthnContextClassRefs().size() > 1) { - log.info("Authn. Req. contains MORE THAN ONE requested LoA, but " - + AuthnContextComparisonTypeEnumeration.MINIMUM + " allows only one" ); - throw new AuthnRequestValidatorException("pvp2.22", - new Object[] {"Authn. Req. contains MORE THAN ONE requested LoA, but " - + AuthnContextComparisonTypeEnumeration.MINIMUM + " allows only one"}); - - } else - result.add(authContext.getAuthnContextClassRefs().get(0).getAuthnContextClassRef()); - - } else if (authContext.getComparison().equals(AuthnContextComparisonTypeEnumeration.EXACT)) { - for (AuthnContextClassRef el : authContext.getAuthnContextClassRefs()) - result.add(el.getAuthnContextClassRef()); - - } else { - log.info("Currently only '" + AuthnContextComparisonTypeEnumeration.MINIMUM + "' and '" - + AuthnContextComparisonTypeEnumeration.EXACT + "' are supported"); - throw new AuthnRequestValidatorException("pvp2.22", - new Object[] {"Currently only '" + AuthnContextComparisonTypeEnumeration.MINIMUM + "' and '" - + AuthnContextComparisonTypeEnumeration.EXACT + "' are supported"}); - - } - - } - - return result; - } - - private String extractScopeRequsterId(AuthnRequest authnReq) { - if (authnReq.getScoping() != null) { - Scoping scoping = authnReq.getScoping(); - if (scoping.getRequesterIDs() != null && - scoping.getRequesterIDs().size() > 0) { - if (scoping.getRequesterIDs().size() == 1) - return scoping.getRequesterIDs().get(0).getRequesterID(); - - else { - log.info("Authn. request contains more than on RequesterIDs! Only use first one"); - return scoping.getRequesterIDs().get(0).getRequesterID(); - - } - } - } - - return null; - } - - -} diff --git a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/verification/MetadataSignatureVerificationFilter.java b/connector/src/main/java/at/gv/egiz/eidas/specific/connector/verification/MetadataSignatureVerificationFilter.java deleted file mode 100644 index 20d419af..00000000 --- a/connector/src/main/java/at/gv/egiz/eidas/specific/connector/verification/MetadataSignatureVerificationFilter.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.verification; - -import java.io.IOException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.cert.Certificate; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; - -import org.opensaml.common.SignableSAMLObject; -import org.opensaml.saml2.metadata.EntitiesDescriptor; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.xml.security.x509.BasicX509Credential; -import org.opensaml.xml.signature.SignatureValidator; -import org.opensaml.xml.validation.ValidationException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; -import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2MetadataException; -import at.gv.egiz.eaaf.modules.pvp2.idp.exception.SAMLRequestNotSignedException; -import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.AbstractMetadataSignatureFilter; - -public class MetadataSignatureVerificationFilter extends AbstractMetadataSignatureFilter{ - private static final Logger log = LoggerFactory.getLogger(MetadataSignatureVerificationFilter.class); - - private String metadataURL; - private List trustedCredential = new ArrayList(); - - public MetadataSignatureVerificationFilter(String trustStorePath, String trustStorePassword, String metadataURL) - throws PVP2MetadataException { - this.metadataURL = metadataURL; - - log.trace("Initialize metadata signature-verification filter with truststore: " + trustStorePath + " ... "); - try { - KeyStore keyStore = KeyStoreUtils.loadKeyStore(trustStorePath, trustStorePassword); - if (keyStore != null) { - //load trusted certificates - Enumeration aliases = keyStore.aliases(); - while(aliases.hasMoreElements()) { - String el = aliases.nextElement(); - log.trace("Process TrustStoreEntry: " + el); - if (keyStore.isCertificateEntry(el)) { - Certificate cert = keyStore.getCertificate(el); - if (cert != null && cert instanceof X509Certificate) { - BasicX509Credential trustedCert = new BasicX509Credential(); - trustedCert.setEntityCertificate((X509Certificate) cert); - this.trustedCredential.add(trustedCert); - log.debug("Add cert: " + ((X509Certificate) cert).getSubjectDN() + " as trusted for metadata: " + metadataURL); - - } else - log.info("Can not process entry: " + el + ". Reason: " + cert.toString()); - - } - } - - - } else - throw new PVP2MetadataException("pvp2.26", - new Object[] {"Can not open trustStore: " + trustStorePath + " for metadata: " + metadataURL}); - - } catch (KeyStoreException | IOException e) { - log.warn("Can not open trustStore: " + trustStorePath + " for metadata: " + metadataURL + " Reason: " + e.getMessage(), e); - throw new PVP2MetadataException("pvp2.26", - new Object[] {"Can not open trustStore: " + trustStorePath + " for metadata"}, e); - - } - - - } - - - @Override - protected void verify(EntityDescriptor desc) throws PVP2MetadataException { - try { - internalVerify(desc); - - } catch (EAAFException e) { - log.info("Metadata verification FAILED for: " + metadataURL + " Reason: " +e.getMessage()); - throw new PVP2MetadataException("pvp2.26", - new Object[] {"Metadata verification FAILED for: " + metadataURL + " Reason: " +e.getMessage()}, e); - - } - } - - @Override - protected void verify(EntitiesDescriptor desc) throws PVP2MetadataException { - throw new PVP2MetadataException("pvp2.26", - new Object[] {"EntitiesDescritors are NOT supported"}); - - } - - @Override - protected void verify(EntityDescriptor entity, EntitiesDescriptor desc) throws PVP2MetadataException { - throw new PVP2MetadataException("pvp2.26", - new Object[] {"EntitiesDescritors are NOT supported"}); - - } - - private void internalVerify(SignableSAMLObject signedElement) - throws EAAFException { - if (signedElement.getSignature() == null) { - throw new SAMLRequestNotSignedException(); - } - - try { - SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator(); - sigValidator.validate(signedElement.getSignature()); - } catch (ValidationException e) { - log.error("Failed to validate Signature", e); - throw new SAMLRequestNotSignedException(e); - } - - boolean isTrusted = false; - for (BasicX509Credential cred : trustedCredential) { - SignatureValidator sigValidator = new SignatureValidator(cred); - try { - sigValidator.validate(signedElement.getSignature()); - isTrusted = true; - - } catch (ValidationException e) { - log.info("Failed to verfiy Signature with cert: " + cred.getEntityCertificate().getSubjectDN() - + " Reason: " + e.getMessage()); - - } - } - - if (!isTrusted) { - log.warn("PVP2 metadata: " + metadataURL + " are NOT trusted!"); - throw new SAMLRequestNotSignedException(); - - } - - } - -} diff --git a/connector/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider b/connector/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider index fafe72f5..d68a187a 100644 --- a/connector/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider +++ b/connector/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider @@ -1 +1 @@ -at.gv.egiz.eidas.specific.connector.MSSpecificeIDASNodeSpringResourceProvider \ No newline at end of file +at.asitplus.eidas.specific.connector.MSSpecificeIDASNodeSpringResourceProvider \ No newline at end of file diff --git a/connector/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule b/connector/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule index 813eba42..146191c0 100644 --- a/connector/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule +++ b/connector/src/main/resources/META-INF/services/at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule @@ -1 +1 @@ -at.gv.egiz.eidas.specific.connector.processes.CountrySelectionProcessImpl \ No newline at end of file +at.asitplus.eidas.specific.connector.processes.CountrySelectionProcessImpl \ No newline at end of file diff --git a/connector/src/main/resources/applicationContext.xml b/connector/src/main/resources/applicationContext.xml index c44c903e..95c3db36 100644 --- a/connector/src/main/resources/applicationContext.xml +++ b/connector/src/main/resources/applicationContext.xml @@ -28,7 +28,7 @@ + class="at.asitplus.eidas.specific.connector.config.BasicConfigurationProvider"> diff --git a/connector/src/main/resources/specific_eIDAS_connector.beans.xml b/connector/src/main/resources/specific_eIDAS_connector.beans.xml index 275c79b8..7722b8e8 100644 --- a/connector/src/main/resources/specific_eIDAS_connector.beans.xml +++ b/connector/src/main/resources/specific_eIDAS_connector.beans.xml @@ -16,32 +16,32 @@ + class="at.asitplus.eidas.specific.connector.controller.ProcessEngineSignalController"/> + class="at.asitplus.eidas.specific.connector.auth.AuthenticationManager" /> + class="at.asitplus.eidas.specific.connector.builder.AuthenticationDataBuilder" /> + class="at.asitplus.eidas.specific.connector.config.PVPEndPointConfiguration"/> + class="at.asitplus.eidas.specific.connector.provider.PVPEndPointCredentialProvider" /> + class="at.asitplus.eidas.specific.connector.provider.PVPMetadataConfigurationFactory" /> + class="at.asitplus.eidas.specific.connector.controller.PVP2SProfileEndpoint"> + class="at.asitplus.eidas.specific.connector.verification.AuthnRequestValidator" /> @@ -61,37 +61,37 @@ + class="at.asitplus.eidas.specific.connector.provider.PVPMetadataProvider" /> + class="at.asitplus.eidas.specific.connector.builder.PVPSubjectNameGenerator"/> + class="at.asitplus.eidas.specific.connector.mapper.LoALevelMapper"/> + class="at.asitplus.eidas.specific.connector.gui.GUIBuilderConfigurationFactory" /> + class="at.asitplus.eidas.specific.connector.gui.DefaultGUIBuilderImpl"/> + class="at.asitplus.eidas.specific.connector.provider.StatusMessageProvider" /> + class="at.asitplus.eidas.specific.connector.logger.RevisionLogger" /> + class="at.asitplus.eidas.specific.connector.logger.StatisticLogger" /> \ No newline at end of file diff --git a/connector/src/main/resources/specific_eIDAS_connector.storage.beans.xml b/connector/src/main/resources/specific_eIDAS_connector.storage.beans.xml index be13e0cf..fa05dc9b 100644 --- a/connector/src/main/resources/specific_eIDAS_connector.storage.beans.xml +++ b/connector/src/main/resources/specific_eIDAS_connector.storage.beans.xml @@ -24,12 +24,12 @@ + class="at.asitplus.eidas.specific.connector.storage.SimpleInMemoryTransactionStorage" /> --> + class="at.asitplus.eidas.specific.connector.storage.eIDASCacheTransactionStoreDecorator"/> - + diff --git a/connector_lib/pom.xml b/connector_lib/pom.xml index e296800f..590adb22 100644 --- a/connector_lib/pom.xml +++ b/connector_lib/pom.xml @@ -3,11 +3,11 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 4.0.0 - at.gv.egiz.eidas + at.asitplus.eidas ms_specific 1.x - at.gv.egiz.eidas.ms_specific + at.asitplus.eidas.ms_specific connector_lib ${egiz.eidas.version} ms_specific_connector_lib diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MSConnectorEventCodes.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MSConnectorEventCodes.java new file mode 100644 index 00000000..e2915bbf --- /dev/null +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MSConnectorEventCodes.java @@ -0,0 +1,18 @@ +package at.asitplus.eidas.specific.connector; + +public class MSConnectorEventCodes { + + public static final int STARTING_COUNTRY_SELECTION = 4100; + public static final int COUNTRY_SELECTED = 4101; + + public static final int PROCESS_STOPPED_BY_USER = 4102; + + public static final int EIDAS_NODE_CONNECTED = 6101; + public static final int RESPONSE_FROM_EIDAS_NODE = 6102; + public static final int RESPONSE_FROM_EIDAS_NODE_VALID = 6103; + public static final int RESPONSE_FROM_EIDAS_NODE_NOT_VALID = 6104; + + public static final int SZR_IDL_RECEIVED = 6200; + public static final int SZR_BPK_RECEIVED = 6201; + +} diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MSeIDASNodeConstants.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MSeIDASNodeConstants.java new file mode 100644 index 00000000..57411f5c --- /dev/null +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/MSeIDASNodeConstants.java @@ -0,0 +1,85 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector; + +import java.util.Arrays; +import java.util.List; + +import at.gv.egiz.eaaf.core.api.data.EAAFConfigConstants; + +public class MSeIDASNodeConstants { + // ************ configuration properties ************ + public static final String PROP_CONFIG_APPLICATION_PREFIX = "eidas.ms."; + public static final String PROP_CONFIG_APPLICATION_PUBLIC_URL_PREFIX = "context.url.prefix"; + public static final String PROP_CONFIG_APPLICATION_PUBLIC_URL_REQUEST_VALIDATION = "context.url.request.validation"; + + private static final String PROP_CONFIG_PVP2_PREFIX = "pvp2."; + public static final String PROP_CONFIG_PVP2_KEYSTORE_PATH = PROP_CONFIG_PVP2_PREFIX + "keystore.path"; + public static final String PROP_CONFIG_PVP2_KEYSTORE_PASSWORD = PROP_CONFIG_PVP2_PREFIX + "keystore.password"; + public static final String PROP_CONFIG_PVP2_KEY_METADATA_ALIAS = PROP_CONFIG_PVP2_PREFIX + "key.metadata.alias"; + public static final String PROP_CONFIG_PVP2_KEY_METADATA_PASSWORD = PROP_CONFIG_PVP2_PREFIX + "key.metadata.password"; + public static final String PROP_CONFIG_PVP2_KEY_SIGNING_ALIAS = PROP_CONFIG_PVP2_PREFIX + "key.signing.alias"; + public static final String PROP_CONFIG_PVP2_KEY_SIGNING_PASSWORD = PROP_CONFIG_PVP2_PREFIX + "key.signing.password"; + public static final String PROP_CONFIG_PVP2_METADATA_VALIDITY = PROP_CONFIG_PVP2_PREFIX + "metadata.validity"; + + //TODO: is not implemented yet + public static final String PROP_CONFIG_SP_VALIDATION_DISABLED = "configuration.sp.disableRegistrationRequirement"; + + public static final String PROP_CONFIG_SP_LIST_PREFIX = "sp."; + public static final String PROP_CONFIG_SP_UNIQUEIDENTIFIER = EAAFConfigConstants.SERVICE_UNIQUEIDENTIFIER; + public static final String PROP_CONFIG_SP_FRIENDLYNAME = "friendlyName"; + public static final String PROP_CONFIG_SP_PVP2_METADATA_URL = "pvp2.metadata.url"; + public static final String PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE = "pvp2.metadata.truststore"; + public static final String PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE_PASSWORD = "pvp2.metadata.truststore.password"; + public static final String PROP_CONFIG_SP_POLICY_ALLOWED_TARGETS = "policy.allowed.requested.targets"; + public static final String PROP_CONFIG_SP_POLICY_BASEIDTRANSFER_RESTRICTION = "policy.hasBaseIdTransferRestriction"; + + public static final String PROP_CONFIG_PVP_SCHEME_VALIDATION = "configuration.pvp.scheme.validation"; + public static final String PROP_CONFIG_PVP_ENABLE_ENTITYCATEGORIES = "configuration.pvp.enable.entitycategories"; + + // ********** default values *************** + + //Default policy for SP-targets requested by MOA-ID to ms-specific eIDAS Connector + public static final String POLICY_DEFAULT_ALLOWED_TARGETS = ".*"; + // EAAFConstants.URN_PREFIX_CDID.replaceAll("\\.", "\\\\.").replaceAll("\\+", "\\\\+") + ".*"; + + public static final int METADATA_SOCKED_TIMEOUT = 20 * 1000; //20 seconds metadata socked timeout + public static final int DEFAULT_PVP_METADATA_VALIDITY = 24; //24 hours + public static final int DEFAULT_PVP_ASSERTION_VALIDITY = 5; //5 minutes + + + // ************ application end-points ************* + public static final String ENDPOINT_PVP_METADATA = "/pvp/metadata"; + public static final String ENDPOINT_PVP_POST = "/pvp/post"; + public static final String ENDPOINT_PVP_REDIRECT = "/pvp/redirect"; + + public static final String ENDPOINT_COUNTRYSELECTION = "/myHomeCountry"; + + + // ************ paths and templates ************ + public static final String CLASSPATH_TEMPLATE_DIR = "/templates/"; + public static final String FILESYSTEM_TEMPLATE_DIR = "./templates/"; + + public static final String TEMPLATE_HTML_ERROR = "error_message.html"; + public static final String TEMPLATE_HTML_PVP_POSTBINDING = "pvp2_post_binding.html"; + public static final String TEMPLATE_HTML_COUNTRYSELECTION = "countrySelection.html"; + + + // ************ execution context and generic data ************ + public static final String REQ_PARAM_SELECTED_COUNTRY = "selectedCountry"; + public static final String REQ_PARAM_SELECTED_ENVIRONMENT = "selectedEnvironment"; + public static final String REQ_PARAM_STOP_PROCESS = "stopAuthProcess"; + + public static final String REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_PRODUCTION = "prod"; + public static final String REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_QS = "qs"; + public static final String REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_TESTING = "test"; + public static final String REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_DEVELOPMENT = "dev"; + + public static final String DATA_REQUESTERID = "req_requesterId"; + public static final String DATA_PROVIDERNAME = "req_providerName"; + public static final String DATA_REQUESTED_LOA_LIST = "req_requestedLoA"; + public static final String DATA_REQUESTED_LOA_COMPERISON = "req_requestedLoAComperision"; + + public static final List COUNTRY_SELECTION_PARAM_WHITELIST = + Arrays.asList(REQ_PARAM_SELECTED_COUNTRY, REQ_PARAM_SELECTED_ENVIRONMENT); +} diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/config/BasicConfigurationProvider.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/config/BasicConfigurationProvider.java new file mode 100644 index 00000000..3bc5c190 --- /dev/null +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/config/BasicConfigurationProvider.java @@ -0,0 +1,122 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.config; + +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.idp.conf.AbstractConfigurationImpl; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; + +@Service("BasicMSSpecificNodeConfig") +public class BasicConfigurationProvider extends AbstractConfigurationImpl{ + private static final Logger log = LoggerFactory.getLogger(BasicConfigurationProvider.class); + + private Map spConfigCache = new HashMap(); + + public BasicConfigurationProvider(String configPath) throws EAAFConfigurationException { + super(configPath); + + } + + @Override + public ISPConfiguration getServiceProviderConfiguration(String entityId) throws EAAFConfigurationException { + if (!spConfigCache.containsKey(entityId)) { + log.debug("SP: " + entityId + " is NOT cached. Starting load operation ... "); + Map allSPs = getBasicMOAIDConfigurationWithPrefix(MSeIDASNodeConstants.PROP_CONFIG_SP_LIST_PREFIX); + for (String key : allSPs.keySet()) { + if (key.endsWith(MSeIDASNodeConstants.PROP_CONFIG_SP_UNIQUEIDENTIFIER) && + allSPs.get(key).equals(entityId)) { + String listId = KeyValueUtils.getParentKey(key); + log.trace("Find SP configuration with list-Id: " + listId + ". Extracting configuration elements ... "); + Map spConfig = KeyValueUtils.getSubSetWithPrefix(allSPs, listId + KeyValueUtils.KEY_DELIMITER); + spConfigCache.put(entityId, + new ServiceProviderConfiguration(spConfig, this)); + break; + } + } + + if (spConfigCache.containsKey(entityId)) + log.info("SP: " + entityId + " is loaded. Continuing auth. process ... "); + else { + log.warn("SP: " + entityId + " is NOT found in configuration. Stopping auth. process ... "); + return null; + + } + + } else + log.trace("SP: " + entityId + " is already cached. Use configuration from there ... "); + + + return spConfigCache.get(entityId); + } + + @Override + public T getServiceProviderConfiguration(String entityId, Class decorator) throws EAAFConfigurationException { + ISPConfiguration spConfig = getServiceProviderConfiguration(entityId); + if (spConfig != null && decorator != null) { + if (decorator.isInstance(spConfig)) + return (T)spConfig; + else + log.error("SPConfig: " + spConfig.getClass().getName() + " is NOT instance of: " + decorator.getName()); + + } + + return null; + + } + + @Override + public String validateIDPURL(URL url) throws EAAFException { + log.trace("Validate requested URL: " + url); + String urlPrefixFromConfig = getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_APPLICATION_PUBLIC_URL_PREFIX); + if (StringUtils.isEmpty(urlPrefixFromConfig)) { + log.warn("Application config containts NO URL prefix"); + throw new EAAFConfigurationException("config.27", + new Object[] {"Application config containts NO " + + getApplicationSpecificKeyPrefix() + MSeIDASNodeConstants.PROP_CONFIG_APPLICATION_PUBLIC_URL_PREFIX }); + + } + + //remove last slash + if (urlPrefixFromConfig.endsWith("/")) + urlPrefixFromConfig = urlPrefixFromConfig.substring(0, urlPrefixFromConfig.length()-1); + + if (getBasicMOAIDConfigurationBoolean( + MSeIDASNodeConstants.PROP_CONFIG_APPLICATION_PUBLIC_URL_REQUEST_VALIDATION, false)) { + if (url != null && url.toExternalForm().startsWith(urlPrefixFromConfig)) + return urlPrefixFromConfig; + + log.info("URL: " + url + " does NOT match to allowed application prefix: " + urlPrefixFromConfig); + return null; + + } else { + return urlPrefixFromConfig; + + } + } + + @Override + public String getApplicationSpecificKeyPrefix() { + return MSeIDASNodeConstants.PROP_CONFIG_APPLICATION_PREFIX; + + } + + @Override + protected String getBackupConfigPath() { + return null; + + } + + +} diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/config/ServiceProviderConfiguration.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/config/ServiceProviderConfiguration.java new file mode 100644 index 00000000..b45e723f --- /dev/null +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/config/ServiceProviderConfiguration.java @@ -0,0 +1,140 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.config; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.idp.conf.SPConfigurationImpl; + +public class ServiceProviderConfiguration extends SPConfigurationImpl { + private static final long serialVersionUID = 1L; + private static final Logger log = LoggerFactory.getLogger(ServiceProviderConfiguration.class); + + private List minimumLoA = Arrays.asList(EAAFConstants.EIDAS_LOA_HIGH); + private String bPKTargetIdentifier; + private String loaMachtingMode = EAAFConstants.EIDAS_LOA_MATCHING_MINIMUM; + + public ServiceProviderConfiguration(Map spConfig, IConfiguration authConfig) { + super(spConfig, authConfig); + + } + + @Override + public boolean hasBaseIdInternalProcessingRestriction() { + return false; + + } + + @Override + public boolean hasBaseIdTransferRestriction() { + Boolean spConfigPolicy = isConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_POLICY_BASEIDTRANSFER_RESTRICTION); + if (spConfigPolicy != null) + return spConfigPolicy; + + else { + log.trace("SP configuration defines no baseID transfer restriction. Enforce default policy ..."); + for (String el : getTargetsWithNoBaseIdTransferRestriction()) { + if (this.bPKTargetIdentifier != null && this.bPKTargetIdentifier.startsWith(el)) { + log.debug("SP-Target: " + this.bPKTargetIdentifier + " has NO baseID transfer restriction in default policy"); + return false; + + } + } + } + + log.debug("Default-policy defines baseID transfer restriction for SP-Target: " + this.bPKTargetIdentifier); + return true; + } + + @Override + public List getRequiredLoA() { + return minimumLoA; + + } + + public String getLoAMatchingMode() { + return loaMachtingMode; + + } + + + @Override + public String getAreaSpecificTargetIdentifier() { + return bPKTargetIdentifier; + } + + + @Override + public String getFriendlyName() { + return getConfigurationValue( + MSeIDASNodeConstants.PROP_CONFIG_SP_FRIENDLYNAME, + "NO FRIENDLYNAME SET"); + + } + + /** + * Set the minimum level of eIDAS authentication for this SP + *
+ * Default: http://eidas.europa.eu/LoA/high + *
+ * Info: In case of MINIMUM matching-mode, only one entry is allowed + * + * @param minimumLoA eIDAS LoA URIs + */ + + public void setRequiredLoA(List minimumLoA) { + this.minimumLoA = minimumLoA; + } + + /** + * Set the mode of operation for LoA matching for this SP + * + * Default: minimum + *
+ * Info: Currently only 'minimum' and 'exact' are supported + * + * @param mode LoA matching mode according to SAML2 core specification + */ + public void setLoAMachtingMode(String mode) { + this.loaMachtingMode = mode; + } + + + /** + * Set the bPK Target for this service provider + * + * @param bPKTargetIdentifier + * @throws EAAFException If the bPKTargetIdentifier is NOT ALLOWED for this service provider + */ + public void setbPKTargetIdentifier(String bPKTargetIdentifier) throws EAAFException { + String allowedTargetIdentifierRegExPattern = getConfigurationValue( + MSeIDASNodeConstants.PROP_CONFIG_SP_POLICY_ALLOWED_TARGETS, + MSeIDASNodeConstants.POLICY_DEFAULT_ALLOWED_TARGETS); + log.trace("Use bPK-target regex pattern: " + allowedTargetIdentifierRegExPattern); + + Pattern p = Pattern.compile(allowedTargetIdentifierRegExPattern); + Matcher m = p.matcher(bPKTargetIdentifier); + if (m.matches()) { + log.debug("Requested bPK-target: " + bPKTargetIdentifier + " matches regex pattern"); + this.bPKTargetIdentifier = bPKTargetIdentifier; + + } else { + log.warn("Requested bPK-target: " + bPKTargetIdentifier + " does NOT match regex pattern."); + throw new EAAFException("auth.37", new Object[] {bPKTargetIdentifier, getUniqueIdentifier()}); + + } + + } + +} diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/DefaultGUIBuilderImpl.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/DefaultGUIBuilderImpl.java new file mode 100644 index 00000000..ed1ceb78 --- /dev/null +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/DefaultGUIBuilderImpl.java @@ -0,0 +1,43 @@ +package at.asitplus.eidas.specific.connector.gui; + +import java.io.InputStream; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; + +import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; +import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; +import at.gv.egiz.eaaf.core.impl.gui.AbstractGUIFormBuilderImpl; + +@Service("DefaultGUIBuilderImpl") +public class DefaultGUIBuilderImpl extends AbstractGUIFormBuilderImpl implements IGUIFormBuilder { + private static final Logger log = LoggerFactory.getLogger(DefaultGUIBuilderImpl.class); + + private static final String CLASSPATH_HTMLTEMPLATES_DIR = "templates/"; + + public DefaultGUIBuilderImpl() throws GUIBuildException { + super(); + + } + + @Override + protected InputStream getInternalTemplate(IGUIBuilderConfiguration config) throws GUIBuildException { + String viewName = config.getViewName(); + log.debug("GUI template:" + viewName + " is not found in configuration directory. " + + " Load template from project library ... "); + String pathLocation = getInternalClasspathTemplateDir(config, CLASSPATH_HTMLTEMPLATES_DIR) + viewName; + try { + InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathLocation); + return is; + + } catch (Exception e1) { + log.error("GUI template:" + pathLocation + " is NOT loadable from classpath!", e1); + throw new GUIBuildException("GUI template:" + pathLocation + " is NOT loadable from classpath!", e1); + + } + + } + +} diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/GUIBuilderConfigurationFactory.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/GUIBuilderConfigurationFactory.java new file mode 100644 index 00000000..cd7b577f --- /dev/null +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/GUIBuilderConfigurationFactory.java @@ -0,0 +1,32 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.gui; + +import java.net.MalformedURLException; +import java.net.URI; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfigurationFactory; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; + +@Service("GUIBuilderConfigurationFactory") +public class GUIBuilderConfigurationFactory implements IGUIBuilderConfigurationFactory { + @Autowired(required=true) private IConfiguration basicConfig; + + @Override + public IGUIBuilderConfiguration getDefaultErrorGUI(String authURL) { + return new StaticGuiBuilderConfiguration(basicConfig, authURL, MSeIDASNodeConstants.TEMPLATE_HTML_ERROR, null); + } + + @Override + public IGUIBuilderConfiguration getSPSpecificSAML2PostConfiguration(IRequest pendingReq, String viewName, URI configRootContextDir) + throws MalformedURLException { + return new StaticGuiBuilderConfiguration(basicConfig, pendingReq,MSeIDASNodeConstants.TEMPLATE_HTML_PVP_POSTBINDING , null); + } + +} diff --git a/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/StaticGuiBuilderConfiguration.java b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/StaticGuiBuilderConfiguration.java new file mode 100644 index 00000000..bcfbdf50 --- /dev/null +++ b/connector_lib/src/main/java/at/asitplus/eidas/specific/connector/gui/StaticGuiBuilderConfiguration.java @@ -0,0 +1,105 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.connector.gui; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.lang.StringEscapeUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.gui.ModifyableGuiBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.impl.gui.AbstractGUIFormBuilderConfiguration; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; + +public class StaticGuiBuilderConfiguration extends AbstractGUIFormBuilderConfiguration implements ModifyableGuiBuilderConfiguration { + private static final Logger log = LoggerFactory.getLogger(StaticGuiBuilderConfiguration.class); + + private IRequest pendingReq = null; + private IConfiguration basicConfig = null; + Map params = new HashMap(); + + public StaticGuiBuilderConfiguration(IConfiguration basicConfig, String authURL, String viewName, String formSubmitEndpoint) { + super(authURL, viewName, formSubmitEndpoint); + this.basicConfig = basicConfig; + } + + public StaticGuiBuilderConfiguration(IConfiguration basicConfig, IRequest pendingReq, String viewName, String formSubmitEndpoint) { + super(pendingReq.getAuthURL(), viewName, formSubmitEndpoint); + this.pendingReq = pendingReq; + this.basicConfig = basicConfig; + + } + + @Override + public String getClasspathTemplateDir() { + return MSeIDASNodeConstants.CLASSPATH_TEMPLATE_DIR; + + } + + @Override + public String getDefaultContentType() { + return null; + + } + + @Override + public InputStream getTemplate(String viewName) { + String templateURL = MSeIDASNodeConstants.FILESYSTEM_TEMPLATE_DIR + viewName; + try { + String absURL = FileUtils.makeAbsoluteURL(templateURL, this.basicConfig.getConfigurationRootDirectory()); + if (!absURL.startsWith("file:")) { + log.warn("Path to template looks like NOT absolut: " + absURL + ". Template loading FAILED"); + + } else { + log.debug("Load template URL for view: " + viewName + " from: " + absURL); + URI uri = new URL(absURL).toURI(); + return new FileInputStream(new File(uri)); + + } + + + } catch (MalformedURLException | URISyntaxException | FileNotFoundException e) { + log.info("Can can build filesytem path to template: " + templateURL + + " Reason: " + e.getMessage()); + + } + + return null; + } + + @Override + protected Map getSpecificViewParameters() { + if (pendingReq != null) { + params.put(PARAM_PENDINGREQUESTID, StringEscapeUtils.escapeHtml(pendingReq.getPendingRequestId())); + + } + + return params; + } + + @Override + public void putCustomParameter(String key, String value) { + params.put(key, StringEscapeUtils.escapeHtml(value)); + + } + + @Override + public void putCustomParameterWithOutEscaption(String arg0, Object arg1) { + log.info("Add GUI-Template parameters WITHOUT escaption ARE NOT supported!!!!!"); + + } + +} diff --git a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/MSConnectorEventCodes.java b/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/MSConnectorEventCodes.java deleted file mode 100644 index 40abb085..00000000 --- a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/MSConnectorEventCodes.java +++ /dev/null @@ -1,18 +0,0 @@ -package at.gv.egiz.eidas.specific.connector; - -public class MSConnectorEventCodes { - - public static final int STARTING_COUNTRY_SELECTION = 4100; - public static final int COUNTRY_SELECTED = 4101; - - public static final int PROCESS_STOPPED_BY_USER = 4102; - - public static final int EIDAS_NODE_CONNECTED = 6101; - public static final int RESPONSE_FROM_EIDAS_NODE = 6102; - public static final int RESPONSE_FROM_EIDAS_NODE_VALID = 6103; - public static final int RESPONSE_FROM_EIDAS_NODE_NOT_VALID = 6104; - - public static final int SZR_IDL_RECEIVED = 6200; - public static final int SZR_BPK_RECEIVED = 6201; - -} diff --git a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/MSeIDASNodeConstants.java b/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/MSeIDASNodeConstants.java deleted file mode 100644 index f3c85b7c..00000000 --- a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/MSeIDASNodeConstants.java +++ /dev/null @@ -1,85 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector; - -import java.util.Arrays; -import java.util.List; - -import at.gv.egiz.eaaf.core.api.data.EAAFConfigConstants; - -public class MSeIDASNodeConstants { - // ************ configuration properties ************ - public static final String PROP_CONFIG_APPLICATION_PREFIX = "eidas.ms."; - public static final String PROP_CONFIG_APPLICATION_PUBLIC_URL_PREFIX = "context.url.prefix"; - public static final String PROP_CONFIG_APPLICATION_PUBLIC_URL_REQUEST_VALIDATION = "context.url.request.validation"; - - private static final String PROP_CONFIG_PVP2_PREFIX = "pvp2."; - public static final String PROP_CONFIG_PVP2_KEYSTORE_PATH = PROP_CONFIG_PVP2_PREFIX + "keystore.path"; - public static final String PROP_CONFIG_PVP2_KEYSTORE_PASSWORD = PROP_CONFIG_PVP2_PREFIX + "keystore.password"; - public static final String PROP_CONFIG_PVP2_KEY_METADATA_ALIAS = PROP_CONFIG_PVP2_PREFIX + "key.metadata.alias"; - public static final String PROP_CONFIG_PVP2_KEY_METADATA_PASSWORD = PROP_CONFIG_PVP2_PREFIX + "key.metadata.password"; - public static final String PROP_CONFIG_PVP2_KEY_SIGNING_ALIAS = PROP_CONFIG_PVP2_PREFIX + "key.signing.alias"; - public static final String PROP_CONFIG_PVP2_KEY_SIGNING_PASSWORD = PROP_CONFIG_PVP2_PREFIX + "key.signing.password"; - public static final String PROP_CONFIG_PVP2_METADATA_VALIDITY = PROP_CONFIG_PVP2_PREFIX + "metadata.validity"; - - //TODO: is not implemented yet - public static final String PROP_CONFIG_SP_VALIDATION_DISABLED = "configuration.sp.disableRegistrationRequirement"; - - public static final String PROP_CONFIG_SP_LIST_PREFIX = "sp."; - public static final String PROP_CONFIG_SP_UNIQUEIDENTIFIER = EAAFConfigConstants.SERVICE_UNIQUEIDENTIFIER; - public static final String PROP_CONFIG_SP_FRIENDLYNAME = "friendlyName"; - public static final String PROP_CONFIG_SP_PVP2_METADATA_URL = "pvp2.metadata.url"; - public static final String PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE = "pvp2.metadata.truststore"; - public static final String PROP_CONFIG_SP_PVP2_METADATA_TRUSTSTORE_PASSWORD = "pvp2.metadata.truststore.password"; - public static final String PROP_CONFIG_SP_POLICY_ALLOWED_TARGETS = "policy.allowed.requested.targets"; - public static final String PROP_CONFIG_SP_POLICY_BASEIDTRANSFER_RESTRICTION = "policy.hasBaseIdTransferRestriction"; - - public static final String PROP_CONFIG_PVP_SCHEME_VALIDATION = "configuration.pvp.scheme.validation"; - public static final String PROP_CONFIG_PVP_ENABLE_ENTITYCATEGORIES = "configuration.pvp.enable.entitycategories"; - - // ********** default values *************** - - //Default policy for SP-targets requested by MOA-ID to ms-specific eIDAS Connector - public static final String POLICY_DEFAULT_ALLOWED_TARGETS = ".*"; - // EAAFConstants.URN_PREFIX_CDID.replaceAll("\\.", "\\\\.").replaceAll("\\+", "\\\\+") + ".*"; - - public static final int METADATA_SOCKED_TIMEOUT = 20 * 1000; //20 seconds metadata socked timeout - public static final int DEFAULT_PVP_METADATA_VALIDITY = 24; //24 hours - public static final int DEFAULT_PVP_ASSERTION_VALIDITY = 5; //5 minutes - - - // ************ application end-points ************* - public static final String ENDPOINT_PVP_METADATA = "/pvp/metadata"; - public static final String ENDPOINT_PVP_POST = "/pvp/post"; - public static final String ENDPOINT_PVP_REDIRECT = "/pvp/redirect"; - - public static final String ENDPOINT_COUNTRYSELECTION = "/myHomeCountry"; - - - // ************ paths and templates ************ - public static final String CLASSPATH_TEMPLATE_DIR = "/templates/"; - public static final String FILESYSTEM_TEMPLATE_DIR = "./templates/"; - - public static final String TEMPLATE_HTML_ERROR = "error_message.html"; - public static final String TEMPLATE_HTML_PVP_POSTBINDING = "pvp2_post_binding.html"; - public static final String TEMPLATE_HTML_COUNTRYSELECTION = "countrySelection.html"; - - - // ************ execution context and generic data ************ - public static final String REQ_PARAM_SELECTED_COUNTRY = "selectedCountry"; - public static final String REQ_PARAM_SELECTED_ENVIRONMENT = "selectedEnvironment"; - public static final String REQ_PARAM_STOP_PROCESS = "stopAuthProcess"; - - public static final String REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_PRODUCTION = "prod"; - public static final String REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_QS = "qs"; - public static final String REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_TESTING = "test"; - public static final String REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_DEVELOPMENT = "dev"; - - public static final String DATA_REQUESTERID = "req_requesterId"; - public static final String DATA_PROVIDERNAME = "req_providerName"; - public static final String DATA_REQUESTED_LOA_LIST = "req_requestedLoA"; - public static final String DATA_REQUESTED_LOA_COMPERISON = "req_requestedLoAComperision"; - - public static final List COUNTRY_SELECTION_PARAM_WHITELIST = - Arrays.asList(REQ_PARAM_SELECTED_COUNTRY, REQ_PARAM_SELECTED_ENVIRONMENT); -} diff --git a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/config/BasicConfigurationProvider.java b/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/config/BasicConfigurationProvider.java deleted file mode 100644 index 553cebc2..00000000 --- a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/config/BasicConfigurationProvider.java +++ /dev/null @@ -1,122 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.config; - -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.impl.idp.conf.AbstractConfigurationImpl; -import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -@Service("BasicMSSpecificNodeConfig") -public class BasicConfigurationProvider extends AbstractConfigurationImpl{ - private static final Logger log = LoggerFactory.getLogger(BasicConfigurationProvider.class); - - private Map spConfigCache = new HashMap(); - - public BasicConfigurationProvider(String configPath) throws EAAFConfigurationException { - super(configPath); - - } - - @Override - public ISPConfiguration getServiceProviderConfiguration(String entityId) throws EAAFConfigurationException { - if (!spConfigCache.containsKey(entityId)) { - log.debug("SP: " + entityId + " is NOT cached. Starting load operation ... "); - Map allSPs = getBasicMOAIDConfigurationWithPrefix(MSeIDASNodeConstants.PROP_CONFIG_SP_LIST_PREFIX); - for (String key : allSPs.keySet()) { - if (key.endsWith(MSeIDASNodeConstants.PROP_CONFIG_SP_UNIQUEIDENTIFIER) && - allSPs.get(key).equals(entityId)) { - String listId = KeyValueUtils.getParentKey(key); - log.trace("Find SP configuration with list-Id: " + listId + ". Extracting configuration elements ... "); - Map spConfig = KeyValueUtils.getSubSetWithPrefix(allSPs, listId + KeyValueUtils.KEY_DELIMITER); - spConfigCache.put(entityId, - new ServiceProviderConfiguration(spConfig, this)); - break; - } - } - - if (spConfigCache.containsKey(entityId)) - log.info("SP: " + entityId + " is loaded. Continuing auth. process ... "); - else { - log.warn("SP: " + entityId + " is NOT found in configuration. Stopping auth. process ... "); - return null; - - } - - } else - log.trace("SP: " + entityId + " is already cached. Use configuration from there ... "); - - - return spConfigCache.get(entityId); - } - - @Override - public T getServiceProviderConfiguration(String entityId, Class decorator) throws EAAFConfigurationException { - ISPConfiguration spConfig = getServiceProviderConfiguration(entityId); - if (spConfig != null && decorator != null) { - if (decorator.isInstance(spConfig)) - return (T)spConfig; - else - log.error("SPConfig: " + spConfig.getClass().getName() + " is NOT instance of: " + decorator.getName()); - - } - - return null; - - } - - @Override - public String validateIDPURL(URL url) throws EAAFException { - log.trace("Validate requested URL: " + url); - String urlPrefixFromConfig = getBasicConfiguration(MSeIDASNodeConstants.PROP_CONFIG_APPLICATION_PUBLIC_URL_PREFIX); - if (StringUtils.isEmpty(urlPrefixFromConfig)) { - log.warn("Application config containts NO URL prefix"); - throw new EAAFConfigurationException("config.27", - new Object[] {"Application config containts NO " - + getApplicationSpecificKeyPrefix() + MSeIDASNodeConstants.PROP_CONFIG_APPLICATION_PUBLIC_URL_PREFIX }); - - } - - //remove last slash - if (urlPrefixFromConfig.endsWith("/")) - urlPrefixFromConfig = urlPrefixFromConfig.substring(0, urlPrefixFromConfig.length()-1); - - if (getBasicMOAIDConfigurationBoolean( - MSeIDASNodeConstants.PROP_CONFIG_APPLICATION_PUBLIC_URL_REQUEST_VALIDATION, false)) { - if (url != null && url.toExternalForm().startsWith(urlPrefixFromConfig)) - return urlPrefixFromConfig; - - log.info("URL: " + url + " does NOT match to allowed application prefix: " + urlPrefixFromConfig); - return null; - - } else { - return urlPrefixFromConfig; - - } - } - - @Override - public String getApplicationSpecificKeyPrefix() { - return MSeIDASNodeConstants.PROP_CONFIG_APPLICATION_PREFIX; - - } - - @Override - protected String getBackupConfigPath() { - return null; - - } - - -} diff --git a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/config/ServiceProviderConfiguration.java b/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/config/ServiceProviderConfiguration.java deleted file mode 100644 index a742db6a..00000000 --- a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/config/ServiceProviderConfiguration.java +++ /dev/null @@ -1,140 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.config; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.impl.idp.conf.SPConfigurationImpl; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -public class ServiceProviderConfiguration extends SPConfigurationImpl { - private static final long serialVersionUID = 1L; - private static final Logger log = LoggerFactory.getLogger(ServiceProviderConfiguration.class); - - private List minimumLoA = Arrays.asList(EAAFConstants.EIDAS_LOA_HIGH); - private String bPKTargetIdentifier; - private String loaMachtingMode = EAAFConstants.EIDAS_LOA_MATCHING_MINIMUM; - - public ServiceProviderConfiguration(Map spConfig, IConfiguration authConfig) { - super(spConfig, authConfig); - - } - - @Override - public boolean hasBaseIdInternalProcessingRestriction() { - return false; - - } - - @Override - public boolean hasBaseIdTransferRestriction() { - Boolean spConfigPolicy = isConfigurationValue(MSeIDASNodeConstants.PROP_CONFIG_SP_POLICY_BASEIDTRANSFER_RESTRICTION); - if (spConfigPolicy != null) - return spConfigPolicy; - - else { - log.trace("SP configuration defines no baseID transfer restriction. Enforce default policy ..."); - for (String el : getTargetsWithNoBaseIdTransferRestriction()) { - if (this.bPKTargetIdentifier != null && this.bPKTargetIdentifier.startsWith(el)) { - log.debug("SP-Target: " + this.bPKTargetIdentifier + " has NO baseID transfer restriction in default policy"); - return false; - - } - } - } - - log.debug("Default-policy defines baseID transfer restriction for SP-Target: " + this.bPKTargetIdentifier); - return true; - } - - @Override - public List getRequiredLoA() { - return minimumLoA; - - } - - public String getLoAMatchingMode() { - return loaMachtingMode; - - } - - - @Override - public String getAreaSpecificTargetIdentifier() { - return bPKTargetIdentifier; - } - - - @Override - public String getFriendlyName() { - return getConfigurationValue( - MSeIDASNodeConstants.PROP_CONFIG_SP_FRIENDLYNAME, - "NO FRIENDLYNAME SET"); - - } - - /** - * Set the minimum level of eIDAS authentication for this SP - *
- * Default: http://eidas.europa.eu/LoA/high - *
- * Info: In case of MINIMUM matching-mode, only one entry is allowed - * - * @param minimumLoA eIDAS LoA URIs - */ - - public void setRequiredLoA(List minimumLoA) { - this.minimumLoA = minimumLoA; - } - - /** - * Set the mode of operation for LoA matching for this SP - * - * Default: minimum - *
- * Info: Currently only 'minimum' and 'exact' are supported - * - * @param mode LoA matching mode according to SAML2 core specification - */ - public void setLoAMachtingMode(String mode) { - this.loaMachtingMode = mode; - } - - - /** - * Set the bPK Target for this service provider - * - * @param bPKTargetIdentifier - * @throws EAAFException If the bPKTargetIdentifier is NOT ALLOWED for this service provider - */ - public void setbPKTargetIdentifier(String bPKTargetIdentifier) throws EAAFException { - String allowedTargetIdentifierRegExPattern = getConfigurationValue( - MSeIDASNodeConstants.PROP_CONFIG_SP_POLICY_ALLOWED_TARGETS, - MSeIDASNodeConstants.POLICY_DEFAULT_ALLOWED_TARGETS); - log.trace("Use bPK-target regex pattern: " + allowedTargetIdentifierRegExPattern); - - Pattern p = Pattern.compile(allowedTargetIdentifierRegExPattern); - Matcher m = p.matcher(bPKTargetIdentifier); - if (m.matches()) { - log.debug("Requested bPK-target: " + bPKTargetIdentifier + " matches regex pattern"); - this.bPKTargetIdentifier = bPKTargetIdentifier; - - } else { - log.warn("Requested bPK-target: " + bPKTargetIdentifier + " does NOT match regex pattern."); - throw new EAAFException("auth.37", new Object[] {bPKTargetIdentifier, getUniqueIdentifier()}); - - } - - } - -} diff --git a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/DefaultGUIBuilderImpl.java b/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/DefaultGUIBuilderImpl.java deleted file mode 100644 index b75c2e23..00000000 --- a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/DefaultGUIBuilderImpl.java +++ /dev/null @@ -1,43 +0,0 @@ -package at.gv.egiz.eidas.specific.connector.gui; - -import java.io.InputStream; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; -import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; -import at.gv.egiz.eaaf.core.impl.gui.AbstractGUIFormBuilderImpl; - -@Service("DefaultGUIBuilderImpl") -public class DefaultGUIBuilderImpl extends AbstractGUIFormBuilderImpl implements IGUIFormBuilder { - private static final Logger log = LoggerFactory.getLogger(DefaultGUIBuilderImpl.class); - - private static final String CLASSPATH_HTMLTEMPLATES_DIR = "templates/"; - - public DefaultGUIBuilderImpl() throws GUIBuildException { - super(); - - } - - @Override - protected InputStream getInternalTemplate(IGUIBuilderConfiguration config) throws GUIBuildException { - String viewName = config.getViewName(); - log.debug("GUI template:" + viewName + " is not found in configuration directory. " - + " Load template from project library ... "); - String pathLocation = getInternalClasspathTemplateDir(config, CLASSPATH_HTMLTEMPLATES_DIR) + viewName; - try { - InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(pathLocation); - return is; - - } catch (Exception e1) { - log.error("GUI template:" + pathLocation + " is NOT loadable from classpath!", e1); - throw new GUIBuildException("GUI template:" + pathLocation + " is NOT loadable from classpath!", e1); - - } - - } - -} diff --git a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/GUIBuilderConfigurationFactory.java b/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/GUIBuilderConfigurationFactory.java deleted file mode 100644 index 8132c063..00000000 --- a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/GUIBuilderConfigurationFactory.java +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.gui; - -import java.net.MalformedURLException; -import java.net.URI; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfigurationFactory; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -@Service("GUIBuilderConfigurationFactory") -public class GUIBuilderConfigurationFactory implements IGUIBuilderConfigurationFactory { - @Autowired(required=true) private IConfiguration basicConfig; - - @Override - public IGUIBuilderConfiguration getDefaultErrorGUI(String authURL) { - return new StaticGuiBuilderConfiguration(basicConfig, authURL, MSeIDASNodeConstants.TEMPLATE_HTML_ERROR, null); - } - - @Override - public IGUIBuilderConfiguration getSPSpecificSAML2PostConfiguration(IRequest pendingReq, String viewName, URI configRootContextDir) - throws MalformedURLException { - return new StaticGuiBuilderConfiguration(basicConfig, pendingReq,MSeIDASNodeConstants.TEMPLATE_HTML_PVP_POSTBINDING , null); - } - -} diff --git a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/StaticGuiBuilderConfiguration.java b/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/StaticGuiBuilderConfiguration.java deleted file mode 100644 index 3a765eb5..00000000 --- a/connector_lib/src/main/java/at/gv/egiz/eidas/specific/connector/gui/StaticGuiBuilderConfiguration.java +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.connector.gui; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; - -import org.apache.commons.lang.StringEscapeUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.api.gui.ModifyableGuiBuilderConfiguration; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.impl.gui.AbstractGUIFormBuilderConfiguration; -import at.gv.egiz.eaaf.core.impl.utils.FileUtils; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -public class StaticGuiBuilderConfiguration extends AbstractGUIFormBuilderConfiguration implements ModifyableGuiBuilderConfiguration { - private static final Logger log = LoggerFactory.getLogger(StaticGuiBuilderConfiguration.class); - - private IRequest pendingReq = null; - private IConfiguration basicConfig = null; - Map params = new HashMap(); - - public StaticGuiBuilderConfiguration(IConfiguration basicConfig, String authURL, String viewName, String formSubmitEndpoint) { - super(authURL, viewName, formSubmitEndpoint); - this.basicConfig = basicConfig; - } - - public StaticGuiBuilderConfiguration(IConfiguration basicConfig, IRequest pendingReq, String viewName, String formSubmitEndpoint) { - super(pendingReq.getAuthURL(), viewName, formSubmitEndpoint); - this.pendingReq = pendingReq; - this.basicConfig = basicConfig; - - } - - @Override - public String getClasspathTemplateDir() { - return MSeIDASNodeConstants.CLASSPATH_TEMPLATE_DIR; - - } - - @Override - public String getDefaultContentType() { - return null; - - } - - @Override - public InputStream getTemplate(String viewName) { - String templateURL = MSeIDASNodeConstants.FILESYSTEM_TEMPLATE_DIR + viewName; - try { - String absURL = FileUtils.makeAbsoluteURL(templateURL, this.basicConfig.getConfigurationRootDirectory()); - if (!absURL.startsWith("file:")) { - log.warn("Path to template looks like NOT absolut: " + absURL + ". Template loading FAILED"); - - } else { - log.debug("Load template URL for view: " + viewName + " from: " + absURL); - URI uri = new URL(absURL).toURI(); - return new FileInputStream(new File(uri)); - - } - - - } catch (MalformedURLException | URISyntaxException | FileNotFoundException e) { - log.info("Can can build filesytem path to template: " + templateURL - + " Reason: " + e.getMessage()); - - } - - return null; - } - - @Override - protected Map getSpecificViewParameters() { - if (pendingReq != null) { - params.put(PARAM_PENDINGREQUESTID, StringEscapeUtils.escapeHtml(pendingReq.getPendingRequestId())); - - } - - return params; - } - - @Override - public void putCustomParameter(String key, String value) { - params.put(key, StringEscapeUtils.escapeHtml(value)); - - } - - @Override - public void putCustomParameterWithOutEscaption(String arg0, Object arg1) { - log.info("Add GUI-Template parameters WITHOUT escaption ARE NOT supported!!!!!"); - - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/pom.xml b/eidas_modules/authmodule-eIDAS-v2/pom.xml index eef89112..51b3004c 100644 --- a/eidas_modules/authmodule-eIDAS-v2/pom.xml +++ b/eidas_modules/authmodule-eIDAS-v2/pom.xml @@ -2,11 +2,11 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 - at.gv.egiz.eidas.ms_specific + at.asitplus.eidas.ms_specific modules 1.x - at.gv.egiz.eidas.ms_specific.modules + at.asitplus.eidas.ms_specific.modules authmodule-eIDAS-v2 eIDAS v2 authentication module ${egiz.eidas.version} @@ -47,7 +47,7 @@ egiz-spring-api - at.gv.egiz.eidas.ms_specific + at.asitplus.eidas.ms_specific connector_lib diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/Constants.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/Constants.java new file mode 100644 index 00000000..64cf6af2 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/Constants.java @@ -0,0 +1,110 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2; + +import java.net.URI; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; + +public class Constants { + + public static final String DATA_REQUESTERID = "req_requesterId"; + public static final String DATA_PROVIDERNAME = "req_providerName"; + public static final String DATA_REQUESTED_LOA_LIST = "req_requestedLoA"; + public static final String DATA_REQUESTED_LOA_COMPERISON = "req_requestedLoAComperision"; + public static final String DATA_FULL_EIDAS_RESPONSE = "resp_fulleIDASResponse"; + + + //templates for post-binding forwarding + public static final String TEMPLATE_POST_FORWARD_NAME = "eidas_node_forward.html"; + public static final String TEMPLATE_POST_FORWARD_ENDPOINT = "endPoint"; + public static final String TEMPLATE_POST_FORWARD_TOKEN_NAME = "tokenName"; + public static final String TEMPLATE_POST_FORWARD_TOKEN_VALUE = "tokenValue"; + + + //configuration properties + public static final String CONIG_PROPS_EIDAS_PREFIX="auth.eIDAS"; + public static final String CONIG_PROPS_EIDAS_NODE= CONIG_PROPS_EIDAS_PREFIX + ".node_v2"; + public static final String CONIG_PROPS_EIDAS_NODE_COUNTRYCODE = CONIG_PROPS_EIDAS_NODE + ".countrycode"; + public static final String CONIG_PROPS_EIDAS_NODE_PUBLICSECTOR_TARGETS = CONIG_PROPS_EIDAS_NODE + ".publicSectorTargets"; + public static final String CONIG_PROPS_EIDAS_NODE_ENTITYID = CONIG_PROPS_EIDAS_NODE + ".entityId"; + public static final String CONIG_PROPS_EIDAS_NODE_FORWARD_URL = CONIG_PROPS_EIDAS_NODE + ".forward.endpoint"; + public static final String CONIG_PROPS_EIDAS_NODE_FORWARD_METHOD = CONIG_PROPS_EIDAS_NODE + ".forward.method"; + public static final String CONIG_PROPS_EIDAS_NODE_ATTRIBUTES_REQUESTED_ONLYNATURAL = CONIG_PROPS_EIDAS_NODE + ".attributes.requested.onlynatural."; + public static final String CONIG_PROPS_EIDAS_NODE_ATTRIBUTES_REQUESTED_REPRESENTATION = CONIG_PROPS_EIDAS_NODE + ".attributes.requested.representation."; + public static final String CONIG_PROPS_EIDAS_NODE_WORKAROUND_ADD_ALWAYS_PROVIDERNAME = CONIG_PROPS_EIDAS_NODE + ".workarounds.addAlwaysProviderName";; + public static final String CONIG_PROPS_EIDAS_NODE_WORKAROUND_USEREQUESTIDASTRANSACTIONIDENTIFIER = CONIG_PROPS_EIDAS_NODE + ".workarounds.useRequestIdAsTransactionIdentifier"; + + public static final String FORWARD_METHOD_POST = "POST"; + public static final String FORWARD_METHOD_GET = "GET"; + + public static final String CONIG_PROPS_EIDAS_SZRCLIENT= CONIG_PROPS_EIDAS_PREFIX + ".szrclient"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_USETESTSERVICE= CONIG_PROPS_EIDAS_SZRCLIENT + ".useTestService"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_TRACEMESSAGES= CONIG_PROPS_EIDAS_SZRCLIENT + ".debug.logfullmessages"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USEDUMMY= CONIG_PROPS_EIDAS_SZRCLIENT + ".debug.useDummySolution"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_INSERTERNB= CONIG_PROPS_EIDAS_SZRCLIENT + ".debug.insertERnB"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_TIMEOUT_CONNECTION= CONIG_PROPS_EIDAS_SZRCLIENT + ".timeout.connection"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_TIMEOUT_RESPONSE= CONIG_PROPS_EIDAS_SZRCLIENT + ".timeout.response"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_ENDPOINT_PROD= CONIG_PROPS_EIDAS_SZRCLIENT + ".endpoint.prod"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_ENDPOINT_TEST= CONIG_PROPS_EIDAS_SZRCLIENT + ".endpoint.test"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_SSL_KEYSTORE_PATH = CONIG_PROPS_EIDAS_SZRCLIENT + ".ssl.keyStore.path"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_SSL_KEYSTORE_PASSWORD = CONIG_PROPS_EIDAS_SZRCLIENT + ".ssl.keyStore.password"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_SSL_TRUSTSTORE_PATH = CONIG_PROPS_EIDAS_SZRCLIENT + ".ssl.trustStore.path"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_SSL_TRUSTSTORE_PASSWORD = CONIG_PROPS_EIDAS_SZRCLIENT + ".ssl.trustStore.password"; + + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE = CONIG_PROPS_EIDAS_SZRCLIENT + ".params.documenttype"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ = CONIG_PROPS_EIDAS_SZRCLIENT + ".params.vkz"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_DATE = CONIG_PROPS_EIDAS_SZRCLIENT + ".params.issuingdate"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_AUTHORITY = CONIG_PROPS_EIDAS_SZRCLIENT + ".params.issuingauthority"; + public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_KEYS_USEDUMMY= CONIG_PROPS_EIDAS_SZRCLIENT + ".params.usedummykeys"; + + //http endpoint descriptions + public static final String eIDAS_HTTP_ENDPOINT_SP_POST = "/eidas/light/sp/post"; + public static final String eIDAS_HTTP_ENDPOINT_SP_REDIRECT = "/eidas/light/sp/redirect"; + public static final String eIDAS_HTTP_ENDPOINT_IDP_COLLEAGUEREQUEST = "/eidas/light/ColleagueRequest"; + public static final String eIDAS_HTTP_ENDPOINT_METADATA = "/eidas/light/metadata"; + + //eIDAS request parameters + public static final String eIDAS_REQ_NAMEID_FORMAT = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"; + + //eIDAS attribute names + public static final String eIDAS_ATTR_PERSONALIDENTIFIER = "PersonIdentifier"; + public static final String eIDAS_ATTR_DATEOFBIRTH = "DateOfBirth"; + public static final String eIDAS_ATTR_CURRENTGIVENNAME = "FirstName"; + public static final String eIDAS_ATTR_CURRENTFAMILYNAME = "FamilyName"; + public static final String eIDAS_ATTR_LEGALPERSONIDENTIFIER = "LegalPersonIdentifier"; + public static final String eIDAS_ATTR_LEGALNAME = "LegalName"; + + public static final List NATURALPERSONMINIMUMDATASETLIST = Collections.unmodifiableList(new ArrayList() { + private static final long serialVersionUID = 1L; + { + //TODO: find correct location of attribute definitions +// add(eu.eidas.auth.engine.core.eidas.spec.NaturalPersonSpec.Definitions.CURRENT_FAMILY_NAME.getNameUri()); +// add(eu.eidas.auth.engine.core.eidas.spec.NaturalPersonSpec.Definitions.CURRENT_GIVEN_NAME.getNameUri()); +// add(eu.eidas.auth.engine.core.eidas.spec.NaturalPersonSpec.Definitions.DATE_OF_BIRTH.getNameUri()); +// add(eu.eidas.auth.engine.core.eidas.spec.NaturalPersonSpec.Definitions.PERSON_IDENTIFIER.getNameUri()); + } + }); + + public static final String POLICY_DEFAULT_ALLOWED_TARGETS = + EAAFConstants.URN_PREFIX_CDID.replaceAll("\\.", "\\\\.").replaceAll("\\+", "\\\\+") + ".*"; + + //SAML2 Constants + public static final String SUCCESS_URI = "urn:oasis:names:tc:SAML:2.0:status:Success"; + + public static final String HTTP_CLIENT_DEFAULT_TIMEOUT_CONNECTION = "30"; //seconds + public static final String HTTP_CLIENT_DEFAULT_TIMEOUT_RESPONSE = "60"; //seconds + + + //Default values for SZR communication + public static final String SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE = "ELEKTR_DOKUMENT"; + + //TODO remove!!! + public static final String SZR_CONSTANTS_DEFAULT_ISSUING_DATE = "2014-01-01"; + public static final String SZR_CONSTANTS_DEFAULT_ISSUING_AUTHORITY = "ms-specific eIDAS-Node for AT"; + public final static byte[] SZR_CONSTANTS_DEFAULT_PUBL_KEY = new byte[] {48, -127, -97, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3, -127, -115, 0, 48, -127, -119, 2, -127, -127, 0, -106, 114, -113, -1, -84, 116, 35, 3, 70, -81, 81, -110, -10, -59, 114, 4, -109, 86, 127, -50, 125, 47, 4, 80, 79, 53, 117, -36, 15, -16, -61, 110, 39, 89, 29, -43, 37, -127, 80, -109, -38, 65, 125, -119, 44, -111, -21, 47, -98, 38, -112, -24, 107, -110, 17, -10, 51, -4, -36, -72, -28, -18, -14, 117, -67, 76, -31, 32, 92, 104, -21, 68, 31, -12, 30, -104, -104, 42, -107, 126, 84, 50, 85, -117, 44, -100, -4, 102, -100, 52, -68, 77, -32, 9, -16, -30, -104, -90, 107, -88, 7, 97, -94, 72, -61, -40, 80, -112, -65, -25, -72, -19, -95, -54, 31, 15, 24, -105, 123, -81, 23, -123, 92, -103, -101, 47, 47, -105, 2, 3, 1, 0, 1}; + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationModulImpl.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationModulImpl.java new file mode 100644 index 00000000..39be3fbd --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationModulImpl.java @@ -0,0 +1,53 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2; + +import org.apache.commons.lang3.StringUtils; + +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; + +/** + * @author tlenz + * + */ +public class eIDASAuthenticationModulImpl implements AuthModule { + + private int priority = 1; + + @Override + public int getPriority() { + return priority; + } + + /** + * Sets the priority of this module. Default value is {@code 0}. + * @param priority The priority. + */ + public void setPriority(int priority) { + this.priority = priority; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#selectProcess(at.gv.egovernment.moa.id.process.api.ExecutionContext) + */ + @Override + public String selectProcess(ExecutionContext context) { + if (StringUtils.isNotBlank((String) context.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_COUNTRY)) || + StringUtils.isNotBlank((String) context.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_COUNTRY))) + return "eIDASAuthentication_v2"; + else + return null; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getProcessDefinitions() + */ + @Override + public String[] getProcessDefinitions() { + return new String[] { "classpath:eIDAS.Authentication.process.xml" }; + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationSpringResourceProvider.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationSpringResourceProvider.java new file mode 100644 index 00000000..d44ef348 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationSpringResourceProvider.java @@ -0,0 +1,30 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import at.gv.egiz.components.spring.api.SpringResourceProvider; + +public class eIDASAuthenticationSpringResourceProvider implements SpringResourceProvider { + + @Override + public String getName() { + return "Auth. module for eIDAS Ref. Impl. v2.x"; + } + + @Override + public String[] getPackagesToScan() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Resource[] getResourcesToLoad() { + ClassPathResource eIDASAuthConfig = new ClassPathResource("/eidas_v2_auth.beans.xml", eIDASAuthenticationSpringResourceProvider.class); + + return new Resource[] {eIDASAuthConfig}; + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASSignalServlet.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASSignalServlet.java new file mode 100644 index 00000000..41e2aa03 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/eIDASSignalServlet.java @@ -0,0 +1,131 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.google.common.collect.ImmutableSortedSet; + +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASAuthenticationException; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.service.eIDASAttributeRegistry; +import at.gv.egiz.eaaf.core.impl.idp.controller.AbstractProcessEngineSignalController; +import eu.eidas.auth.commons.EidasParameterKeys; +import eu.eidas.auth.commons.light.ILightResponse; +import eu.eidas.specificcommunication.SpecificCommunicationDefinitionBeanNames; +import eu.eidas.specificcommunication.exception.SpecificCommunicationException; +import eu.eidas.specificcommunication.protocol.impl.SpecificConnectorCommunicationServiceImpl; + + +/** + * @author tlenz + * + */ +@Controller +public class eIDASSignalServlet extends AbstractProcessEngineSignalController { + + private static final Logger log = LoggerFactory.getLogger(eIDASSignalServlet.class); + @Autowired private ApplicationContext context; + @Autowired private eIDASAttributeRegistry attrRegistry; + + public eIDASSignalServlet() { + super(); + log.debug("Registering servlet " + getClass().getName() + + " with mappings '"+ Constants.eIDAS_HTTP_ENDPOINT_SP_POST + + "' and '"+ Constants.eIDAS_HTTP_ENDPOINT_SP_REDIRECT + "'."); + + } + + @RequestMapping(value = { Constants.eIDAS_HTTP_ENDPOINT_SP_POST, + Constants.eIDAS_HTTP_ENDPOINT_SP_REDIRECT + }, + method = {RequestMethod.POST, RequestMethod.GET}) + public void restoreEidasAuthProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException { + signalProcessManagement(req, resp); + } + + + /** + * Protocol specific implementation to get the pending-requestID + * from http request object + * + * @param request The http Servlet-Request object + * @return The Pending-request id + * + */ + @Override + public String getPendingRequestId(HttpServletRequest request) { + //String sessionId = super.getPendingRequestId(request); + + try { + //get token from Request + final String tokenBase64 = request.getParameter(EidasParameterKeys.TOKEN.toString()); + if (StringUtils.isEmpty(tokenBase64)) { + log.warn("NO eIDAS message token found."); + throw new eIDASAuthenticationException("eidas.04", null); + + } + log.trace("Receive eIDAS-node token: " + tokenBase64 + " Starting transaction-restore process ... "); + + + + final SpecificConnectorCommunicationServiceImpl specificConnectorCommunicationService = + (SpecificConnectorCommunicationServiceImpl) context.getBean(SpecificCommunicationDefinitionBeanNames.SPECIFIC_CONNECTOR_COMMUNICATION_SERVICE.toString()); + ILightResponse eIDASResponse = specificConnectorCommunicationService.getAndRemoveResponse(tokenBase64, + ImmutableSortedSet.copyOf(attrRegistry.getCoreAttributeRegistry().getAttributes())); + + String pendingReqId = null; + if (StringUtils.isEmpty(eIDASResponse.getRelayState())) { + log.debug("eIDAS Node returns no RelayState. "); + + if (authConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_NODE_WORKAROUND_USEREQUESTIDASTRANSACTIONIDENTIFIER, + false)) { + log.trace("Use lightRequestId to recover session ... "); + pendingReqId = transactionStorage.get(eIDASResponse.getInResponseToId(), String.class); + if (StringUtils.isNotEmpty(pendingReqId)) { + log.debug("Restoring session with lightRequestId ... "); + transactionStorage.remove(eIDASResponse.getInResponseToId()); + + } + } + + } else { + log.debug("Find transaction identifier in SAML2 'RelayState': " + eIDASResponse.getRelayState()); + pendingReqId = eIDASResponse.getRelayState(); + + } + + if (StringUtils.isNotEmpty(pendingReqId)) { + request.setAttribute(Constants.DATA_FULL_EIDAS_RESPONSE, eIDASResponse); + return pendingReqId; + + } + + log.info("NO transaction identifier found! Stopping process ...."); + log.trace("FullResponse: " + eIDASResponse.toString()); + + } catch (SpecificCommunicationException e) { + log.warn("Can NOT load eIDAS Response from cache.", e); + log.debug("eIDAS response token was: " + request.getParameter(EidasParameterKeys.TOKEN.toString())); + + } catch (Exception e) { + log.warn("Unable to retrieve moa session id.", e); + + } + + return null; + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/SZRCommunicationException.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/SZRCommunicationException.java new file mode 100644 index 00000000..defc03db --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/SZRCommunicationException.java @@ -0,0 +1,15 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception; + +public class SZRCommunicationException extends eIDASAuthenticationException { + + private static final long serialVersionUID = 1L; + + public SZRCommunicationException(String internalMsgId, Object[] params) { + super(internalMsgId, params); + } + + public SZRCommunicationException(String internalMsgId, Object[] params, Throwable e) { + super(internalMsgId, params, e); + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAttributeException.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAttributeException.java new file mode 100644 index 00000000..2ce9fcd7 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAttributeException.java @@ -0,0 +1,15 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception; + +public class eIDASAttributeException extends eIDASAuthenticationException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public eIDASAttributeException(String attrbuteName) { + super("eidas.00", new Object[] {attrbuteName}); + + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAuthenticationException.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAuthenticationException.java new file mode 100644 index 00000000..93298a92 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAuthenticationException.java @@ -0,0 +1,20 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception; + +import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; + +public class eIDASAuthenticationException extends EAAFAuthenticationException{ + + /** + * + */ + private static final long serialVersionUID = 1L; + + public eIDASAuthenticationException(String internalMsgId, Object[] params) { + super(internalMsgId, params); + } + + public eIDASAuthenticationException(String internalMsgId, Object[] params, Throwable e) { + super(internalMsgId, params, e); + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASValidationException.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASValidationException.java new file mode 100644 index 00000000..2bac7d04 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASValidationException.java @@ -0,0 +1,14 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception; + +public class eIDASValidationException extends eIDASAuthenticationException { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public eIDASValidationException(String internalMsgId, Object[] params) { + super(internalMsgId, params); + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/service/eIDASAttributeRegistry.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/service/eIDASAttributeRegistry.java new file mode 100644 index 00000000..de9f6455 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/service/eIDASAttributeRegistry.java @@ -0,0 +1,115 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.service; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.Constants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; +import eu.eidas.auth.commons.attribute.AttributeRegistries; +import eu.eidas.auth.commons.attribute.AttributeRegistry; + +@Service("attributeRegistry") +public class eIDASAttributeRegistry { + private static final Logger log = LoggerFactory.getLogger(eIDASAttributeRegistry.class); + @Autowired private IConfiguration basicConfig; + + private AttributeRegistry coreAttributeRegistry; + + private String eidasAttributesFile; + private String additionalAttributesFile; + + @PostConstruct + private void initialize() throws RuntimeException { + try { + if (eidasAttributesFile.isEmpty()) { + log.error("Basic eIDAS addribute definition NOT defined"); + throw new EAAFConfigurationException("config.30", + new Object[] {"eidas-attributes.xml"}); + + } + + boolean additionalAttrAvailabe = false; + if (!additionalAttributesFile.isEmpty()) { + File file = new File(additionalAttributesFile); + if (file.exists()) + additionalAttrAvailabe = true; + + } + + if (!additionalAttrAvailabe) { + log.info("Start eIDAS ref. impl. Core without additional eIDAS attribute definitions ... "); + coreAttributeRegistry = AttributeRegistries.fromFiles(eidasAttributesFile, null); + + } else { + //load attribute definitions + log.info("Start eIDAS ref. impl. Core with additional eIDAS attribute definitions ... "); + coreAttributeRegistry = AttributeRegistries.fromFiles(eidasAttributesFile, null, additionalAttributesFile); + + } + + } catch (Throwable e) { + log.error("Can NOT initialize eIDAS attribute definition." , e); + new RuntimeException("Can NOT initialize eIDAS attribute definition.", e); + + } + } + + + public AttributeRegistry getCoreAttributeRegistry() { + return coreAttributeRegistry; + } + + public Map getAttributeSetFromConfiguration() { + Map result = new HashMap(); + + /*TODO: select set for representation if mandates should be used. + * It's an open task in respect to requested eIDAS attributes and isRequired flag, + * because there can be a decision problem in case of natural or legal person representation! + * From an Austrian use-case point of view, an Austrian service provider can support mandates for + * natural and legal persons at the same time. However, we CAN NOT request attributes for natural AND + * legal persons on the same time, because it's not possible to represent both simultaneously. + */ + Map configAttributes = + basicConfig.getBasicMOAIDConfigurationWithPrefix( + Constants.CONIG_PROPS_EIDAS_NODE_ATTRIBUTES_REQUESTED_ONLYNATURAL); + for (String el: configAttributes.values()) { + if (StringUtils.isNotEmpty(el.trim())) { + List attrDef = KeyValueUtils.getListOfCSVValues(el.trim()); + boolean isRequired = false; + if (attrDef.size() == 2) + isRequired = Boolean.parseBoolean(attrDef.get(1)); + + result.put(attrDef.get(0), isRequired); + + } + } + + log.trace("Load #" + result.size() + " requested attributes from configuration"); + return result; + + } + + + public void setEidasAttributesFile(String eidasAttributesFile) { + this.eidasAttributesFile = eidasAttributesFile; + } + + public void setAdditionalAttributesFile(String additionalAttributesFile) { + this.additionalAttributesFile = additionalAttributesFile; + } + + +} + diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/szr/SZRClient.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/szr/SZRClient.java new file mode 100644 index 00000000..cec36d4b --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/szr/SZRClient.java @@ -0,0 +1,372 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.szr; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.URL; +import java.security.KeyManagementException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.security.UnrecoverableKeyException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.namespace.QName; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.stream.StreamResult; +import javax.xml.transform.stream.StreamSource; +import javax.xml.ws.BindingProvider; +import javax.xml.ws.Dispatch; +import javax.xml.ws.WebServiceContext; +import javax.xml.ws.handler.Handler; + +import org.apache.commons.lang3.StringUtils; +import org.apache.cxf.configuration.jsse.TLSClientParameters; +import org.apache.cxf.endpoint.Client; +import org.apache.cxf.frontend.ClientProxy; +import org.apache.cxf.jaxws.DispatchImpl; +import org.apache.cxf.transport.http.HTTPConduit; +import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; +import org.apache.xpath.XPathAPI; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.w3._2000._09.xmldsig.KeyValueType; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.Constants; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception.SZRCommunicationException; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.utils.LoggingHandler; +import at.gv.egiz.eaaf.core.api.data.XMLNamespaceConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; +import szrservices.GetBPK; +import szrservices.GetBPKResponse; +import szrservices.GetIdentityLink; +import szrservices.GetIdentityLinkResponse; +import szrservices.IdentityLinkType; +import szrservices.PersonInfoType; +import szrservices.SZR; +import szrservices.SZRException_Exception; + +@Service("SZRClientForeIDAS") +public class SZRClient { + private static final Logger log = LoggerFactory.getLogger(SZRClient.class); + + private static final String CLIENT_DEFAULT = "DefaultClient"; + private static final String CLIENT_RAW = "RawClient"; + + @Autowired private IConfiguration basicConfig; + @Resource private WebServiceContext wsContext; + + //client for anything, without identitylink + private SZR szr = null; + + //RAW client is needed for identitylink + private Dispatch dispatch = null; + + + private SZRService szrService = null; + private String szrURL = null; + private QName qname = null; + + public IdentityLinkType getIdentityLink(PersonInfoType personInfo, List keyValue, Boolean insertERnP) throws SZRCommunicationException { + try { + return szr.getIdentityLink( + personInfo, + keyValue, + insertERnP); + + } catch (SZRException_Exception e) { + log.warn("SZR communication FAILED. Reason: " + e.getMessage(), e); + throw new SZRCommunicationException("ernb.02", new Object[] {e.getMessage()}, e); + + } + + } + + public IdentityLinkType getIdentityLinkInRawMode(PersonInfoType personInfo, List keyValue, Boolean insertERnP) throws SZRCommunicationException { + try { + GetIdentityLink getIDL = new GetIdentityLink(); + getIDL.setInsertERnP(insertERnP); + getIDL.setPersonInfo(personInfo); + getIDL.getKeyValue().addAll(keyValue); + + JAXBContext jaxbContext = JAXBContext.newInstance(GetIdentityLink.class); + Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); + + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + jaxbMarshaller.marshal(getIDL, outputStream); + outputStream.flush(); + + Source source = new StreamSource(new ByteArrayInputStream(outputStream.toByteArray())); + outputStream.close(); + + log.trace("Requesting SZR ... "); + Source response = dispatch.invoke(source); + log.trace("Receive RAW response from SZR"); + + byte[] szrResponse = sourceToByteArray(response); + JAXBContext ctx = JAXBContext.newInstance(IdentityLinkType.class + .getPackage().getName()); + GetIdentityLinkResponse jaxbElement = (GetIdentityLinkResponse) ctx + .createUnmarshaller().unmarshal(new ByteArrayInputStream(szrResponse)); + + + //build response + log.trace(new String(szrResponse)); + log.trace("Signature successfully created. Extracting from MOA-SS container."); + + // ok, we have success + Document doc = DOMUtils.parseDocument( + new ByteArrayInputStream(szrResponse), + true, XMLNamespaceConstants.ALL_SCHEMA_LOCATIONS, null, null + ); + String xpathExpression = "//saml:Assertion"; + Element nsNode = doc.createElementNS("urn:oasis:names:tc:SAML:1.0:assertion", "saml:NSNode"); + + log.trace("Selecting signed doc " + xpathExpression); + Element documentNode = (Element) XPathAPI.selectSingleNode(doc, + xpathExpression, nsNode); + log.trace("Signed document: " + DOMUtils.serializeNode(documentNode)); + + + IdentityLinkType idl = new IdentityLinkType(); + idl.setAssertion(documentNode); + idl.setPersonInfo(jaxbElement.getGetIdentityLinkReturn().getPersonInfo()); + + return idl; + + + //IdentityLinkType idlResp = this.szr.getIdentityLink(personInfo, keyValue, insertERnP); + + } catch ( Exception e) { + log.warn("SZR communication FAILED. Reason: " + e.getMessage(), e); + throw new SZRCommunicationException("ernb.02", new Object[] {e.getMessage()}, e); + + } + + } + + public String getBPK(PersonInfoType personInfo, String target, String vkz) throws SZRCommunicationException { + try { + GetBPK parameters = new GetBPK(); + parameters.setPersonInfo(personInfo); + parameters.setBereichsKennung(target); + parameters.setVKZ(vkz); + GetBPKResponse result = this.szr.getBPK(parameters); + + return result.getGetBPKReturn(); + + } catch (SZRException_Exception e) { + log.warn("SZR communication FAILED. Reason: " + e.getMessage(), e); + throw new SZRCommunicationException("ernb.02", new Object[] {e.getMessage()}, e); + + } + + } + + + @PostConstruct + private void initialize() { + log.info("Starting SZR-Client initialization .... "); + URL url = SZRClient.class.getResource("/szr_client/SZR-1.WSDL"); + + boolean useTestSZR = basicConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_USETESTSERVICE, + true); + + if (useTestSZR) { + log.debug("Initializing SZR test environment configuration."); + qname = SZRService.SZRTestumgebung; + szrService = new SZRService(url, new QName("urn:SZRServices", "SZRService")); + szr = szrService.getSZRTestumgebung(); + szrURL = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_ENDPOINT_TEST); + + + } else { + log.debug("Initializing SZR productive configuration."); + qname = SZRService.SZRProduktionsumgebung; + szrService = new SZRService(url, new QName("urn:SZRServices", "SZRService")); + szr = szrService.getSZRProduktionsumgebung(); + szrURL = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_ENDPOINT_PROD); + + } + + //create raw client; + dispatch = szrService.createDispatch(qname, Source.class, javax.xml.ws.Service.Mode.PAYLOAD); + + if (StringUtils.isEmpty(szrURL)) { + log.error("No SZR service-URL found. SZR-Client initalisiation failed."); + throw new RuntimeException("No SZR service URL found. SZR-Client initalisiation failed."); + + } + + log.info("Use SZR service-URL: " + szrURL); + injectBindingProvider((BindingProvider) szr, CLIENT_DEFAULT); + injectBindingProvider((BindingProvider) dispatch, CLIENT_RAW); + + log.debug("Inject HTTP client settings ... "); + injectHTTPClient(szr, CLIENT_DEFAULT); + injectHTTPClient(dispatch, CLIENT_RAW); + + log.info("SZR-Client initialization successfull"); + } + + private void injectHTTPClient(Object raw, String clientType) { + //extract client from implementation + Client client = null; + if (raw instanceof DispatchImpl) + client = ((DispatchImpl)raw).getClient(); + else if (raw instanceof Client) + client = ClientProxy.getClient(raw); + else + throw new RuntimeException("SOAP Client for SZR connection is of UNSUPPORTED type: " + raw.getClass().getName()); + + //set basic connection policies + HTTPConduit http = (HTTPConduit) client.getConduit(); + + //set timeout policy + HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); + httpClientPolicy.setConnectionTimeout( + Integer.parseInt(basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_TIMEOUT_CONNECTION, + Constants.HTTP_CLIENT_DEFAULT_TIMEOUT_CONNECTION)) * 1000); + httpClientPolicy.setReceiveTimeout( + Integer.parseInt(basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_TIMEOUT_RESPONSE, + Constants.HTTP_CLIENT_DEFAULT_TIMEOUT_RESPONSE)) * 1000); + http.setClient(httpClientPolicy); + + //inject SSL context in case of https + if (szrURL.toLowerCase().startsWith("https")) { + log.debug("Adding SSLContext to client: " + clientType +" ... "); + TLSClientParameters tlsParams = new TLSClientParameters(); + tlsParams.setSSLSocketFactory(createSSLContext(clientType).getSocketFactory()); + http.setTlsClientParameters(tlsParams ); + log.info("SSLContext initialized for client: " + clientType); + + } + + } + + private void injectBindingProvider(BindingProvider bindingProvider, String clientType) { + Map requestContext = bindingProvider.getRequestContext(); + requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, szrURL); + + log.trace("Adding JAX-WS request/response trace handler to client: " + clientType); + List handlerList = bindingProvider.getBinding().getHandlerChain(); + if (handlerList == null) { + handlerList = new ArrayList(); + bindingProvider.getBinding().setHandlerChain(handlerList); + + } + + //add logging handler to trace messages if required + if (basicConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_TRACEMESSAGES, + false)) { + LoggingHandler loggingHandler = new LoggingHandler(); + handlerList.add(loggingHandler); + + } + } + + private SSLContext createSSLContext(String clientType) { + try { + SSLContext context = SSLContext.getInstance("TLS"); + + //initialize key-mangager for SSL client-authentication + KeyManager[] keyManager = null; + String keyStorePath = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_SSL_KEYSTORE_PATH); + String keyStorePassword = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_SSL_KEYSTORE_PASSWORD); + if (StringUtils.isNotEmpty(keyStorePath)) { + log.trace("Find keyStore path: " + keyStorePath + " Injecting SSL client certificate ... "); + try { + KeyStore keyStore = KeyStoreUtils.loadKeyStore( + FileUtils.makeAbsoluteURL(keyStorePath, basicConfig.getConfigurationRootDirectory()), + keyStorePassword); + + KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); + kmf.init(keyStore, keyStorePassword.toCharArray()); + keyManager = kmf.getKeyManagers(); + log.debug("SSL client certificate injected to client: " + clientType); + + } catch (KeyStoreException | IOException | UnrecoverableKeyException e) { + log.error("Can NOT load SSL client certificate from path: " + keyStorePath); + throw new RuntimeException("Can NOT load SSL client certificate from path: " + keyStorePath, e); + + } + } + + + //initialize SSL TrustStore + TrustManager[] trustManager = null; + String trustStorePath = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_SSL_TRUSTSTORE_PATH); + String trustStorePassword = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_SSL_TRUSTSTORE_PASSWORD); + if (StringUtils.isNotEmpty(trustStorePath)) { + log.trace("Find trustStore path: " + trustStorePath + " Injecting SSL TrustStore ... "); + try { + KeyStore trustStore = KeyStoreUtils.loadKeyStore( + FileUtils.makeAbsoluteURL(trustStorePath, basicConfig.getConfigurationRootDirectory()), + trustStorePassword); + + TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); + tmf.init(trustStore); + trustManager = tmf.getTrustManagers(); + log.debug("SSL TrustStore injected to client: " + clientType); + + } catch (KeyStoreException | IOException e) { + log.error("Can NOT open SSL TrustStore from path: " + trustStorePath); + throw new RuntimeException("Can NOT open SSL TrustStore from path: " + trustStorePath, e); + + } + + } + + + context.init(keyManager, trustManager, new SecureRandom()); + return context; + + } catch (NoSuchAlgorithmException | KeyManagementException e) { + log.error("SSLContext initialization FAILED.", e); + throw new RuntimeException("SSLContext initialization FAILED.", e); + + } + + } + + private byte[] sourceToByteArray(Source result) throws TransformerException { + TransformerFactory factory = TransformerFactory.newInstance(); + Transformer transformer = factory.newTransformer(); + transformer.setOutputProperty("omit-xml-declaration", "yes"); + transformer.setOutputProperty("method", "xml"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + StreamResult streamResult = new StreamResult(); + streamResult.setOutputStream(out); + transformer.transform(result, streamResult); + return out.toByteArray(); + } + + + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/szr/SZRService.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/szr/SZRService.java new file mode 100644 index 00000000..ce2a1324 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/szr/SZRService.java @@ -0,0 +1,139 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.szr; + +import java.net.URL; + +import javax.xml.namespace.QName; +import javax.xml.ws.Service; +import javax.xml.ws.WebEndpoint; +import javax.xml.ws.WebServiceClient; +import javax.xml.ws.WebServiceFeature; + +import szrservices.SZR; + +/** + * This class was generated by Apache CXF 3.1.16 + * 2018-07-10T09:36:01.466+02:00 + * Generated source version: 3.1.16 + * + */ +@WebServiceClient(name = "SZRService", + wsdlLocation = "./src/main/resources/szr_client/SZR-1.WSDL", + targetNamespace = "urn:SZRServices") +public class SZRService extends Service { + + public final static URL WSDL_LOCATION; + + public final static QName SERVICE = new QName("urn:SZRServices", "SZRService"); + public final static QName SZRProduktionsumgebung = new QName("urn:SZRServices", "SZRProduktionsumgebung"); + public final static QName SZRTestumgebung = new QName("urn:SZRServices", "SZRTestumgebung"); + public final static QName SZRBusinesspartnerTestumgebung = new QName("urn:SZRServices", "SZRBusinesspartnerTestumgebung"); + static { + URL url = SZRService.class.getResource("./src/main/resources/szr_client/SZR-1.WSDL"); + if (url == null) { + url = SZRService.class.getClassLoader().getResource("/szr_client/SZR-1.WSDL"); + } + if (url == null) { + java.util.logging.Logger.getLogger(SZRService.class.getName()) + .log(java.util.logging.Level.INFO, + "Can not initialize the default wsdl from {0}", "/szr_client/SZR-1.WSDL"); + } + WSDL_LOCATION = url; + + } + + public SZRService(URL wsdlLocation) { + super(wsdlLocation, SERVICE); + } + + public SZRService(URL wsdlLocation, QName serviceName) { + super(wsdlLocation, serviceName); + } + + public SZRService() { + super(WSDL_LOCATION, SERVICE); + } + + public SZRService(WebServiceFeature ... features) { + super(WSDL_LOCATION, SERVICE, features); + } + + public SZRService(URL wsdlLocation, WebServiceFeature ... features) { + super(wsdlLocation, SERVICE, features); + } + + public SZRService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) { + super(wsdlLocation, serviceName, features); + } + + + + + /** + * + * @return + * returns SZR + */ + @WebEndpoint(name = "SZRProduktionsumgebung") + public SZR getSZRProduktionsumgebung() { + return super.getPort(SZRProduktionsumgebung, SZR.class); + } + + /** + * + * @param features + * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. + * @return + * returns SZR + */ + @WebEndpoint(name = "SZRProduktionsumgebung") + public SZR getSZRProduktionsumgebung(WebServiceFeature... features) { + return super.getPort(SZRProduktionsumgebung, SZR.class, features); + } + + + /** + * + * @return + * returns SZR + */ + @WebEndpoint(name = "SZRTestumgebung") + public SZR getSZRTestumgebung() { + return super.getPort(SZRTestumgebung, SZR.class); + } + + /** + * + * @param features + * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. + * @return + * returns SZR + */ + @WebEndpoint(name = "SZRTestumgebung") + public SZR getSZRTestumgebung(WebServiceFeature... features) { + return super.getPort(SZRTestumgebung, SZR.class, features); + } + + + /** + * + * @return + * returns SZR + */ + @WebEndpoint(name = "SZRBusinesspartnerTestumgebung") + public SZR getSZRBusinesspartnerTestumgebung() { + return super.getPort(SZRBusinesspartnerTestumgebung, SZR.class); + } + + /** + * + * @param features + * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. + * @return + * returns SZR + */ + @WebEndpoint(name = "SZRBusinesspartnerTestumgebung") + public SZR getSZRBusinesspartnerTestumgebung(WebServiceFeature... features) { + return super.getPort(SZRBusinesspartnerTestumgebung, SZR.class, features); + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/CreateIdentityLinkTask.java new file mode 100644 index 00000000..c5d33b73 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/CreateIdentityLinkTask.java @@ -0,0 +1,380 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.tasks; + +import java.io.InputStream; +import java.math.BigInteger; +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.interfaces.RSAPublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.StringUtils; +import org.joda.time.DateTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.Base64Utils; +import org.w3._2000._09.xmldsig.KeyValueType; +import org.w3._2000._09.xmldsig.RSAKeyValueType; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; + +import at.asitplus.eidas.specific.connector.MSConnectorEventCodes; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.Constants; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception.SZRCommunicationException; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASAttributeException; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.szr.SZRClient; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.utils.eIDASResponseUtils; +import at.gv.e_government.reference.namespace.persondata._20020228.PersonNameType; +import at.gv.e_government.reference.namespace.persondata._20020228.PhysicalPersonType; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.data.Trible; +import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BPKBuilder; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; +import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; +import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; +import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.AttributeValue; +import eu.eidas.auth.commons.light.ILightResponse; +import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress; +import szrservices.IdentityLinkType; +import szrservices.PersonInfoType; +import szrservices.TravelDocumentType; + +/** + * @author tlenz + * + */ +@Component("CreateIdentityLinkTask") +public class CreateIdentityLinkTask extends AbstractAuthServletTask { + private static final Logger log = LoggerFactory.getLogger(CreateIdentityLinkTask.class); + + //@Autowired private eIDASAttributeRegistry attrRegistry; + @Autowired private IConfiguration basicConfig; + @Autowired private SZRClient szrClient; + + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, + HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try{ + AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + ILightResponse eIDASResponse = authProcessData.getGenericDataFromSession( + Constants.DATA_FULL_EIDAS_RESPONSE, ILightResponse.class); + Map simpleAttrMap = converteIDASAttrToSimpleMap(eIDASResponse.getAttributes().getAttributeMap()); + + IIdentityLink identityLink = null; + String bPK = null; + + //extract attributes + Object eIdentifierObj = simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER); + Object familyNameObj = simpleAttrMap.get(Constants.eIDAS_ATTR_CURRENTFAMILYNAME); + Object givenNameObj = simpleAttrMap.get(Constants.eIDAS_ATTR_CURRENTGIVENNAME); + Object dateOfBirthObj = simpleAttrMap.get(Constants.eIDAS_ATTR_DATEOFBIRTH); + + //check if availabe + if (eIdentifierObj == null || !(eIdentifierObj instanceof String)) + throw new eIDASAttributeException(Constants.eIDAS_ATTR_PERSONALIDENTIFIER); + + if (familyNameObj == null || !(familyNameObj instanceof String)) + throw new eIDASAttributeException(Constants.eIDAS_ATTR_CURRENTFAMILYNAME); + + if (givenNameObj == null || !(givenNameObj instanceof String)) + throw new eIDASAttributeException(Constants.eIDAS_ATTR_CURRENTGIVENNAME); + + if (dateOfBirthObj == null || !(dateOfBirthObj instanceof DateTime)) + throw new eIDASAttributeException(Constants.eIDAS_ATTR_DATEOFBIRTH); + + //connect SZR-Gateway + if(basicConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USEDUMMY, false)) { + log.warn("SZR-Dummy IS ACTIVE! IdentityLink is NOT VALID!!!!"); + // create fake IdL + // - fetch IdL template from resources + InputStream s = CreateIdentityLinkTask.class.getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); + Element idlTemplate = DOMUtils.parseXmlValidating(s); + + identityLink = new SimpleIdentityLinkAssertionParser(idlTemplate).parseIdentityLink(); + + // replace data + Element idlassertion = identityLink.getSamlAssertion(); + + // - set fake baseID; + Node prIdentification = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); + prIdentification.getFirstChild().setNodeValue((String) eIdentifierObj); + + //build personal identifier which looks like a baseID +// String fakeBaseID = new BPKBuilder().buildBPK(eIdentifier, "baseID"); +// Logger.info("Map eIDAS eIdentifier:" + eIdentifier + " to fake baseID:" + fakeBaseID); +// prIdentification.getFirstChild().setNodeValue(fakeBaseID); + + // - set last name + Node prFamilyName = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH); + prFamilyName.getFirstChild().setNodeValue((String) familyNameObj); + + // - set first name + Node prGivenName = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH); + prGivenName.getFirstChild().setNodeValue((String) givenNameObj); + + // - set date of birth + Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH); + String formatedDateOfBirth = new SimpleDateFormat("yyyy-MM-dd").format(((DateTime)dateOfBirthObj).toDate()); + prDateOfBirth.getFirstChild().setNodeValue(formatedDateOfBirth); + + identityLink = new SimpleIdentityLinkAssertionParser(idlassertion).parseIdentityLink(); + + Pair bPKCalc = new BPKBuilder().generateAreaSpecificPersonIdentifier( + identityLink.getIdentificationValue(), + identityLink.getIdentificationType(), + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + bPK = bPKCalc.getFirst(); + + + } else { + //contact SZR Gateway + log.debug("Starting connecting SZR Gateway"); + PersonInfoType personInfo = new PersonInfoType(); + PersonNameType personName = new PersonNameType(); + PhysicalPersonType naturalPerson = new PhysicalPersonType(); + TravelDocumentType eDocument = new TravelDocumentType(); + + naturalPerson.setName(personName ); + personInfo.setPerson(naturalPerson ); + personInfo.setTravelDocument(eDocument ); + + //parse some eID attributes + String dateOfBirth = new SimpleDateFormat("yyyy-MM-dd").format(((DateTime)dateOfBirthObj).toDate()); + Trible eIdentifier = + eIDASResponseUtils.parseEidasPersonalIdentifier((String)eIdentifierObj); + String uniqueId = (String)eIdentifierObj; + String citizenCountry = eIdentifier.getFirst(); + + //person information + personName.setFamilyName((String)familyNameObj); + personName.setGivenName((String)givenNameObj); + naturalPerson.setDateOfBirth(dateOfBirth); + eDocument.setIssuingCountry(citizenCountry); + eDocument.setDocumentNumber(uniqueId); + + //eID document information + eDocument.setDocumentType(basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, + Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); + + //TODO: that should be removed + eDocument.setIssueDate(basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_DATE, + Constants.SZR_CONSTANTS_DEFAULT_ISSUING_DATE)); + eDocument.setIssuingAuthority(basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_AUTHORITY, + Constants.SZR_CONSTANTS_DEFAULT_ISSUING_AUTHORITY)); + + //TODO: keys are not available in eIDAS + List keyValue = dummyCodeForKeys(); + + /*TODO: + * Validate if IDL signature is valid after using this method + * MAYBE we had to switch to 'getIdentityLinkInRawMode' method! + */ + IdentityLinkType result = szrClient.getIdentityLink( + personInfo, + keyValue, + basicConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_INSERTERNB, + true) + ); + + Element idlFromSZR = (Element)result.getAssertion(); + identityLink = new SimpleIdentityLinkAssertionParser(idlFromSZR).parseIdentityLink(); + + + //get bPK from SZR + bPK = szrClient.getBPK( + personInfo, + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), + basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, + "no VKZ defined")); + + } + + if (identityLink == null) { + log.error("ERnB did not return an identity link."); + throw new SZRCommunicationException("ernb.00", null); + + } + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.SZR_IDL_RECEIVED); + + + if (bPK == null) { + log.error("ERnB did not return a bPK for target: " + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + throw new SZRCommunicationException("ernb.01", null); + + } + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.SZR_BPK_RECEIVED); + + log.debug("ERnB communication was successfull"); + + authProcessData.setForeigner(true); + authProcessData.setIdentityLink(identityLink); + authProcessData.setGenericDataToSession( + PVPAttributeDefinitions.EID_ISSUING_NATION_NAME, + eIDASResponseUtils.parseEidasPersonalIdentifier((String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)).getFirst()); + + //set bPK and bPKType into auth session + authProcessData.setGenericDataToSession( + PVPAttributeDefinitions.BPK_NAME, + extendBPKbyPrefix( + bPK, + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()) + ); + authProcessData.setGenericDataToSession( + PVPAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); + + + + //store pending-request + requestStoreage.storePendingRequest(pendingReq); + + } catch (eIDASAttributeException e) { + throw new TaskExecutionException(pendingReq, "Minimum required eIDAS attributeset not found.", e); + + } catch (EAAFException e) { + throw new TaskExecutionException(pendingReq, "IdentityLink generation for foreign person FAILED.", e); + + } catch (Exception e) { + log.error("IdentityLink generation for foreign person FAILED.", e); + throw new TaskExecutionException(pendingReq, "IdentityLink generation for foreign person FAILED.", e); + + } + } + + private List dummyCodeForKeys() { + if (basicConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_KEYS_USEDUMMY, + false)) { + List keyvalueList = new ArrayList(); + try { + PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Constants.SZR_CONSTANTS_DEFAULT_PUBL_KEY); + KeyFactory kf = KeyFactory.getInstance("RSA"); + + PublicKey pb = kf.generatePublic(spec); + + RSAPublicKey rsapb = (RSAPublicKey)pb; + BigInteger modulus = rsapb.getModulus(); + BigInteger exponent = rsapb.getPublicExponent(); + + // set key values + RSAKeyValueType rsa = new RSAKeyValueType(); + rsa.setExponent(new String(Base64Utils.encode(exponent.toByteArray()))); + rsa.setModulus(new String(Base64Utils.encode(modulus.toByteArray()))); + + KeyValueType key = new KeyValueType(); + key.setRSAKeyValue(rsa); + + keyvalueList.add(key); + + return keyvalueList; + } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { + log.error("TestCode has an internal ERROR", e); + + } + + } + + return null; + + } + + private String extendBPKbyPrefix(String bpk, String type) { + String bPKType = null; + + if (type.startsWith(EAAFConstants.URN_PREFIX_WBPK)) + bPKType = type.substring((EAAFConstants.URN_PREFIX_WBPK).length()); + + else if (type.startsWith(EAAFConstants.URN_PREFIX_CDID)) + bPKType = type.substring((EAAFConstants.URN_PREFIX_CDID).length()); + + else if (type.startsWith(EAAFConstants.URN_PREFIX_EIDAS)) + bPKType = type.substring((EAAFConstants.URN_PREFIX_EIDAS).length()); + + + if (bPKType != null ) { + log.trace("Authenticate user with bPK/wbPK " + bpk + " and Type=" + bPKType); + return bPKType + ":" + bpk; + + } else { + log.warn("Service Provider Target with: " + type + " is NOT supported. Set bPK as it is ..."); + return bpk; + + } + + } + + //TODO: update for complexe attributes + private Map converteIDASAttrToSimpleMap( + ImmutableMap, ImmutableSet>> attributeMap) { + Map result = new HashMap(); + + for (AttributeDefinition el : attributeMap.keySet()) { + + final Class parameterizedType = el.getParameterizedType(); + if ((DateTime.class).equals(parameterizedType)) { + DateTime attribute = eIDASResponseUtils.translateDateAttribute(el, attributeMap.get(el).asList()); + if (attribute != null) + result.put(el.getFriendlyName(), attribute); + else + log.info("Ignore empty 'DateTime' attribute"); + + } else if ((PostalAddress.class).equals(parameterizedType)) { + PostalAddress addressAttribute = eIDASResponseUtils.translateAddressAttribute(el, attributeMap.get(el).asList()); + if (addressAttribute != null) + result.put(el.getFriendlyName(), addressAttribute); + else + log.info("Ignore empty 'PostalAddress' attribute"); + + } else { + List natPersonIdObj = eIDASResponseUtils.translateStringListAttribute(el, attributeMap.get(el).asList()); + String stringAttr = natPersonIdObj.get(0); + if (StringUtils.isNotEmpty(stringAttr)) + result.put(el.getFriendlyName(), stringAttr); + else + log.info("Ignore empty 'String' attribute"); + + } + } + + return result; + } + + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/GenerateAuthnRequestTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/GenerateAuthnRequestTask.java new file mode 100644 index 00000000..74c98de1 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/GenerateAuthnRequestTask.java @@ -0,0 +1,306 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.tasks; + +import java.util.Map; +import java.util.UUID; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; +import org.springframework.web.util.UriComponentsBuilder; + +import com.google.common.collect.ImmutableSortedSet; + +import at.asitplus.eidas.specific.connector.MSConnectorEventCodes; +import at.asitplus.eidas.specific.connector.MSeIDASNodeConstants; +import at.asitplus.eidas.specific.connector.gui.StaticGuiBuilderConfiguration; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.Constants; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASAuthenticationException; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.service.eIDASAttributeRegistry; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; +import eu.eidas.auth.commons.EidasParameterKeys; +import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; +import eu.eidas.auth.commons.light.ILightRequest; +import eu.eidas.auth.commons.light.impl.LightRequest; +import eu.eidas.auth.commons.protocol.eidas.SpType; +import eu.eidas.auth.commons.tx.BinaryLightToken; +import eu.eidas.specificcommunication.BinaryLightTokenHelper; +import eu.eidas.specificcommunication.SpecificCommunicationDefinitionBeanNames; +import eu.eidas.specificcommunication.exception.SpecificCommunicationException; +import eu.eidas.specificcommunication.protocol.impl.SpecificConnectorCommunicationServiceImpl; + +/** + * @author tlenz + * + */ +@Component("ConnecteIDASNodeTask") +public class GenerateAuthnRequestTask extends AbstractAuthServletTask { + private static final Logger log = LoggerFactory.getLogger(GenerateAuthnRequestTask.class); + + @Autowired IConfiguration basicConfig; + @Autowired eIDASAttributeRegistry attrRegistry; + @Autowired ApplicationContext context; + @Autowired ITransactionStorage transactionStore; + @Autowired IGUIFormBuilder guiBuilder; + + @Override + public void execute(ExecutionContext executionContext, + HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + + try{ + //get service-provider configuration + ISPConfiguration spConfig = pendingReq.getServiceProviderConfiguration(); + + // get target, environment and validate citizen countryCode + String citizenCountryCode = (String) executionContext.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_COUNTRY); + String environment = (String) executionContext.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT); + + if (StringUtils.isEmpty(citizenCountryCode)) { + // illegal state; task should not have been executed without a selected country + throw new eIDASAuthenticationException("eidas.03", new Object[] { "" }); + + } + + //TODO: maybe add countryCode validation before request ref. impl. eIDAS node + log.debug("Request eIDAS auth. for citizen of country: " + citizenCountryCode); + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.COUNTRY_SELECTED, citizenCountryCode); + + //build eIDAS AuthnRequest + LightRequest.Builder authnRequestBuilder = LightRequest.builder(); + authnRequestBuilder.id(UUID.randomUUID().toString()); + + + String issur = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_ENTITYID); + if (StringUtils.isEmpty(issur)) { + log.error("Found NO 'eIDAS node issuer' in configuration. Authentication NOT possible!"); + throw new EAAFConfigurationException("config.27", + new Object[] {"Application config containts NO " + Constants.CONIG_PROPS_EIDAS_NODE_ENTITYID }); + + } + authnRequestBuilder.issuer(issur); + + + //TODO: set matching mode if eIDAS ref. impl. support this method + + + //TODO: update if eIDAS ref. impl. supports exact matching for non-notified LoA schemes + String loa = EAAFConstants.EIDAS_LOA_HIGH; + if (spConfig.getRequiredLoA() != null) { + if (spConfig.getRequiredLoA().isEmpty()) + log.info("No eIDAS LoA requested. Use LoA HIGH as default"); + + else { + if (spConfig.getRequiredLoA().size() > 1 ) + log.info("Currently only ONE requested LoA is supported for service provider. Use first one ... "); + + loa = spConfig.getRequiredLoA().get(0); + + } + } + + log.debug("Request eIdAS node with LoA: " + loa); + authnRequestBuilder.levelOfAssurance(loa); + + //set correct SPType for requested target sector + String publicSectorTargetSelector = basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_NODE_PUBLICSECTOR_TARGETS, + Constants.POLICY_DEFAULT_ALLOWED_TARGETS); + Pattern p = Pattern.compile(publicSectorTargetSelector); + Matcher m = p.matcher(spConfig.getAreaSpecificTargetIdentifier()); + if (m.matches()) { + log.debug("Map " + spConfig.getAreaSpecificTargetIdentifier() + " to 'PublicSector'"); + authnRequestBuilder.spType(SpType.PUBLIC.getValue()); + + //TODO: only for eIDAS ref. node 2.0 and 2.1 because it need 'Providername' for any SPType + String providerName = pendingReq.getRawData(Constants.DATA_PROVIDERNAME, String.class); + if (StringUtils.isNotEmpty(providerName) + && basicConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_NODE_WORKAROUND_ADD_ALWAYS_PROVIDERNAME, + false) + ) + authnRequestBuilder.providerName(providerName); + + } else { + log.debug("Map " + spConfig.getAreaSpecificTargetIdentifier() + " to 'PrivateSector'"); + authnRequestBuilder.spType(SpType.PRIVATE.getValue()); + + //TODO: switch to RequesterId in further version + //set provider name for private sector applications + String providerName = pendingReq.getRawData(Constants.DATA_PROVIDERNAME, String.class); + if (StringUtils.isNotEmpty(providerName)) + authnRequestBuilder.providerName(providerName); + + } + + //set nameIDFormat + authnRequestBuilder.nameIdFormat(Constants.eIDAS_REQ_NAMEID_FORMAT); + + //set citizen country code for foreign uses + authnRequestBuilder.citizenCountryCode(citizenCountryCode); + + //set relay state + authnRequestBuilder.relayState(pendingReq.getPendingRequestId()); + + //build and add requested attribute set + ImmutableAttributeMap reqAttrMap = translateToEidasAttributes(attrRegistry.getAttributeSetFromConfiguration()); + authnRequestBuilder.requestedAttributes(reqAttrMap); + + //build request + LightRequest lightAuthnReq = authnRequestBuilder.build(); + + //put request into cache + BinaryLightToken token = putRequestInCommunicationCache(lightAuthnReq); + final String tokenBase64 = BinaryLightTokenHelper.encodeBinaryLightTokenBase64(token); + + //Workaround, because eIDAS node ref. impl. does not return relayState + if (basicConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_NODE_WORKAROUND_USEREQUESTIDASTRANSACTIONIDENTIFIER, + false)) { + log.trace("Put lightRequestId into transactionstore as session-handling backup"); + transactionStore.put(lightAuthnReq.getId(), pendingReq.getPendingRequestId(), -1); + + } + + //select forward URL regarding the selected environment + String forwardURL = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL); + if (StringUtils.isNotEmpty(environment)) + forwardURL = selectedForwardURLForEnvironment(environment); + + if (StringUtils.isEmpty(forwardURL)) { + log.warn("NO ForwardURL defined in configuration. Can NOT forward to eIDAS node! Process stops"); + throw new EAAFConfigurationException("config.08", new Object[] {Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL}); + + } + log.debug("ForwardURL: " + forwardURL + " selected to forward eIDAS request"); + + if (basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_METHOD, + Constants.FORWARD_METHOD_GET + ).equals(Constants.FORWARD_METHOD_GET)) { + + log.debug("Use http-redirect for eIDAS node forwarding ... "); + //send redirect + UriComponentsBuilder redirectUrl = UriComponentsBuilder.fromHttpUrl(forwardURL); + redirectUrl.queryParam(EidasParameterKeys.TOKEN.toString(), tokenBase64); + response.sendRedirect(redirectUrl.build().encode().toString()); + + } else { + log.debug("Use http-post for eIDAS node forwarding ... "); + StaticGuiBuilderConfiguration config = new StaticGuiBuilderConfiguration( + basicConfig, + pendingReq, + Constants.TEMPLATE_POST_FORWARD_NAME, + null); + + config.putCustomParameter(Constants.TEMPLATE_POST_FORWARD_ENDPOINT, forwardURL); + config.putCustomParameter(Constants.TEMPLATE_POST_FORWARD_TOKEN_NAME, + EidasParameterKeys.TOKEN.toString()); + config.putCustomParameter(Constants.TEMPLATE_POST_FORWARD_TOKEN_VALUE, + tokenBase64); + + guiBuilder.build(response, config, "BKU-Selection form"); + + } + + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.EIDAS_NODE_CONNECTED, lightAuthnReq.getId()); + + + } catch (eIDASAuthenticationException e) { + throw new TaskExecutionException(pendingReq, "eIDAS AuthnRequest generation FAILED.", e); + + } catch (Exception e) { + log.warn("eIDAS AuthnRequest generation FAILED.", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + + } + + /** + * Select a forward URL from configuration for a specific environment + *

+ * Info: This method is needed, because eIDAS Ref. Impl only supports one countrycode on each instance. + * In consequence, more than one eIDAS Ref. Impl nodes are required to support producation, testing, or QS stages + * for one country by using one ms-specific eIDAS connector + * + * @param environment Environment selector from CountrySlection page + * @return + */ + private String selectedForwardURLForEnvironment(String environment) { + log.trace("Starting endpoint selection process for environment: " + environment + " ... "); + if (environment.equalsIgnoreCase(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_PRODUCTION)) + return basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL); + + else if (environment.equalsIgnoreCase(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_QS)) + return basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL + + "." + MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_QS); + + else if (environment.equalsIgnoreCase(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_TESTING)) + return basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL + + "." + MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_TESTING); + + else if (environment.equalsIgnoreCase(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_DEVELOPMENT)) + return basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL + + "." + MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_DEVELOPMENT); + + log.info("Environment selector: " + environment + " is not supported"); + return null; + + } + + private ImmutableAttributeMap translateToEidasAttributes(final Map requiredAttributes) { + ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder(); + for (Map.Entry attribute : requiredAttributes.entrySet()) { + final String name = attribute.getKey(); + final ImmutableSortedSet> byFriendlyName = attrRegistry.getCoreAttributeRegistry().getByFriendlyName(name); + if (!byFriendlyName.isEmpty()) { + final AttributeDefinition attributeDefinition = byFriendlyName.first(); + builder.put(AttributeDefinition.builder(attributeDefinition).required(attribute.getValue()).build()); + + } else + log.warn("Can NOT request UNKNOWN attribute: " + attribute.getKey() + " Ignore it!"); + + } + + return builder.build(); + + } + + private BinaryLightToken putRequestInCommunicationCache(ILightRequest iLightRequest) throws ServletException { + final BinaryLightToken binaryLightToken; + try { + final SpecificConnectorCommunicationServiceImpl springManagedSpecificConnectorCommunicationService = + (SpecificConnectorCommunicationServiceImpl) context.getBean(SpecificCommunicationDefinitionBeanNames.SPECIFIC_CONNECTOR_COMMUNICATION_SERVICE.toString()); + + binaryLightToken = springManagedSpecificConnectorCommunicationService.putRequest(iLightRequest); + + } catch (SpecificCommunicationException e) { + log.error("Unable to process specific request"); + throw new ServletException(e); + + } + + return binaryLightToken; + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/ReceiveAuthnResponseTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/ReceiveAuthnResponseTask.java new file mode 100644 index 00000000..2970c073 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/tasks/ReceiveAuthnResponseTask.java @@ -0,0 +1,97 @@ +/******************************************************************************* + *******************************************************************************/ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.tasks; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.stereotype.Component; + +import at.asitplus.eidas.specific.connector.MSConnectorEventCodes; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.Constants; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASAuthenticationException; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.service.eIDASAttributeRegistry; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.validator.eIDASResponseValidator; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; +import eu.eidas.auth.commons.light.ILightResponse; + +@Component("ReceiveResponseFromeIDASNodeTask") +public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { + private static final Logger log = LoggerFactory.getLogger(ReceiveAuthnResponseTask.class); + + @Autowired private ApplicationContext context; + @Autowired private IConfiguration basicConfig; + @Autowired private eIDASAttributeRegistry attrRegistry; + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { + try{ + ILightResponse eIDASResponse = (ILightResponse) request.getAttribute(Constants.DATA_FULL_EIDAS_RESPONSE); + if (eIDASResponse == null) { + log.warn("NO eIDAS response-message found."); + throw new eIDASAuthenticationException("eidas.01", null); + + } + + log.debug("Receive eIDAS response with RespId:" + eIDASResponse.getId() + " for ReqId:" + eIDASResponse.getInResponseToId()); + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.RESPONSE_FROM_EIDAS_NODE, eIDASResponse.getId()); + + + //check response StatusCode + if (!eIDASResponse.getStatus().getStatusCode().equals(Constants.SUCCESS_URI)) { + log.info("Receice eIDAS Response with StatusCode:" + eIDASResponse.getStatus().getStatusCode() + + " Subcode:" + eIDASResponse.getStatus().getSubStatusCode() + " Msg:" + eIDASResponse.getStatus().getStatusMessage()); + throw new eIDASAuthenticationException("eidas.02", new Object[]{eIDASResponse.getStatus().getStatusCode(), eIDASResponse.getStatus().getStatusMessage()}); + + } + + // extract all Attributes from response + + + + // ********************************************************** + // ******* MS-specificresponse validation ********** + // ********************************************************** + String spCountry = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_COUNTRYCODE, "AT"); + eIDASResponseValidator.validateResponse(pendingReq, eIDASResponse, spCountry, attrRegistry); + + + // ********************************************************** + // ******* Store resonse infos into session object ********** + // ********************************************************** + + //update MOA-Session data with received information + log.debug("Store eIDAS response information into pending-request."); + AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); + authProcessData.setQAALevel(eIDASResponse.getLevelOfAssurance()); + authProcessData.setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, eIDASResponse); + + //store MOA-session to database + requestStoreage.storePendingRequest(pendingReq); + + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.RESPONSE_FROM_EIDAS_NODE_VALID); + + } catch (EAAFException e) { + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.RESPONSE_FROM_EIDAS_NODE_NOT_VALID); + throw new TaskExecutionException(pendingReq, "eIDAS Response processing FAILED.", e); + + } catch (Exception e) { + log.warn("eIDAS Response processing FAILED.", e); + revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.RESPONSE_FROM_EIDAS_NODE_NOT_VALID); + throw new TaskExecutionException(pendingReq, e.getMessage(), + new eIDASAuthenticationException("eidas.05", new Object[]{e.getMessage()}, e)); + + } + + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/utils/LoggingHandler.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/utils/LoggingHandler.java new file mode 100644 index 00000000..2f6e7c3a --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/utils/LoggingHandler.java @@ -0,0 +1,52 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.utils; + +import java.io.ByteArrayOutputStream; +import java.util.Set; + +import javax.xml.namespace.QName; +import javax.xml.soap.SOAPMessage; +import javax.xml.ws.handler.MessageContext; +import javax.xml.ws.handler.soap.SOAPHandler; +import javax.xml.ws.handler.soap.SOAPMessageContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LoggingHandler implements SOAPHandler { + + Logger log = LoggerFactory.getLogger(LoggingHandler.class); + + public boolean handleMessage(SOAPMessageContext context) { + SOAPMessage msg = context.getMessage(); + boolean request = ((Boolean) context + .get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue(); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + + try { + if (request) { + msg.writeTo(bos); + } else { // This is the response message + msg.writeTo(bos); + } + + log.trace(bos.toString()); + log.trace(new String(bos.toByteArray())); + + } catch (Exception e) { + log.trace(e.getMessage(), e); + } + return true; + } + + public boolean handleFault(SOAPMessageContext context) { + return handleMessage(context); + } + + public void close(MessageContext context) { + } + + public Set getHeaders() { + return null; + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/utils/eIDASResponseUtils.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/utils/eIDASResponseUtils.java new file mode 100644 index 00000000..6269d242 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/utils/eIDASResponseUtils.java @@ -0,0 +1,98 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.joda.time.DateTime; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.collect.ImmutableList; + +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.Constants; +import at.gv.egiz.eaaf.core.impl.data.Trible; +import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.AttributeValue; +import eu.eidas.auth.commons.attribute.AttributeValueMarshaller; +import eu.eidas.auth.commons.attribute.AttributeValueMarshallingException; +import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress; + +public class eIDASResponseUtils { + private static final Logger log = LoggerFactory.getLogger(eIDASResponseUtils.class); + + public static final String PERSONALIDENIFIER_VALIDATION_PATTERN = "^[A-Z,a-z]{2}/[A-Z,a-z]{2}/.*"; + + /** + * Validate a eIDAS PersonalIdentifier attribute value + * This validation is done according to eIDAS SAML Attribute Profile - Section 2.2.3 Unique Identifier + * + * @param uniqueID eIDAS attribute value of a unique identifier + * @return true if the uniqueID matches to eIDAS to Unique Identifier specification, otherwise false + */ + public static boolean validateEidasPersonalIdentifier(String uniqueID) { + Pattern pattern = Pattern.compile(PERSONALIDENIFIER_VALIDATION_PATTERN ); + Matcher matcher = pattern.matcher(uniqueID); + return matcher.matches(); + + } + + + /** + * Parse an eIDAS PersonalIdentifier attribute value into it components. + * This processing is done according to eIDAS SAML Attribute Profile - Section 2.2.3 Unique Identifier + * + * @param uniqueID eIDAS attribute value of a unique identifier + * @return {@link Trible} that contains: + *
First : citizen country + *
Second: destination country + *
Third : unique identifier + *
or null if the attribute value has a wrong format + */ + public static Trible parseEidasPersonalIdentifier(String uniqueID) { + if (!validateEidasPersonalIdentifier(uniqueID)) { + log.error("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER + + " looks wrong formated. Value:" + ((String)uniqueID)); + return null; + + } + return Trible.newInstance(uniqueID.substring(0, 2), uniqueID.substring(3, 5), uniqueID.substring(6)); + + } + + public static List translateStringListAttribute(AttributeDefinition attributeDefinition, ImmutableList> attributeValues) { + final List stringListAttribute = new ArrayList(); + AttributeValueMarshaller attributeValueMarshaller = attributeDefinition.getAttributeValueMarshaller(); + for (AttributeValue attributeValue : attributeValues) { + String valueString = null; + try { + valueString = attributeValueMarshaller.marshal((AttributeValue) attributeValue); + stringListAttribute.add(valueString); + } catch (AttributeValueMarshallingException e) { + throw new IllegalStateException(e); + + } + } + + return stringListAttribute; + + } + + public static DateTime translateDateAttribute(AttributeDefinition attributeDefinition, ImmutableList> attributeValues) { + if (attributeValues.size() != 0) { + final AttributeValue firstAttributeValue = attributeValues.get(0); + return (DateTime) firstAttributeValue.getValue(); + + } + + return null; + } + + public static PostalAddress translateAddressAttribute(AttributeDefinition attributeDefinition, ImmutableList> attributeValues) { + final AttributeValue firstAttributeValue = attributeValues.get(0); + return (PostalAddress) firstAttributeValue.getValue(); + + } + +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/validator/eIDASResponseValidator.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/validator/eIDASResponseValidator.java new file mode 100644 index 00000000..4af4e7cf --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/asitplus/eidas/specific/modules/authmodule_eIDASv2/validator/eIDASResponseValidator.java @@ -0,0 +1,135 @@ +package at.asitplus.eidas.specific.modules.authmodule_eIDASv2.validator; + +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.google.common.collect.ImmutableList; + +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.Constants; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASValidationException; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.service.eIDASAttributeRegistry; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.utils.eIDASResponseUtils; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.impl.data.Trible; +import eu.eidas.auth.commons.attribute.AttributeDefinition; +import eu.eidas.auth.commons.attribute.AttributeValue; +import eu.eidas.auth.commons.light.ILightResponse; +import eu.eidas.auth.commons.protocol.eidas.LevelOfAssurance; + +/** + * @author tlenz + * + */ +public class eIDASResponseValidator { + private static final Logger log = LoggerFactory.getLogger(eIDASResponseValidator.class); + + public static void validateResponse(IRequest pendingReq, ILightResponse eIDASResponse, String spCountry, eIDASAttributeRegistry attrRegistry) throws eIDASValidationException { + + /*-----------------------------------------------------| + * validate received LoA against minimum required LoA | + *_____________________________________________________| + */ + LevelOfAssurance respLoA = LevelOfAssurance.fromString(eIDASResponse.getLevelOfAssurance()); + List allowedLoAs = pendingReq.getServiceProviderConfiguration().getRequiredLoA(); + boolean loaValid = false; + for (String allowedLoaString : allowedLoAs) { + LevelOfAssurance allowedLoa = LevelOfAssurance.fromString(allowedLoaString); + if (respLoA.numericValue() >= allowedLoa.numericValue()) { + log.debug("Response contains valid LoA. Resume process ... "); + loaValid = true; + break; + + } else + log.trace("Allowed LoA: " + allowedLoaString + " DOES NOT match response LoA: " + eIDASResponse.getLevelOfAssurance()); + + } + + if (!loaValid) { + log.error("eIDAS Response LevelOfAssurance is lower than the required! " + + "(Resp-LoA:" + respLoA.getValue() + " Req-LoA:" + allowedLoAs.toArray() + ")"); + throw new eIDASValidationException("eidas.06", new Object[]{respLoA.getValue()}); + + } + + + + /*-----------------------------------------------------| + * validate 'PersonalIdentifier' attribute | + *_____________________________________________________| + */ + AttributeDefinition attrDefinition = attrRegistry.getCoreAttributeRegistry().getByFriendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).first(); + final ImmutableList> attributeValues = eIDASResponse.getAttributes().getAttributeMap().get(attrDefinition).asList(); + List personalIdObj = eIDASResponseUtils.translateStringListAttribute(attrDefinition, attributeValues); + + //check if attribute exists + if (personalIdObj == null || personalIdObj.isEmpty()) { + log.warn("eIDAS Response include NO 'PersonalIdentifier' attriubte " + + ".... That can be a BIG problem in further processing steps"); + throw new eIDASValidationException("eidas.05", new Object[] {"NO 'PersonalIdentifier' attriubte"}); + + } else if (personalIdObj.size() > 1) { + log.warn("eIDAS Response include MORE THAN ONE 'PersonalIdentifier' attriubtes " + + ".... That can be a BIG problem in further processing steps"); + throw new eIDASValidationException("eidas.05", new Object[] {"MORE THAN ONE 'PersonalIdentifier' attriubtes"}); + + } else { + String natPersId = personalIdObj.get(0); + //validate attribute value format + Trible split = + eIDASResponseUtils.parseEidasPersonalIdentifier(natPersId); + if (split == null) { + throw new eIDASValidationException("eidas.07", + new Object[]{ + Constants.eIDAS_ATTR_PERSONALIDENTIFIER, + "Wrong identifier format"}); + + } else { + //validation according to eIDAS SAML Attribute Profile, Section 2.2.3 + if (StringUtils.isEmpty(split.getSecond())) { + log.warn("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER + + " includes NO destination country. Value:" + natPersId); + throw new eIDASValidationException("eidas.07", + new Object[]{ + Constants.eIDAS_ATTR_PERSONALIDENTIFIER, + "No or empty destination country"}); + + } + if (!split.getSecond().equalsIgnoreCase(spCountry)) { + log.warn("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER + + " includes wrong destination country. Value:" + natPersId + + " SP-Country:" + spCountry); + throw new eIDASValidationException("eidas.07", + new Object[]{ + Constants.eIDAS_ATTR_PERSONALIDENTIFIER, + "Destination country does not match to SP country"}); + + } + + if (StringUtils.isEmpty(split.getFirst())) { + log.warn("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER + + " includes NO citizen country. Value:" + natPersId); + throw new eIDASValidationException("eidas.07", + new Object[]{ + Constants.eIDAS_ATTR_PERSONALIDENTIFIER, + "No or empty citizen country"}); + + } + if (!split.getSecond().equalsIgnoreCase(spCountry)) { + log.warn("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER + + " includes a relaying-party country that does not match to service-provider country. " + + " Value:" + natPersId + + " SP Country:" + spCountry); + throw new eIDASValidationException("eidas.07", + new Object[]{ + Constants.eIDAS_ATTR_PERSONALIDENTIFIER, + "Citizen country does not match to eIDAS-node country that generates the response"}); + + } + } + } + + } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/Constants.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/Constants.java deleted file mode 100644 index beb3cce7..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/Constants.java +++ /dev/null @@ -1,110 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2; - -import java.net.URI; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; - -public class Constants { - - public static final String DATA_REQUESTERID = "req_requesterId"; - public static final String DATA_PROVIDERNAME = "req_providerName"; - public static final String DATA_REQUESTED_LOA_LIST = "req_requestedLoA"; - public static final String DATA_REQUESTED_LOA_COMPERISON = "req_requestedLoAComperision"; - public static final String DATA_FULL_EIDAS_RESPONSE = "resp_fulleIDASResponse"; - - - //templates for post-binding forwarding - public static final String TEMPLATE_POST_FORWARD_NAME = "eidas_node_forward.html"; - public static final String TEMPLATE_POST_FORWARD_ENDPOINT = "endPoint"; - public static final String TEMPLATE_POST_FORWARD_TOKEN_NAME = "tokenName"; - public static final String TEMPLATE_POST_FORWARD_TOKEN_VALUE = "tokenValue"; - - - //configuration properties - public static final String CONIG_PROPS_EIDAS_PREFIX="auth.eIDAS"; - public static final String CONIG_PROPS_EIDAS_NODE= CONIG_PROPS_EIDAS_PREFIX + ".node_v2"; - public static final String CONIG_PROPS_EIDAS_NODE_COUNTRYCODE = CONIG_PROPS_EIDAS_NODE + ".countrycode"; - public static final String CONIG_PROPS_EIDAS_NODE_PUBLICSECTOR_TARGETS = CONIG_PROPS_EIDAS_NODE + ".publicSectorTargets"; - public static final String CONIG_PROPS_EIDAS_NODE_ENTITYID = CONIG_PROPS_EIDAS_NODE + ".entityId"; - public static final String CONIG_PROPS_EIDAS_NODE_FORWARD_URL = CONIG_PROPS_EIDAS_NODE + ".forward.endpoint"; - public static final String CONIG_PROPS_EIDAS_NODE_FORWARD_METHOD = CONIG_PROPS_EIDAS_NODE + ".forward.method"; - public static final String CONIG_PROPS_EIDAS_NODE_ATTRIBUTES_REQUESTED_ONLYNATURAL = CONIG_PROPS_EIDAS_NODE + ".attributes.requested.onlynatural."; - public static final String CONIG_PROPS_EIDAS_NODE_ATTRIBUTES_REQUESTED_REPRESENTATION = CONIG_PROPS_EIDAS_NODE + ".attributes.requested.representation."; - public static final String CONIG_PROPS_EIDAS_NODE_WORKAROUND_ADD_ALWAYS_PROVIDERNAME = CONIG_PROPS_EIDAS_NODE + ".workarounds.addAlwaysProviderName";; - public static final String CONIG_PROPS_EIDAS_NODE_WORKAROUND_USEREQUESTIDASTRANSACTIONIDENTIFIER = CONIG_PROPS_EIDAS_NODE + ".workarounds.useRequestIdAsTransactionIdentifier"; - - public static final String FORWARD_METHOD_POST = "POST"; - public static final String FORWARD_METHOD_GET = "GET"; - - public static final String CONIG_PROPS_EIDAS_SZRCLIENT= CONIG_PROPS_EIDAS_PREFIX + ".szrclient"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_USETESTSERVICE= CONIG_PROPS_EIDAS_SZRCLIENT + ".useTestService"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_TRACEMESSAGES= CONIG_PROPS_EIDAS_SZRCLIENT + ".debug.logfullmessages"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USEDUMMY= CONIG_PROPS_EIDAS_SZRCLIENT + ".debug.useDummySolution"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_INSERTERNB= CONIG_PROPS_EIDAS_SZRCLIENT + ".debug.insertERnB"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_TIMEOUT_CONNECTION= CONIG_PROPS_EIDAS_SZRCLIENT + ".timeout.connection"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_TIMEOUT_RESPONSE= CONIG_PROPS_EIDAS_SZRCLIENT + ".timeout.response"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_ENDPOINT_PROD= CONIG_PROPS_EIDAS_SZRCLIENT + ".endpoint.prod"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_ENDPOINT_TEST= CONIG_PROPS_EIDAS_SZRCLIENT + ".endpoint.test"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_SSL_KEYSTORE_PATH = CONIG_PROPS_EIDAS_SZRCLIENT + ".ssl.keyStore.path"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_SSL_KEYSTORE_PASSWORD = CONIG_PROPS_EIDAS_SZRCLIENT + ".ssl.keyStore.password"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_SSL_TRUSTSTORE_PATH = CONIG_PROPS_EIDAS_SZRCLIENT + ".ssl.trustStore.path"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_SSL_TRUSTSTORE_PASSWORD = CONIG_PROPS_EIDAS_SZRCLIENT + ".ssl.trustStore.password"; - - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE = CONIG_PROPS_EIDAS_SZRCLIENT + ".params.documenttype"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ = CONIG_PROPS_EIDAS_SZRCLIENT + ".params.vkz"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_DATE = CONIG_PROPS_EIDAS_SZRCLIENT + ".params.issuingdate"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_AUTHORITY = CONIG_PROPS_EIDAS_SZRCLIENT + ".params.issuingauthority"; - public static final String CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_KEYS_USEDUMMY= CONIG_PROPS_EIDAS_SZRCLIENT + ".params.usedummykeys"; - - //http endpoint descriptions - public static final String eIDAS_HTTP_ENDPOINT_SP_POST = "/eidas/light/sp/post"; - public static final String eIDAS_HTTP_ENDPOINT_SP_REDIRECT = "/eidas/light/sp/redirect"; - public static final String eIDAS_HTTP_ENDPOINT_IDP_COLLEAGUEREQUEST = "/eidas/light/ColleagueRequest"; - public static final String eIDAS_HTTP_ENDPOINT_METADATA = "/eidas/light/metadata"; - - //eIDAS request parameters - public static final String eIDAS_REQ_NAMEID_FORMAT = "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent"; - - //eIDAS attribute names - public static final String eIDAS_ATTR_PERSONALIDENTIFIER = "PersonIdentifier"; - public static final String eIDAS_ATTR_DATEOFBIRTH = "DateOfBirth"; - public static final String eIDAS_ATTR_CURRENTGIVENNAME = "FirstName"; - public static final String eIDAS_ATTR_CURRENTFAMILYNAME = "FamilyName"; - public static final String eIDAS_ATTR_LEGALPERSONIDENTIFIER = "LegalPersonIdentifier"; - public static final String eIDAS_ATTR_LEGALNAME = "LegalName"; - - public static final List NATURALPERSONMINIMUMDATASETLIST = Collections.unmodifiableList(new ArrayList() { - private static final long serialVersionUID = 1L; - { - //TODO: find correct location of attribute definitions -// add(eu.eidas.auth.engine.core.eidas.spec.NaturalPersonSpec.Definitions.CURRENT_FAMILY_NAME.getNameUri()); -// add(eu.eidas.auth.engine.core.eidas.spec.NaturalPersonSpec.Definitions.CURRENT_GIVEN_NAME.getNameUri()); -// add(eu.eidas.auth.engine.core.eidas.spec.NaturalPersonSpec.Definitions.DATE_OF_BIRTH.getNameUri()); -// add(eu.eidas.auth.engine.core.eidas.spec.NaturalPersonSpec.Definitions.PERSON_IDENTIFIER.getNameUri()); - } - }); - - public static final String POLICY_DEFAULT_ALLOWED_TARGETS = - EAAFConstants.URN_PREFIX_CDID.replaceAll("\\.", "\\\\.").replaceAll("\\+", "\\\\+") + ".*"; - - //SAML2 Constants - public static final String SUCCESS_URI = "urn:oasis:names:tc:SAML:2.0:status:Success"; - - public static final String HTTP_CLIENT_DEFAULT_TIMEOUT_CONNECTION = "30"; //seconds - public static final String HTTP_CLIENT_DEFAULT_TIMEOUT_RESPONSE = "60"; //seconds - - - //Default values for SZR communication - public static final String SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE = "ELEKTR_DOKUMENT"; - - //TODO remove!!! - public static final String SZR_CONSTANTS_DEFAULT_ISSUING_DATE = "2014-01-01"; - public static final String SZR_CONSTANTS_DEFAULT_ISSUING_AUTHORITY = "ms-specific eIDAS-Node for AT"; - public final static byte[] SZR_CONSTANTS_DEFAULT_PUBL_KEY = new byte[] {48, -127, -97, 48, 13, 6, 9, 42, -122, 72, -122, -9, 13, 1, 1, 1, 5, 0, 3, -127, -115, 0, 48, -127, -119, 2, -127, -127, 0, -106, 114, -113, -1, -84, 116, 35, 3, 70, -81, 81, -110, -10, -59, 114, 4, -109, 86, 127, -50, 125, 47, 4, 80, 79, 53, 117, -36, 15, -16, -61, 110, 39, 89, 29, -43, 37, -127, 80, -109, -38, 65, 125, -119, 44, -111, -21, 47, -98, 38, -112, -24, 107, -110, 17, -10, 51, -4, -36, -72, -28, -18, -14, 117, -67, 76, -31, 32, 92, 104, -21, 68, 31, -12, 30, -104, -104, 42, -107, 126, 84, 50, 85, -117, 44, -100, -4, 102, -100, 52, -68, 77, -32, 9, -16, -30, -104, -90, 107, -88, 7, 97, -94, 72, -61, -40, 80, -112, -65, -25, -72, -19, -95, -54, 31, 15, 24, -105, 123, -81, 23, -123, 92, -103, -101, 47, 47, -105, 2, 3, 1, 0, 1}; - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationModulImpl.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationModulImpl.java deleted file mode 100644 index c41559b8..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationModulImpl.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2; - -import org.apache.commons.lang3.StringUtils; - -import at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; - -/** - * @author tlenz - * - */ -public class eIDASAuthenticationModulImpl implements AuthModule { - - private int priority = 1; - - @Override - public int getPriority() { - return priority; - } - - /** - * Sets the priority of this module. Default value is {@code 0}. - * @param priority The priority. - */ - public void setPriority(int priority) { - this.priority = priority; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#selectProcess(at.gv.egovernment.moa.id.process.api.ExecutionContext) - */ - @Override - public String selectProcess(ExecutionContext context) { - if (StringUtils.isNotBlank((String) context.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_COUNTRY)) || - StringUtils.isNotBlank((String) context.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_COUNTRY))) - return "eIDASAuthentication_v2"; - else - return null; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getProcessDefinitions() - */ - @Override - public String[] getProcessDefinitions() { - return new String[] { "classpath:eIDAS.Authentication.process.xml" }; - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationSpringResourceProvider.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationSpringResourceProvider.java deleted file mode 100644 index e067acfb..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASAuthenticationSpringResourceProvider.java +++ /dev/null @@ -1,30 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import at.gv.egiz.components.spring.api.SpringResourceProvider; - -public class eIDASAuthenticationSpringResourceProvider implements SpringResourceProvider { - - @Override - public String getName() { - return "Auth. module for eIDAS Ref. Impl. v2.x"; - } - - @Override - public String[] getPackagesToScan() { - // TODO Auto-generated method stub - return null; - } - - @Override - public Resource[] getResourcesToLoad() { - ClassPathResource eIDASAuthConfig = new ClassPathResource("/eidas_v2_auth.beans.xml", eIDASAuthenticationSpringResourceProvider.class); - - return new Resource[] {eIDASAuthConfig}; - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASSignalServlet.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASSignalServlet.java deleted file mode 100644 index 77f799e7..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/eIDASSignalServlet.java +++ /dev/null @@ -1,131 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import com.google.common.collect.ImmutableSortedSet; - -import at.gv.egiz.eaaf.core.impl.idp.controller.AbstractProcessEngineSignalController; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASAuthenticationException; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.service.eIDASAttributeRegistry; -import eu.eidas.auth.commons.EidasParameterKeys; -import eu.eidas.auth.commons.light.ILightResponse; -import eu.eidas.specificcommunication.SpecificCommunicationDefinitionBeanNames; -import eu.eidas.specificcommunication.exception.SpecificCommunicationException; -import eu.eidas.specificcommunication.protocol.impl.SpecificConnectorCommunicationServiceImpl; - - -/** - * @author tlenz - * - */ -@Controller -public class eIDASSignalServlet extends AbstractProcessEngineSignalController { - - private static final Logger log = LoggerFactory.getLogger(eIDASSignalServlet.class); - @Autowired private ApplicationContext context; - @Autowired private eIDASAttributeRegistry attrRegistry; - - public eIDASSignalServlet() { - super(); - log.debug("Registering servlet " + getClass().getName() + - " with mappings '"+ Constants.eIDAS_HTTP_ENDPOINT_SP_POST + - "' and '"+ Constants.eIDAS_HTTP_ENDPOINT_SP_REDIRECT + "'."); - - } - - @RequestMapping(value = { Constants.eIDAS_HTTP_ENDPOINT_SP_POST, - Constants.eIDAS_HTTP_ENDPOINT_SP_REDIRECT - }, - method = {RequestMethod.POST, RequestMethod.GET}) - public void restoreEidasAuthProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException { - signalProcessManagement(req, resp); - } - - - /** - * Protocol specific implementation to get the pending-requestID - * from http request object - * - * @param request The http Servlet-Request object - * @return The Pending-request id - * - */ - @Override - public String getPendingRequestId(HttpServletRequest request) { - //String sessionId = super.getPendingRequestId(request); - - try { - //get token from Request - final String tokenBase64 = request.getParameter(EidasParameterKeys.TOKEN.toString()); - if (StringUtils.isEmpty(tokenBase64)) { - log.warn("NO eIDAS message token found."); - throw new eIDASAuthenticationException("eidas.04", null); - - } - log.trace("Receive eIDAS-node token: " + tokenBase64 + " Starting transaction-restore process ... "); - - - - final SpecificConnectorCommunicationServiceImpl specificConnectorCommunicationService = - (SpecificConnectorCommunicationServiceImpl) context.getBean(SpecificCommunicationDefinitionBeanNames.SPECIFIC_CONNECTOR_COMMUNICATION_SERVICE.toString()); - ILightResponse eIDASResponse = specificConnectorCommunicationService.getAndRemoveResponse(tokenBase64, - ImmutableSortedSet.copyOf(attrRegistry.getCoreAttributeRegistry().getAttributes())); - - String pendingReqId = null; - if (StringUtils.isEmpty(eIDASResponse.getRelayState())) { - log.debug("eIDAS Node returns no RelayState. "); - - if (authConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_NODE_WORKAROUND_USEREQUESTIDASTRANSACTIONIDENTIFIER, - false)) { - log.trace("Use lightRequestId to recover session ... "); - pendingReqId = transactionStorage.get(eIDASResponse.getInResponseToId(), String.class); - if (StringUtils.isNotEmpty(pendingReqId)) { - log.debug("Restoring session with lightRequestId ... "); - transactionStorage.remove(eIDASResponse.getInResponseToId()); - - } - } - - } else { - log.debug("Find transaction identifier in SAML2 'RelayState': " + eIDASResponse.getRelayState()); - pendingReqId = eIDASResponse.getRelayState(); - - } - - if (StringUtils.isNotEmpty(pendingReqId)) { - request.setAttribute(Constants.DATA_FULL_EIDAS_RESPONSE, eIDASResponse); - return pendingReqId; - - } - - log.info("NO transaction identifier found! Stopping process ...."); - log.trace("FullResponse: " + eIDASResponse.toString()); - - } catch (SpecificCommunicationException e) { - log.warn("Can NOT load eIDAS Response from cache.", e); - log.debug("eIDAS response token was: " + request.getParameter(EidasParameterKeys.TOKEN.toString())); - - } catch (Exception e) { - log.warn("Unable to retrieve moa session id.", e); - - } - - return null; - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/SZRCommunicationException.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/SZRCommunicationException.java deleted file mode 100644 index a0c3cf88..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/SZRCommunicationException.java +++ /dev/null @@ -1,15 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception; - -public class SZRCommunicationException extends eIDASAuthenticationException { - - private static final long serialVersionUID = 1L; - - public SZRCommunicationException(String internalMsgId, Object[] params) { - super(internalMsgId, params); - } - - public SZRCommunicationException(String internalMsgId, Object[] params, Throwable e) { - super(internalMsgId, params, e); - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAttributeException.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAttributeException.java deleted file mode 100644 index f1d4280f..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAttributeException.java +++ /dev/null @@ -1,15 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception; - -public class eIDASAttributeException extends eIDASAuthenticationException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public eIDASAttributeException(String attrbuteName) { - super("eidas.00", new Object[] {attrbuteName}); - - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAuthenticationException.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAuthenticationException.java deleted file mode 100644 index 939e7471..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASAuthenticationException.java +++ /dev/null @@ -1,20 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception; - -import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; - -public class eIDASAuthenticationException extends EAAFAuthenticationException{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public eIDASAuthenticationException(String internalMsgId, Object[] params) { - super(internalMsgId, params); - } - - public eIDASAuthenticationException(String internalMsgId, Object[] params, Throwable e) { - super(internalMsgId, params, e); - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASValidationException.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASValidationException.java deleted file mode 100644 index 7b81eacd..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/exception/eIDASValidationException.java +++ /dev/null @@ -1,14 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception; - -public class eIDASValidationException extends eIDASAuthenticationException { - - /** - * - */ - private static final long serialVersionUID = 1L; - - public eIDASValidationException(String internalMsgId, Object[] params) { - super(internalMsgId, params); - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/service/eIDASAttributeRegistry.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/service/eIDASAttributeRegistry.java deleted file mode 100644 index 2bb3e0b0..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/service/eIDASAttributeRegistry.java +++ /dev/null @@ -1,115 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.service; - -import java.io.File; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.Constants; -import eu.eidas.auth.commons.attribute.AttributeRegistries; -import eu.eidas.auth.commons.attribute.AttributeRegistry; - -@Service("attributeRegistry") -public class eIDASAttributeRegistry { - private static final Logger log = LoggerFactory.getLogger(eIDASAttributeRegistry.class); - @Autowired private IConfiguration basicConfig; - - private AttributeRegistry coreAttributeRegistry; - - private String eidasAttributesFile; - private String additionalAttributesFile; - - @PostConstruct - private void initialize() throws RuntimeException { - try { - if (eidasAttributesFile.isEmpty()) { - log.error("Basic eIDAS addribute definition NOT defined"); - throw new EAAFConfigurationException("config.30", - new Object[] {"eidas-attributes.xml"}); - - } - - boolean additionalAttrAvailabe = false; - if (!additionalAttributesFile.isEmpty()) { - File file = new File(additionalAttributesFile); - if (file.exists()) - additionalAttrAvailabe = true; - - } - - if (!additionalAttrAvailabe) { - log.info("Start eIDAS ref. impl. Core without additional eIDAS attribute definitions ... "); - coreAttributeRegistry = AttributeRegistries.fromFiles(eidasAttributesFile, null); - - } else { - //load attribute definitions - log.info("Start eIDAS ref. impl. Core with additional eIDAS attribute definitions ... "); - coreAttributeRegistry = AttributeRegistries.fromFiles(eidasAttributesFile, null, additionalAttributesFile); - - } - - } catch (Throwable e) { - log.error("Can NOT initialize eIDAS attribute definition." , e); - new RuntimeException("Can NOT initialize eIDAS attribute definition.", e); - - } - } - - - public AttributeRegistry getCoreAttributeRegistry() { - return coreAttributeRegistry; - } - - public Map getAttributeSetFromConfiguration() { - Map result = new HashMap(); - - /*TODO: select set for representation if mandates should be used. - * It's an open task in respect to requested eIDAS attributes and isRequired flag, - * because there can be a decision problem in case of natural or legal person representation! - * From an Austrian use-case point of view, an Austrian service provider can support mandates for - * natural and legal persons at the same time. However, we CAN NOT request attributes for natural AND - * legal persons on the same time, because it's not possible to represent both simultaneously. - */ - Map configAttributes = - basicConfig.getBasicMOAIDConfigurationWithPrefix( - Constants.CONIG_PROPS_EIDAS_NODE_ATTRIBUTES_REQUESTED_ONLYNATURAL); - for (String el: configAttributes.values()) { - if (StringUtils.isNotEmpty(el.trim())) { - List attrDef = KeyValueUtils.getListOfCSVValues(el.trim()); - boolean isRequired = false; - if (attrDef.size() == 2) - isRequired = Boolean.parseBoolean(attrDef.get(1)); - - result.put(attrDef.get(0), isRequired); - - } - } - - log.trace("Load #" + result.size() + " requested attributes from configuration"); - return result; - - } - - - public void setEidasAttributesFile(String eidasAttributesFile) { - this.eidasAttributesFile = eidasAttributesFile; - } - - public void setAdditionalAttributesFile(String additionalAttributesFile) { - this.additionalAttributesFile = additionalAttributesFile; - } - - -} - diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/szr/SZRClient.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/szr/SZRClient.java deleted file mode 100644 index 86f0d0bb..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/szr/SZRClient.java +++ /dev/null @@ -1,372 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.szr; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.net.URL; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.security.UnrecoverableKeyException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import javax.annotation.PostConstruct; -import javax.annotation.Resource; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; -import javax.xml.namespace.QName; -import javax.xml.transform.Source; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; -import javax.xml.ws.BindingProvider; -import javax.xml.ws.Dispatch; -import javax.xml.ws.WebServiceContext; -import javax.xml.ws.handler.Handler; - -import org.apache.commons.lang3.StringUtils; -import org.apache.cxf.configuration.jsse.TLSClientParameters; -import org.apache.cxf.endpoint.Client; -import org.apache.cxf.frontend.ClientProxy; -import org.apache.cxf.jaxws.DispatchImpl; -import org.apache.cxf.transport.http.HTTPConduit; -import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; -import org.apache.xpath.XPathAPI; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.w3._2000._09.xmldsig.KeyValueType; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import at.gv.egiz.eaaf.core.api.data.XMLNamespaceConstants; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; -import at.gv.egiz.eaaf.core.impl.utils.FileUtils; -import at.gv.egiz.eaaf.core.impl.utils.KeyStoreUtils; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.Constants; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception.SZRCommunicationException; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.utils.LoggingHandler; -import szrservices.GetBPK; -import szrservices.GetBPKResponse; -import szrservices.GetIdentityLink; -import szrservices.GetIdentityLinkResponse; -import szrservices.IdentityLinkType; -import szrservices.PersonInfoType; -import szrservices.SZR; -import szrservices.SZRException_Exception; - -@Service("SZRClientForeIDAS") -public class SZRClient { - private static final Logger log = LoggerFactory.getLogger(SZRClient.class); - - private static final String CLIENT_DEFAULT = "DefaultClient"; - private static final String CLIENT_RAW = "RawClient"; - - @Autowired private IConfiguration basicConfig; - @Resource private WebServiceContext wsContext; - - //client for anything, without identitylink - private SZR szr = null; - - //RAW client is needed for identitylink - private Dispatch dispatch = null; - - - private SZRService szrService = null; - private String szrURL = null; - private QName qname = null; - - public IdentityLinkType getIdentityLink(PersonInfoType personInfo, List keyValue, Boolean insertERnP) throws SZRCommunicationException { - try { - return szr.getIdentityLink( - personInfo, - keyValue, - insertERnP); - - } catch (SZRException_Exception e) { - log.warn("SZR communication FAILED. Reason: " + e.getMessage(), e); - throw new SZRCommunicationException("ernb.02", new Object[] {e.getMessage()}, e); - - } - - } - - public IdentityLinkType getIdentityLinkInRawMode(PersonInfoType personInfo, List keyValue, Boolean insertERnP) throws SZRCommunicationException { - try { - GetIdentityLink getIDL = new GetIdentityLink(); - getIDL.setInsertERnP(insertERnP); - getIDL.setPersonInfo(personInfo); - getIDL.getKeyValue().addAll(keyValue); - - JAXBContext jaxbContext = JAXBContext.newInstance(GetIdentityLink.class); - Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); - - final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - jaxbMarshaller.marshal(getIDL, outputStream); - outputStream.flush(); - - Source source = new StreamSource(new ByteArrayInputStream(outputStream.toByteArray())); - outputStream.close(); - - log.trace("Requesting SZR ... "); - Source response = dispatch.invoke(source); - log.trace("Receive RAW response from SZR"); - - byte[] szrResponse = sourceToByteArray(response); - JAXBContext ctx = JAXBContext.newInstance(IdentityLinkType.class - .getPackage().getName()); - GetIdentityLinkResponse jaxbElement = (GetIdentityLinkResponse) ctx - .createUnmarshaller().unmarshal(new ByteArrayInputStream(szrResponse)); - - - //build response - log.trace(new String(szrResponse)); - log.trace("Signature successfully created. Extracting from MOA-SS container."); - - // ok, we have success - Document doc = DOMUtils.parseDocument( - new ByteArrayInputStream(szrResponse), - true, XMLNamespaceConstants.ALL_SCHEMA_LOCATIONS, null, null - ); - String xpathExpression = "//saml:Assertion"; - Element nsNode = doc.createElementNS("urn:oasis:names:tc:SAML:1.0:assertion", "saml:NSNode"); - - log.trace("Selecting signed doc " + xpathExpression); - Element documentNode = (Element) XPathAPI.selectSingleNode(doc, - xpathExpression, nsNode); - log.trace("Signed document: " + DOMUtils.serializeNode(documentNode)); - - - IdentityLinkType idl = new IdentityLinkType(); - idl.setAssertion(documentNode); - idl.setPersonInfo(jaxbElement.getGetIdentityLinkReturn().getPersonInfo()); - - return idl; - - - //IdentityLinkType idlResp = this.szr.getIdentityLink(personInfo, keyValue, insertERnP); - - } catch ( Exception e) { - log.warn("SZR communication FAILED. Reason: " + e.getMessage(), e); - throw new SZRCommunicationException("ernb.02", new Object[] {e.getMessage()}, e); - - } - - } - - public String getBPK(PersonInfoType personInfo, String target, String vkz) throws SZRCommunicationException { - try { - GetBPK parameters = new GetBPK(); - parameters.setPersonInfo(personInfo); - parameters.setBereichsKennung(target); - parameters.setVKZ(vkz); - GetBPKResponse result = this.szr.getBPK(parameters); - - return result.getGetBPKReturn(); - - } catch (SZRException_Exception e) { - log.warn("SZR communication FAILED. Reason: " + e.getMessage(), e); - throw new SZRCommunicationException("ernb.02", new Object[] {e.getMessage()}, e); - - } - - } - - - @PostConstruct - private void initialize() { - log.info("Starting SZR-Client initialization .... "); - URL url = SZRClient.class.getResource("/szr_client/SZR-1.WSDL"); - - boolean useTestSZR = basicConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_USETESTSERVICE, - true); - - if (useTestSZR) { - log.debug("Initializing SZR test environment configuration."); - qname = SZRService.SZRTestumgebung; - szrService = new SZRService(url, new QName("urn:SZRServices", "SZRService")); - szr = szrService.getSZRTestumgebung(); - szrURL = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_ENDPOINT_TEST); - - - } else { - log.debug("Initializing SZR productive configuration."); - qname = SZRService.SZRProduktionsumgebung; - szrService = new SZRService(url, new QName("urn:SZRServices", "SZRService")); - szr = szrService.getSZRProduktionsumgebung(); - szrURL = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_ENDPOINT_PROD); - - } - - //create raw client; - dispatch = szrService.createDispatch(qname, Source.class, javax.xml.ws.Service.Mode.PAYLOAD); - - if (StringUtils.isEmpty(szrURL)) { - log.error("No SZR service-URL found. SZR-Client initalisiation failed."); - throw new RuntimeException("No SZR service URL found. SZR-Client initalisiation failed."); - - } - - log.info("Use SZR service-URL: " + szrURL); - injectBindingProvider((BindingProvider) szr, CLIENT_DEFAULT); - injectBindingProvider((BindingProvider) dispatch, CLIENT_RAW); - - log.debug("Inject HTTP client settings ... "); - injectHTTPClient(szr, CLIENT_DEFAULT); - injectHTTPClient(dispatch, CLIENT_RAW); - - log.info("SZR-Client initialization successfull"); - } - - private void injectHTTPClient(Object raw, String clientType) { - //extract client from implementation - Client client = null; - if (raw instanceof DispatchImpl) - client = ((DispatchImpl)raw).getClient(); - else if (raw instanceof Client) - client = ClientProxy.getClient(raw); - else - throw new RuntimeException("SOAP Client for SZR connection is of UNSUPPORTED type: " + raw.getClass().getName()); - - //set basic connection policies - HTTPConduit http = (HTTPConduit) client.getConduit(); - - //set timeout policy - HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy(); - httpClientPolicy.setConnectionTimeout( - Integer.parseInt(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_TIMEOUT_CONNECTION, - Constants.HTTP_CLIENT_DEFAULT_TIMEOUT_CONNECTION)) * 1000); - httpClientPolicy.setReceiveTimeout( - Integer.parseInt(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_TIMEOUT_RESPONSE, - Constants.HTTP_CLIENT_DEFAULT_TIMEOUT_RESPONSE)) * 1000); - http.setClient(httpClientPolicy); - - //inject SSL context in case of https - if (szrURL.toLowerCase().startsWith("https")) { - log.debug("Adding SSLContext to client: " + clientType +" ... "); - TLSClientParameters tlsParams = new TLSClientParameters(); - tlsParams.setSSLSocketFactory(createSSLContext(clientType).getSocketFactory()); - http.setTlsClientParameters(tlsParams ); - log.info("SSLContext initialized for client: " + clientType); - - } - - } - - private void injectBindingProvider(BindingProvider bindingProvider, String clientType) { - Map requestContext = bindingProvider.getRequestContext(); - requestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, szrURL); - - log.trace("Adding JAX-WS request/response trace handler to client: " + clientType); - List handlerList = bindingProvider.getBinding().getHandlerChain(); - if (handlerList == null) { - handlerList = new ArrayList(); - bindingProvider.getBinding().setHandlerChain(handlerList); - - } - - //add logging handler to trace messages if required - if (basicConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_TRACEMESSAGES, - false)) { - LoggingHandler loggingHandler = new LoggingHandler(); - handlerList.add(loggingHandler); - - } - } - - private SSLContext createSSLContext(String clientType) { - try { - SSLContext context = SSLContext.getInstance("TLS"); - - //initialize key-mangager for SSL client-authentication - KeyManager[] keyManager = null; - String keyStorePath = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_SSL_KEYSTORE_PATH); - String keyStorePassword = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_SSL_KEYSTORE_PASSWORD); - if (StringUtils.isNotEmpty(keyStorePath)) { - log.trace("Find keyStore path: " + keyStorePath + " Injecting SSL client certificate ... "); - try { - KeyStore keyStore = KeyStoreUtils.loadKeyStore( - FileUtils.makeAbsoluteURL(keyStorePath, basicConfig.getConfigurationRootDirectory()), - keyStorePassword); - - KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); - kmf.init(keyStore, keyStorePassword.toCharArray()); - keyManager = kmf.getKeyManagers(); - log.debug("SSL client certificate injected to client: " + clientType); - - } catch (KeyStoreException | IOException | UnrecoverableKeyException e) { - log.error("Can NOT load SSL client certificate from path: " + keyStorePath); - throw new RuntimeException("Can NOT load SSL client certificate from path: " + keyStorePath, e); - - } - } - - - //initialize SSL TrustStore - TrustManager[] trustManager = null; - String trustStorePath = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_SSL_TRUSTSTORE_PATH); - String trustStorePassword = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_SZRCLIENT_SSL_TRUSTSTORE_PASSWORD); - if (StringUtils.isNotEmpty(trustStorePath)) { - log.trace("Find trustStore path: " + trustStorePath + " Injecting SSL TrustStore ... "); - try { - KeyStore trustStore = KeyStoreUtils.loadKeyStore( - FileUtils.makeAbsoluteURL(trustStorePath, basicConfig.getConfigurationRootDirectory()), - trustStorePassword); - - TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); - tmf.init(trustStore); - trustManager = tmf.getTrustManagers(); - log.debug("SSL TrustStore injected to client: " + clientType); - - } catch (KeyStoreException | IOException e) { - log.error("Can NOT open SSL TrustStore from path: " + trustStorePath); - throw new RuntimeException("Can NOT open SSL TrustStore from path: " + trustStorePath, e); - - } - - } - - - context.init(keyManager, trustManager, new SecureRandom()); - return context; - - } catch (NoSuchAlgorithmException | KeyManagementException e) { - log.error("SSLContext initialization FAILED.", e); - throw new RuntimeException("SSLContext initialization FAILED.", e); - - } - - } - - private byte[] sourceToByteArray(Source result) throws TransformerException { - TransformerFactory factory = TransformerFactory.newInstance(); - Transformer transformer = factory.newTransformer(); - transformer.setOutputProperty("omit-xml-declaration", "yes"); - transformer.setOutputProperty("method", "xml"); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - StreamResult streamResult = new StreamResult(); - streamResult.setOutputStream(out); - transformer.transform(result, streamResult); - return out.toByteArray(); - } - - - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/szr/SZRService.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/szr/SZRService.java deleted file mode 100644 index 8e4911b9..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/szr/SZRService.java +++ /dev/null @@ -1,139 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.szr; - -import java.net.URL; - -import javax.xml.namespace.QName; -import javax.xml.ws.Service; -import javax.xml.ws.WebEndpoint; -import javax.xml.ws.WebServiceClient; -import javax.xml.ws.WebServiceFeature; - -import szrservices.SZR; - -/** - * This class was generated by Apache CXF 3.1.16 - * 2018-07-10T09:36:01.466+02:00 - * Generated source version: 3.1.16 - * - */ -@WebServiceClient(name = "SZRService", - wsdlLocation = "./src/main/resources/szr_client/SZR-1.WSDL", - targetNamespace = "urn:SZRServices") -public class SZRService extends Service { - - public final static URL WSDL_LOCATION; - - public final static QName SERVICE = new QName("urn:SZRServices", "SZRService"); - public final static QName SZRProduktionsumgebung = new QName("urn:SZRServices", "SZRProduktionsumgebung"); - public final static QName SZRTestumgebung = new QName("urn:SZRServices", "SZRTestumgebung"); - public final static QName SZRBusinesspartnerTestumgebung = new QName("urn:SZRServices", "SZRBusinesspartnerTestumgebung"); - static { - URL url = SZRService.class.getResource("./src/main/resources/szr_client/SZR-1.WSDL"); - if (url == null) { - url = SZRService.class.getClassLoader().getResource("/szr_client/SZR-1.WSDL"); - } - if (url == null) { - java.util.logging.Logger.getLogger(SZRService.class.getName()) - .log(java.util.logging.Level.INFO, - "Can not initialize the default wsdl from {0}", "/szr_client/SZR-1.WSDL"); - } - WSDL_LOCATION = url; - - } - - public SZRService(URL wsdlLocation) { - super(wsdlLocation, SERVICE); - } - - public SZRService(URL wsdlLocation, QName serviceName) { - super(wsdlLocation, serviceName); - } - - public SZRService() { - super(WSDL_LOCATION, SERVICE); - } - - public SZRService(WebServiceFeature ... features) { - super(WSDL_LOCATION, SERVICE, features); - } - - public SZRService(URL wsdlLocation, WebServiceFeature ... features) { - super(wsdlLocation, SERVICE, features); - } - - public SZRService(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) { - super(wsdlLocation, serviceName, features); - } - - - - - /** - * - * @return - * returns SZR - */ - @WebEndpoint(name = "SZRProduktionsumgebung") - public SZR getSZRProduktionsumgebung() { - return super.getPort(SZRProduktionsumgebung, SZR.class); - } - - /** - * - * @param features - * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. - * @return - * returns SZR - */ - @WebEndpoint(name = "SZRProduktionsumgebung") - public SZR getSZRProduktionsumgebung(WebServiceFeature... features) { - return super.getPort(SZRProduktionsumgebung, SZR.class, features); - } - - - /** - * - * @return - * returns SZR - */ - @WebEndpoint(name = "SZRTestumgebung") - public SZR getSZRTestumgebung() { - return super.getPort(SZRTestumgebung, SZR.class); - } - - /** - * - * @param features - * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. - * @return - * returns SZR - */ - @WebEndpoint(name = "SZRTestumgebung") - public SZR getSZRTestumgebung(WebServiceFeature... features) { - return super.getPort(SZRTestumgebung, SZR.class, features); - } - - - /** - * - * @return - * returns SZR - */ - @WebEndpoint(name = "SZRBusinesspartnerTestumgebung") - public SZR getSZRBusinesspartnerTestumgebung() { - return super.getPort(SZRBusinesspartnerTestumgebung, SZR.class); - } - - /** - * - * @param features - * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the features parameter will have their default values. - * @return - * returns SZR - */ - @WebEndpoint(name = "SZRBusinesspartnerTestumgebung") - public SZR getSZRBusinesspartnerTestumgebung(WebServiceFeature... features) { - return super.getPort(SZRBusinesspartnerTestumgebung, SZR.class, features); - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/CreateIdentityLinkTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/CreateIdentityLinkTask.java deleted file mode 100644 index 8766783f..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/CreateIdentityLinkTask.java +++ /dev/null @@ -1,380 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.tasks; - -import java.io.InputStream; -import java.math.BigInteger; -import java.security.KeyFactory; -import java.security.NoSuchAlgorithmException; -import java.security.PublicKey; -import java.security.interfaces.RSAPublicKey; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.joda.time.DateTime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.util.Base64Utils; -import org.w3._2000._09.xmldsig.KeyValueType; -import org.w3._2000._09.xmldsig.RSAKeyValueType; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; - -import at.gv.e_government.reference.namespace.persondata._20020228.PersonNameType; -import at.gv.e_government.reference.namespace.persondata._20020228.PhysicalPersonType; -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.data.Pair; -import at.gv.egiz.eaaf.core.impl.data.Trible; -import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BPKBuilder; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; -import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; -import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; -import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; -import at.gv.egiz.eidas.specific.connector.MSConnectorEventCodes; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.Constants; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception.SZRCommunicationException; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASAttributeException; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.szr.SZRClient; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.utils.eIDASResponseUtils; -import eu.eidas.auth.commons.attribute.AttributeDefinition; -import eu.eidas.auth.commons.attribute.AttributeValue; -import eu.eidas.auth.commons.light.ILightResponse; -import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress; -import szrservices.IdentityLinkType; -import szrservices.PersonInfoType; -import szrservices.TravelDocumentType; - -/** - * @author tlenz - * - */ -@Component("CreateIdentityLinkTask") -public class CreateIdentityLinkTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(CreateIdentityLinkTask.class); - - //@Autowired private eIDASAttributeRegistry attrRegistry; - @Autowired private IConfiguration basicConfig; - @Autowired private SZRClient szrClient; - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public void execute(ExecutionContext executionContext, - HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - try{ - AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - ILightResponse eIDASResponse = authProcessData.getGenericDataFromSession( - Constants.DATA_FULL_EIDAS_RESPONSE, ILightResponse.class); - Map simpleAttrMap = converteIDASAttrToSimpleMap(eIDASResponse.getAttributes().getAttributeMap()); - - IIdentityLink identityLink = null; - String bPK = null; - - //extract attributes - Object eIdentifierObj = simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER); - Object familyNameObj = simpleAttrMap.get(Constants.eIDAS_ATTR_CURRENTFAMILYNAME); - Object givenNameObj = simpleAttrMap.get(Constants.eIDAS_ATTR_CURRENTGIVENNAME); - Object dateOfBirthObj = simpleAttrMap.get(Constants.eIDAS_ATTR_DATEOFBIRTH); - - //check if availabe - if (eIdentifierObj == null || !(eIdentifierObj instanceof String)) - throw new eIDASAttributeException(Constants.eIDAS_ATTR_PERSONALIDENTIFIER); - - if (familyNameObj == null || !(familyNameObj instanceof String)) - throw new eIDASAttributeException(Constants.eIDAS_ATTR_CURRENTFAMILYNAME); - - if (givenNameObj == null || !(givenNameObj instanceof String)) - throw new eIDASAttributeException(Constants.eIDAS_ATTR_CURRENTGIVENNAME); - - if (dateOfBirthObj == null || !(dateOfBirthObj instanceof DateTime)) - throw new eIDASAttributeException(Constants.eIDAS_ATTR_DATEOFBIRTH); - - //connect SZR-Gateway - if(basicConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_USEDUMMY, false)) { - log.warn("SZR-Dummy IS ACTIVE! IdentityLink is NOT VALID!!!!"); - // create fake IdL - // - fetch IdL template from resources - InputStream s = CreateIdentityLinkTask.class.getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); - Element idlTemplate = DOMUtils.parseXmlValidating(s); - - identityLink = new SimpleIdentityLinkAssertionParser(idlTemplate).parseIdentityLink(); - - // replace data - Element idlassertion = identityLink.getSamlAssertion(); - - // - set fake baseID; - Node prIdentification = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - prIdentification.getFirstChild().setNodeValue((String) eIdentifierObj); - - //build personal identifier which looks like a baseID -// String fakeBaseID = new BPKBuilder().buildBPK(eIdentifier, "baseID"); -// Logger.info("Map eIDAS eIdentifier:" + eIdentifier + " to fake baseID:" + fakeBaseID); -// prIdentification.getFirstChild().setNodeValue(fakeBaseID); - - // - set last name - Node prFamilyName = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH); - prFamilyName.getFirstChild().setNodeValue((String) familyNameObj); - - // - set first name - Node prGivenName = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH); - prGivenName.getFirstChild().setNodeValue((String) givenNameObj); - - // - set date of birth - Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion, SimpleIdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH); - String formatedDateOfBirth = new SimpleDateFormat("yyyy-MM-dd").format(((DateTime)dateOfBirthObj).toDate()); - prDateOfBirth.getFirstChild().setNodeValue(formatedDateOfBirth); - - identityLink = new SimpleIdentityLinkAssertionParser(idlassertion).parseIdentityLink(); - - Pair bPKCalc = new BPKBuilder().generateAreaSpecificPersonIdentifier( - identityLink.getIdentificationValue(), - identityLink.getIdentificationType(), - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); - bPK = bPKCalc.getFirst(); - - - } else { - //contact SZR Gateway - log.debug("Starting connecting SZR Gateway"); - PersonInfoType personInfo = new PersonInfoType(); - PersonNameType personName = new PersonNameType(); - PhysicalPersonType naturalPerson = new PhysicalPersonType(); - TravelDocumentType eDocument = new TravelDocumentType(); - - naturalPerson.setName(personName ); - personInfo.setPerson(naturalPerson ); - personInfo.setTravelDocument(eDocument ); - - //parse some eID attributes - String dateOfBirth = new SimpleDateFormat("yyyy-MM-dd").format(((DateTime)dateOfBirthObj).toDate()); - Trible eIdentifier = - eIDASResponseUtils.parseEidasPersonalIdentifier((String)eIdentifierObj); - String uniqueId = (String)eIdentifierObj; - String citizenCountry = eIdentifier.getFirst(); - - //person information - personName.setFamilyName((String)familyNameObj); - personName.setGivenName((String)givenNameObj); - naturalPerson.setDateOfBirth(dateOfBirth); - eDocument.setIssuingCountry(citizenCountry); - eDocument.setDocumentNumber(uniqueId); - - //eID document information - eDocument.setDocumentType(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, - Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); - - //TODO: that should be removed - eDocument.setIssueDate(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_DATE, - Constants.SZR_CONSTANTS_DEFAULT_ISSUING_DATE)); - eDocument.setIssuingAuthority(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_AUTHORITY, - Constants.SZR_CONSTANTS_DEFAULT_ISSUING_AUTHORITY)); - - //TODO: keys are not available in eIDAS - List keyValue = dummyCodeForKeys(); - - /*TODO: - * Validate if IDL signature is valid after using this method - * MAYBE we had to switch to 'getIdentityLinkInRawMode' method! - */ - IdentityLinkType result = szrClient.getIdentityLink( - personInfo, - keyValue, - basicConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_INSERTERNB, - true) - ); - - Element idlFromSZR = (Element)result.getAssertion(); - identityLink = new SimpleIdentityLinkAssertionParser(idlFromSZR).parseIdentityLink(); - - - //get bPK from SZR - bPK = szrClient.getBPK( - personInfo, - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier(), - basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, - "no VKZ defined")); - - } - - if (identityLink == null) { - log.error("ERnB did not return an identity link."); - throw new SZRCommunicationException("ernb.00", null); - - } - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.SZR_IDL_RECEIVED); - - - if (bPK == null) { - log.error("ERnB did not return a bPK for target: " + pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); - throw new SZRCommunicationException("ernb.01", null); - - } - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.SZR_BPK_RECEIVED); - - log.debug("ERnB communication was successfull"); - - authProcessData.setForeigner(true); - authProcessData.setIdentityLink(identityLink); - authProcessData.setGenericDataToSession( - PVPAttributeDefinitions.EID_ISSUING_NATION_NAME, - eIDASResponseUtils.parseEidasPersonalIdentifier((String) simpleAttrMap.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)).getFirst()); - - //set bPK and bPKType into auth session - authProcessData.setGenericDataToSession( - PVPAttributeDefinitions.BPK_NAME, - extendBPKbyPrefix( - bPK, - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()) - ); - authProcessData.setGenericDataToSession( - PVPAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME, - pendingReq.getServiceProviderConfiguration().getAreaSpecificTargetIdentifier()); - - - - //store pending-request - requestStoreage.storePendingRequest(pendingReq); - - } catch (eIDASAttributeException e) { - throw new TaskExecutionException(pendingReq, "Minimum required eIDAS attributeset not found.", e); - - } catch (EAAFException e) { - throw new TaskExecutionException(pendingReq, "IdentityLink generation for foreign person FAILED.", e); - - } catch (Exception e) { - log.error("IdentityLink generation for foreign person FAILED.", e); - throw new TaskExecutionException(pendingReq, "IdentityLink generation for foreign person FAILED.", e); - - } - } - - private List dummyCodeForKeys() { - if (basicConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_KEYS_USEDUMMY, - false)) { - List keyvalueList = new ArrayList(); - try { - PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Constants.SZR_CONSTANTS_DEFAULT_PUBL_KEY); - KeyFactory kf = KeyFactory.getInstance("RSA"); - - PublicKey pb = kf.generatePublic(spec); - - RSAPublicKey rsapb = (RSAPublicKey)pb; - BigInteger modulus = rsapb.getModulus(); - BigInteger exponent = rsapb.getPublicExponent(); - - // set key values - RSAKeyValueType rsa = new RSAKeyValueType(); - rsa.setExponent(new String(Base64Utils.encode(exponent.toByteArray()))); - rsa.setModulus(new String(Base64Utils.encode(modulus.toByteArray()))); - - KeyValueType key = new KeyValueType(); - key.setRSAKeyValue(rsa); - - keyvalueList.add(key); - - return keyvalueList; - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - log.error("TestCode has an internal ERROR", e); - - } - - } - - return null; - - } - - private String extendBPKbyPrefix(String bpk, String type) { - String bPKType = null; - - if (type.startsWith(EAAFConstants.URN_PREFIX_WBPK)) - bPKType = type.substring((EAAFConstants.URN_PREFIX_WBPK).length()); - - else if (type.startsWith(EAAFConstants.URN_PREFIX_CDID)) - bPKType = type.substring((EAAFConstants.URN_PREFIX_CDID).length()); - - else if (type.startsWith(EAAFConstants.URN_PREFIX_EIDAS)) - bPKType = type.substring((EAAFConstants.URN_PREFIX_EIDAS).length()); - - - if (bPKType != null ) { - log.trace("Authenticate user with bPK/wbPK " + bpk + " and Type=" + bPKType); - return bPKType + ":" + bpk; - - } else { - log.warn("Service Provider Target with: " + type + " is NOT supported. Set bPK as it is ..."); - return bpk; - - } - - } - - //TODO: update for complexe attributes - private Map converteIDASAttrToSimpleMap( - ImmutableMap, ImmutableSet>> attributeMap) { - Map result = new HashMap(); - - for (AttributeDefinition el : attributeMap.keySet()) { - - final Class parameterizedType = el.getParameterizedType(); - if ((DateTime.class).equals(parameterizedType)) { - DateTime attribute = eIDASResponseUtils.translateDateAttribute(el, attributeMap.get(el).asList()); - if (attribute != null) - result.put(el.getFriendlyName(), attribute); - else - log.info("Ignore empty 'DateTime' attribute"); - - } else if ((PostalAddress.class).equals(parameterizedType)) { - PostalAddress addressAttribute = eIDASResponseUtils.translateAddressAttribute(el, attributeMap.get(el).asList()); - if (addressAttribute != null) - result.put(el.getFriendlyName(), addressAttribute); - else - log.info("Ignore empty 'PostalAddress' attribute"); - - } else { - List natPersonIdObj = eIDASResponseUtils.translateStringListAttribute(el, attributeMap.get(el).asList()); - String stringAttr = natPersonIdObj.get(0); - if (StringUtils.isNotEmpty(stringAttr)) - result.put(el.getFriendlyName(), stringAttr); - else - log.info("Ignore empty 'String' attribute"); - - } - } - - return result; - } - - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/GenerateAuthnRequestTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/GenerateAuthnRequestTask.java deleted file mode 100644 index 111aa00f..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/GenerateAuthnRequestTask.java +++ /dev/null @@ -1,306 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.tasks; - -import java.util.Map; -import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; -import org.springframework.web.util.UriComponentsBuilder; - -import com.google.common.collect.ImmutableSortedSet; - -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; -import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; -import at.gv.egiz.eidas.specific.connector.MSConnectorEventCodes; -import at.gv.egiz.eidas.specific.connector.MSeIDASNodeConstants; -import at.gv.egiz.eidas.specific.connector.gui.StaticGuiBuilderConfiguration; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.Constants; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASAuthenticationException; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.service.eIDASAttributeRegistry; -import eu.eidas.auth.commons.EidasParameterKeys; -import eu.eidas.auth.commons.attribute.AttributeDefinition; -import eu.eidas.auth.commons.attribute.ImmutableAttributeMap; -import eu.eidas.auth.commons.light.ILightRequest; -import eu.eidas.auth.commons.light.impl.LightRequest; -import eu.eidas.auth.commons.protocol.eidas.SpType; -import eu.eidas.auth.commons.tx.BinaryLightToken; -import eu.eidas.specificcommunication.BinaryLightTokenHelper; -import eu.eidas.specificcommunication.SpecificCommunicationDefinitionBeanNames; -import eu.eidas.specificcommunication.exception.SpecificCommunicationException; -import eu.eidas.specificcommunication.protocol.impl.SpecificConnectorCommunicationServiceImpl; - -/** - * @author tlenz - * - */ -@Component("ConnecteIDASNodeTask") -public class GenerateAuthnRequestTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(GenerateAuthnRequestTask.class); - - @Autowired IConfiguration basicConfig; - @Autowired eIDASAttributeRegistry attrRegistry; - @Autowired ApplicationContext context; - @Autowired ITransactionStorage transactionStore; - @Autowired IGUIFormBuilder guiBuilder; - - @Override - public void execute(ExecutionContext executionContext, - HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - - try{ - //get service-provider configuration - ISPConfiguration spConfig = pendingReq.getServiceProviderConfiguration(); - - // get target, environment and validate citizen countryCode - String citizenCountryCode = (String) executionContext.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_COUNTRY); - String environment = (String) executionContext.get(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT); - - if (StringUtils.isEmpty(citizenCountryCode)) { - // illegal state; task should not have been executed without a selected country - throw new eIDASAuthenticationException("eidas.03", new Object[] { "" }); - - } - - //TODO: maybe add countryCode validation before request ref. impl. eIDAS node - log.debug("Request eIDAS auth. for citizen of country: " + citizenCountryCode); - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.COUNTRY_SELECTED, citizenCountryCode); - - //build eIDAS AuthnRequest - LightRequest.Builder authnRequestBuilder = LightRequest.builder(); - authnRequestBuilder.id(UUID.randomUUID().toString()); - - - String issur = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_ENTITYID); - if (StringUtils.isEmpty(issur)) { - log.error("Found NO 'eIDAS node issuer' in configuration. Authentication NOT possible!"); - throw new EAAFConfigurationException("config.27", - new Object[] {"Application config containts NO " + Constants.CONIG_PROPS_EIDAS_NODE_ENTITYID }); - - } - authnRequestBuilder.issuer(issur); - - - //TODO: set matching mode if eIDAS ref. impl. support this method - - - //TODO: update if eIDAS ref. impl. supports exact matching for non-notified LoA schemes - String loa = EAAFConstants.EIDAS_LOA_HIGH; - if (spConfig.getRequiredLoA() != null) { - if (spConfig.getRequiredLoA().isEmpty()) - log.info("No eIDAS LoA requested. Use LoA HIGH as default"); - - else { - if (spConfig.getRequiredLoA().size() > 1 ) - log.info("Currently only ONE requested LoA is supported for service provider. Use first one ... "); - - loa = spConfig.getRequiredLoA().get(0); - - } - } - - log.debug("Request eIdAS node with LoA: " + loa); - authnRequestBuilder.levelOfAssurance(loa); - - //set correct SPType for requested target sector - String publicSectorTargetSelector = basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_NODE_PUBLICSECTOR_TARGETS, - Constants.POLICY_DEFAULT_ALLOWED_TARGETS); - Pattern p = Pattern.compile(publicSectorTargetSelector); - Matcher m = p.matcher(spConfig.getAreaSpecificTargetIdentifier()); - if (m.matches()) { - log.debug("Map " + spConfig.getAreaSpecificTargetIdentifier() + " to 'PublicSector'"); - authnRequestBuilder.spType(SpType.PUBLIC.getValue()); - - //TODO: only for eIDAS ref. node 2.0 and 2.1 because it need 'Providername' for any SPType - String providerName = pendingReq.getRawData(Constants.DATA_PROVIDERNAME, String.class); - if (StringUtils.isNotEmpty(providerName) - && basicConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_NODE_WORKAROUND_ADD_ALWAYS_PROVIDERNAME, - false) - ) - authnRequestBuilder.providerName(providerName); - - } else { - log.debug("Map " + spConfig.getAreaSpecificTargetIdentifier() + " to 'PrivateSector'"); - authnRequestBuilder.spType(SpType.PRIVATE.getValue()); - - //TODO: switch to RequesterId in further version - //set provider name for private sector applications - String providerName = pendingReq.getRawData(Constants.DATA_PROVIDERNAME, String.class); - if (StringUtils.isNotEmpty(providerName)) - authnRequestBuilder.providerName(providerName); - - } - - //set nameIDFormat - authnRequestBuilder.nameIdFormat(Constants.eIDAS_REQ_NAMEID_FORMAT); - - //set citizen country code for foreign uses - authnRequestBuilder.citizenCountryCode(citizenCountryCode); - - //set relay state - authnRequestBuilder.relayState(pendingReq.getPendingRequestId()); - - //build and add requested attribute set - ImmutableAttributeMap reqAttrMap = translateToEidasAttributes(attrRegistry.getAttributeSetFromConfiguration()); - authnRequestBuilder.requestedAttributes(reqAttrMap); - - //build request - LightRequest lightAuthnReq = authnRequestBuilder.build(); - - //put request into cache - BinaryLightToken token = putRequestInCommunicationCache(lightAuthnReq); - final String tokenBase64 = BinaryLightTokenHelper.encodeBinaryLightTokenBase64(token); - - //Workaround, because eIDAS node ref. impl. does not return relayState - if (basicConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_NODE_WORKAROUND_USEREQUESTIDASTRANSACTIONIDENTIFIER, - false)) { - log.trace("Put lightRequestId into transactionstore as session-handling backup"); - transactionStore.put(lightAuthnReq.getId(), pendingReq.getPendingRequestId(), -1); - - } - - //select forward URL regarding the selected environment - String forwardURL = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL); - if (StringUtils.isNotEmpty(environment)) - forwardURL = selectedForwardURLForEnvironment(environment); - - if (StringUtils.isEmpty(forwardURL)) { - log.warn("NO ForwardURL defined in configuration. Can NOT forward to eIDAS node! Process stops"); - throw new EAAFConfigurationException("config.08", new Object[] {Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL}); - - } - log.debug("ForwardURL: " + forwardURL + " selected to forward eIDAS request"); - - if (basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_METHOD, - Constants.FORWARD_METHOD_GET - ).equals(Constants.FORWARD_METHOD_GET)) { - - log.debug("Use http-redirect for eIDAS node forwarding ... "); - //send redirect - UriComponentsBuilder redirectUrl = UriComponentsBuilder.fromHttpUrl(forwardURL); - redirectUrl.queryParam(EidasParameterKeys.TOKEN.toString(), tokenBase64); - response.sendRedirect(redirectUrl.build().encode().toString()); - - } else { - log.debug("Use http-post for eIDAS node forwarding ... "); - StaticGuiBuilderConfiguration config = new StaticGuiBuilderConfiguration( - basicConfig, - pendingReq, - Constants.TEMPLATE_POST_FORWARD_NAME, - null); - - config.putCustomParameter(Constants.TEMPLATE_POST_FORWARD_ENDPOINT, forwardURL); - config.putCustomParameter(Constants.TEMPLATE_POST_FORWARD_TOKEN_NAME, - EidasParameterKeys.TOKEN.toString()); - config.putCustomParameter(Constants.TEMPLATE_POST_FORWARD_TOKEN_VALUE, - tokenBase64); - - guiBuilder.build(response, config, "BKU-Selection form"); - - } - - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.EIDAS_NODE_CONNECTED, lightAuthnReq.getId()); - - - } catch (eIDASAuthenticationException e) { - throw new TaskExecutionException(pendingReq, "eIDAS AuthnRequest generation FAILED.", e); - - } catch (Exception e) { - log.warn("eIDAS AuthnRequest generation FAILED.", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } - - } - - /** - * Select a forward URL from configuration for a specific environment - *

- * Info: This method is needed, because eIDAS Ref. Impl only supports one countrycode on each instance. - * In consequence, more than one eIDAS Ref. Impl nodes are required to support producation, testing, or QS stages - * for one country by using one ms-specific eIDAS connector - * - * @param environment Environment selector from CountrySlection page - * @return - */ - private String selectedForwardURLForEnvironment(String environment) { - log.trace("Starting endpoint selection process for environment: " + environment + " ... "); - if (environment.equalsIgnoreCase(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_PRODUCTION)) - return basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL); - - else if (environment.equalsIgnoreCase(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_QS)) - return basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL - + "." + MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_QS); - - else if (environment.equalsIgnoreCase(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_TESTING)) - return basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL - + "." + MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_TESTING); - - else if (environment.equalsIgnoreCase(MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_DEVELOPMENT)) - return basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_FORWARD_URL - + "." + MSeIDASNodeConstants.REQ_PARAM_SELECTED_ENVIRONMENT_VALUE_DEVELOPMENT); - - log.info("Environment selector: " + environment + " is not supported"); - return null; - - } - - private ImmutableAttributeMap translateToEidasAttributes(final Map requiredAttributes) { - ImmutableAttributeMap.Builder builder = ImmutableAttributeMap.builder(); - for (Map.Entry attribute : requiredAttributes.entrySet()) { - final String name = attribute.getKey(); - final ImmutableSortedSet> byFriendlyName = attrRegistry.getCoreAttributeRegistry().getByFriendlyName(name); - if (!byFriendlyName.isEmpty()) { - final AttributeDefinition attributeDefinition = byFriendlyName.first(); - builder.put(AttributeDefinition.builder(attributeDefinition).required(attribute.getValue()).build()); - - } else - log.warn("Can NOT request UNKNOWN attribute: " + attribute.getKey() + " Ignore it!"); - - } - - return builder.build(); - - } - - private BinaryLightToken putRequestInCommunicationCache(ILightRequest iLightRequest) throws ServletException { - final BinaryLightToken binaryLightToken; - try { - final SpecificConnectorCommunicationServiceImpl springManagedSpecificConnectorCommunicationService = - (SpecificConnectorCommunicationServiceImpl) context.getBean(SpecificCommunicationDefinitionBeanNames.SPECIFIC_CONNECTOR_COMMUNICATION_SERVICE.toString()); - - binaryLightToken = springManagedSpecificConnectorCommunicationService.putRequest(iLightRequest); - - } catch (SpecificCommunicationException e) { - log.error("Unable to process specific request"); - throw new ServletException(e); - - } - - return binaryLightToken; - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/ReceiveAuthnResponseTask.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/ReceiveAuthnResponseTask.java deleted file mode 100644 index 16030c52..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/tasks/ReceiveAuthnResponseTask.java +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************* - *******************************************************************************/ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.tasks; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Component; - -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; -import at.gv.egiz.eaaf.core.exceptions.EAAFException; -import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; -import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; -import at.gv.egiz.eidas.specific.connector.MSConnectorEventCodes; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.Constants; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASAuthenticationException; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.service.eIDASAttributeRegistry; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.validator.eIDASResponseValidator; -import eu.eidas.auth.commons.light.ILightResponse; - -@Component("ReceiveResponseFromeIDASNodeTask") -public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { - private static final Logger log = LoggerFactory.getLogger(ReceiveAuthnResponseTask.class); - - @Autowired private ApplicationContext context; - @Autowired private IConfiguration basicConfig; - @Autowired private eIDASAttributeRegistry attrRegistry; - - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { - try{ - ILightResponse eIDASResponse = (ILightResponse) request.getAttribute(Constants.DATA_FULL_EIDAS_RESPONSE); - if (eIDASResponse == null) { - log.warn("NO eIDAS response-message found."); - throw new eIDASAuthenticationException("eidas.01", null); - - } - - log.debug("Receive eIDAS response with RespId:" + eIDASResponse.getId() + " for ReqId:" + eIDASResponse.getInResponseToId()); - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.RESPONSE_FROM_EIDAS_NODE, eIDASResponse.getId()); - - - //check response StatusCode - if (!eIDASResponse.getStatus().getStatusCode().equals(Constants.SUCCESS_URI)) { - log.info("Receice eIDAS Response with StatusCode:" + eIDASResponse.getStatus().getStatusCode() - + " Subcode:" + eIDASResponse.getStatus().getSubStatusCode() + " Msg:" + eIDASResponse.getStatus().getStatusMessage()); - throw new eIDASAuthenticationException("eidas.02", new Object[]{eIDASResponse.getStatus().getStatusCode(), eIDASResponse.getStatus().getStatusMessage()}); - - } - - // extract all Attributes from response - - - - // ********************************************************** - // ******* MS-specificresponse validation ********** - // ********************************************************** - String spCountry = basicConfig.getBasicConfiguration(Constants.CONIG_PROPS_EIDAS_NODE_COUNTRYCODE, "AT"); - eIDASResponseValidator.validateResponse(pendingReq, eIDASResponse, spCountry, attrRegistry); - - - // ********************************************************** - // ******* Store resonse infos into session object ********** - // ********************************************************** - - //update MOA-Session data with received information - log.debug("Store eIDAS response information into pending-request."); - AuthProcessDataWrapper authProcessData = pendingReq.getSessionData(AuthProcessDataWrapper.class); - authProcessData.setQAALevel(eIDASResponse.getLevelOfAssurance()); - authProcessData.setGenericDataToSession(Constants.DATA_FULL_EIDAS_RESPONSE, eIDASResponse); - - //store MOA-session to database - requestStoreage.storePendingRequest(pendingReq); - - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.RESPONSE_FROM_EIDAS_NODE_VALID); - - } catch (EAAFException e) { - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.RESPONSE_FROM_EIDAS_NODE_NOT_VALID); - throw new TaskExecutionException(pendingReq, "eIDAS Response processing FAILED.", e); - - } catch (Exception e) { - log.warn("eIDAS Response processing FAILED.", e); - revisionsLogger.logEvent(pendingReq, MSConnectorEventCodes.RESPONSE_FROM_EIDAS_NODE_NOT_VALID); - throw new TaskExecutionException(pendingReq, e.getMessage(), - new eIDASAuthenticationException("eidas.05", new Object[]{e.getMessage()}, e)); - - } - - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/utils/LoggingHandler.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/utils/LoggingHandler.java deleted file mode 100644 index c58d369b..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/utils/LoggingHandler.java +++ /dev/null @@ -1,52 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.utils; - -import java.io.ByteArrayOutputStream; -import java.util.Set; - -import javax.xml.namespace.QName; -import javax.xml.soap.SOAPMessage; -import javax.xml.ws.handler.MessageContext; -import javax.xml.ws.handler.soap.SOAPHandler; -import javax.xml.ws.handler.soap.SOAPMessageContext; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class LoggingHandler implements SOAPHandler { - - Logger log = LoggerFactory.getLogger(LoggingHandler.class); - - public boolean handleMessage(SOAPMessageContext context) { - SOAPMessage msg = context.getMessage(); - boolean request = ((Boolean) context - .get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY)).booleanValue(); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - - try { - if (request) { - msg.writeTo(bos); - } else { // This is the response message - msg.writeTo(bos); - } - - log.trace(bos.toString()); - log.trace(new String(bos.toByteArray())); - - } catch (Exception e) { - log.trace(e.getMessage(), e); - } - return true; - } - - public boolean handleFault(SOAPMessageContext context) { - return handleMessage(context); - } - - public void close(MessageContext context) { - } - - public Set getHeaders() { - return null; - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/utils/eIDASResponseUtils.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/utils/eIDASResponseUtils.java deleted file mode 100644 index 165c35cb..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/utils/eIDASResponseUtils.java +++ /dev/null @@ -1,98 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.utils; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.joda.time.DateTime; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.ImmutableList; - -import at.gv.egiz.eaaf.core.impl.data.Trible; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.Constants; -import eu.eidas.auth.commons.attribute.AttributeDefinition; -import eu.eidas.auth.commons.attribute.AttributeValue; -import eu.eidas.auth.commons.attribute.AttributeValueMarshaller; -import eu.eidas.auth.commons.attribute.AttributeValueMarshallingException; -import eu.eidas.auth.commons.protocol.eidas.impl.PostalAddress; - -public class eIDASResponseUtils { - private static final Logger log = LoggerFactory.getLogger(eIDASResponseUtils.class); - - public static final String PERSONALIDENIFIER_VALIDATION_PATTERN = "^[A-Z,a-z]{2}/[A-Z,a-z]{2}/.*"; - - /** - * Validate a eIDAS PersonalIdentifier attribute value - * This validation is done according to eIDAS SAML Attribute Profile - Section 2.2.3 Unique Identifier - * - * @param uniqueID eIDAS attribute value of a unique identifier - * @return true if the uniqueID matches to eIDAS to Unique Identifier specification, otherwise false - */ - public static boolean validateEidasPersonalIdentifier(String uniqueID) { - Pattern pattern = Pattern.compile(PERSONALIDENIFIER_VALIDATION_PATTERN ); - Matcher matcher = pattern.matcher(uniqueID); - return matcher.matches(); - - } - - - /** - * Parse an eIDAS PersonalIdentifier attribute value into it components. - * This processing is done according to eIDAS SAML Attribute Profile - Section 2.2.3 Unique Identifier - * - * @param uniqueID eIDAS attribute value of a unique identifier - * @return {@link Trible} that contains: - *
First : citizen country - *
Second: destination country - *
Third : unique identifier - *
or null if the attribute value has a wrong format - */ - public static Trible parseEidasPersonalIdentifier(String uniqueID) { - if (!validateEidasPersonalIdentifier(uniqueID)) { - log.error("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER - + " looks wrong formated. Value:" + ((String)uniqueID)); - return null; - - } - return Trible.newInstance(uniqueID.substring(0, 2), uniqueID.substring(3, 5), uniqueID.substring(6)); - - } - - public static List translateStringListAttribute(AttributeDefinition attributeDefinition, ImmutableList> attributeValues) { - final List stringListAttribute = new ArrayList(); - AttributeValueMarshaller attributeValueMarshaller = attributeDefinition.getAttributeValueMarshaller(); - for (AttributeValue attributeValue : attributeValues) { - String valueString = null; - try { - valueString = attributeValueMarshaller.marshal((AttributeValue) attributeValue); - stringListAttribute.add(valueString); - } catch (AttributeValueMarshallingException e) { - throw new IllegalStateException(e); - - } - } - - return stringListAttribute; - - } - - public static DateTime translateDateAttribute(AttributeDefinition attributeDefinition, ImmutableList> attributeValues) { - if (attributeValues.size() != 0) { - final AttributeValue firstAttributeValue = attributeValues.get(0); - return (DateTime) firstAttributeValue.getValue(); - - } - - return null; - } - - public static PostalAddress translateAddressAttribute(AttributeDefinition attributeDefinition, ImmutableList> attributeValues) { - final AttributeValue firstAttributeValue = attributeValues.get(0); - return (PostalAddress) firstAttributeValue.getValue(); - - } - -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/validator/eIDASResponseValidator.java b/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/validator/eIDASResponseValidator.java deleted file mode 100644 index 3791d0d7..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/java/at/gv/egiz/eidas/specific/modules/authmodule_eIDASv2/validator/eIDASResponseValidator.java +++ /dev/null @@ -1,135 +0,0 @@ -package at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.validator; - -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.ImmutableList; - -import at.gv.egiz.eaaf.core.api.IRequest; -import at.gv.egiz.eaaf.core.impl.data.Trible; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.Constants; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception.eIDASValidationException; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.service.eIDASAttributeRegistry; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.utils.eIDASResponseUtils; -import eu.eidas.auth.commons.attribute.AttributeDefinition; -import eu.eidas.auth.commons.attribute.AttributeValue; -import eu.eidas.auth.commons.light.ILightResponse; -import eu.eidas.auth.commons.protocol.eidas.LevelOfAssurance; - -/** - * @author tlenz - * - */ -public class eIDASResponseValidator { - private static final Logger log = LoggerFactory.getLogger(eIDASResponseValidator.class); - - public static void validateResponse(IRequest pendingReq, ILightResponse eIDASResponse, String spCountry, eIDASAttributeRegistry attrRegistry) throws eIDASValidationException { - - /*-----------------------------------------------------| - * validate received LoA against minimum required LoA | - *_____________________________________________________| - */ - LevelOfAssurance respLoA = LevelOfAssurance.fromString(eIDASResponse.getLevelOfAssurance()); - List allowedLoAs = pendingReq.getServiceProviderConfiguration().getRequiredLoA(); - boolean loaValid = false; - for (String allowedLoaString : allowedLoAs) { - LevelOfAssurance allowedLoa = LevelOfAssurance.fromString(allowedLoaString); - if (respLoA.numericValue() >= allowedLoa.numericValue()) { - log.debug("Response contains valid LoA. Resume process ... "); - loaValid = true; - break; - - } else - log.trace("Allowed LoA: " + allowedLoaString + " DOES NOT match response LoA: " + eIDASResponse.getLevelOfAssurance()); - - } - - if (!loaValid) { - log.error("eIDAS Response LevelOfAssurance is lower than the required! " - + "(Resp-LoA:" + respLoA.getValue() + " Req-LoA:" + allowedLoAs.toArray() + ")"); - throw new eIDASValidationException("eidas.06", new Object[]{respLoA.getValue()}); - - } - - - - /*-----------------------------------------------------| - * validate 'PersonalIdentifier' attribute | - *_____________________________________________________| - */ - AttributeDefinition attrDefinition = attrRegistry.getCoreAttributeRegistry().getByFriendlyName(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).first(); - final ImmutableList> attributeValues = eIDASResponse.getAttributes().getAttributeMap().get(attrDefinition).asList(); - List personalIdObj = eIDASResponseUtils.translateStringListAttribute(attrDefinition, attributeValues); - - //check if attribute exists - if (personalIdObj == null || personalIdObj.isEmpty()) { - log.warn("eIDAS Response include NO 'PersonalIdentifier' attriubte " - + ".... That can be a BIG problem in further processing steps"); - throw new eIDASValidationException("eidas.05", new Object[] {"NO 'PersonalIdentifier' attriubte"}); - - } else if (personalIdObj.size() > 1) { - log.warn("eIDAS Response include MORE THAN ONE 'PersonalIdentifier' attriubtes " - + ".... That can be a BIG problem in further processing steps"); - throw new eIDASValidationException("eidas.05", new Object[] {"MORE THAN ONE 'PersonalIdentifier' attriubtes"}); - - } else { - String natPersId = personalIdObj.get(0); - //validate attribute value format - Trible split = - eIDASResponseUtils.parseEidasPersonalIdentifier(natPersId); - if (split == null) { - throw new eIDASValidationException("eidas.07", - new Object[]{ - Constants.eIDAS_ATTR_PERSONALIDENTIFIER, - "Wrong identifier format"}); - - } else { - //validation according to eIDAS SAML Attribute Profile, Section 2.2.3 - if (StringUtils.isEmpty(split.getSecond())) { - log.warn("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER - + " includes NO destination country. Value:" + natPersId); - throw new eIDASValidationException("eidas.07", - new Object[]{ - Constants.eIDAS_ATTR_PERSONALIDENTIFIER, - "No or empty destination country"}); - - } - if (!split.getSecond().equalsIgnoreCase(spCountry)) { - log.warn("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER - + " includes wrong destination country. Value:" + natPersId - + " SP-Country:" + spCountry); - throw new eIDASValidationException("eidas.07", - new Object[]{ - Constants.eIDAS_ATTR_PERSONALIDENTIFIER, - "Destination country does not match to SP country"}); - - } - - if (StringUtils.isEmpty(split.getFirst())) { - log.warn("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER - + " includes NO citizen country. Value:" + natPersId); - throw new eIDASValidationException("eidas.07", - new Object[]{ - Constants.eIDAS_ATTR_PERSONALIDENTIFIER, - "No or empty citizen country"}); - - } - if (!split.getSecond().equalsIgnoreCase(spCountry)) { - log.warn("eIDAS attribute value for " + Constants.eIDAS_ATTR_PERSONALIDENTIFIER - + " includes a relaying-party country that does not match to service-provider country. " - + " Value:" + natPersId - + " SP Country:" + spCountry); - throw new eIDASValidationException("eidas.07", - new Object[]{ - Constants.eIDAS_ATTR_PERSONALIDENTIFIER, - "Citizen country does not match to eIDAS-node country that generates the response"}); - - } - } - } - - } -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider index f5af2dc4..19134513 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider @@ -1 +1 @@ -at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.eIDASAuthenticationSpringResourceProvider \ No newline at end of file +at.asitplus.eidas.specific.modules.authmodule_eIDASv2.eIDASAuthenticationSpringResourceProvider \ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/eidas_v2_auth.beans.xml b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/eidas_v2_auth.beans.xml index 4664bc27..433a0499 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/main/resources/eidas_v2_auth.beans.xml +++ b/eidas_modules/authmodule-eIDAS-v2/src/main/resources/eidas_v2_auth.beans.xml @@ -12,7 +12,7 @@ + class="at.asitplus.eidas.specific.modules.authmodule_eIDASv2.szr.SZRClient" /> @@ -31,30 +31,30 @@ + class="at.asitplus.eidas.specific.modules.authmodule_eIDASv2.eIDASAuthenticationModulImpl"> + class="at.asitplus.eidas.specific.modules.authmodule_eIDASv2.eIDASSignalServlet" /> + class="at.asitplus.eidas.specific.modules.authmodule_eIDASv2.service.eIDASAttributeRegistry"> \ No newline at end of file diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/test/eidas/specific/modules/authmodule_eIDASv2/SZRClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/test/eidas/specific/modules/authmodule_eIDASv2/SZRClientTest.java new file mode 100644 index 00000000..926ea2c9 --- /dev/null +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/asitplus/test/eidas/specific/modules/authmodule_eIDASv2/SZRClientTest.java @@ -0,0 +1,172 @@ +package at.asitplus.test.eidas.specific.modules.authmodule_eIDASv2; + +import java.io.IOException; +import java.math.BigInteger; +import java.security.InvalidKeyException; +import java.security.NoSuchProviderException; +import java.security.PublicKey; +import java.security.interfaces.RSAPublicKey; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.util.Base64Utils; +import org.w3._2000._09.xmldsig.KeyValueType; +import org.w3._2000._09.xmldsig.RSAKeyValueType; +import org.w3c.dom.Element; + +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.Constants; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.exception.SZRCommunicationException; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.szr.SZRClient; +import at.asitplus.eidas.specific.modules.authmodule_eIDASv2.utils.eIDASResponseUtils; +import at.gv.e_government.reference.namespace.persondata._20020228.PersonNameType; +import at.gv.e_government.reference.namespace.persondata._20020228.PhysicalPersonType; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.IConfiguration; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.exceptions.EAAFParserException; +import at.gv.egiz.eaaf.core.impl.data.Trible; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; +import szrservices.IdentityLinkType; +import szrservices.PersonInfoType; +import szrservices.SZRException_Exception; +import szrservices.TravelDocumentType; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("/SpringTest-context_basic_test.xml") +public class SZRClientTest { + private static final Logger log = LoggerFactory.getLogger(SZRClientTest.class); + + @Autowired SZRClient szrClient; + @Autowired IConfiguration basicConfig; + + private static final String givenName = "Franz"; + private static final String familyName = "Mustermann"; + private static final String dateOfBirth = "1987-05-05"; + private static final String eIDASeID = "IS/AT/123456789ABCDE"; + + private static final String DUMMY_TARGET = EAAFConstants.URN_PREFIX_CDID + "ZP"; + + @Test + public void dummyTest() { + + } + + + //@Test + public void getIdentityLink() throws SZRException_Exception, EAAFParserException, NoSuchProviderException, IOException, InvalidKeyException, SZRCommunicationException { + log.debug("Starting connecting SZR Gateway"); + IdentityLinkType result = szrClient.getIdentityLink( + getPersonInfo(), + dummyCodeForKeys(), + basicConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_INSERTERNB, + true) + ); + + Element idlFromSZR = (Element)result.getAssertion(); + IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser(idlFromSZR).parseIdentityLink(); + if (identityLink == null) + throw new SZRCommunicationException("ernb.00", new Object[] {"bPK is null or empty"}); + + } + + //@Test + public void getbPKTest() throws SZRException_Exception, SZRCommunicationException { + String bPK = szrClient.getBPK(getPersonInfo(), DUMMY_TARGET, + basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, + "no VKZ defined")); + + if (StringUtils.isEmpty(bPK)) + throw new SZRCommunicationException("ernb.01", new Object[] {"bPK is null or empty"}); + + + } + + private PersonInfoType getPersonInfo() { + PersonInfoType personInfo = new PersonInfoType(); + PersonNameType personName = new PersonNameType(); + PhysicalPersonType naturalPerson = new PhysicalPersonType(); + TravelDocumentType eDocument = new TravelDocumentType(); + + naturalPerson.setName(personName ); + personInfo.setPerson(naturalPerson ); + personInfo.setTravelDocument(eDocument ); + + //parse some eID attributes + Trible eIdentifier = + eIDASResponseUtils.parseEidasPersonalIdentifier((String)eIDASeID); + String uniqueId = (String)eIDASeID; + String citizenCountry = eIdentifier.getFirst(); + + //person information + personName.setFamilyName((String)familyName); + personName.setGivenName((String)givenName); + naturalPerson.setDateOfBirth(dateOfBirth); + eDocument.setIssuingCountry(citizenCountry); + eDocument.setDocumentNumber(uniqueId); + + //eID document information + eDocument.setDocumentType(basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, + Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); + + //TODO: that should be removed + eDocument.setIssueDate(basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_DATE, + Constants.SZR_CONSTANTS_DEFAULT_ISSUING_DATE)); + eDocument.setIssuingAuthority(basicConfig.getBasicConfiguration( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_AUTHORITY, + Constants.SZR_CONSTANTS_DEFAULT_ISSUING_AUTHORITY)); + + return personInfo; + } + + + private List dummyCodeForKeys() throws IOException, NoSuchProviderException, InvalidKeyException { + if (basicConfig.getBasicMOAIDConfigurationBoolean( + Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_KEYS_USEDUMMY, + false)) { + List keyvalueList = new ArrayList(); + try { + //Security.addProvider(new BouncyCastleProvider()); + //PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Constants.SZR_CONSTANTS_DEFAULT_PUBL_KEY); + //KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); + + //PublicKey pb = kf.generatePublic(spec); + PublicKey pb = new iaik.security.rsa.RSAPublicKey(Constants.SZR_CONSTANTS_DEFAULT_PUBL_KEY); + + RSAPublicKey rsapb = (RSAPublicKey)pb; + BigInteger modulus = rsapb.getModulus(); + BigInteger exponent = rsapb.getPublicExponent(); + + // set key values + RSAKeyValueType rsa = new RSAKeyValueType(); + rsa.setExponent(new String(Base64Utils.encode(exponent.toByteArray()))); + rsa.setModulus(new String(Base64Utils.encode(modulus.toByteArray()))); + + KeyValueType key = new KeyValueType(); + key.setRSAKeyValue(rsa); + + keyvalueList.add(key); + + return keyvalueList; + } catch (Exception e) { + log.error("TestCode has an internal ERROR", e); + throw e; + } + + } + + return null; + + } +} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/gv/egiz/test/eidas/specific/modules/authmodule_eIDASv2/SZRClientTest.java b/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/gv/egiz/test/eidas/specific/modules/authmodule_eIDASv2/SZRClientTest.java deleted file mode 100644 index 33050b12..00000000 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/java/at/gv/egiz/test/eidas/specific/modules/authmodule_eIDASv2/SZRClientTest.java +++ /dev/null @@ -1,172 +0,0 @@ -package at.gv.egiz.test.eidas.specific.modules.authmodule_eIDASv2; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.InvalidKeyException; -import java.security.NoSuchProviderException; -import java.security.PublicKey; -import java.security.interfaces.RSAPublicKey; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.lang3.StringUtils; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.util.Base64Utils; -import org.w3._2000._09.xmldsig.KeyValueType; -import org.w3._2000._09.xmldsig.RSAKeyValueType; -import org.w3c.dom.Element; - -import at.gv.e_government.reference.namespace.persondata._20020228.PersonNameType; -import at.gv.e_government.reference.namespace.persondata._20020228.PhysicalPersonType; -import at.gv.egiz.eaaf.core.api.data.EAAFConstants; -import at.gv.egiz.eaaf.core.api.idp.IConfiguration; -import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; -import at.gv.egiz.eaaf.core.exceptions.EAAFParserException; -import at.gv.egiz.eaaf.core.impl.data.Trible; -import at.gv.egiz.eaaf.core.impl.idp.auth.data.SimpleIdentityLinkAssertionParser; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.Constants; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.exception.SZRCommunicationException; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.szr.SZRClient; -import at.gv.egiz.eidas.specific.modules.authmodule_eIDASv2.utils.eIDASResponseUtils; -import szrservices.IdentityLinkType; -import szrservices.PersonInfoType; -import szrservices.SZRException_Exception; -import szrservices.TravelDocumentType; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("/SpringTest-context_basic_test.xml") -public class SZRClientTest { - private static final Logger log = LoggerFactory.getLogger(SZRClientTest.class); - - @Autowired SZRClient szrClient; - @Autowired IConfiguration basicConfig; - - private static final String givenName = "Franz"; - private static final String familyName = "Mustermann"; - private static final String dateOfBirth = "1987-05-05"; - private static final String eIDASeID = "IS/AT/123456789ABCDE"; - - private static final String DUMMY_TARGET = EAAFConstants.URN_PREFIX_CDID + "ZP"; - - @Test - public void dummyTest() { - - } - - - //@Test - public void getIdentityLink() throws SZRException_Exception, EAAFParserException, NoSuchProviderException, IOException, InvalidKeyException, SZRCommunicationException { - log.debug("Starting connecting SZR Gateway"); - IdentityLinkType result = szrClient.getIdentityLink( - getPersonInfo(), - dummyCodeForKeys(), - basicConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_DEBUG_INSERTERNB, - true) - ); - - Element idlFromSZR = (Element)result.getAssertion(); - IIdentityLink identityLink = new SimpleIdentityLinkAssertionParser(idlFromSZR).parseIdentityLink(); - if (identityLink == null) - throw new SZRCommunicationException("ernb.00", new Object[] {"bPK is null or empty"}); - - } - - //@Test - public void getbPKTest() throws SZRException_Exception, SZRCommunicationException { - String bPK = szrClient.getBPK(getPersonInfo(), DUMMY_TARGET, - basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_VKZ, - "no VKZ defined")); - - if (StringUtils.isEmpty(bPK)) - throw new SZRCommunicationException("ernb.01", new Object[] {"bPK is null or empty"}); - - - } - - private PersonInfoType getPersonInfo() { - PersonInfoType personInfo = new PersonInfoType(); - PersonNameType personName = new PersonNameType(); - PhysicalPersonType naturalPerson = new PhysicalPersonType(); - TravelDocumentType eDocument = new TravelDocumentType(); - - naturalPerson.setName(personName ); - personInfo.setPerson(naturalPerson ); - personInfo.setTravelDocument(eDocument ); - - //parse some eID attributes - Trible eIdentifier = - eIDASResponseUtils.parseEidasPersonalIdentifier((String)eIDASeID); - String uniqueId = (String)eIDASeID; - String citizenCountry = eIdentifier.getFirst(); - - //person information - personName.setFamilyName((String)familyName); - personName.setGivenName((String)givenName); - naturalPerson.setDateOfBirth(dateOfBirth); - eDocument.setIssuingCountry(citizenCountry); - eDocument.setDocumentNumber(uniqueId); - - //eID document information - eDocument.setDocumentType(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_EDOCUMENTTYPE, - Constants.SZR_CONSTANTS_DEFAULT_DOCUMENT_TYPE)); - - //TODO: that should be removed - eDocument.setIssueDate(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_DATE, - Constants.SZR_CONSTANTS_DEFAULT_ISSUING_DATE)); - eDocument.setIssuingAuthority(basicConfig.getBasicConfiguration( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_ISSUING_AUTHORITY, - Constants.SZR_CONSTANTS_DEFAULT_ISSUING_AUTHORITY)); - - return personInfo; - } - - - private List dummyCodeForKeys() throws IOException, NoSuchProviderException, InvalidKeyException { - if (basicConfig.getBasicMOAIDConfigurationBoolean( - Constants.CONIG_PROPS_EIDAS_SZRCLIENT_PARAMS_KEYS_USEDUMMY, - false)) { - List keyvalueList = new ArrayList(); - try { - //Security.addProvider(new BouncyCastleProvider()); - //PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Constants.SZR_CONSTANTS_DEFAULT_PUBL_KEY); - //KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); - - //PublicKey pb = kf.generatePublic(spec); - PublicKey pb = new iaik.security.rsa.RSAPublicKey(Constants.SZR_CONSTANTS_DEFAULT_PUBL_KEY); - - RSAPublicKey rsapb = (RSAPublicKey)pb; - BigInteger modulus = rsapb.getModulus(); - BigInteger exponent = rsapb.getPublicExponent(); - - // set key values - RSAKeyValueType rsa = new RSAKeyValueType(); - rsa.setExponent(new String(Base64Utils.encode(exponent.toByteArray()))); - rsa.setModulus(new String(Base64Utils.encode(modulus.toByteArray()))); - - KeyValueType key = new KeyValueType(); - key.setRSAKeyValue(rsa); - - keyvalueList.add(key); - - return keyvalueList; - } catch (Exception e) { - log.error("TestCode has an internal ERROR", e); - throw e; - } - - } - - return null; - - } -} diff --git a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_test.xml b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_test.xml index b381a0e9..ae320b27 100644 --- a/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_test.xml +++ b/eidas_modules/authmodule-eIDAS-v2/src/test/resources/SpringTest-context_basic_test.xml @@ -10,10 +10,10 @@ + class="at.asitplus.eidas.specific.modules.authmodule_eIDASv2.szr.SZRClient" /> + class="at.asitplus.eidas.specific.connector.config.BasicConfigurationProvider"> diff --git a/eidas_modules/pom.xml b/eidas_modules/pom.xml index 1502ae6b..219096ff 100644 --- a/eidas_modules/pom.xml +++ b/eidas_modules/pom.xml @@ -2,11 +2,11 @@ 4.0.0 - at.gv.egiz.eidas + at.asitplus.eidas ms_specific 1.x - at.gv.egiz.eidas.ms_specific + at.asitplus.eidas.ms_specific modules pom diff --git a/pom.xml b/pom.xml index d640c41a..7b0015b9 100644 --- a/pom.xml +++ b/pom.xml @@ -1,7 +1,7 @@ 4.0.0 - at.gv.egiz.eidas + at.asitplus.eidas ms_specific 1.x pom @@ -84,17 +84,17 @@ ${eaaf-core.version}
- at.gv.egiz.eidas.ms_specific.modules + at.asitplus.eidas.ms_specific.modules authmodule-eIDAS-v2 ${egiz.eidas.version} - at.gv.egiz.eidas.ms_specific + at.asitplus.eidas.ms_specific modules ${egiz.eidas.version} - at.gv.egiz.eidas.ms_specific + at.asitplus.eidas.ms_specific connector_lib ${egiz.eidas.version} -- cgit v1.2.3