diff options
Diffstat (limited to 'id/server/idserverlib')
61 files changed, 2282 insertions, 739 deletions
diff --git a/id/server/idserverlib/pom.xml b/id/server/idserverlib/pom.xml index fb6ba1bc6..6c6353be0 100644 --- a/id/server/idserverlib/pom.xml +++ b/id/server/idserverlib/pom.xml @@ -85,11 +85,11 @@ </exclusion>
</exclusions>
</dependency>
- <dependency>
+ <!-- dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
- </dependency>
+ </dependency-->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
@@ -205,6 +205,12 @@ <artifactId>unitils-core</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
<!-- <dependency>
<groupId>MOA</groupId>
<artifactId>moa-common</artifactId>
@@ -315,6 +321,13 @@ <scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>iaik.prod</groupId>
+ <artifactId>iaik_ixsil</artifactId>
+ <version>1.2.2.5</version>
+ <scope>test</scope>
+ </dependency>
+
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
@@ -386,7 +399,41 @@ <artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
-
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-tx</artifactId>
+ <version>${org.springframework.version}</version>
+ </dependency>
+
+
+ <!-- Redis -->
+ <dependency>
+ <groupId>org.springframework.data</groupId>
+ <artifactId>spring-data-redis</artifactId>
+ <version>1.7.2.RELEASE</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-pool2</artifactId>
+ <version>2.4.2</version>
+ </dependency>
+ <dependency>
+ <groupId>redis.clients</groupId>
+ <artifactId>jedis</artifactId>
+ <version>2.8.1</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.codehaus.jackson</groupId>
+ <artifactId>jackson-core-asl</artifactId>
+ <version>1.9.13</version>
+ </dependency>
+ <dependency>
+ <groupId>org.codehaus.jackson</groupId>
+ <artifactId>jackson-mapper-asl</artifactId>
+ <version>1.9.13</version>
+ </dependency>
</dependencies>
<build>
@@ -457,6 +504,9 @@ <goals>
<goal>jar</goal>
</goals>
+ <configuration>
+ <additionalparam>-Xdoclint:none</additionalparam>
+ </configuration>
</execution>
</executions>
</plugin>
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/DummyStatisticLogger.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/DummyStatisticLogger.java new file mode 100644 index 000000000..5a1b7205d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/DummyStatisticLogger.java @@ -0,0 +1,49 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.advancedlogging; + + +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.data.IAuthData; +import at.gv.egovernment.moa.logging.Logger; + +@Service("StatisticLogger") +public class DummyStatisticLogger implements IStatisticLogger{ + + @Override + public void logSuccessOperation(IRequest protocolRequest, + IAuthData authData, boolean isSSOSession) { + Logger.trace("Dummy-logSuccessOperation"); + } + + @Override + public void logErrorOperation(Throwable throwable) { + Logger.trace("Dummy-logErrorOperation"); + } + + @Override + public void logErrorOperation(Throwable throwable, IRequest errorRequest) { + Logger.trace("Dummy-logErrorOperation"); + }} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/IStatisticLogger.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/IStatisticLogger.java new file mode 100644 index 000000000..2d97d7258 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/IStatisticLogger.java @@ -0,0 +1,37 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.advancedlogging; + +import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.data.IAuthData; + + +public interface IStatisticLogger { + + public void logSuccessOperation(IRequest protocolRequest, IAuthData authData, boolean isSSOSession); + + public void logErrorOperation(Throwable throwable); + + public void logErrorOperation(Throwable throwable, IRequest errorRequest); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java index 0171f9d90..34bdd350b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java @@ -33,6 +33,7 @@ import javax.xml.bind.Unmarshaller; import org.apache.commons.lang3.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; @@ -48,6 +49,7 @@ import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.commons.api.IRequest; import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; +import at.gv.egovernment.moa.id.commons.config.SpringProfileConstants; import at.gv.egovernment.moa.id.commons.db.StatisticLogDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.statistic.StatisticLog; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; @@ -60,7 +62,7 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Service("StatisticLogger") -public class StatisticLogger { +public class StatisticLogger implements IStatisticLogger{ private static final String GENERIC_LOCALBKU = ":3496/https-security-layer-request"; private static final String GENERIC_HANDYBKU = "https://www.handy-signatur.at/"; @@ -79,6 +81,7 @@ public class StatisticLogger { @Autowired AuthConfiguration authConfig; @Autowired IAuthenticationSessionStoreage authenticatedSessionStorage; + @Autowired StatisticLogDBUtils statisticLogDBUtils; public void logSuccessOperation(IRequest protocolRequest, IAuthData authData, boolean isSSOSession) { @@ -191,7 +194,7 @@ public class StatisticLogger { try { - StatisticLogDBUtils.saveOrUpdate(dblog); + statisticLogDBUtils.saveOrUpdate(dblog); } catch (MOADatabaseException e) { Logger.warn("Statistic Log can not be stored into Database", e); @@ -217,7 +220,7 @@ public class StatisticLogger { try { - StatisticLogDBUtils.saveOrUpdate(dblog); + statisticLogDBUtils.saveOrUpdate(dblog); } catch (MOADatabaseException e) { Logger.warn("Statistic Log can not be stored into Database", e); @@ -268,7 +271,7 @@ public class StatisticLogger { try { - StatisticLogDBUtils.saveOrUpdate(dblog); + statisticLogDBUtils.saveOrUpdate(dblog); } catch (MOADatabaseException e) { Logger.warn("Statistic Log can not be stored into Database", e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java index e0552c337..bbb322a4f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java @@ -8,6 +8,8 @@ import java.util.List; import org.hibernate.HibernateException; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; @@ -29,6 +31,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * @version $Id$ */ @Service("AuthenticationSessionCleaner") +@EnableScheduling public class AuthenticationSessionCleaner implements Runnable { @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; @@ -36,7 +39,7 @@ public class AuthenticationSessionCleaner implements Runnable { @Autowired protected AuthConfiguration authConfig; /** interval the <code>AuthenticationSessionCleaner</code> is run in */ - private static final long SESSION_CLEANUP_INTERVAL = 5 * 60; // 5 min + private static final long SESSION_CLEANUP_INTERVAL = 5 * 60 *1000 ; // 5 min /** * Runs the thread. Cleans the <code>AuthenticationServer</code> session store @@ -45,8 +48,8 @@ public class AuthenticationSessionCleaner implements Runnable { * Cleans up expired session and authentication data stores. * */ + @Scheduled(fixedRate = SESSION_CLEANUP_INTERVAL) public void run() { - while (true) { try { Logger.debug("AuthenticationSessionCleaner run"); Date now = new Date(); @@ -66,7 +69,7 @@ public class AuthenticationSessionCleaner implements Runnable { try { try { Object entry = transactionStorage.get(entryKey); - //if entry is an exception --> log it because is could be unhandled + //if entry is an exception --> log it because it could be unhandled if (entry != null && entry instanceof ExceptionContainer) { ExceptionContainer exContainer = (ExceptionContainer) entry; @@ -115,12 +118,6 @@ public class AuthenticationSessionCleaner implements Runnable { } catch (Exception e) { Logger.error(MOAIDMessageProvider.getInstance().getMessage("cleaner.01", null), e); } - try { - Thread.sleep(SESSION_CLEANUP_INTERVAL * 1000); - } - catch (InterruptedException e) { - } - } } /** @@ -143,18 +140,4 @@ public class AuthenticationSessionCleaner implements Runnable { } } } - - /** - * start the sessionCleaner - */ - public static void start(Runnable clazz) { - // start the session cleanup thread - Thread sessionCleaner = - new Thread(clazz, "AuthenticationSessionCleaner"); - sessionCleaner.setName("SessionCleaner"); - sessionCleaner.setDaemon(true); - sessionCleaner.setPriority(Thread.MIN_PRIORITY); - sessionCleaner.start(); - } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IDestroyableObject.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IDestroyableObject.java new file mode 100644 index 000000000..6f98357e2 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IDestroyableObject.java @@ -0,0 +1,36 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth; + +/** + * @author tlenz + * + */ +public interface IDestroyableObject { + /** + * Manually deep destroy a Java object with all child objects like timers and threads + * + */ + public void fullyDestroy(); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IGarbageCollectorProcessing.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IGarbageCollectorProcessing.java index a1008e883..27d142f2c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IGarbageCollectorProcessing.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IGarbageCollectorProcessing.java @@ -20,7 +20,7 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. */ -package at.gv.egovernment.moa.id.config.auth; +package at.gv.egovernment.moa.id.auth; /** * @author tlenz diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAGarbageCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAGarbageCollector.java new file mode 100644 index 000000000..52e30a2f0 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAGarbageCollector.java @@ -0,0 +1,93 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.auth; + + +import java.util.Iterator; +import java.util.Map; +import java.util.Map.Entry; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.logging.Logger; + +@Service("MOAGarbageCollector") +@EnableScheduling +public class MOAGarbageCollector implements Runnable { + + @Autowired ApplicationContext context; + + private static final long INTERVAL = 24 * 60 * 60 * 1000; // 24 hours + //private static final long INITAL_DELAY = 12 * 60 * 60 * 1000; // 12 hours + + private static final long INITAL_DELAY = 2 * 60 * 1000; // 12 hours + +// private static final List<IGarbageCollectorProcessing> processModules = +// new ArrayList<IGarbageCollectorProcessing>(); + + + @Scheduled(fixedRate = INTERVAL, initialDelay = INITAL_DELAY) + public void run() { + + Map<String, IGarbageCollectorProcessing> processModules = + context.getBeansOfType(IGarbageCollectorProcessing.class); + + if (processModules != null) { + Iterator<Entry<String, IGarbageCollectorProcessing>> interator = processModules.entrySet().iterator(); + while (interator.hasNext()) { + try { + interator.next().getValue().runGarbageCollector(); + + } catch (Throwable e1) { + Logger.warn("Garbage collection FAILED in some module.", e1); + + } + + } + } + } + +// /** +// * Add a module to MOA internal garbage collector. Every module is executed once a day +// * +// * @param modul Module which should be executed by the garbage collector. +// */ +// public static void addModulForGarbageCollection(IGarbageCollectorProcessing modul) { +// processModules.add(modul); +// +// } + +// public static void start() { +// // start the session cleanup thread +// Thread configLoader = new Thread(new MOAGarbageCollector(), "MOAGarbageCollector"); +// configLoader.setName("MOAGarbageCollectorr"); +// configLoader.setDaemon(true); +// configLoader.setPriority(Thread.MIN_PRIORITY); +// configLoader.start(); +// } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index d1cf3338a..11f47052e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -36,18 +36,16 @@ import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.id.util.SSLUtils; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.logging.LoggingContext; -import at.gv.egovernment.moa.logging.LoggingContextManager; import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.iaik.config.IaikConfigurator; -import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.MiscUtil; +import at.gv.egovernment.moaspss.logging.LoggingContext; +import at.gv.egovernment.moaspss.logging.LoggingContextManager; import iaik.pki.PKIException; -import iaik.security.ecc.provider.ECCProvider; +import iaik.security.ec.provider.ECCelerate; import iaik.security.provider.IAIK; /** @@ -104,17 +102,11 @@ public class MOAIDAuthInitializer { Logger.info("Loading Java security providers."); IAIK.addAsProvider(); - ECCProvider.addAsProvider(); + ECCelerate.addAsProvider(); // Initializes SSLSocketFactory store SSLUtils.initialize(); - // Initializes Namespace Map - Constants.nSMap.put(Constants.SAML_PREFIX, Constants.SAML_NS_URI); - Constants.nSMap.put(Constants.ECDSA_PREFIX, - "http://www.w3.org/2001/04/xmldsig-more#"); - Constants.nSMap.put(Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); - //seed the random number generator Random.seedRandom(); Logger.debug("Random-number generator is seeded."); @@ -147,7 +139,12 @@ public class MOAIDAuthInitializer { //ECCProvider.addAsProvider(); Security.insertProviderAt(IAIK.getInstance(), 0); - Security.addProvider(new ECCProvider()); + + ECCelerate eccProvider = ECCelerate.getInstance(); + if (Security.getProvider(eccProvider.getName()) != null) + Security.removeProvider(eccProvider.getName()); + + Security.addProvider(new ECCelerate()); if (Logger.isDebugEnabled()) { Logger.debug("Loaded Security Provider:"); @@ -156,12 +153,5 @@ public class MOAIDAuthInitializer { Logger.debug(i + ": " + providerList[i].getName() + " Version " + providerList[i].getVersion()); } - - - // Starts the session cleaner thread to remove unpicked authentication data - AuthenticationSessionCleaner sessioncleaner = rootContext.getBean("AuthenticationSessionCleaner", AuthenticationSessionCleaner.class); - AuthenticationSessionCleaner.start(sessioncleaner); - - MOAGarbageCollector.start(); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 908c7e7b6..16d320ea5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -106,6 +106,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { @Autowired protected AuthConfiguration authConfig; @Autowired private AttributQueryBuilder attributQueryBuilder; @Autowired private SAMLVerificationEngineSP samlVerificationEngine; + @Autowired(required=true) private MOAMetadataProvider metadataProvider; public IAuthData buildAuthenticationData(IRequest pendingReq, @@ -222,7 +223,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { try { samlVerificationEngine.verifyIDPResponse(intfResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine( - MOAMetadataProvider.getInstance())); + metadataProvider)); //create assertion attribute extractor from AttributeQuery response return new AssertionAttributeExtractor(intfResp); @@ -1106,10 +1107,15 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { String eIDASOutboundCountry = pendingReq.getGenericData(RequestImpl.eIDAS_GENERIC_REQ_DATA_COUNTRY, String.class); + //TODO: maybe find a better solution + String cititzenCountryCode = + authConfig.getBasicMOAIDConfiguration("moa.id.protocols.eIDAS.node.countrycode", + MOAIDAuthConstants.COUNTRYCODE_AUSTRIA); + if (Constants.URN_PREFIX_BASEID.equals(baseIDType)) { - if (MiscUtil.isNotEmpty(eIDASOutboundCountry) && !COUNTRYCODE_AUSTRIA.equals(eIDASOutboundCountry)) { + if (MiscUtil.isNotEmpty(eIDASOutboundCountry) && !cititzenCountryCode.equals(eIDASOutboundCountry)) { Pair<String, String> eIDASID = new BPKBuilder().buildeIDASIdentifer(baseIDType, baseID, - COUNTRYCODE_AUSTRIA, eIDASOutboundCountry); + cititzenCountryCode, eIDASOutboundCountry); Logger.debug("Authenticate user with bPK:" + eIDASID.getFirst() + " Type:" + eIDASID.getSecond()); return eIDASID; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MISSimpleClientException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MISSimpleClientException.java index 718c35df3..ab3d2cae2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MISSimpleClientException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MISSimpleClientException.java @@ -73,6 +73,10 @@ public class MISSimpleClientException extends MOAIDException { super(message, null, cause);
}
+ public MISSimpleClientException(String message, Object[] params, Throwable cause) {
+ super(message, params, cause);
+ }
+
/**
* @return the bkuErrorCode
*/
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index e3efdeac0..1431911a3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -33,10 +33,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ExceptionHandler; import com.google.common.net.MediaType; - +import at.gv.egovernment.moa.id.advancedlogging.IStatisticLogger; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; import at.gv.egovernment.moa.id.auth.frontend.builder.DefaultGUIFormBuilderConfiguration; @@ -71,7 +70,7 @@ public abstract class AbstractController extends MOAIDAuthConstants { public static final String ERROR_CODE_PARAM = "errorid"; - @Autowired protected StatisticLogger statisticLogger; + @Autowired protected IStatisticLogger statisticLogger; @Autowired protected IRequestStorage requestStorage; @Autowired protected ITransactionStorage transactionStorage; @Autowired protected MOAReversionLogger revisionsLogger; @@ -141,12 +140,12 @@ public abstract class AbstractController extends MOAIDAuthConstants { revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR); transactionStorage.put(key, new ExceptionContainer(pendingReq.getUniqueSessionIdentifier(), - pendingReq.getUniqueTransactionIdentifier(), loggedException)); + pendingReq.getUniqueTransactionIdentifier(), loggedException),-1); } else { transactionStorage.put(key, new ExceptionContainer(null, - null, loggedException)); + null, loggedException),-1); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java index 66e8757ad..5e09380ae 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java @@ -179,7 +179,7 @@ public class IDPSingleLogOutServlet extends AbstractController { else statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; - transactionStorage.put(artifact, statusCode); + transactionStorage.put(artifact, statusCode, -1); redirectURL = HTTPUtils.addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProviderImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProviderImpl.java index 5c2f86732..67ad4762c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProviderImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProviderImpl.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.config; +import java.util.ArrayList; import java.util.Map; import java.util.Properties; @@ -53,6 +54,7 @@ import org.hibernate.cfg.Configuration; import at.gv.egovernment.moa.id.commons.api.ConfigurationProvider; import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.commons.config.SpringProfileConstants; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.StatisticLogDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; @@ -185,6 +187,10 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider String propertyName = key.toString().substring(propPrefix.length()); moaSessionProp.put(propertyName, props.get(key.toString())); } + if (key.toString().startsWith(propPrefix+"dbcp")) { + String propertyName = "hibernate."+(key.toString().substring(propPrefix.length())); + moaSessionProp.put(propertyName, props.get(key.toString())); + } } // read Config Hibernate properties @@ -222,17 +228,17 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider config.addAnnotatedClass(InterfederationSessionStore.class); //config.addAnnotatedClass(ProcessInstanceStore.class); config.addProperties(moaSessionProp); - MOASessionDBUtils.initHibernate(config, moaSessionProp); + //MOASessionDBUtils.initHibernate(config, moaSessionProp); //initial advanced logging - if (Boolean.valueOf(props.getProperty("configuration.advancedlogging.active", "false"))) { - Logger.info("Advanced statistic log is activated, starting initialization process ..."); - Configuration statisticconfig = new Configuration(); - statisticconfig.addAnnotatedClass(StatisticLog.class); - statisticconfig.addProperties(statisticProps); - StatisticLogDBUtils.initHibernate(statisticconfig, statisticProps); - Logger.info("Advanced statistic log is initialized."); - } +// if (Boolean.valueOf(props.getProperty("configuration.advancedlogging.active", "false"))) { +// Logger.info("Advanced statistic log is activated, starting initialization process ..."); +// Configuration statisticconfig = new Configuration(); +// statisticconfig.addAnnotatedClass(StatisticLog.class); +// statisticconfig.addProperties(statisticProps); +// StatisticLogDBUtils.initHibernate(statisticconfig, statisticProps); +// Logger.info("Advanced statistic log is initialized."); +// } } Logger.trace("Hibernate initialization finished."); @@ -267,6 +273,7 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider eGovUtilsConfig = new EgovUtilPropertiesConfiguration(eGovUtilsConfigProp, rootConfigFileDir); } + this.generateActiveProfiles(props); } @@ -277,5 +284,24 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider public EgovUtilPropertiesConfiguration geteGovUtilsConfig() { return eGovUtilsConfig; } + + private ArrayList<String> activeProfiles = new ArrayList<String>(); + + public void generateActiveProfiles(Properties props){ + if (Boolean.valueOf(props.getProperty("configuration.advancedlogging.active", "false"))) { + activeProfiles.add(SpringProfileConstants.ADVANCED_LOG); + }else{ + activeProfiles.add("advancedLogOff"); + } + if (Boolean.valueOf(props.getProperty("redis.active", "false"))) { + activeProfiles.add(SpringProfileConstants.REDIS_BACKEND); + }else{ + activeProfiles.add(SpringProfileConstants.DB_BACKEND); + } + } + + public String[] getActiveProfiles(){ + return activeProfiles.toArray(new String[0]); + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/MOAGarbageCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/MOAGarbageCollector.java deleted file mode 100644 index 1072bec5c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/MOAGarbageCollector.java +++ /dev/null @@ -1,77 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.config.auth; - - -import java.util.ArrayList; -import java.util.List; - -import at.gv.egovernment.moa.logging.Logger; - -public class MOAGarbageCollector implements Runnable { - - private static final long INTERVAL = 24 * 60 * 60; // 24 hours - private static final List<IGarbageCollectorProcessing> processModules = - new ArrayList<IGarbageCollectorProcessing>(); - - public void run() { - while (true) { - try { - Thread.sleep(INTERVAL * 1000); - - try { - for (IGarbageCollectorProcessing element : processModules) - element.runGarbageCollector(); - - } catch (Throwable e1) { - Logger.warn("Garbage collection FAILED in some module.", e1); - } - - } catch (Throwable e) { - Logger.warn("MOA-ID garbage collection is not possible, actually.", e); - - } finally { - - } - } - } - - /** - * Add a module to MOA internal garbage collector. Every module is executed once a day - * - * @param modul Module which should be executed by the garbage collector. - */ - public static void addModulForGarbageCollection(IGarbageCollectorProcessing modul) { - processModules.add(modul); - - } - - public static void start() { - // start the session cleanup thread - Thread configLoader = new Thread(new MOAGarbageCollector(), "MOAGarbageCollector"); - configLoader.setName("MOAGarbageCollectorr"); - configLoader.setDaemon(true); - configLoader.setPriority(Thread.MIN_PRIORITY); - configLoader.start(); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java index b1bba6c17..6a6359058 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java @@ -122,7 +122,10 @@ public String getIdentityLinkDomainIdentifier() { if (MiscUtil.isNotEmpty(type) && MiscUtil.isNotEmpty(value)) { if (MOAIDConstants.IDENIFICATIONTYPE_STORK.equals(type)) { return MOAIDConstants.PREFIX_STORK + "AT" + "+" + value; - + + } else if (MOAIDConstants.IDENIFICATIONTYPE_EIDAS.equals(type)) { + return MOAIDConstants.PREFIX_EIDAS + value; + } else { return MOAIDConstants.PREFIX_WPBK + type + "+" + value; @@ -395,25 +398,13 @@ public boolean isOnlyMandateAllowed() { * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getQaaLevel() */ @Override -public Integer getQaaLevel() { - try { - Integer storkQAALevel = Integer.parseInt(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_MINQAALEVEL)); - - if (storkQAALevel >= 1 && - storkQAALevel <= 4) - return storkQAALevel; - - else { - Logger.info("STORK minimal QAA level is not in a valid range. Use minimal QAA 4"); - return 4; +public String getQaaLevel() { + String eidasLoALevel = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_MINQAALEVEL); + if (MiscUtil.isEmpty(eidasLoALevel)) + return MOAIDConstants.eIDAS_LOA_HIGH; + else + return eidasLoALevel; - } - - } catch (NumberFormatException e) { - Logger.warn("STORK minimal QAA level is not a number.", e); - return 4; - - } } /* (non-Javadoc) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java index 348b1c45a..e62a4a8d5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/PropertyBasedAuthConfigurationProvider.java @@ -228,6 +228,12 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } + public String getBasicMOAIDConfiguration(final String key, final String defaultValue) { + return properties.getProperty(key, defaultValue); + + } + + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getPropertyWithKey(java.lang.String) */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/DynamicOAAuthParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/DynamicOAAuthParameters.java index 8d70b1444..9fd58b5c7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/DynamicOAAuthParameters.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/DynamicOAAuthParameters.java @@ -201,7 +201,7 @@ public class DynamicOAAuthParameters implements IOAAuthParameters, Serializable{ * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getQaaLevel() */ @Override - public Integer getQaaLevel() { + public String getQaaLevel() { // TODO Auto-generated method stub return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index a1f2c6558..34b250bf0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -104,7 +104,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { @Autowired private SingleLogOutBuilder sloBuilder; @Autowired private SAMLVerificationEngineSP samlVerificationEngine; @Autowired private IGUIFormBuilder guiBuilder; - + @Autowired(required=true) private MOAMetadataProvider metadataProvider; + public void performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { performSingleLogOut(httpReq, httpResp, session, pvpReq, null); @@ -527,7 +528,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { } else { samlVerificationEngine.verifySLOResponse(sloResp, - TrustEngineFactory.getSignatureKnownKeysTrustEngine(MOAMetadataProvider.getInstance())); + TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); } @@ -569,7 +570,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { } //put SLO process-information into transaction storage - transactionStorage.put(relayState, sloContainer); + transactionStorage.put(relayState, sloContainer, -1); if (MiscUtil.isEmpty(authURL)) authURL = pvpReq.getAuthURL(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index 85e4dc99b..ffc6012c9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -32,6 +32,8 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; +import org.opensaml.saml2.metadata.provider.MetadataProvider; + import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; import at.gv.egovernment.moa.id.commons.MOAIDConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; @@ -52,7 +54,12 @@ public abstract class RequestImpl implements IRequest, Serializable{ public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; public static final String DATAID_INTERFEDERATIOIDP_ENTITYID = "interIDPEntityID"; + public static final String DATAID_REQUESTER_IP_ADDRESS = "requesterIP"; + public static final String eIDAS_GENERIC_REQ_DATA_COUNTRY = "country"; + public static final String eIDAS_GENERIC_REQ_DATA_LEVELOFASSURENCE = "eIDAS_LoA"; + + private static final long serialVersionUID = 1L; @@ -91,10 +98,10 @@ public abstract class RequestImpl implements IRequest, Serializable{ */ public final void initialize(HttpServletRequest req) throws ConfigurationException { //set requestID - requestID = Random.nextRandom(); + requestID = Random.nextLongRandom(); //set unique transaction identifier for logging - uniqueTransactionIdentifer = Random.nextRandom(); + uniqueTransactionIdentifer = Random.nextLongRandom(); TransactionIDUtils.setTransactionId(uniqueTransactionIdentifer); @@ -167,6 +174,15 @@ public abstract class RequestImpl implements IRequest, Serializable{ else Logger.warn("No unique session-identifier FOUND, but it should be allready set into request!?!"); + //set requester's IP address + try { + setGenericDataToSession(DATAID_REQUESTER_IP_ADDRESS, req.getRemoteAddr()); + + } catch (SessionDataStorageException e) { + Logger.warn("Can not store remote IP address to 'pendingRequest' during an exception." , e); + + } + } /** @@ -174,7 +190,7 @@ public abstract class RequestImpl implements IRequest, Serializable{ * * @return List of PVP 2.1 attribute names with maps all protocol specific attributes */ - public abstract Collection<String> getRequestedAttributes(); + public abstract Collection<String> getRequestedAttributes(MetadataProvider metadataProvider); public void setOAURL(String value) { oaURL = value; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java index 1b550881e..eec48e0f3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java @@ -68,7 +68,7 @@ public class RequestStorage implements IRequestStorage{ public void storePendingRequest(IRequest pendingRequest) throws MOAIDException { try { if (pendingRequest instanceof IRequest) { - transactionStorage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest); + transactionStorage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest, -1); } else { throw new MOAIDException("auth.20", null); @@ -123,6 +123,7 @@ public class RequestStorage implements IRequestStorage{ ((RequestImpl)pendingRequest).setRequestID(newRequestID); transactionStorage.changeKey(oldRequestID, newRequestID, pendingRequest); + //only delete oldRequestID, no change. return newRequestID; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java index bc7dd272b..0799760ce 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java @@ -63,6 +63,7 @@ public class SSOManager { @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; @Autowired protected AuthConfiguration authConfig; + @Autowired private MOASessionDBUtils moaSessionDBUtils; /** * Check if interfederation IDP is requested via HTTP GET parameter or if interfederation cookie exists. @@ -159,7 +160,7 @@ public class SSOManager { } else { Logger.warn("MOASession is marked as interfederated SSO session but no interfederated IDP is found. Switch to local authentication ..."); - MOASessionDBUtils.delete(storedSession); + moaSessionDBUtils.delete(storedSession); } } @@ -200,7 +201,7 @@ public class SSOManager { public String existsOldSSOSession(String ssoId) { Logger.trace("Check that the SSOID has already been used"); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<OldSSOSessionIDStore> result; @@ -289,7 +290,7 @@ public class SSOManager { //no local SSO session exist -> request interfederated IDP Logger.info("Delete interfederated IDP " + selectedIDP.getIdpurlprefix() + " from MOASession " + storedSession.getSessionid()); - MOASessionDBUtils.delete(selectedIDP); + moaSessionDBUtils.delete(selectedIDP); } else { Logger.warn("MOASession is marked as interfederated SSO session but no interfederated IDP is found. Switch to local authentication ..."); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index a9a9322ad..428931b5e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -22,7 +22,7 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { @Override public void saveOrUpdate(ProcessInstanceStore pIStore) throws MOADatabaseException { try { - transactionStorage.put(pIStore.getProcessInstanceId(), pIStore); + transactionStorage.put(pIStore.getProcessInstanceId(), pIStore, -1); // MOASessionDBUtils.saveOrUpdate(pIStore); log.debug("Store process instance with='{}' in the database.", pIStore.getProcessInstanceId()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java index 2168316ab..6375f26a3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java @@ -80,6 +80,8 @@ public class AttributQueryAction implements IAction { @Autowired private AuthenticationDataBuilder authDataBuilder; @Autowired private IDPCredentialProvider pvpCredentials; @Autowired private AuthConfiguration authConfig; + @Autowired private MOASessionDBUtils moaSessionDBUtils; + @Autowired(required=true) private MOAMetadataProvider metadataProvider; private final static List<String> DEFAULTSTORKATTRIBUTES = Arrays.asList( new String[]{PVPConstants.EID_STORK_TOKEN_NAME}); @@ -139,7 +141,7 @@ public class AttributQueryAction implements IAction { //build PVP 2.1 response Response authResponse = AuthResponseBuilder.buildResponse( - MOAMetadataProvider.getInstance(), issuerEntityID, attrQuery, date, + metadataProvider, issuerEntityID, attrQuery, date, assertion, authConfig.isPVP2AssertionEncryptionActive()); SoapBinding decoder = new SoapBinding(); @@ -198,7 +200,7 @@ public class AttributQueryAction implements IAction { ((PVPTargetConfiguration) pendingReq).getRequest().getInboundMessage() instanceof AttributeQuery) { try { activeOA.setAttributeQueryUsed(true); - MOASessionDBUtils.saveOrUpdate(activeOA); + moaSessionDBUtils.saveOrUpdate(activeOA); } catch (MOADatabaseException e) { Logger.error("MOASession interfederation information can not stored to database.", e); @@ -251,11 +253,11 @@ public class AttributQueryAction implements IAction { //mark attribute request as used if (nextIDPInformation.isStoreSSOInformation()) { nextIDPInformation.setAttributesRequested(true); - MOASessionDBUtils.saveOrUpdate(nextIDPInformation); + moaSessionDBUtils.saveOrUpdate(nextIDPInformation); //delete federated IDP from Session } else { - MOASessionDBUtils.delete(nextIDPInformation); + moaSessionDBUtils.delete(nextIDPInformation); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java index 8de44a2e8..aac49844e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java @@ -61,6 +61,7 @@ import at.gv.egovernment.moa.logging.Logger; public class AuthenticationAction implements IAction { @Autowired IDPCredentialProvider pvpCredentials; @Autowired AuthConfiguration authConfig; + @Autowired(required=true) private MOAMetadataProvider metadataProvider; public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { @@ -70,7 +71,7 @@ public class AuthenticationAction implements IAction { //get basic information MOARequest moaRequest = (MOARequest) pvpRequest.getRequest(); AuthnRequest authnRequest = (AuthnRequest) moaRequest.getSamlRequest(); - EntityDescriptor peerEntity = moaRequest.getEntityMetadata(); + EntityDescriptor peerEntity = moaRequest.getEntityMetadata(metadataProvider); AssertionConsumerService consumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); @@ -94,7 +95,7 @@ public class AuthenticationAction implements IAction { peerEntity, date, consumerService, sloInformation); Response authResponse = AuthResponseBuilder.buildResponse( - MOAMetadataProvider.getInstance(), issuerEntityID, authnRequest, + metadataProvider, issuerEntityID, authnRequest, date, assertion, authConfig.isPVP2AssertionEncryptionActive()); IEncoder binding = null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java index 350690f82..f09a3c30c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java @@ -104,6 +104,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { @Autowired IDPCredentialProvider pvpCredentials; @Autowired SAMLVerificationEngineSP samlVerificationEngine; + @Autowired(required=true) private MOAMetadataProvider metadataProvider; public static final String NAME = PVP2XProtocol.class.getName(); public static final String PATH = "id_pvp2x"; @@ -187,7 +188,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { //get POST-Binding decoder implementation InboundMessage msg = (InboundMessage) new PostBinding().decode( - req, resp, MOAMetadataProvider.getInstance(), false, + req, resp, metadataProvider, false, new MOAURICompare(PVPConfiguration.getInstance().getIDPSSOPostService(pendingReq.getAuthURL()))); pendingReq.setRequest(msg); @@ -240,7 +241,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { //get POST-Binding decoder implementation InboundMessage msg = (InboundMessage) new RedirectBinding().decode( - req, resp, MOAMetadataProvider.getInstance(), false, + req, resp, metadataProvider, false, new MOAURICompare(PVPConfiguration.getInstance().getIDPSSORedirectService(pendingReq.getAuthURL()))); pendingReq.setRequest(msg); @@ -294,7 +295,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { //get POST-Binding decoder implementation InboundMessage msg = (InboundMessage) new SoapBinding().decode( - req, resp, MOAMetadataProvider.getInstance(), false, + req, resp, metadataProvider, false, new MOAURICompare(PVPConfiguration.getInstance().getIDPSSOPostService(pendingReq.getAuthURL()))); pendingReq.setRequest(msg); @@ -336,7 +337,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { if(!msg.isVerified()) { samlVerificationEngine.verify(msg, - TrustEngineFactory.getSignatureKnownKeysTrustEngine(MOAMetadataProvider.getInstance())); + TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); msg.setVerified(true); } @@ -494,7 +495,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { msg = (MOARequest) inMsg; - EntityDescriptor metadata = msg.getEntityMetadata(); + EntityDescriptor metadata = msg.getEntityMetadata(metadataProvider); if(metadata == null) { throw new NoMetadataInformationException(); } @@ -526,7 +527,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { boolean isAllowedDestination = false; for (String prefix : allowedPublicURLPrefix) { - if (!resp.getDestination().startsWith( + if (resp.getDestination().startsWith( prefix)) { isAllowedDestination = true; break; @@ -644,7 +645,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { throw new MOAIDException("Unsupported request", new Object[] {}); } - EntityDescriptor metadata = moaRequest.getEntityMetadata(); + EntityDescriptor metadata = moaRequest.getEntityMetadata(metadataProvider); if(metadata == null) { throw new NoMetadataInformationException(); } @@ -736,7 +737,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { } } - String oaURL = moaRequest.getEntityMetadata().getEntityID(); + String oaURL = moaRequest.getEntityMetadata(metadataProvider).getEntityID(); oaURL = StringEscapeUtils.escapeHtml(oaURL); IOAAuthParameters oa = authConfig.getOnlineApplicationParameter(oaURL); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPAssertionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPAssertionStorage.java index 0dd309154..62105abda 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPAssertionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPAssertionStorage.java @@ -49,7 +49,7 @@ public class PVPAssertionStorage implements SAMLArtifactMap { samlMessage); try { - transactionStorage.put(artifact, assertion); + transactionStorage.put(artifact, assertion, -1); } catch (MOADatabaseException e) { // TODO Insert Error Handling, if Assertion could not be stored diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index e7f2a7d4b..caf66942e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -32,6 +32,7 @@ import org.opensaml.saml2.core.impl.AuthnRequestImpl; import org.opensaml.saml2.metadata.AttributeConsumingService; import org.opensaml.saml2.metadata.RequestedAttribute; import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @@ -54,7 +55,6 @@ public class PVPTargetConfiguration extends RequestImpl { private static final long serialVersionUID = 4889919265919638188L; - InboundMessage request; String binding; String consumerURL; @@ -88,14 +88,14 @@ public class PVPTargetConfiguration extends RequestImpl { * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes() */ @Override - public Collection<String> getRequestedAttributes() { + public Collection<String> getRequestedAttributes(MetadataProvider metadataProvider) { Map<String, String> reqAttr = new HashMap<String, String>(); for (String el : PVP2XProtocol.DEFAULTREQUESTEDATTRFORINTERFEDERATION) reqAttr.put(el, ""); try { - SPSSODescriptor spSSODescriptor = getRequest().getEntityMetadata().getSPSSODescriptor(SAMLConstants.SAML20P_NS); + SPSSODescriptor spSSODescriptor = getRequest().getEntityMetadata(metadataProvider).getSPSSODescriptor(SAMLConstants.SAML20P_NS); if (spSSODescriptor.getAttributeConsumingServices() != null && spSSODescriptor.getAttributeConsumingServices().size() > 0) { @@ -139,5 +139,6 @@ public class PVPTargetConfiguration extends RequestImpl { } - } + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java index 52bf16247..c762e2505 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java @@ -24,17 +24,11 @@ package at.gv.egovernment.moa.id.protocols.pvp2x; import java.io.Serializable; import java.io.UnsupportedEncodingException; -import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.SerializationUtils; -import org.hibernate.HibernateException; -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.resource.transaction.spi.TransactionStatus; import org.opensaml.saml2.core.LogoutRequest; import org.opensaml.saml2.core.LogoutResponse; import org.opensaml.saml2.metadata.SingleLogoutService; @@ -49,7 +43,6 @@ import at.gv.egovernment.moa.id.auth.servlet.RedirectServlet; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.api.IRequest; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.data.IAuthData; @@ -83,8 +76,8 @@ public class SingleLogOutAction implements IAction { @Autowired private ITransactionStorage transactionStorage; @Autowired private SingleLogOutBuilder sloBuilder; @Autowired private MOAReversionLogger revisionsLogger; - - + + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.data.IAuthData) */ @@ -94,142 +87,148 @@ public class SingleLogOutAction implements IAction { IAuthData authData) throws MOAIDException { PVPTargetConfiguration pvpReq = (PVPTargetConfiguration) req; - + if (pvpReq.getRequest() instanceof MOARequest && ((MOARequest)pvpReq.getRequest()).getSamlRequest() instanceof LogoutRequest) { Logger.debug("Process Single LogOut request"); MOARequest samlReq = (MOARequest) pvpReq.getRequest(); LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); - + AuthenticationSession session = authenticationSessionStorage.searchMOASessionWithNameIDandOAID( logOutReq.getIssuer().getValue(), logOutReq.getNameID().getValue()); - - if (session == null) { - Logger.warn("Can not find active SSO session with nameID " - + logOutReq.getNameID().getValue() + " and OA " - + logOutReq.getIssuer().getValue()); - Logger.info("Search active SSO session with SSO session cookie"); - String ssoID = ssomanager.getSSOSessionID(httpReq); - if (MiscUtil.isEmpty(ssoID)) { + + if (session == null) { + Logger.warn("Can not find active SSO session with nameID " + + logOutReq.getNameID().getValue() + " and OA " + + logOutReq.getIssuer().getValue()); + Logger.info("Search active SSO session with SSO session cookie"); + String ssoID = ssomanager.getSSOSessionID(httpReq); + if (MiscUtil.isEmpty(ssoID)) { + Logger.info("Can not find active Session. Single LogOut not possible!"); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); + //LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, null); + Logger.info("Sending SLO success message to requester ..."); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); + return null; + + } else { + String moasession = ssomanager.getMOASession(ssoID); + try { + session = authenticationSessionStorage.getSession(moasession); + + if (session == null) + throw new MOADatabaseException(); + + } catch (MOADatabaseException e) { Logger.info("Can not find active Session. Single LogOut not possible!"); SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); //LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, null); Logger.info("Sending SLO success message to requester ..."); - sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); return null; - - } else { - String moasession = ssomanager.getMOASession(ssoID); - try { - session = authenticationSessionStorage.getSession(moasession); - - if (session == null) - throw new MOADatabaseException(); - - } catch (MOADatabaseException e) { - Logger.info("Can not find active Session. Single LogOut not possible!"); - SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); - //LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, null); - Logger.info("Sending SLO success message to requester ..."); - sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); - return null; - - } - } + + } + } + } + + authManager.performSingleLogOut(httpReq, httpResp, session, pvpReq); + + } else if (pvpReq.getRequest() instanceof MOAResponse && + ((MOAResponse)pvpReq.getRequest()).getResponse() instanceof LogoutResponse) { + Logger.debug("Process Single LogOut response"); + LogoutResponse logOutResp = (LogoutResponse) ((MOAResponse)pvpReq.getRequest()).getResponse(); + + //Transaction tx = null; + + try { + String relayState = pvpReq.getRequest().getRelayState(); + if (MiscUtil.isEmpty(relayState)) { + Logger.warn("SLO Response from " + logOutResp.getIssuer().getValue() + + " has no SAML2 RelayState."); + throw new SLOException("pvp2.19", null); + } - - authManager.performSingleLogOut(httpReq, httpResp, session, pvpReq); - - } else if (pvpReq.getRequest() instanceof MOAResponse && - ((MOAResponse)pvpReq.getRequest()).getResponse() instanceof LogoutResponse) { - Logger.debug("Process Single LogOut response"); - LogoutResponse logOutResp = (LogoutResponse) ((MOAResponse)pvpReq.getRequest()).getResponse(); - - Transaction tx = null; - - try { - String relayState = pvpReq.getRequest().getRelayState(); - if (MiscUtil.isEmpty(relayState)) { - Logger.warn("SLO Response from " + logOutResp.getIssuer().getValue() - + " has no SAML2 RelayState."); - throw new SLOException("pvp2.19", null); - - } - - Session session = MOASessionDBUtils.getCurrentSession(); - boolean storageSuccess = false; - int counter = 0; - - //TODO: add counter to prevent deadlock - + + //Session session = MOASessionDBUtils.getCurrentSession(); + boolean storageSuccess = false; + int counter = 0; + + //TODO: add counter to prevent deadlock + synchronized(this){ while (!storageSuccess) { - tx = session.beginTransaction(); - - List result; - Query query = session.getNamedQuery("getAssertionWithArtifact"); - query.setParameter("artifact", relayState); - result = query.list(); - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { + // tx = session.beginTransaction(); + // + // List result; + // Query query = session.getNamedQuery("getAssertionWithArtifact"); + // query.setParameter("artifact", relayState); + // result = query.list(); + // + // + // Logger.trace("Found entries: " + result.size()); + // + // //Assertion requires an unique artifact + // if (result.size() != 1) { + // Logger.trace("No entries found."); + // throw new MOADatabaseException("No sessioninformation found with this ID"); + // } + // + // AssertionStore element = (AssertionStore) result.get(0); + // Object data = SerializationUtils.deserialize(element.getAssertion()); + Logger.debug("Current Thread getAssertionStore: "+Thread.currentThread().getId()); + Object o = transactionStorage.getAssertionStore(relayState); + if(o==null){ Logger.trace("No entries found."); - throw new MOADatabaseException("No sessioninformation found with this ID"); + throw new MOADatabaseException("No sessioninformation found with this ID"); } - - AssertionStore element = (AssertionStore) result.get(0); - Object data = SerializationUtils.deserialize(element.getAssertion()); - + AssertionStore element = (AssertionStore) o; + Object data = SerializationUtils.deserialize(element.getAssertion()); + if (data instanceof SLOInformationContainer) { ISLOInformationContainer sloContainer = (ISLOInformationContainer) data; - + //check status sloBuilder.checkStatusCode(sloContainer, logOutResp); - + if (sloContainer.hasFrontChannelOA()) { try { //some response are open byte[] serializedSLOContainer = SerializationUtils.serialize((Serializable) sloContainer); element.setAssertion(serializedSLOContainer); element.setType(sloContainer.getClass().getName()); - - session.saveOrUpdate(element); - tx.commit(); - + + // session.saveOrUpdate(element); + // tx.commit(); + Logger.debug("Current Thread putAssertionStore: "+Thread.currentThread().getId()); + transactionStorage.putAssertionStore(element); + //sloContainer could be stored to database storageSuccess = true; - - } catch(HibernateException e) { - tx.rollback(); + + } catch(MOADatabaseException e) { + //tx.rollback(); counter++; Logger.debug("SLOContainter could not stored to database. Wait some time and restart storage process ... "); java.util.Random rand = new java.util.Random(); - + try { Thread.sleep(rand.nextInt(20)*10); - + } catch (InterruptedException e1) { Logger.warn("Thread could not stopped. ReStart storage process immediately", e1); } } - + } else { - //last response received. - try { - session.delete(element); - tx.commit(); - - } catch(HibernateException e) { - tx.rollback(); - Logger.error("SLOContainter could not deleted from database. "); - - } - + Logger.debug("Current Thread removeElement by Artifact: "+Thread.currentThread().getId()); + transactionStorage.remove(element.getArtifact()); + // session.delete(element); + // tx.commit(); + storageSuccess = true; String redirectURL = null; if (sloContainer.getSloRequest() != null) { @@ -237,70 +236,72 @@ public class SingleLogOutAction implements IAction { SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(sloContainer.getSloRequest()); LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, sloContainer.getSloRequest(), sloContainer.getSloFailedOAs()); redirectURL = sloBuilder.getFrontChannelSLOMessageURL(sloService, message, httpReq, httpResp, sloContainer.getSloRequest().getRequest().getRelayState()); - + } else { //print SLO information directly redirectURL = req.getAuthURL() + "/idpSingleLogout"; - + String artifact = Random.nextRandom(); - - String statusCode = null; + + String statusCode = null; if (sloContainer.getSloFailedOAs() == null || - sloContainer.getSloFailedOAs().size() == 0) { - statusCode = MOAIDAuthConstants.SLOSTATUS_SUCCESS; - revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), - MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); - + sloContainer.getSloFailedOAs().size() == 0) { + statusCode = MOAIDAuthConstants.SLOSTATUS_SUCCESS; + revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), + MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); + } else { revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); - statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; - + statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; + } - transactionStorage.put(artifact, statusCode); - redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); - + transactionStorage.put(artifact, statusCode, -1); + redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); + } //redirect to Redirect Servlet String url = req.getAuthURL() + "/RedirectServlet"; url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(redirectURL, "UTF-8")); url = httpResp.encodeRedirectURL(url); - + httpResp.setContentType("text/html"); httpResp.setStatus(302); httpResp.addHeader("Location", url); - + } } else { Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + relayState); throw new MOADatabaseException("Sessioninformation Cast-Exception"); - + } } - - } catch (MOADatabaseException e) { - Logger.error("MOA AssertionDatabase ERROR", e); - throw new SLOException("pvp2.19", null); - - } catch (UnsupportedEncodingException e) { - Logger.error("Finale SLO redirct not possible.", e); - throw new AuthenticationException("pvp2.13", new Object[]{}); - - } finally { - if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) { - tx.commit(); - - } } - - - - } else { - Logger.error("Process SingleLogOutAction but request is NOT of type LogoutRequest or LogoutResponse."); - throw new MOAIDException("pvp2.13", null); - - } - + } catch (MOADatabaseException e) { + Logger.error("MOA AssertionDatabase ERROR", e); + throw new SLOException("pvp2.19", null); + + } catch (UnsupportedEncodingException e) { + Logger.error("Finale SLO redirct not possible.", e); + throw new AuthenticationException("pvp2.13", new Object[]{}); + + } + + // finally { + // if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) { + // tx.commit(); + // + // } + // } + + + + } else { + Logger.error("Process SingleLogOutAction but request is NOT of type LogoutRequest or LogoutResponse."); + throw new MOAIDException("pvp2.13", null); + + } + return null; } @@ -320,7 +321,7 @@ public class SingleLogOutAction implements IAction { public String getDefaultActionName() { return PVP2XProtocol.SINGLELOGOUT; } - + protected static String addURLParameter(String url, String paramname, String paramvalue) { String param = paramname + "=" + paramvalue; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index 25b22f0ad..94d91694a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -62,6 +62,7 @@ import at.gv.egovernment.moa.util.MiscUtil; public class SoapBinding implements IDecoder, IEncoder { + @Autowired(required=true) private MOAMetadataProvider metadataProvider; @Autowired private IDPCredentialProvider credentialProvider; public InboundMessageInterface decode(HttpServletRequest req, @@ -109,7 +110,7 @@ public class SoapBinding implements IDecoder, IEncoder { RequestAbstractType attributeRequest = (RequestAbstractType) attrReq; try { if (MiscUtil.isNotEmpty(attributeRequest.getIssuer().getValue()) && - MOAMetadataProvider.getInstance().getRole( + metadataProvider.getRole( attributeRequest.getIssuer().getValue(), SPSSODescriptor.DEFAULT_ELEMENT_NAME) != null) request.setEntityID(attributeRequest.getIssuer().getValue()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java index 855925272..e2f8664d8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java @@ -24,8 +24,6 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder; import java.io.IOException; import java.io.StringWriter; -import java.security.PrivateKey; -import java.security.interfaces.RSAPrivateKey; import java.util.List; import javax.xml.parsers.DocumentBuilder; @@ -66,7 +64,6 @@ import org.opensaml.xml.security.credential.UsageType; import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; import org.opensaml.xml.signature.Signature; -import org.opensaml.xml.signature.SignatureConstants; import org.opensaml.xml.signature.SignatureException; import org.opensaml.xml.signature.Signer; import org.springframework.stereotype.Service; @@ -74,6 +71,7 @@ import org.w3c.dom.Document; import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; @@ -153,7 +151,7 @@ public class PVPMetadataBuilder { //set metadata signature parameters Credential metadataSignCred = config.getMetadataSigningCredentials(); - Signature signature = getIDPSignature(metadataSignCred); + Signature signature = AbstractCredentialProvider.getIDPSignature(metadataSignCred); SecurityHelper.prepareSignatureParams(signature, metadataSignCred, null, null); @@ -437,27 +435,5 @@ public class PVPMetadataBuilder { return idpSSODescriptor; } - - private Signature getIDPSignature(Credential credentials) { - PrivateKey privatekey = credentials.getPrivateKey(); - Signature signer = SAML2Utils.createSAMLObject(Signature.class); - if (privatekey instanceof RSAPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); - - } else if (privatekey instanceof iaik.security.ecc.ecdsa.ECPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); - - } else { - Logger.warn("Could NOT evaluate the Private-Key type from " + credentials.getEntityId() + " credential."); - - - } - - signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); - signer.setSigningCredential(credentials); - return signer; - - } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java index e5c897aa6..de59e6055 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java @@ -94,8 +94,9 @@ import at.gv.egovernment.moa.logging.Logger; @Service("PVP_SingleLogOutBuilder") public class SingleLogOutBuilder { + @Autowired(required=true) private MOAMetadataProvider metadataProvider; @Autowired private IDPCredentialProvider credentialProvider; - + public void checkStatusCode(ISLOInformationContainer sloContainer, LogoutResponse logOutResp) { Status status = logOutResp.getStatus(); if (!status.getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { @@ -353,7 +354,7 @@ public class SingleLogOutBuilder { public SingleLogoutService getRequestSLODescriptor(String entityID) throws NOSLOServiceDescriptorException { try { - EntityDescriptor entity = MOAMetadataProvider.getInstance().getEntityDescriptor(entityID); + EntityDescriptor entity = metadataProvider.getEntityDescriptor(entityID); SSODescriptor spsso = entity.getSPSSODescriptor(SAMLConstants.SAML20P_NS); SingleLogoutService sloService = null; @@ -394,7 +395,7 @@ public class SingleLogOutBuilder { public SingleLogoutService getResponseSLODescriptor(PVPTargetConfiguration spRequest) throws NoMetadataInformationException, NOSLOServiceDescriptorException { MOARequest moaReq = (MOARequest) spRequest.getRequest(); - EntityDescriptor metadata = moaReq.getEntityMetadata(); + EntityDescriptor metadata = moaReq.getEntityMetadata(metadataProvider); SSODescriptor ssodesc = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); if (ssodesc == null) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index 200429093..55d8fa1ff 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -459,8 +459,15 @@ public class PVP2AssertionBuilder implements PVPConstants { subjectConfirmationData.setNotOnOrAfter(new DateTime(authData.getSsoSessionValidTo().getTime())); // subjectConfirmationData.setNotBefore(date); + //set 'recipient' attribute in subjectConformationData subjectConfirmationData.setRecipient(assertionConsumerService.getLocation()); + //set IP address of the user machine as 'Address' attribute in subjectConformationData + String usersIPAddress = pendingReq.getGenericData( + PVPTargetConfiguration.DATAID_REQUESTER_IP_ADDRESS, String.class); + if (MiscUtil.isNotEmpty(usersIPAddress)) + subjectConfirmationData.setAddress(usersIPAddress); + //set SLO information sloInformation.setUserNameIdentifier(subjectNameID.getValue()); sloInformation.setNameIDFormat(subjectNameID.getFormat()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/InboundMessage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/InboundMessage.java index 332caf967..8c8345bbf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/InboundMessage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/InboundMessage.java @@ -25,11 +25,11 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.messages; import java.io.Serializable; import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.saml2.metadata.provider.MetadataProviderException; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMetadataInformationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.logging.Logger; /** @@ -46,10 +46,12 @@ public class InboundMessage implements InboundMessageInterface, Serializable{ private String relayState = null; - public EntityDescriptor getEntityMetadata() throws NoMetadataInformationException { - + public EntityDescriptor getEntityMetadata(MetadataProvider metadataProvider) throws NoMetadataInformationException { try { - return MOAMetadataProvider.getInstance().getEntityDescriptor(this.entityID); + if (metadataProvider == null) + throw new NullPointerException("No PVP MetadataProvider found."); + + return metadataProvider.getEntityDescriptor(this.entityID); } catch (MetadataProviderException e) { Logger.warn("No Metadata for EntitiyID " + entityID); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java index 3002ca179..19adfe4c4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java @@ -44,13 +44,14 @@ import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.saml2.metadata.provider.MetadataProviderException; import org.opensaml.saml2.metadata.provider.ObservableMetadataProvider; import org.opensaml.xml.XMLObject; +import org.springframework.stereotype.Service; +import at.gv.egovernment.moa.id.auth.IDestroyableObject; +import at.gv.egovernment.moa.id.auth.IGarbageCollectorProcessing; import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing; -import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.InterfederatedIDPPublicServiceFilter; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.PVPMetadataFilterChain; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.SchemaValidationFilter; @@ -58,65 +59,85 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; +@Service("PVPMetadataProvider") public class MOAMetadataProvider extends SimpleMOAMetadataProvider - implements ObservableMetadataProvider, IGarbageCollectorProcessing, IMOARefreshableMetadataProvider { + implements ObservableMetadataProvider, IGarbageCollectorProcessing, + IMOARefreshableMetadataProvider, IDestroyableObject { - private static MOAMetadataProvider instance = null; + //private static final int METADATA_GARBAGE_TIMEOUT_SEC = 604800; //7 days + +// private static MOAMetadataProvider instance = null; + MetadataProvider internalProvider = null; private static Object mutex = new Object(); + //private Map<String, Date> lastAccess = null; - public static MOAMetadataProvider getInstance() { - if (instance == null) { - synchronized (mutex) { - if (instance == null) { - instance = new MOAMetadataProvider(); - - //add this to MOA garbage collector - MOAGarbageCollector.addModulForGarbageCollection(instance); - - } - } - } - return instance; + public MOAMetadataProvider() { + internalProvider = new ChainingMetadataProvider(); + //lastAccess = new HashMap<String, Date>(); + } +// public static MOAMetadataProvider getInstance() { +// if (instance == null) { +// synchronized (mutex) { +// if (instance == null) { +// instance = new MOAMetadataProvider(); +// +// //add this to MOA garbage collector +// MOAGarbageCollector.addModulForGarbageCollection(instance); +// +// } +// } +// } +// return instance; +// } + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing#runGarbageCollector() */ @Override public void runGarbageCollector() { - reInitialize(); - - } - - private static void reInitialize() { synchronized (mutex) { /**add new Metadataprovider or remove Metadataprovider which are not in use any more.**/ - if (instance != null) - try { - Logger.trace("Check consistence of PVP2X metadata"); - instance.addAndRemoveMetadataProvider(); + try { + Logger.trace("Check consistence of PVP2X metadata"); + addAndRemoveMetadataProvider(); - } catch (ConfigurationException e) { - Logger.error("Access to MOA-ID configuration FAILED.", e); + } catch (ConfigurationException e) { + Logger.error("Access to MOA-ID configuration FAILED.", e); - } - else - Logger.info("MOAMetadataProvider is not loaded."); + } } + } - public static void destroy() { - if (instance != null) { - instance.internalDestroy(); + +// private static void reInitialize() { +// synchronized (mutex) { +// +// /**add new Metadataprovider or remove Metadataprovider which are not in use any more.**/ +// if (instance != null) +// try { +// Logger.trace("Check consistence of PVP2X metadata"); +// instance.addAndRemoveMetadataProvider(); +// +// } catch (ConfigurationException e) { +// Logger.error("Access to MOA-ID configuration FAILED.", e); +// +// } +// else +// Logger.info("MOAMetadataProvider is not loaded."); +// } +// } + + public void fullyDestroy() { + internalDestroy(); - } else { - Logger.info("MOAMetadataProvider is not loaded. Accordingly it can not be destroyed"); - } } - MetadataProvider internalProvider; + @Override public boolean refreshMetadataProvider(String entityID) { @@ -208,7 +229,7 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider private void addAndRemoveMetadataProvider() throws ConfigurationException { if (internalProvider != null && internalProvider instanceof ChainingMetadataProvider) { - Logger.info("Relaod MOAMetaDataProvider."); + Logger.info("Reload MOAMetaDataProvider."); /*OpenSAML ChainingMetadataProvider can not remove a MetadataProvider (UnsupportedOperationException) *The ChainingMetadataProvider use internal a unmodifiableList to hold all registrated MetadataProviders.*/ @@ -217,7 +238,19 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider //get all actually loaded metadata providers Map<String, HTTPMetadataProvider> loadedproviders = getAllActuallyLoadedProviders(); - + + /* TODO: maybe add metadata provider destroy after timeout. + * But could be a problem if one Metadataprovider load an EntitiesDescriptor + * with more the multiple EntityDescriptors. If one of this EntityDesciptors + * are expired the full EntitiesDescriptor is removed. + * + * Timeout requires a better solution in this case! + */ +// Date now = new Date(); +// Date expioredate = new Date(now.getTime() - (METADATA_GARBAGE_TIMEOUT_SEC * 1000)); +// Logger.debug("Starting PVP Metadata garbag collection (Expioredate:" +// + expioredate + ")"); + //load all PVP2 OAs form ConfigurationDatabase and //compare actually loaded Providers with configured PVP2 OAs Map<String, String> allOAs = AuthConfigurationProviderFactory.getInstance().getConfigurationWithWildCard( @@ -238,30 +271,31 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider HTTPMetadataProvider httpProvider = null; try { if (MiscUtil.isNotEmpty(metadataurl)) { - if (loadedproviders.containsKey(metadataurl)) { + if (loadedproviders.containsKey(metadataurl)) { // PVP2 OA is actually loaded, to nothing providersinuse.put(metadataurl, loadedproviders.get(metadataurl)); loadedproviders.remove(metadataurl); - } else if ( MiscUtil.isNotEmpty(metadataurl) && - !providersinuse.containsKey(metadataurl) ) { - //PVP2 OA is new, add it to MOAMetadataProvider - String certBase64 = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); - if (MiscUtil.isNotEmpty(certBase64)) { - byte[] cert = Base64Utils.decode(certBase64, false); - String oaFriendlyName = oaParam.getFriendlyName(); - - - Logger.info("Loading metadata for: " + oaFriendlyName); - httpProvider = createNewHTTPMetaDataProvider( - metadataurl, - buildMetadataFilterChain(oaParam, metadataurl, cert), - oaFriendlyName); - - if (httpProvider != null) - providersinuse.put(metadataurl, httpProvider); - } + //INFO: load metadata dynamically if they are requested +// } else if ( MiscUtil.isNotEmpty(metadataurl) && +// !providersinuse.containsKey(metadataurl) ) { +// //PVP2 OA is new, add it to MOAMetadataProvider +// String certBase64 = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); +// if (MiscUtil.isNotEmpty(certBase64)) { +// byte[] cert = Base64Utils.decode(certBase64, false); +// String oaFriendlyName = oaParam.getFriendlyName(); +// +// +// Logger.info("Loading metadata for: " + oaFriendlyName); +// httpProvider = createNewHTTPMetaDataProvider( +// metadataurl, +// buildMetadataFilterChain(oaParam, metadataurl, cert), +// oaFriendlyName); +// +// if (httpProvider != null) +// providersinuse.put(metadataurl, httpProvider); +// } } } @@ -339,15 +373,21 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider } } - instance = null; + internalProvider = new ChainingMetadataProvider(); } else { Logger.warn("ReInitalize MOAMetaDataProvider is not possible! MOA-ID Instance has to be restarted manualy"); } } - private MOAMetadataProvider() { + @Deprecated + /** + * Load all PVP metadata from OA configuration + * + * This method is deprecated because OA metadata should be loaded dynamically + * if the corresponding OA is requested. + */ + private void loadAllPVPMetadataFromKonfiguration() { ChainingMetadataProvider chainProvider = new ChainingMetadataProvider(); - Logger.info("Loading metadata"); Map<String, MetadataProvider> providersinuse = new HashMap<String, MetadataProvider>(); try { @@ -417,14 +457,15 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider + e.getMessage(), e); } + internalProvider = chainProvider; + } catch (ConfigurationException e) { Logger.error("Access MOA-ID configuration FAILED.", e); } - - internalProvider = chainProvider; + } - + private PVPMetadataFilterChain buildMetadataFilterChain(IOAAuthParameters oaParam, String metadataURL, byte[] certificate) throws CertificateException { PVPMetadataFilterChain filterChain = new PVPMetadataFilterChain(metadataURL, certificate); filterChain.getFilters().add(new SchemaValidationFilter()); @@ -505,17 +546,30 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider } +// if (entityDesc != null) +// lastAccess.put(entityID, new Date()); + return entityDesc; } public List<RoleDescriptor> getRole(String entityID, QName roleName) - throws MetadataProviderException { - return internalProvider.getRole(entityID, roleName); + throws MetadataProviderException { + List<RoleDescriptor> result = internalProvider.getRole(entityID, roleName); + +// if (result != null) +// lastAccess.put(entityID, new Date()); + + return result; } public RoleDescriptor getRole(String entityID, QName roleName, String supportedProtocol) throws MetadataProviderException { - return internalProvider.getRole(entityID, roleName, supportedProtocol); + RoleDescriptor result = internalProvider.getRole(entityID, roleName, supportedProtocol); + +// if (result != null) +// lastAccess.put(entityID, new Date()); + + return result; } /* (non-Javadoc) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java index 442455d4b..8261a86c1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java @@ -81,7 +81,7 @@ public abstract class SimpleMOAMetadataProvider implements MetadataProvider{ } } - timer = new Timer(); + timer = new Timer(true); httpProvider = new HTTPMetadataProvider(timer, httpClient, metadataURL); httpProvider.setParserPool(new BasicParserPool()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java index bf4cfd480..77cc7228b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java @@ -24,6 +24,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.signer; import java.security.KeyStore; import java.security.PrivateKey; +import java.security.interfaces.ECPrivateKey; import java.security.interfaces.RSAPrivateKey; import org.opensaml.xml.security.credential.Credential; @@ -198,7 +199,7 @@ public abstract class AbstractCredentialProvider { if (privatekey instanceof RSAPrivateKey) { signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); - } else if (privatekey instanceof iaik.security.ecc.ecdsa.ECPrivateKey) { + } else if (privatekey instanceof ECPrivateKey) { signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); } else { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index f384dd511..f6104bdeb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -41,6 +41,7 @@ import org.opensaml.xml.security.criteria.EntityIDCriteria; import org.opensaml.xml.security.criteria.UsageCriteria; import org.opensaml.xml.signature.SignatureTrustEngine; import org.opensaml.xml.validation.ValidationException; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Element; import org.xml.sax.SAXException; @@ -56,6 +57,8 @@ import at.gv.egovernment.moa.util.MiscUtil; @Service("SAMLVerificationEngine") public class SAMLVerificationEngine { + + @Autowired(required=true) MOAMetadataProvider metadataProvider; public void verify(InboundMessage msg, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { try { @@ -72,7 +75,8 @@ public class SAMLVerificationEngine { } Logger.debug("PVP2X message validation FAILED. Relead metadata for entityID: " + msg.getEntityID()); - if (!MOAMetadataProvider.getInstance().refreshMetadataProvider(msg.getEntityID())) + + if (metadataProvider == null || !metadataProvider.refreshMetadataProvider(msg.getEntityID())) throw e; else { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MOASPMetadataSignatureFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MOASPMetadataSignatureFilter.java index 3d69b0380..6e97913bf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MOASPMetadataSignatureFilter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MOASPMetadataSignatureFilter.java @@ -102,6 +102,7 @@ public class MOASPMetadataSignatureFilter implements MetadataFilter { } + Logger.debug("SAML metadata for entityID:" + entityDes.getEntityID() + " is valid"); } catch (MOAIDException | TransformerFactoryConfigurationError | TransformerException | IOException e) { Logger.error("Metadata verification has an interal error.", e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java index 094e25040..4d7936f25 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java @@ -35,6 +35,7 @@ import org.hibernate.Transaction; import org.hibernate.resource.transaction.spi.TransactionStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.core.JsonProcessingException; @@ -65,7 +66,7 @@ import at.gv.egovernment.moa.util.MiscUtil; public class DBAuthenticationSessionStoreage implements IAuthenticationSessionStoreage{ @Autowired AuthConfiguration authConfig; - + @Autowired MOASessionDBUtils moaSessionDBUtils; private static JsonMapper mapper = new JsonMapper(); @Override @@ -74,7 +75,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt AuthenticatedSessionStore session; try { - session = searchInDatabase(moaSessionID, true); + session = searchInDatabase(moaSessionID); return session.isAuthenticated(); } catch (MOADatabaseException e) { @@ -104,7 +105,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt encryptSession(session, dbsession); //store AssertionStore element to Database - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); Logger.info("Create MOASession with sessionID: " + id); return session; @@ -128,7 +129,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return null; try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); return decryptSession(dbsession); } catch (MOADatabaseException e) { @@ -143,7 +144,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public AuthenticationSessionExtensions getAuthenticationSessionExtensions(String sessionID) throws MOADatabaseException { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); if (MiscUtil.isNotEmpty(dbsession.getAdditionalInformation())) { try { @@ -161,12 +162,12 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public void setAuthenticationSessionExtensions(String sessionID, AuthenticationSessionExtensions sessionExtensions) throws MOADatabaseException { try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); dbsession.setAdditionalInformation( mapper.serialize(sessionExtensions)); - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); Logger.debug("MOASession with sessionID=" + sessionID + " is stored in Database"); @@ -185,7 +186,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public void storeSession(AuthenticationSession session) throws MOADatabaseException, BuildException { try { - AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true); + AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID()); encryptSession(session, dbsession); @@ -193,7 +194,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt dbsession.setAuthenticated(session.isAuthenticated()); dbsession.setUpdated(new Date()); - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); Logger.debug("MOASession with sessionID=" + session.getSessionID() + " is stored in Database"); } catch (MOADatabaseException e) { @@ -205,7 +206,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public void destroySession(String moaSessionID) throws MOADatabaseException { - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; Transaction tx = null; @@ -216,6 +217,8 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt Query query = session.getNamedQuery("getSessionWithID"); query.setParameter("sessionid", moaSessionID); result = query.list(); + + Logger.trace("Found entries: " + result.size()); @@ -243,7 +246,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public String changeSessionID(AuthenticationSession session, String newSessionID) throws BuildException, MOADatabaseException { - AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true); + AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID()); Logger.debug("Change SessionID from " + session.getSessionID() + "to " + newSessionID); @@ -257,7 +260,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1 dbsession.setUpdated(new Date()); - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); Logger.trace("Change SessionID complete."); @@ -279,9 +282,9 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt AuthenticatedSessionStore session; try { - session = searchInDatabase(moaSessionID, true); + session = searchInDatabase(moaSessionID); session.setAuthenticated(isAuthenticated); - MOASessionDBUtils.saveOrUpdate(session); + moaSessionDBUtils.saveOrUpdate(session); } catch (MOADatabaseException e) { @@ -293,7 +296,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt public String getMOASessionSSOID(String SSOSessionID) { MiscUtil.assertNotNull(SSOSessionID, "SSOsessionID"); Logger.trace("Get authenticated session with SSOID " + SSOSessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; Transaction tx = null; @@ -331,7 +334,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public boolean isSSOSession(String sessionID) throws MOADatabaseException { try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); return dbsession.isSSOSession(); } catch (MOADatabaseException e) { @@ -346,7 +349,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt //TODO: is this method really needed?? MiscUtil.assertNotNull(SSOId, "SSOSessionID"); Logger.trace("Get authenticated session with SSOID " + SSOId + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; Transaction tx = null; @@ -387,7 +390,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt try { - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; Logger.trace("Add SSO information to session " + moaSessionID); @@ -487,63 +490,63 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt @Override public List<OASessionStore> getAllActiveOAFromMOASession(AuthenticationSession moaSession) { MiscUtil.assertNotNull(moaSession, "MOASession"); - Session session = null; - - try { - List<OASessionStore> oas = new ArrayList<OASessionStore>(); - - AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); - oas.addAll(dbsession.getActiveOAsessions()); - - session = MOASessionDBUtils.getCurrentSession(); - session.getTransaction().commit(); - - return oas; - - } catch (MOADatabaseException e) { - Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e); - - } catch (Exception e) { - if (session != null && session.getTransaction() != null - && !session.getTransaction().getStatus().equals(TransactionStatus.COMMITTED)) { - session.getTransaction().rollback(); - throw e; - - } - - } - - return null; + + Logger.trace("Get OAs for moaSession " + moaSession.getSessionID() + " from database."); + Session session = moaSessionDBUtils.getCurrentSession(); + + List<OASessionStore> result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getAllActiveOAsForSessionID"); + query.setParameter("sessionID", moaSession.getSessionID()); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + return result; + + } catch (Exception e) { + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) + tx.rollback(); + throw e; + } } @Override public List<InterfederationSessionStore> getAllActiveIDPsFromMOASession(AuthenticationSession moaSession) { MiscUtil.assertNotNull(moaSession, "MOASession"); - Session session = null; - try { - List<InterfederationSessionStore> idps = new ArrayList<InterfederationSessionStore>(); - AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); - idps.addAll(dbsession.getInderfederation()); - - session = MOASessionDBUtils.getCurrentSession(); - session.getTransaction().commit(); - - return idps; - - } catch (MOADatabaseException e) { - Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e); - - } catch (Exception e) { - if (session != null && session.getTransaction() != null - && !session.getTransaction().getStatus().equals(TransactionStatus.COMMITTED)) { - session.getTransaction().rollback(); - throw e; - - } - - } - - return null; + + Logger.trace("Get active IDPs for moaSession " + moaSession.getSessionID() + " from database."); + Session session = moaSessionDBUtils.getCurrentSession(); + + List<InterfederationSessionStore> result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getAllActiveIDPsForSessionID"); + query.setParameter("sessionID", moaSession.getSessionID()); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + return result; + + } catch (Exception e) { + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) + tx.rollback(); + throw e; + } } @Override @@ -552,7 +555,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt MiscUtil.assertNotNull(userNameID, "userNameID"); Logger.trace("Get moaSession for userNameID " + userNameID + " and OA " + oaID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); Transaction tx = null; List<AuthenticatedSessionStore> result = null;; @@ -598,7 +601,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt MiscUtil.assertNotNull(protocolType, "usedProtocol"); Logger.trace("Get active OnlineApplication for sessionID " + moaSession.getSessionID() + " with OAID " + oaID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; Transaction tx = null; @@ -640,7 +643,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt try { MiscUtil.assertNotNull(nameID, "nameID"); Logger.trace("Get authenticated session with pedingRequestID " + nameID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; @@ -677,7 +680,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt public InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASession(String sessionID) { MiscUtil.assertNotNull(sessionID, "MOASession"); Logger.trace("Get interfederated IDP for SSO with sessionID " + sessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; Transaction tx = null; @@ -714,7 +717,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt MiscUtil.assertNotNull(sessionID, "MOASession"); MiscUtil.assertNotNull(idpID, "Interfederated IDP ID"); Logger.trace("Get interfederated IDP "+ idpID + " for SSO with sessionID " + sessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; Transaction tx = null; @@ -756,7 +759,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt String moaSession = getMOASessionSSOID(req.getMOASessionIdentifier()); if (MiscUtil.isNotEmpty(moaSession)) { try { - dbsession = searchInDatabase(moaSession, true); + dbsession = searchInDatabase(moaSession); }catch (MOADatabaseException e) { Logger.error("NO MOASession found but MOASession MUST already exist!"); @@ -818,7 +821,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt //store AssertionStore element to Database try { - MOASessionDBUtils.saveOrUpdate(dbsession); + moaSessionDBUtils.saveOrUpdate(dbsession); } catch (MOADatabaseException e) { Logger.warn("MOASession could not be created."); @@ -831,7 +834,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt public InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(String moaSessionID) { MiscUtil.assertNotNull(moaSessionID, "MOASessionID"); Logger.trace("Get interfederated IDP for AttributeQuery with sessionID " + moaSessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; Transaction tx = null; @@ -872,7 +875,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID"); Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List<AuthenticatedSessionStore> result; @@ -907,7 +910,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } } - MOASessionDBUtils.saveOrUpdate(authsession); + moaSessionDBUtils.saveOrUpdate(authsession); return true; } catch (Throwable e) { @@ -922,7 +925,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt Date expioredateupdate = new Date(now.getTime() - authDataTimeOutUpdated); List<AuthenticatedSessionStore> results; - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); Transaction tx = null; try { synchronized (session) { @@ -972,26 +975,26 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } - private static void cleanDelete(AuthenticatedSessionStore result) { + private void cleanDelete(AuthenticatedSessionStore result) { try { result.setSession("blank".getBytes()); - MOASessionDBUtils.saveOrUpdate(result); + moaSessionDBUtils.saveOrUpdate(result); } catch (MOADatabaseException e) { Logger.warn("Blank authenticated session with sessionID=" + result.getSessionid() + " FAILED.", e); } finally { - if (!MOASessionDBUtils.delete(result)) + if (!moaSessionDBUtils.delete(result)) Logger.error("Authenticated session with sessionID=" + result.getSessionid() + " not removed! (Error during Database communication)"); } } @SuppressWarnings("rawtypes") - private static AuthenticatedSessionStore searchInDatabase(String sessionID, boolean commit) throws MOADatabaseException { + private AuthenticatedSessionStore searchInDatabase(String sessionID) throws MOADatabaseException { MiscUtil.assertNotNull(sessionID, "moasessionID"); Logger.trace("Get authenticated session with sessionID " + sessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); + Session session = moaSessionDBUtils.getCurrentSession(); List result; Transaction tx = null; @@ -1003,8 +1006,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt result = query.list(); //send transaction - if (commit) - tx.commit(); + tx.commit(); } Logger.trace("Found entries: " + result.size()); @@ -1019,7 +1021,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return (AuthenticatedSessionStore) result.get(0); } catch (Exception e) { - if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED) && commit) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java index c2b3b0fc5..f17e4a99a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java @@ -27,24 +27,31 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; +import javax.persistence.EntityManager; +import javax.persistence.PersistenceContext; +import javax.persistence.PersistenceException; +import javax.persistence.Query; + import org.apache.commons.lang.SerializationUtils; import org.hibernate.HibernateException; -import org.hibernate.Query; -import org.hibernate.Session; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Repository; +import org.springframework.transaction.annotation.Transactional; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -@Service("TransactionStorage") +@Repository +@Transactional("sessionTransactionManager") public class DBTransactionStorage implements ITransactionStorage { - + + @PersistenceContext(unitName="session") + private EntityManager entityManager; + public boolean containsKey(String key) { - try { + try { searchInDatabase(key); return true; @@ -73,7 +80,7 @@ public class DBTransactionStorage implements ITransactionStorage { } - public void put(String key, Object value) throws MOADatabaseException { + public void put(String key, Object value, int timeout_ms) throws MOADatabaseException { //search if key already exists AssertionStore element = searchInDatabase(key); @@ -97,7 +104,11 @@ public class DBTransactionStorage implements ITransactionStorage { Logger.error("This exeption should not occur!!!!", e); return null; - } + } + } + + public Object getAssertionStore(String key) throws MOADatabaseException{ + return searchInDatabase(key); } public Object get(String key) throws MOADatabaseException { @@ -151,16 +162,12 @@ public class DBTransactionStorage implements ITransactionStorage { List<AssertionStore> results; List<String> returnValues = new ArrayList<String>();; - Session session = MOASessionDBUtils.getCurrentSession(); - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getAssertionWithTimeOut"); - query.setTimestamp("timeout", expioredate); - results = query.list(); - session.getTransaction().commit(); - } + Query query = entityManager.createNamedQuery("getAssertionWithTimeOut"); + query.setParameter("timeout", expioredate); + results = query.getResultList(); + if (results != null) { for (AssertionStore el : results) returnValues.add(el.getArtifact()); @@ -187,24 +194,21 @@ public class DBTransactionStorage implements ITransactionStorage { Logger.info("Sessioninformation not removed! (Message:"+ e.getMessage() + ")"); } catch (HibernateException e) { - Logger.warn("Sessioninformation not removed! (Error during Database communication)", e); + Logger.warn("Sessioninformation not removed! (Erreor during Database communication)", e); } } private void cleanDelete(AssertionStore element) { - try { - element.setAssertion("blank".getBytes()); - MOASessionDBUtils.saveOrUpdate(element); - - } catch (MOADatabaseException e) { - Logger.warn("Blank shortTime session with artifact=" + element.getArtifact() + " FAILED.", e); + - } finally { - if (!MOASessionDBUtils.delete(element)) + try{ + element.setAssertion("blank".getBytes()); + entityManager.merge(element); + entityManager.remove(element); + }catch(PersistenceException e){ Logger.error("ShortTime session with artifact=" + element.getArtifact() + " not removed! (Error during Database communication)"); - - } + } } @@ -212,29 +216,23 @@ public class DBTransactionStorage implements ITransactionStorage { private AssertionStore searchInDatabase(String artifact) throws MOADatabaseException { MiscUtil.assertNotNull(artifact, "artifact"); Logger.trace("Getting sessioninformation with ID " + artifact + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - List result; + List<AssertionStore> results; - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getAssertionWithArtifact"); - query.setParameter("artifact", artifact); - result = query.list(); + Query query = entityManager.createNamedQuery("getAssertionWithArtifact"); + query.setParameter("artifact", artifact); - //send transaction - session.getTransaction().commit(); - } + results = query.getResultList(); - Logger.trace("Found entries: " + result.size()); + Logger.trace("Found entries: " + results.size()); //Assertion requires an unique artifact - if (result.size() != 1) { + if (results.size() != 1) { Logger.debug("No transaction information with ID:" + artifact + " found."); return null; } - return (AssertionStore) result.get(0); + return results.get(0); } private void put(AssertionStore element, String key, Object value) throws MOADatabaseException { @@ -253,15 +251,23 @@ public class DBTransactionStorage implements ITransactionStorage { element.setAssertion(data); //store AssertionStore element to Database - try { - MOASessionDBUtils.saveOrUpdate(element); + //try { + entityManager.persist(element); + //MOASessionDBUtils.saveOrUpdate(element); Logger.debug(value.getClass().getName() + " with ID: " + key + " is stored in Database"); - - } catch (MOADatabaseException e) { - Logger.warn("Sessioninformation could not be stored."); - throw new MOADatabaseException(e); - - } +// +// } catch (MOADatabaseException e) { +// Logger.warn("Sessioninformation could not be stored."); +// throw new MOADatabaseException(e); +// +// } + + } + + @Override + public void putAssertionStore(Object element) throws MOADatabaseException{ + // TODO Auto-generated method stub + entityManager.merge(element); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java index 493f24ee8..53a7f4f5e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java @@ -48,9 +48,10 @@ public interface ITransactionStorage { * @param key Id which identifiers the data object * @param value Data object which should be stored. * This data must implement the <code>java.io.Serializable</code> interface + * @param timeout_ms Defines the period of time a data object is kept within the storage * @throws MOADatabaseException In case of store operation failed */ - public void put(String key, Object value) throws MOADatabaseException; + public void put(String key, Object value, int timeout_ms) throws MOADatabaseException; /** * Get a data object from transaction storage @@ -110,4 +111,21 @@ public interface ITransactionStorage { */ public List<String> clean(Date now, long dataTimeOut); + + /** + * Get whole AssertionStoreObject, required for SLO + * + * @param key key Id which identifiers the data object + * @return The transaction-data object, or null + * @throws MOADatabaseException In case of load operation failed + */ + public Object getAssertionStore(String key) throws MOADatabaseException; + + /** + * Put whole AssertionStoreObject to db, required for SLO + * + * @param element assertion store object + */ + public void putAssertionStore(Object element) throws MOADatabaseException; + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java new file mode 100644 index 000000000..c17bff358 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/RedisTransactionStorage.java @@ -0,0 +1,377 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.storage; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +import org.apache.commons.lang.SerializationUtils; +import org.hibernate.HibernateException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.dao.DataAccessException; +import org.springframework.data.redis.core.RedisOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.SessionCallback; +import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; +import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +@Service("TransactionStorage") +public class RedisTransactionStorage implements ITransactionStorage { + + @Autowired + private RedisTemplate<String, Object> redisTemplate; + + @Autowired + protected AuthConfiguration authConfig; + + @Autowired + private JacksonJsonRedisSerializer assertionStoreSerializer; + + public RedisTemplate<String, Object> getTemplate(){ + return this.redisTemplate; + } + + public void setTemplate(RedisTemplate<String, Object> t){ + this.redisTemplate = t; + } + + public boolean containsKey(String key) { + try { + searchInDatabase(key); + return true; + + } catch (MOADatabaseException e) { + return false; + } + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.storage.ITransactionStorage#changeKey(java.lang.String, java.lang.String, java.lang.Object) + */ + @Override + public void changeKey(String oldKey, String newKey, Object value) throws MOADatabaseException { + + //search if key already exists + final int expTime = redisTemplate.getExpire(oldKey, TimeUnit.MILLISECONDS).intValue(); + //AssertionStore element = searchInDatabase(oldKey); + if (expTime < 0) { + Logger.info("No transaction-data with oldKey:" + oldKey + + " found. Process gets stopped."); + throw new MOADatabaseException("No transaction-data with oldKey:" + oldKey + + " found. Process gets stopped."); + + } + + //Important: Rename not working here, because the new ID also has to be put into the + //value object. + //redisTemplate.rename(oldKey, newKey); + + final String old_key = oldKey; + + //redisTemplate.delete(oldKey); + //put(null, newKey, value, expTime); + final AssertionStore assertion = prepareAssertion(null, newKey, value); + List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() { + public List<Object> execute(RedisOperations operations) throws DataAccessException { + operations.multi(); + operations.delete(old_key); + operations.opsForValue().set(assertion.getArtifact(), new String(assertionStoreSerializer.serialize(assertion)),expTime,TimeUnit.MILLISECONDS); + // This will contain the results of all ops in the transaction + return operations.exec(); + } + }); + + int a= txResults.size(); + } + + public void put(String key, Object value, int timeoutms) throws MOADatabaseException { + + //search if key already exists + AssertionStore element = searchInDatabase(key); + + //create a new entry if key does not exists already + if (element == null) { + element = new AssertionStore(); + + } + + put(element, key, value, timeoutms); + } + + public <T> T get(String key, + final Class<T> clazz) throws MOADatabaseException { + + try { + return get(key, clazz, -1); + + } catch (AuthenticationException e) { + //this execption only occurs if an additional timeOut is used + Logger.error("This exeption should not occur!!!!", e); + return null; + + } + } + + public Object get(String key) throws MOADatabaseException { + AssertionStore element = searchInDatabase(key); + + if (element == null) + return null; + + return SerializationUtils.deserialize(element.getAssertion()); + + + } + + public <T> T get(String key, final Class<T> clazz, long dataTimeOut) throws MOADatabaseException, AuthenticationException { + + AssertionStore element = searchInDatabase(key); + + if (element == null) + return null; + +// dataTimeOut = -1; +// if (dataTimeOut > -1) { +// //check timeout +// long now = new Date().getTime(); +// +// if (now - element.getDatatime().getTime() > dataTimeOut) { +// Logger.info("Transaction-Data with key: " + key + " is out of time."); +// throw new AuthenticationException("1207", new Object[] { key }); +// +// } +// } + + + //Deserialize Assertion + Object data = SerializationUtils.deserialize(element.getAssertion()); + + //check if assertion has the correct class type + try { + @SuppressWarnings("unchecked") + T test = (T) Class.forName(element.getType()).cast(data); + return test; + + } catch (Exception e) { + Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + key); + throw new MOADatabaseException("Sessioninformation Cast-Exception"); + + } + } + + //NOT USED with REDIS + public List<String> clean(Date now, long dataTimeOut) { + + //redis enables to set TTL when creating new values, so we don't need this function anymore + +// Date expioredate = new Date(now.getTime() - dataTimeOut); +// +// List<AssertionStore> results; + List<String> returnValues = new ArrayList<String>(); +// Session session = MOASessionDBUtils.getCurrentSession(); +// +// synchronized (session) { +// session.beginTransaction(); +// Query query = session.getNamedQuery("getAssertionWithTimeOut"); +// query.setTimestamp("timeout", expioredate); +// results = query.list(); +// session.getTransaction().commit(); +// } +// +// if (results != null) { +// for (AssertionStore el : results) +// returnValues.add(el.getArtifact()); +// +// } + return returnValues; + } + + public void remove(String key) { + + try { + + AssertionStore element = searchInDatabase(key); + if (element == null) { + Logger.debug("Sessioninformation not removed! (Sessioninformation with ID=" + key + + "not found)"); + return; + } + + redisTemplate.delete(key); + //cleanDelete(element); + Logger.debug("Removed stored information with ID: " + key); + + + } catch (MOADatabaseException e) { + Logger.info("Sessioninformation not removed! (Message:"+ e.getMessage() + ")"); + + } catch (HibernateException e) { + Logger.warn("Sessioninformation not removed! (Error during Database communication)", e); + } + } + + //Not used within REDIS store + private void cleanDelete(AssertionStore element) { +// try { +// element.setAssertion("blank".getBytes()); +// MOASessionDBUtils.saveOrUpdate(element); +// +// } catch (MOADatabaseException e) { +// Logger.warn("Blank shortTime session with artifact=" + element.getArtifact() + " FAILED.", e); +// +// } finally { +// if (!MOASessionDBUtils.delete(element)) +// Logger.error("ShortTime session with artifact=" + element.getArtifact() +// + " not removed! (Error during Database communication)"); +// +// } + + } + + //name="getAssertionWithArtifact", query = "select assertionstore from AssertionStore assertionstore where assertionstore.artifact = :artifact"), + //@NamedQuery(name="getAssertionWithTimeOut", query = "select assertionstore from AssertionStore assertionstore where assertionstore.timestamp < :timeout") + + @SuppressWarnings("rawtypes") + private AssertionStore searchInDatabase(String artifact) throws MOADatabaseException { + MiscUtil.assertNotNull(artifact, "artifact"); + Logger.trace("Getting sessioninformation with ID " + artifact + " from database."); + + +// Session session = MOASessionDBUtils.getCurrentSession(); +// List result; +// +// synchronized (session) { +// session.beginTransaction(); +// Query query = session.getNamedQuery("getAssertionWithArtifact"); +// query.setParameter("artifact", artifact); +// result = query.list(); +// +// //send transaction +// session.getTransaction().commit(); +// } + //String id = (String) redisTemplate.opsForSet().pop(artifact); + String assertion = (String) redisTemplate.opsForValue().get(artifact); + //String id = (String) redisTemplate.opsForValue().get(artifact); + if(assertion == null){ + Logger.debug("No transaction information with ID:" + artifact + " found."); + return null; + } + + AssertionStore as = (AssertionStore) assertionStoreSerializer.deserialize(assertion.getBytes()); + //delete the timestamp entry +// String ts = as.getDatatime().toString(); +// redisTemplate.opsForSet().pop(ts); + + if(as == null){ + Logger.debug("No transaction information with ID:" + artifact + " found."); + return null; + } + return as; + + //Assertion requires an unique artifact +// if (result.size() != 1) { +// Logger.debug("No transaction information with ID:" + artifact + " found."); +// +// +// } +// +// return (AssertionStore) result.get(0); + } + + private void put(AssertionStore element, String key, Object value, int timeoutms) throws MOADatabaseException { + + element = prepareAssertion(element, key, value); + + int authDataTimeOut = authConfig.getTransactionTimeOut() * 1000; + + if(timeoutms != -1){ + authDataTimeOut = timeoutms; + } + redisTemplate.opsForValue().set(element.getArtifact(), new String(assertionStoreSerializer.serialize(element)),authDataTimeOut,TimeUnit.MILLISECONDS); + //MOASessionDBUtils.saveOrUpdate(element); + Logger.debug(value.getClass().getName() + " with ID: " + key + " is stored in Database"); + + } + +private AssertionStore prepareAssertion(AssertionStore element, String key, Object value) throws MOADatabaseException { + + if(element == null) + element = new AssertionStore(); + + element.setArtifact(key); + element.setType(value.getClass().getName()); + element.setDatatime(new Date()); + + if (!Serializable.class.isInstance(value)) { + Logger.warn("Transaction-Storage can only store objects which implements the 'Seralizable' interface"); + throw new MOADatabaseException("Transaction-Storage can only store objects which implements the 'Seralizable' interface", null); + } + + //serialize the Assertion for Database storage + byte[] data = SerializationUtils.serialize((Serializable) value); + element.setAssertion(data); + + long id = new Random().nextLong(); + element.setId(id); + + return element; + + } + +@Override +public Object getAssertionStore(String key) throws MOADatabaseException { + return searchInDatabase(key); +} + +@Override +public void putAssertionStore(Object element) throws MOADatabaseException { + // TODO Auto-generated method stub + AssertionStore as = (AssertionStore)element; + final int expTime = redisTemplate.getExpire(as.getArtifact(), TimeUnit.MILLISECONDS).intValue(); + //AssertionStore element = searchInDatabase(oldKey); + if (expTime < 0) { + Logger.info("No transaction-data with oldKey:" + as.getArtifact() + + " found. Process gets stopped."); + throw new MOADatabaseException("No transaction-data with oldKey:" + as.getArtifact() + + " found. Process gets stopped."); + + } + redisTemplate.opsForValue().set(as.getArtifact(), new String(assertionStoreSerializer.serialize(element)),expTime,TimeUnit.MILLISECONDS); + +} + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ECDSAKeyValueConverter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ECDSAKeyValueConverter.java index 2c0a82708..f37ae0b0b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ECDSAKeyValueConverter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ECDSAKeyValueConverter.java @@ -20,48 +20,15 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. ******************************************************************************/ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - package at.gv.egovernment.moa.id.util; -import iaik.security.ecc.ecdsa.ECDSAParameter; -import iaik.security.ecc.ecdsa.ECPublicKey; -import iaik.security.ecc.math.ecgroup.AffineCoordinate; -import iaik.security.ecc.math.ecgroup.Coordinate; -import iaik.security.ecc.math.ecgroup.CoordinateTypes; -import iaik.security.ecc.math.ecgroup.ECGroupFactory; -import iaik.security.ecc.math.ecgroup.ECPoint; -import iaik.security.ecc.math.ecgroup.EllipticCurve; -import iaik.security.ecc.math.field.Field; -import iaik.security.ecc.math.field.FieldElement; -import iaik.security.ecc.math.field.PrimeField; -import iaik.security.ecc.parameter.ECCParameterFactory; -import iaik.security.ecc.spec.ECCParameterSpec; - import java.math.BigInteger; import java.security.PublicKey; +import java.security.spec.ECField; +import java.security.spec.ECFieldF2m; +import java.security.spec.ECFieldFp; +import java.security.spec.ECPoint; import java.util.HashMap; import java.util.Iterator; import java.util.Vector; @@ -72,6 +39,15 @@ import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import at.gv.egovernment.moa.logging.Logger; +import iaik.security.ec.common.ECParameterSpec; +import iaik.security.ec.common.ECPublicKey; +import iaik.security.ec.common.ECStandardizedParameterFactory; +import iaik.security.ec.common.EllipticCurve; +import iaik.security.ec.math.field.Field; +import iaik.security.ec.math.field.FieldElement; +import iaik.security.ec.math.field.PrimeField; + public class ECDSAKeyValueConverter { @@ -94,15 +70,13 @@ public class ECDSAKeyValueConverter if (domainParams == null) throw new Exception("Domain parameters must not be implicit."); Element namedCurve = getChildElement(domainParams, ecdsaNS, "NamedCurve", 1); - ECCParameterSpec eccParameterSpec; + ECParameterSpec eccParameterSpec; if (namedCurve != null) { // URL curveNameURN = new URL(namedCurve.getAttributeNS(null, "URN")); String curveNameOID = namedCurve.getAttributeNS(null, "URN").substring(8); - ECCParameterFactory eccParamFactory = ECCParameterFactory.getInstance(); - // eccParameterSpec = eccParamFactory.getParameterByOID(curveNameURN.getPath().substring(4)); - eccParameterSpec = eccParamFactory.getParameterByOID(curveNameOID); + eccParameterSpec = ECStandardizedParameterFactory.getParametersByOID(curveNameOID); } else { @@ -167,14 +141,21 @@ public class ECDSAKeyValueConverter String cofactorStr = getChildElementText(basePointParams, ecdsaNS, "Cofactor", 1); BigInteger cofactor = (cofactorStr != null) ? new BigInteger(cofactorStr, 10) : null; + BigInteger a = new BigInteger(aStr, 10); + BigInteger b = new BigInteger(bStr, 10); + BigInteger basePointX = new BigInteger(basePointXStr, 10); + BigInteger basePointY = new BigInteger(basePointYStr, 10); + if (fieldParamsType == FIELD_TYPE_PRIME) - { - BigInteger a = new BigInteger(aStr, 10); - BigInteger b = new BigInteger(bStr, 10); - BigInteger basePointX = new BigInteger(basePointXStr, 10); - BigInteger basePointY = new BigInteger(basePointYStr, 10); - eccParameterSpec = new ECCParameterSpec(p, cofactor, order, seed, null, a, b, basePointX, - basePointY, null); + { + ECField javaECField = new ECFieldFp(p); + java.security.spec.EllipticCurve curve = + new java.security.spec.EllipticCurve(javaECField, a, b, seed.toByteArray()); + java.security.spec.ECPoint javaECbasePoint = + new java.security.spec.ECPoint(basePointX, basePointY); + java.security.spec.ECParameterSpec javaECSpec = + new java.security.spec.ECParameterSpec(curve, javaECbasePoint, order, cofactor.intValue()); + eccParameterSpec = ECParameterSpec.getParameterSpec(javaECSpec); } else { @@ -193,9 +174,19 @@ public class ECDSAKeyValueConverter irreducible[k1/32] += 1 << k1 % 32; irreducible[0] += 1; } - eccParameterSpec = new ECCParameterSpec(irreducible, cofactor, order, octetString2IntArray(aStr), - octetString2IntArray(bStr), octetString2IntArray(basePointXStr), - octetString2IntArray(basePointYStr), null); + + ECField javaECField = new ECFieldF2m(m, irreducible); + java.security.spec.EllipticCurve curve = + new java.security.spec.EllipticCurve(javaECField, a, b, seed.toByteArray()); + java.security.spec.ECPoint javaECbasePoint = + new java.security.spec.ECPoint(basePointX, basePointY); + java.security.spec.ECParameterSpec javaECSpec = + new java.security.spec.ECParameterSpec(curve, javaECbasePoint, order, cofactor.intValue()); + eccParameterSpec = ECParameterSpec.getParameterSpec(javaECSpec); + +// eccParameterSpec = new ECCParameterSpec(irreducible, cofactor, order, octetString2IntArray(aStr), +// octetString2IntArray(bStr), octetString2IntArray(basePointXStr), +// octetString2IntArray(basePointYStr), null); } } @@ -206,10 +197,14 @@ public class ECDSAKeyValueConverter Element publicKeyYElem = getChildElement(publicKeyElem, ecdsaNS, "Y", 1); String publicKeyYStr = publicKeyYElem.getAttributeNS(null, "Value"); - ECDSAParameter ecdsaParams = new ECDSAParameter(eccParameterSpec, CoordinateTypes.PROJECTIVE_COORDINATES); - ECGroupFactory ecGroupFactory = ECGroupFactory.getInstance(); - EllipticCurve eCurve = ecGroupFactory.getCurve(eccParameterSpec.getA(), - eccParameterSpec.getB(), eccParameterSpec.getR(), CoordinateTypes.PROJECTIVE_COORDINATES); + //ECParameterSpec ecdsaParams = new ECParameterSpec(eccParameterSpec, CoordinateTypes.PROJECTIVE_COORDINATES); + //ECGroupFactory ecGroupFactory = ECGroupFactory.getInstance(); + + EllipticCurve eCurve = eccParameterSpec.getCurve(); + +// EllipticCurve eCurve = ecGroupFactory.getCurve(eccParameterSpec.getA(), +// eccParameterSpec.getB(), eccParameterSpec.getR(), CoordinateTypes.PROJECTIVE_COORDINATES); + Field field = eCurve.getField(); // Detect type of public key field elements @@ -239,10 +234,19 @@ public class ECDSAKeyValueConverter } // ProjectiveCoordinate publicKeyPointCoordinate = new ProjectiveCoordinate(publicKeyPointX, // publicKeyPointY, field.getONEelement()); - Coordinate publicKeyPointCoordinate = new AffineCoordinate(publicKeyPointX, - publicKeyPointY).toProjective(); - ECPoint publicKeyPoint = eCurve.newPoint(publicKeyPointCoordinate); - ECPublicKey publicKey = new ECPublicKey(ecdsaParams, publicKeyPoint); +// Coordinate publicKeyPointCoordinate = new AffineCoordinate(publicKeyPointX, +// publicKeyPointY).toProjective(); + + ECPoint publicKeyPointECPoint = new ECPoint(publicKeyPointX.toBigInteger(), + publicKeyPointY.toBigInteger()); + + if (!eCurve.containsPoint(publicKeyPointECPoint)) { + Logger.error("IDL ECC parameter extraction FAILED! Public-Key ECPoint is not on the curve!"); + throw new Exception("IDL ECC parameter extraction FAILED! Public-Key ECPoint is not on the curve!"); + + } + + ECPublicKey publicKey = new ECPublicKey(eccParameterSpec, publicKeyPointECPoint); return publicKey; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/SSLUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/SSLUtils.java index f0cec1d61..caf7f570f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/SSLUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/SSLUtils.java @@ -46,9 +46,6 @@ package at.gv.egovernment.moa.id.util; -import iaik.pki.PKIException; -import iaik.security.provider.IAIK; - import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; @@ -57,7 +54,6 @@ import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.security.GeneralSecurityException; -import java.security.Security; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSocketFactory; @@ -71,6 +67,7 @@ import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.commons.utils.ssl.SSLConfigurationException; import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import iaik.pki.PKIException; /** @@ -86,7 +83,7 @@ public class SSLUtils { public static void initialize() { // JSSE Abhängigkeit //Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); - Security.addProvider(new IAIK()); + //Security.addProvider(new IAIK()); //System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol"); @@ -126,8 +123,7 @@ public class SSLUtils { //INFO: MOA-ID 2.x always use defaultChainingMode try { - SSLSocketFactory ssf = - at.gv.egovernment.moa.id.commons.utils.ssl.SSLUtils.getSSLSocketFactory( + SSLSocketFactory ssf = at.gv.egovernment.moa.id.commons.utils.ssl.SSLUtils.getSSLSocketFactory( connParam.getUrl(), conf.getCertstoreDirectory(), trustStoreURL, diff --git a/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml b/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml index 11d92cea3..ba8c47304 100644 --- a/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml +++ b/id/server/idserverlib/src/main/resources/moaid.authentication.beans.xml @@ -4,10 +4,17 @@ xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" + xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd - http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd + http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd"> + + <task:annotation-driven executor="MOA-ID-Auth_TaskExecutor" scheduler="MOA-ID-Auth_Scheduler"/> + <task:executor id="MOA-ID-Auth_TaskExecutor" pool-size="5"/> + <task:scheduler id="MOA-ID-Auth_Scheduler" pool-size="10"/> <bean id="processEngine" class="at.gv.egovernment.moa.id.process.ProcessEngineImpl"> <property name="transitionConditionExpressionEvaluator"> @@ -35,8 +42,7 @@ <bean id="MOAID_SSOManager" class="at.gv.egovernment.moa.id.moduls.SSOManager"/> - <bean id="TransactionStorage" - class="at.gv.egovernment.moa.id.storage.DBTransactionStorage"/> + <bean id="AuthenticationSessionStoreage" class="at.gv.egovernment.moa.id.storage.DBAuthenticationSessionStoreage"/> @@ -47,14 +53,20 @@ <bean id="ProcessInstanceStoreage" class="at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAOImpl"/> - <bean id="StatisticLogger" - class="at.gv.egovernment.moa.id.advancedlogging.StatisticLogger"/> - <bean id="MOAReversionLogger" class="at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger"/> <bean id="AuthenticationSessionCleaner" - class="at.gv.egovernment.moa.id.auth.AuthenticationSessionCleaner"/> + class="at.gv.egovernment.moa.id.auth.AuthenticationSessionCleaner"/> + + <bean id="MOAGarbageCollector" + class="at.gv.egovernment.moa.id.auth.MOAGarbageCollector"/> + +<!-- <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> + <property name="corePoolSize" value="5" /> + <property name="maxPoolSize" value="10" /> + <property name="queueCapacity" value="25" /> + </bean> --> <!-- Authentication Process Tasks --> <bean id="GenerateBKUSelectionFrameTask" @@ -79,6 +91,18 @@ <bean id="EvaluateSSOConsentsTaskImpl" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.EvaluateSSOConsentsTaskImpl" - scope="prototype"/> + scope="prototype"/> -</beans>
\ No newline at end of file + <beans profile="advancedLogOn"> + <bean id="StatisticLogger" + class="at.gv.egovernment.moa.id.advancedlogging.StatisticLogger"/> + </beans> + + <beans profile="advancedLogOff"> + <bean id="StatisticLogger" + class="at.gv.egovernment.moa.id.advancedlogging.DummyStatisticLogger"/> + </beans> + +</beans> + + diff --git a/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties b/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties index 400b0bc25..36f1392d5 100644 --- a/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties +++ b/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties @@ -113,9 +113,9 @@ service.00=Fehler beim Aufruf des Web Service: {0} service.01=Fehler beim Aufruf des Web Service: kein Endpoint
service.02=Fehler beim Aufruf des Web Service, Status {0}: {1}
service.03=Fehler beim Aufruf des SPSS-API: {0}
-service.04=Das Online-Vollmachten Service ist unter {0} nicht erreichbar.
+service.04=Das Online-Vollmachten Service ist unter {0} nicht erreichbar. Ursache:{1}
service.05=Fehler beim Anfragen des Online-Vollmachen Service: {0} / {1}
-service.06=Allgemeiner Fehler beim Anfragen des Online-Vollmachten Service
+service.06=Allgemeiner Fehler beim Anfragen des Online-Vollmachten Service. Ursache:{0}
service.07=Der SZR-Gateway ist unter {0} nicht erreichbar.
service.08=Die Eintragung der ausländischen Person am SZR-Gateway ist fehlgeschlagen.
service.09=Der SZR-Gateway Client konnte nicht initialisiert werden.
@@ -258,7 +258,7 @@ stork.29=Fehler bei der Generierung von STORK-Attribut (eIdentifier/eLPIdentifie eIDAS.00=eIDAS Engine initialization FAILED. Reason:{0}
eIDAS.01=Received eIDAS AuthnRequest is not valid. Reason:{0}
-eIDAS.02=Generate eIDAS AuthnRequest FAILED. Reason:{0}
+eIDAS.02=Generation of eIDAS AuthnRequest FAILED. Reason:{0}
eIDAS.03=Can not connect to eIDAS Node. Reason:No CitizenCountry selected.
eIDAS.04=Can not connect to eIDAS Node. Reason:{0} is not a valid CitizenCountry.
eIDAS.05=Can not generate eIDAS metadata. Reason:{0}
@@ -267,7 +267,10 @@ eIDAS.07=Missing eIDAS-Attribute:{0} eIDAS.08=No valid eIDAs-Node configuration for enityID:{0}
eIDAS.09=Received eIDAS Response is not valid. Reason:{0}
eIDAS.10=Internal server error. Reason:{0}
-eIDAS.11=Received eIDAS Error-Response. Reason:{0}
+eIDAS.11=Received eIDAS Error-Response. Reason:{0}
+eIDAS.12=Received eIDAS AuthnRequest is not valid. Reason:{0}
+eIDAS.13=Generation of eIDAS Response FAILED. Reason:{0}
+eIDAS.14=eIDAS Response validation FAILED: LevelOfAssurance {0} is to low.
pvp2.01=Fehler beim kodieren der PVP2 Antwort
pvp2.02=Ungueltiges Datumsformat
diff --git a/id/server/idserverlib/src/main/resources/resources/properties/protocol_response_statuscodes_de.properties b/id/server/idserverlib/src/main/resources/resources/properties/protocol_response_statuscodes_de.properties index bfaf5ffb1..e72a28046 100644 --- a/id/server/idserverlib/src/main/resources/resources/properties/protocol_response_statuscodes_de.properties +++ b/id/server/idserverlib/src/main/resources/resources/properties/protocol_response_statuscodes_de.properties @@ -225,6 +225,9 @@ eIDAS.08=1304 eIDAS.09=1301 eIDAS.10=9199 eIDAS.11=1302 +eIDAS.12=1305 +eIDAS.13=1307 +eIDAS.14=1301 pvp2.01=6100 pvp2.06=6100 diff --git a/id/server/idserverlib/src/main/resources/session.common.beans.xml b/id/server/idserverlib/src/main/resources/session.common.beans.xml new file mode 100644 index 000000000..defa47ec0 --- /dev/null +++ b/id/server/idserverlib/src/main/resources/session.common.beans.xml @@ -0,0 +1,74 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans + xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + <context:property-placeholder location="${moa.id.configuration}"/> + <context:annotation-config/> + + <bean id="sessionDataSource" class="org.apache.commons.dbcp2.BasicDataSource" lazy-init="true" destroy-method="close"> + <aop:scoped-proxy/> + <property name="driverClassName" value="${moasession.hibernate.connection.driver_class}" /> + <property name="url" value="${moasession.hibernate.connection.url}"/> + <property name="username" value="${moasession.hibernate.connection.username}" /> + <property name="password" value="${moasession.hibernate.connection.password}" /> + + <property name="connectionProperties" value="${moasession.dbcp.connectionProperties}" /> + <property name="initialSize" value="${moasession.dbcp.initialSize}" /> + <property name="maxTotal" value="${moasession.dbcp.maxActive}" /> + <property name="maxIdle" value="${moasession.dbcp.maxIdle}" /> + <property name="minIdle" value="${moasession.dbcp.minIdle}" /> + <!-- property name="maxWait" value="${moasession.dbcp.maxWaitMillis}" / --> + <property name="testOnBorrow" value="${moasession.dbcp.testOnBorrow}" /> + <property name="testOnReturn" value="${moasession.dbcp.testOnReturn}" /> + <property name="testWhileIdle" value="${moasession.dbcp.testWhileIdle}" /> + <property name="validationQuery" value="${moasession.dbcp.validationQuery}" /> + </bean> + + <bean id="sessionSessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> + <property name="dataSource" ref="sessionDataSource"/> + <property name="packagesToScan" value="at.gv.egovernment.moa.id.commons.db.dao.session" /> + <property name="hibernateProperties"> + <props> + <prop key="hibernate.dialect">${moasession.hibernate.dialect}</prop> + <prop key="hibernate.show_sql">${moasession.hibernate.show_sql}</prop> + <prop key="hibernate.hbm2ddl.auto">${moasession.hibernate.hbm2ddl.auto}</prop> + <prop key="current_session_context_class">${moasession.hibernate.current_session_context_class}</prop> + <prop key="hibernate.transaction.flush_before_completion">${moasession.hibernate.transaction.flush_before_completion}</prop> + <prop key="hibernate.transaction.auto_close_session">${moasession.hibernate.transaction.auto_close_session}</prop> + </props> + </property> + </bean> + + <!-- MYSQL Conector --> + <tx:annotation-driven transaction-manager="sessionTransactionManager"/> + + <bean id="sessionJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> + <property name="showSql" value="${moasession.hibernate.show_sql}" /> + <property name="generateDdl" value="${moasession.jpaVendorAdapter.generateDdl}" /> + <property name="databasePlatform" value="${moasession.hibernate.dialect}" /> + </bean> + + <bean name="session" id="session" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" depends-on="sessionDataSource"> + <property name="dataSource" ref="sessionDataSource" /> + <property name="jpaVendorAdapter" ref="sessionJpaVendorAdapter" /> + <property name="packagesToScan" value="at.gv.egovernment.moa.id.commons.db.dao.session" /> + <property name="persistenceUnitName" value="session" /> + </bean> + + <bean name="sessionTransactionManager" id="sessionTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> + <property name="entityManagerFactory" ref="session" /> + </bean> + + <bean id="moaSessionDBUtils" class="at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils"> + </bean> + +</beans>
\ No newline at end of file diff --git a/id/server/idserverlib/src/main/resources/session.db.beans.xml b/id/server/idserverlib/src/main/resources/session.db.beans.xml new file mode 100644 index 000000000..5ed390ffe --- /dev/null +++ b/id/server/idserverlib/src/main/resources/session.db.beans.xml @@ -0,0 +1,20 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans profile="dbBackend" + xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + <context:property-placeholder location="${moa.id.configuration}"/> + + <bean id="TransactionStorage" + class="at.gv.egovernment.moa.id.storage.DBTransactionStorage" + /> + +</beans>
\ No newline at end of file diff --git a/id/server/idserverlib/src/main/resources/session.redis.beans.xml b/id/server/idserverlib/src/main/resources/session.redis.beans.xml new file mode 100644 index 000000000..feda9b273 --- /dev/null +++ b/id/server/idserverlib/src/main/resources/session.redis.beans.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans profile="redisBackend" + xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + <context:property-placeholder location="${moa.id.configuration}"/> + + <bean id="TransactionStorage" + class="at.gv.egovernment.moa.id.storage.RedisTransactionStorage"/> + + <!-- Redis Beans --> + <bean id="jedisConnFactory" + class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" + p:use-pool="${redis.use-pool}" + p:host-name="${redis.host-name}" + p:port="${redis.port}"/> + + <bean id="RedisStringSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /> + <bean id="assertionStoreSerializer" class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer"> + <constructor-arg type="java.lang.Class" value="at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore"/> + </bean> + + <bean id="redisTemplate" + class="org.springframework.data.redis.core.RedisTemplate" + p:connection-factory-ref="jedisConnFactory" + p:value-serializer-ref="RedisStringSerializer" + p:key-serializer-ref="RedisStringSerializer"/> + +</beans>
\ No newline at end of file diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/module/test/TestRequestImpl.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/module/test/TestRequestImpl.java index 66dffe311..0b5128c8b 100644 --- a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/module/test/TestRequestImpl.java +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/module/test/TestRequestImpl.java @@ -24,6 +24,8 @@ package at.gv.egovernment.moa.id.module.test; import java.util.Collection; +import org.opensaml.saml2.metadata.provider.MetadataProvider; + import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.commons.api.IRequest; import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; @@ -254,7 +256,7 @@ public class TestRequestImpl implements IRequest { * @see at.gv.egovernment.moa.id.moduls.IRequest#getRequestedAttributes() */ @Override - public Collection<String> getRequestedAttributes() { + public Collection<String> getRequestedAttributes(MetadataProvider metadataProvider) { // TODO Auto-generated method stub return null; } diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java new file mode 100644 index 000000000..ab08c0f5c --- /dev/null +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/DummyTransactionStorage.java @@ -0,0 +1,147 @@ +package at.gv.egovernment.moa.id.process.spring.test; + +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import javax.sql.DataSource; + +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; +import at.gv.egovernment.moa.logging.Logger; + +/** + * Dummy DataSource implementation for convenience in test cases where a + * database connection will never actually be acquired. + * + * @see DataSource + * @author Chris Beams + */ +public class DummyTransactionStorage implements ITransactionStorage { + + public class DummyDBEntry{ + public DummyDBEntry(String key, Object value){ + this.obj =value; + this.key = key; + } + public String getKey() { + return key; + } + public void setKey(String key) { + this.key = key; + } + public Object getObj() { + return obj; + } + public void setObj(Object obj) { + this.obj = obj; + } + private String key; + private Object obj; + } + + private ArrayList<DummyDBEntry> ds = new ArrayList<DummyDBEntry>(); + + + + @Override + public boolean containsKey(String key) { + // TODO Auto-generated method stub + Iterator<DummyDBEntry> it = ds.iterator(); + while(it.hasNext()){ + DummyDBEntry t = it.next(); + if(t.getKey().equals(key)) + return true; + } + return false; + } + + @Override + public void put(String key, Object value, int timeout_ms) + throws MOADatabaseException { + // TODO Auto-generated method stub + this.remove(key); + this.ds.add(new DummyDBEntry(key, value)); + + } + + @Override + public Object get(String key) throws MOADatabaseException { + // TODO Auto-generated method stub + Iterator<DummyDBEntry> it = ds.iterator(); + while(it.hasNext()){ + DummyDBEntry t = it.next(); + if(t.getKey().equals(key)) + return t; + } + return null; + } + + @Override + public <T> T get(String key, Class<T> clazz) throws MOADatabaseException { + + DummyDBEntry o = (DummyDBEntry) get(key); + if(o == null) + return null; + try { + @SuppressWarnings("unchecked") + T test = (T) (clazz.cast(o.getObj())); + return test; + + } catch (Exception e) { + Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + key); + throw new MOADatabaseException("Sessioninformation Cast-Exception"); + + } + } + + @Override + public <T> T get(String key, Class<T> clazz, long dataTimeOut) + throws MOADatabaseException, AuthenticationException { + // TODO Auto-generated method stub + return get(key,clazz); + } + + @Override + public void changeKey(String oldKey, String newKey, Object value) + throws MOADatabaseException { + this.remove(oldKey); + this.put(newKey, value, -1); + + } + + @Override + public void remove(String key) { + Iterator<DummyDBEntry> it = ds.iterator(); + while(it.hasNext()){ + DummyDBEntry t = it.next(); + if(t.getKey().equals(key)){ + this.ds.remove(t); + return; + } + } + + } + + @Override + public List<String> clean(Date now, long dataTimeOut) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Object getAssertionStore(String key) throws MOADatabaseException { + // TODO Auto-generated method stub + return null; + } + + @Override + public void putAssertionStore(Object element) throws MOADatabaseException { + // TODO Auto-generated method stub + + } + + +}
\ No newline at end of file diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest.java index 2cb2a3278..b308e2fa8 100644 --- a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest.java +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest.java @@ -78,7 +78,7 @@ public class SpringExpressionAwareProcessEngineTest { config.addProperties(props); //config.addAnnotatedClass(ProcessInstanceStore.class); config.addAnnotatedClass(AssertionStore.class); - MOASessionDBUtils.initHibernate(config, props); + //MOASessionDBUtils.initHibernate(config, props); } catch (Exception e) { e.printStackTrace(); } diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/test/ProcessEngineTest.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/test/ProcessEngineTest.java index a7e351e25..197627a66 100644 --- a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/test/ProcessEngineTest.java +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/process/test/ProcessEngineTest.java @@ -73,7 +73,7 @@ public class ProcessEngineTest { config.addProperties(props); //config.addAnnotatedClass(ProcessInstanceStore.class); config.addAnnotatedClass(AssertionStore.class); - MOASessionDBUtils.initHibernate(config, props); + //MOASessionDBUtils.initHibernate(config, props); } catch (Exception e) { e.printStackTrace(); } diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/DBTransactionStorageTest.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/DBTransactionStorageTest.java new file mode 100644 index 000000000..4b7f61ef5 --- /dev/null +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/DBTransactionStorageTest.java @@ -0,0 +1,122 @@ +package at.gv.egovernment.moa.id.storage.test; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.DBTransactionStorage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; +import at.gv.egovernment.moa.util.Constants; +import at.gv.util.DOMUtils; + +public class DBTransactionStorageTest { + + public static void main (String[] args) throws SAXException, IOException, ParserConfigurationException, MOADatabaseException{ + DBTransactionStorageTest t = new DBTransactionStorageTest(); + t.test(); + } + + @Autowired + DBTransactionStorage rts; + + public DBTransactionStorageTest(){ + + } + + + public void test() throws SAXException, IOException, ParserConfigurationException, MOADatabaseException{ + + + ApplicationContext context = new FileSystemXmlApplicationContext("src/test/java/testBeans.xml"); + + + String requestString = + "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + + "<samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" RequestID=\"123456\" MajorVersion=\"1\" MinorVersion=\"0\" IssueInstant=\"2003-02-13T13:59:00\">" + + "<samlp:AssertionArtifact>WRONGARTIFACT</samlp:AssertionArtifact>" + + "</samlp:Request>"; + Element request = DOMUtils.parseDocument(requestString, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + + ITransactionStorage rts = (ITransactionStorage) context.getBean("DBTransactionStorage"); + //GenericToStringSerializer redisStringSerializer = (GenericToStringSerializer) context.getBean("valueObjectSerializer"); + + // rts.getTemplate().setValueSerializer(new GenericToStringSerializer<Object>(Object.class)); + // rts.getTemplate().setHashValueSerializer(new GenericToStringSerializer<Object>(Object.class)); + + int cnt = 10; + int averageCnt = 10; + long putTime = 0, getTime = 0, changeTime = 0, removeTime = 0; + long total = 0; + for(int a=0;a<averageCnt;a++){ + long totalPerRound = 0; + + System.out.println("Starting MySql store operation."); + long start = System.currentTimeMillis(); + for(int i=0; i<cnt;i++) + rts.put("test"+i, request,-1); + long end = System.currentTimeMillis(); + putTime += end-start; + System.out.println("MySql store operation done in "+(end-start)+" ms."); + totalPerRound+=(end-start); + + Element test; + System.out.println("Starting MySql get operation."); + start = System.currentTimeMillis(); + for(int i=0; i<cnt;i++) + test = (Element)rts.get("test"+i); + end = System.currentTimeMillis(); + getTime += end-start; + System.out.println("MySql get operation done in "+(end-start)+" ms."); + totalPerRound+=(end-start); + //Element test = (Element)rts.get("test0"); + //System.out.println("Read Element from Redis Store: "+test.getTextContent()); + + String requestString2 = + "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + + "<samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" RequestID=\"test_new\" MajorVersion=\"1\" MinorVersion=\"0\" IssueInstant=\"2003-02-13T13:59:00\">" + + "<samlp:AssertionArtifact>WRONGARTIFACT</samlp:AssertionArtifact>" + + "</samlp:Request>"; + Element request2 = DOMUtils.parseDocument(requestString2, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + + System.out.println("Starting MySql change operation."); + start = System.currentTimeMillis(); + for(int i=0; i<cnt;i++) + rts.changeKey("test"+i, "test_new"+i, request2); + end = System.currentTimeMillis(); + changeTime += end-start; + System.out.println("MySql change operation done in "+(end-start)+" ms."); + totalPerRound+=(end-start); + + + + System.out.println("Starting MySql remove operation."); + start = System.currentTimeMillis(); + for(int i=0; i<cnt;i++) + rts.remove("test_new"+i); + end = System.currentTimeMillis(); + removeTime += end-start; + System.out.println("MySql remove operation done in "+(end-start)+" ms."); + totalPerRound+=(end-start); + total+=totalPerRound; + + System.out.println("Redis Total Time in this round: "+totalPerRound+" ms."); + System.out.println("______________________________________________________"); + } + System.out.println("______________________________________________________"); + System.out.println("Redis average get time over " + averageCnt +" rounds: "+getTime/averageCnt+" ms."); + System.out.println("Redis average put time over " + averageCnt +" rounds: "+putTime/averageCnt+" ms."); + System.out.println("Redis average change time over " + averageCnt +" rounds: "+changeTime/averageCnt+" ms."); + System.out.println("Redis average remove time over " + averageCnt +" rounds: "+removeTime/averageCnt+" ms."); + System.out.println("Redis average total time over " + averageCnt +" rounds: "+total/averageCnt+" ms."); + ((ConfigurableApplicationContext)context).close(); + } + +} diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionMultiThreadTest.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionMultiThreadTest.java new file mode 100644 index 000000000..60b55f497 --- /dev/null +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionMultiThreadTest.java @@ -0,0 +1,130 @@ +package at.gv.egovernment.moa.id.storage.test; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.springframework.core.task.TaskExecutor; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.RedisTransactionStorage; +import at.gv.egovernment.moa.util.Constants; +import at.gv.util.DOMUtils; + +public class RedisTransactionMultiThreadTest { + + private ApplicationContext context; + + public RedisTransactionMultiThreadTest() throws SAXException, IOException, ParserConfigurationException, MOADatabaseException{ + this.context = new FileSystemXmlApplicationContext("src/test/java/testBeans.xml"); + TaskExecutor te = (TaskExecutor) context.getBean("taskExecutor"); + + for(int i=0;i<50;i++){ + te.execute(new RedisTask("Task"+i)); + } + + + } + + public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, MOADatabaseException{ + + RedisTransactionMultiThreadTest t = new RedisTransactionMultiThreadTest(); + System.out.println("End"); + +// String requestString = +// "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + +// "<samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" RequestID=\"123456\" MajorVersion=\"1\" MinorVersion=\"0\" IssueInstant=\"2003-02-13T13:59:00\">" + +// "<samlp:AssertionArtifact>WRONGARTIFACT</samlp:AssertionArtifact>" + +// "</samlp:Request>"; +// Element request = DOMUtils.parseDocument(requestString, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); +// +// +// +// +// RedisTransactionStorage rts = (RedisTransactionStorage) context.getBean("TransactionStorage"); +// //GenericToStringSerializer redisStringSerializer = (GenericToStringSerializer) context.getBean("valueObjectSerializer"); +// +//// rts.getTemplate().setValueSerializer(new GenericToStringSerializer<Object>(Object.class)); +//// rts.getTemplate().setHashValueSerializer(new GenericToStringSerializer<Object>(Object.class)); +// +// +// rts.put("test", request,-1); +// System.out.println("Redis store operation done!"); +// +// Element test = (Element)rts.get("test"); +// System.out.println("Read Element from Redis Store: "+test.getTextContent()); +// +// String requestString2 = +// "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + +// "<samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" RequestID=\"test_new\" MajorVersion=\"1\" MinorVersion=\"0\" IssueInstant=\"2003-02-13T13:59:00\">" + +// "<samlp:AssertionArtifact>WRONGARTIFACT</samlp:AssertionArtifact>" + +// "</samlp:Request>"; +// Element request2 = DOMUtils.parseDocument(requestString2, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); +// +// +// rts.changeKey("test", "test_new", request2); +// +// rts.remove("test"); +// rts.remove("test_new"); +// +// ((ConfigurableApplicationContext)context).close(); + } + + private class RedisTask implements Runnable { + + private String message; + + public RedisTask(String message) throws SAXException, IOException, ParserConfigurationException, MOADatabaseException { + + this.message = message; + + + + } + + public void run() { + String requestString = + "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + + "<samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" RequestID=\"123456\" MajorVersion=\"1\" MinorVersion=\"0\" IssueInstant=\"2003-02-13T13:59:00\">" + + "<samlp:AssertionArtifact>WRONGARTIFACT</samlp:AssertionArtifact>" + + "</samlp:Request>"; + + Element request = null; + try { + request = DOMUtils.parseDocument(requestString, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + } catch (SAXException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return; + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return; + } catch (ParserConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return; + } + + RedisTransactionStorage rts = (RedisTransactionStorage) context.getBean("RedisTransactionStorage"); + + try { + rts.put(message, request,-1); + rts.changeKey(message, message+"n", request); + } catch (MOADatabaseException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + return; + } + System.out.println("Done with task "+message); + } + + } + +} diff --git a/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionStorageTest.java b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionStorageTest.java new file mode 100644 index 000000000..e957ffe05 --- /dev/null +++ b/id/server/idserverlib/src/test/java/at/gv/egovernment/moa/id/storage/test/RedisTransactionStorageTest.java @@ -0,0 +1,116 @@ +package at.gv.egovernment.moa.id.storage.test; + +import java.io.IOException; + +import javax.xml.parsers.ParserConfigurationException; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.DBTransactionStorage; +import at.gv.egovernment.moa.id.storage.RedisTransactionStorage; +import at.gv.egovernment.moa.util.Constants; +import at.gv.util.DOMUtils; + +public class RedisTransactionStorageTest { + + + public RedisTransactionStorageTest(){ + + } + + public static void main(String[] args) throws SAXException, IOException, ParserConfigurationException, MOADatabaseException{ + + + ApplicationContext context = new FileSystemXmlApplicationContext("src/test/java/testBeans.xml"); + + + String requestString = + "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + + "<samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" RequestID=\"123456\" MajorVersion=\"1\" MinorVersion=\"0\" IssueInstant=\"2003-02-13T13:59:00\">" + + "<samlp:AssertionArtifact>WRONGARTIFACT</samlp:AssertionArtifact>" + + "</samlp:Request>"; + Element request = DOMUtils.parseDocument(requestString, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + + RedisTransactionStorage rts = (RedisTransactionStorage) context.getBean("RedisTransactionStorage"); + //GenericToStringSerializer redisStringSerializer = (GenericToStringSerializer) context.getBean("valueObjectSerializer"); + + // rts.getTemplate().setValueSerializer(new GenericToStringSerializer<Object>(Object.class)); + // rts.getTemplate().setHashValueSerializer(new GenericToStringSerializer<Object>(Object.class)); + + int cnt = 100; + int averageCnt = 10; + long putTime = 0, getTime = 0, changeTime = 0, removeTime = 0; + long total = 0; + for(int a=0;a<averageCnt;a++){ + long totalPerRound = 0; + + System.out.println("Starting Redis store operation."); + long start = System.currentTimeMillis(); + for(int i=0; i<cnt;i++) + rts.put("test"+i, request,-1); + long end = System.currentTimeMillis(); + putTime += end-start; + System.out.println("Redis store operation done in "+(end-start)+" ms."); + totalPerRound+=(end-start); + + Element test; + System.out.println("Starting Redis get operation."); + start = System.currentTimeMillis(); + for(int i=0; i<cnt;i++) + test = (Element)rts.get("test"+i); + end = System.currentTimeMillis(); + getTime += end-start; + System.out.println("Redis get operation done in "+(end-start)+" ms."); + totalPerRound+=(end-start); + //Element test = (Element)rts.get("test0"); + //System.out.println("Read Element from Redis Store: "+test.getTextContent()); + + String requestString2 = + "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + + "<samlp:Request xmlns:samlp=\"urn:oasis:names:tc:SAML:1.0:protocol\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\" RequestID=\"test_new\" MajorVersion=\"1\" MinorVersion=\"0\" IssueInstant=\"2003-02-13T13:59:00\">" + + "<samlp:AssertionArtifact>WRONGARTIFACT</samlp:AssertionArtifact>" + + "</samlp:Request>"; + Element request2 = DOMUtils.parseDocument(requestString2, false, Constants.ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); + + System.out.println("Starting Redis change operation."); + start = System.currentTimeMillis(); + for(int i=0; i<cnt;i++) + rts.changeKey("test"+i, "test_new"+i, request2); + end = System.currentTimeMillis(); + changeTime += end-start; + System.out.println("Redis change operation done in "+(end-start)+" ms."); + totalPerRound+=(end-start); + + + + System.out.println("Starting Redis remove operation."); + start = System.currentTimeMillis(); + for(int i=0; i<cnt;i++) + rts.remove("test_new"+i); + end = System.currentTimeMillis(); + removeTime += end-start; + System.out.println("Redis remove operation done in "+(end-start)+" ms."); + totalPerRound+=(end-start); + total+=totalPerRound; + + System.out.println("Redis Total Time in this round: "+totalPerRound+" ms."); + System.out.println("______________________________________________________"); + } + System.out.println("______________________________________________________"); + System.out.println("Redis average get time over " + averageCnt +" rounds: "+getTime/averageCnt+" ms."); + System.out.println("Redis average put time over " + averageCnt +" rounds: "+putTime/averageCnt+" ms."); + System.out.println("Redis average change time over " + averageCnt +" rounds: "+changeTime/averageCnt+" ms."); + System.out.println("Redis average remove time over " + averageCnt +" rounds: "+removeTime/averageCnt+" ms."); + System.out.println("Redis average total time over " + averageCnt +" rounds: "+total/averageCnt+" ms."); + + ((ConfigurableApplicationContext)context).close(); + + + } + +} diff --git a/id/server/idserverlib/src/test/java/test/tlenz/simpletest.java b/id/server/idserverlib/src/test/java/test/tlenz/simpletest.java index 2c80b7ffd..05cd74ed2 100644 --- a/id/server/idserverlib/src/test/java/test/tlenz/simpletest.java +++ b/id/server/idserverlib/src/test/java/test/tlenz/simpletest.java @@ -1,23 +1,23 @@ package test.tlenz; -import java.io.File; import java.io.FileInputStream; -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.net.URI; -import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.List; -import org.w3c.dom.Element; +import org.apache.commons.io.IOUtils; +import org.w3c.dom.NodeList; -import iaik.asn1.structures.Name; -import iaik.utils.RFC2253NameParser; -import iaik.utils.RFC2253NameParserException; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; -import at.gv.egovernment.moa.id.data.AuthenticationRole; -import at.gv.egovernment.moa.id.data.AuthenticationRoleFactory; -import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; -import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.egovernment.moa.spss.api.SPSSFactory; +import at.gv.egovernment.moa.spss.api.SignatureVerificationService; +import at.gv.egovernment.moa.spss.api.common.Content; +import at.gv.egovernment.moa.spss.api.common.ContentBinary; +import at.gv.egovernment.moa.spss.api.common.ContentXML; +import at.gv.egovernment.moa.spss.api.common.InputData; +import at.gv.egovernment.moa.spss.api.common.SignerInfo; +import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureInfo; +import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation; +import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; +import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; /******************************************************************************* * Copyright 2014 Federal Chancellery Austria @@ -62,71 +62,130 @@ import at.gv.egovernment.moa.util.DOMUtils; public class simpletest { // public static void main(String[] args) { - - URI fileURI = null; - try { - fileURI = new URI("file:c:/moa3/tomcat8/conf/moa-id/moa-id.properties"); - File propertiesFile = new File(fileURI); + try { + FileInputStream sigDocFIS = null; + sigDocFIS = new FileInputStream("D:/idl_test/identity_link.xml"); - InputStream in = new FileInputStream(propertiesFile); - ObjectInputStream testOIS = new ObjectInputStream(in); + SPSSFactory spssFac = SPSSFactory.getInstance(); + SignatureVerificationService sigVerifyService = SignatureVerificationService.getInstance(); + Content sigDocContent = spssFac.createContent(sigDocFIS, null); + + + // Position der zu pruefenden Signatur + HashMap nSMap = new HashMap(); + nSMap.put("dsig", "http://www.w3.org/2000/09/xmldsig#"); + VerifySignatureLocation sigLocation = spssFac.createVerifySignatureLocation("//dsig:Signature", nSMap); + + // Pruefrequest zusammenstellen + VerifySignatureInfo sigInfo = spssFac.createVerifySignatureInfo(sigDocContent, sigLocation); + VerifyXMLSignatureRequest verifyRequest = spssFac.createVerifyXMLSignatureRequest( + null, // Verwende aktuelle Zeit als Pruefzeit + sigInfo, + null, // Keine Ergaenzungsobjekte + null, // Signaturmanifest-Pruefung soll nicht durchgefuehrt werden + true, // Hash-Inputdaten, d.h. tatsaechlich signierte Daten werden nicht zurueckgeliefert + "MOAIDBuergerkarteAuthentisierungsDaten"); + + + VerifyXMLSignatureResponse verifyResponse = null; + verifyResponse = sigVerifyService.verifyXMLSignature(verifyRequest); + + SignerInfo signerInfo = verifyResponse.getSignerInfo(); + String signerCertificateEncoded = null; + + List hashInputDatas = verifyResponse.getHashInputDatas(); + if (hashInputDatas != null && !hashInputDatas.isEmpty()) { + for (Object el : hashInputDatas) { + InputData inputData = (InputData) el; + switch (inputData.getContentType()) { + case Content.XML_CONTENT : + ContentXML contentXml = (ContentXML) inputData; + NodeList input_XML = contentXml.getXMLContent(); + + break; + case Content.BINARY_CONTENT : + ContentBinary contentBinary = (ContentBinary) inputData; + String input_Binary = IOUtils.toString(contentBinary.getBinaryContent()); + + } + } + } + + - Object test = testOIS.readObject(); + } catch (Exception e) { - } catch (Exception e1) { - e1.printStackTrace(); - } - - try { - fileURI = new URI("file:/c:/moa3/tomcat8/conf/moa-id/moa-id.properties"); - File propertiesFile = new File(fileURI); - } catch (Exception e1) { - e1.printStackTrace(); - } - - try { - fileURI = new URI("file://c:/moa3/tomcat8/conf/moa-id/moa-id.properties"); - File propertiesFile = new File(fileURI); - } catch (Exception e1) { - e1.printStackTrace(); - } - - try { - fileURI = new URI("file:///c:/moa3/tomcat8/conf/moa-id/moa-id.properties"); - File propertiesFile = new File(fileURI); - } catch (Exception e1) { - e1.printStackTrace(); } - try { - InputStream s = new FileInputStream("D:/idl_test/identity_link.xml"); - Element idlTemplate = DOMUtils.parseXmlValidating(s); - - //resign IDL - IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); - Element resignedilAssertion = identitylinkresigner.resignIdentityLink(idlTemplate, "IDLSigning"); - IdentityLink identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink(); - - } catch (Exception e) { - System.out.println(e.getMessage()); - - } - String subjectName = "serialNumber=896929130327, givenName=OCSP, SN=Responder 03-1, CN=OCSP Responder 03-1, C=AT"; - try { - Name test = new RFC2253NameParser(subjectName).parse(); - - System.out.println(test.getRFC2253String()); - - } catch (RFC2253NameParserException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } +// URI fileURI = null; +// try { +// fileURI = new URI("file:c:/moa3/tomcat8/conf/moa-id/moa-id.properties"); +// File propertiesFile = new File(fileURI); +// +// InputStream in = new FileInputStream(propertiesFile); +// ObjectInputStream testOIS = new ObjectInputStream(in); +// +// Object test = testOIS.readObject(); +// +// +// } catch (Exception e1) { +// e1.printStackTrace(); +// } +// +// try { +// fileURI = new URI("file:/c:/moa3/tomcat8/conf/moa-id/moa-id.properties"); +// File propertiesFile = new File(fileURI); +// } catch (Exception e1) { +// e1.printStackTrace(); +// } +// +// try { +// fileURI = new URI("file://c:/moa3/tomcat8/conf/moa-id/moa-id.properties"); +// File propertiesFile = new File(fileURI); +// } catch (Exception e1) { +// e1.printStackTrace(); +// } +// +// try { +// fileURI = new URI("file:///c:/moa3/tomcat8/conf/moa-id/moa-id.properties"); +// File propertiesFile = new File(fileURI); +// } catch (Exception e1) { +// e1.printStackTrace(); +// } +// +// +// +// try { +// InputStream s = new FileInputStream("D:/idl_test/identity_link.xml"); +// Element idlTemplate = DOMUtils.parseXmlValidating(s); +// +// //resign IDL +// IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); +// Element resignedilAssertion = identitylinkresigner.resignIdentityLink(idlTemplate, "IDLSigning"); +// IdentityLink identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink(); +// +// } catch (Exception e) { +// System.out.println(e.getMessage()); +// +// } +// +// String subjectName = "serialNumber=896929130327, givenName=OCSP, SN=Responder 03-1, CN=OCSP Responder 03-1, C=AT"; +// +// try { +// Name test = new RFC2253NameParser(subjectName).parse(); +// +// System.out.println(test.getRFC2253String()); +// +// } catch (RFC2253NameParserException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } // AuthenticationRole test = AuthenticationRoleFactory.buildFormPVPole("ecas-demo-EUROPEAN_COMMISSION(key=A\\,B)"); diff --git a/id/server/idserverlib/src/test/java/testBeans.xml b/id/server/idserverlib/src/test/java/testBeans.xml new file mode 100644 index 000000000..238a571cb --- /dev/null +++ b/id/server/idserverlib/src/test/java/testBeans.xml @@ -0,0 +1,130 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xmlns:p="http://www.springframework.org/schema/p" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + +<context:annotation-config /> + <bean id="configPropertyDao" + class="at.gv.egovernment.moa.id.commons.db.dao.config.DatabaseConfigPropertyImpl"/> + + <bean id="moaidconfig" class="at.gv.egovernment.moa.id.commons.config.persistence.MOAIDConfigurationImpl" /> + + <bean name="config" id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> + <property name="dataSource" ref="dataSource" /> + <property name="jpaVendorAdapter" ref="jpaVendorAdapter" /> + <property name="persistenceUnitName" value="config" /> + </bean> + + <bean name="transactionManager" id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> + <property name="entityManagerFactory" ref="entityManagerFactory" /> + </bean> + <tx:annotation-driven transaction-manager="transactionManager"/> + + <bean id="RedisTransactionStorage" + class="at.gv.egovernment.moa.id.storage.RedisTransactionStorage"/> + + <bean id="DBTransactionStorage" + class="at.gv.egovernment.moa.id.storage.DBTransactionStorage"/> + + <!-- Redis Beans --> + <bean id="jedisConnFactory" + class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" + p:use-pool="true" + p:poolConfig-ref="jedisPoolConfig"/> + + <bean id="jedisPoolConfig" + class="redis.clients.jedis.JedisPoolConfig" + p:maxTotal="100" + p:maxIdle="10"/> + + <bean id="RedisStringSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /> + <bean id="assertionStoreSerializer" class="org.springframework.data.redis.serializer.JacksonJsonRedisSerializer"> + <constructor-arg type="java.lang.Class" value="at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore"/> + </bean> + + <bean id="redisTemplate" + class="org.springframework.data.redis.core.RedisTemplate" + p:connection-factory-ref="jedisConnFactory" + p:value-serializer-ref="RedisStringSerializer" + p:key-serializer-ref="RedisStringSerializer" + p:enableTransactionSupport="true"/> + + <context:property-placeholder location="${moa.id.configuration}"/> + + <bean id="moaidauthconfig" class="at.gv.egovernment.moa.id.config.auth.PropertyBasedAuthConfigurationProvider"> + <constructor-arg value="#{systemProperties['moa.id.configuration']}"/> + </bean> + + <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" lazy-init="true" destroy-method="close"> + <aop:scoped-proxy/> + <property name="driverClassName" value="${configuration.hibernate.connection.driver_class}" /> + <property name="url" value="${configuration.hibernate.connection.url}"/> + <property name="username" value="${configuration.hibernate.connection.username}" /> + <property name="password" value="${configuration.hibernate.connection.password}" /> + + <property name="connectionProperties" value="${configuration.dbcp.connectionProperties}" /> + <property name="initialSize" value="${configuration.dbcp.initialSize}" /> + <property name="maxTotal" value="${configuration.dbcp.maxActive}" /> + <property name="maxIdle" value="${configuration.dbcp.maxIdle}" /> + <property name="minIdle" value="${configuration.dbcp.minIdle}" /> + <!-- property name="maxWait" value="${configuration.dbcp.maxWaitMillis}" / --> + <property name="testOnBorrow" value="${configuration.dbcp.testOnBorrow}" /> + <property name="testOnReturn" value="${configuration.dbcp.testOnReturn}" /> + <property name="testWhileIdle" value="${configuration.dbcp.testWhileIdle}" /> + <property name="validationQuery" value="${configuration.dbcp.validationQuery}" /> + </bean> + + <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> + <property name="showSql" value="${configuration.hibernate.show_sql}" /> + <property name="generateDdl" value="${configuration.jpaVendorAdapter.generateDdl}" /> + <property name="databasePlatform" value="${configuration.hibernate.dialect}" /> + </bean> + + <bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> + <property name="corePoolSize" value="1" /> + <property name="maxPoolSize" value="50" /> + <property name="queueCapacity" value="50" /> + </bean> + + <bean id="sessionDataSource" class="org.apache.commons.dbcp2.BasicDataSource" lazy-init="true" destroy-method="close"> + <aop:scoped-proxy/> + <property name="driverClassName" value="${moasession.hibernate.connection.driver_class}" /> + <property name="url" value="${moasession.hibernate.connection.url}"/> + <property name="username" value="${moasession.hibernate.connection.username}" /> + <property name="password" value="${moasession.hibernate.connection.password}" /> + + <property name="connectionProperties" value="${moasession.dbcp.connectionProperties}" /> + <property name="initialSize" value="${moasession.dbcp.initialSize}" /> + <property name="maxTotal" value="${moasession.dbcp.maxActive}" /> + <property name="maxIdle" value="${moasession.dbcp.maxIdle}" /> + <property name="minIdle" value="${moasession.dbcp.minIdle}" /> + <!-- property name="maxWait" value="${moasession.dbcp.maxWaitMillis}" / --> + <property name="testOnBorrow" value="${moasession.dbcp.testOnBorrow}" /> + <property name="testOnReturn" value="${moasession.dbcp.testOnReturn}" /> + <property name="testWhileIdle" value="${moasession.dbcp.testWhileIdle}" /> + <property name="validationQuery" value="${moasession.dbcp.validationQuery}" /> + </bean> + + <bean id="sessionJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> + <property name="showSql" value="${moasession.hibernate.show_sql}" /> + <property name="generateDdl" value="${moasession.jpaVendorAdapter.generateDdl}" /> + <property name="databasePlatform" value="${moasession.hibernate.dialect}" /> + </bean> + + <bean name="sessionEntityManagerFactory" id="sessionEntityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> + <property name="dataSource" ref="sessionDataSource" /> + <property name="jpaVendorAdapter" ref="sessionJpaVendorAdapter" /> + <property name="persistenceUnitName" value="session" /> + </bean> + + <bean name="sessionTransactionManager" id="sessionTransactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> + <property name="entityManagerFactory" ref="sessionEntityManagerFactory" /> + </bean> +</beans>
\ No newline at end of file diff --git a/id/server/idserverlib/src/test/resources/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml b/id/server/idserverlib/src/test/resources/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml index bf47c0445..7d9db0ab7 100644 --- a/id/server/idserverlib/src/test/resources/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml +++ b/id/server/idserverlib/src/test/resources/at/gv/egovernment/moa/id/process/spring/test/SpringExpressionAwareProcessEngineTest-context.xml @@ -1,9 +1,13 @@ <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xmlns:task="http://www.springframework.org/schema/task" - xsi:schemaLocation="http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd - http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <bean id="springElAwareExpressionEvaluator" class="at.gv.egovernment.moa.id.process.spring.SpringExpressionEvaluator" /> @@ -12,7 +16,7 @@ </bean> <bean id="TransactionStorage" - class="at.gv.egovernment.moa.id.storage.DBTransactionStorage"/> + class="at.gv.egovernment.moa.id.process.spring.test.DummyTransactionStorage"/> <bean id="ProcessInstanceStoreage" class="at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAOImpl"/> @@ -40,4 +44,5 @@ <bean id="ValidateSignedAuthBlockTask" class="at.gv.egovernment.moa.id.process.spring.test.task.ValidateSignedAuthBlockTask"/> + </beans> |