diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at/gv')
260 files changed, 6135 insertions, 22335 deletions
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 deleted file mode 100644 index 8fff6b20b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/DummyStatisticLogger.java +++ /dev/null @@ -1,58 +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.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"); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.advancedlogging.IStatisticLogger#testConnection() - */ - @Override - public void testConnection() throws Exception { - 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 deleted file mode 100644 index e0f21c012..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/IStatisticLogger.java +++ /dev/null @@ -1,39 +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.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); - - public void testConnection() throws Exception; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java index 54e459db1..05d344fb6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java @@ -35,10 +35,7 @@ import at.gv.egiz.components.eventlog.api.EventConstants; public interface MOAIDEventConstants extends EventConstants { //auth protocol specific information - public static final int AUTHPROTOCOL_TYPE = 3000; - public static final int AUTHPROTOCOL_PVP_METADATA = 3100; - public static final int AUTHPROTOCOL_PVP_REQUEST_AUTHREQUEST = 3101; public static final int AUTHPROTOCOL_PVP_REQUEST_AUTHRESPONSE = 3102; public static final int AUTHPROTOCOL_PVP_REQUEST_SLO = 3103; public static final int AUTHPROTOCOL_PVP_REQUEST_ATTRIBUTQUERY = 3104; @@ -88,7 +85,13 @@ public interface MOAIDEventConstants extends EventConstants { public static final int AUTHPROCESS_PEPS_RECEIVED = 6102; public static final int AUTHPROCESS_PEPS_RECEIVED_ERROR = 6103; public static final int AUTHPROCESS_PEPS_IDL_RECEIVED = 6104; - + + public static final int AUTHPROCESS_EIDAS_AT_CONNECTOR_SELECTED = 6200; + public static final int AUTHPROCESS_EIDAS_AT_CONNECTOR_REQUESTED = 6201; + public static final int AUTHPROCESS_EIDAS_AT_CONNECTOR_RECEIVED = 6202; + public static final int AUTHPROCESS_EIDAS_AT_CONNECTOR_RECEIVED_ERROR = 6203; + public static final int AUTHPROCESS_EIDAS_AT_CONNECTOR_MDS_VALID = 6204; + //person information public static final int PERSONAL_INFORMATION_PROF_REPRESENTATIVE_BPK = 5000; public static final int PERSONAL_INFORMATION_PROF_REPRESENTATIVE = 5001; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAReversionLogger.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAReversionLogger.java index b26c9c1a9..1c1cc4168 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAReversionLogger.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAReversionLogger.java @@ -31,11 +31,15 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; +import at.gv.egiz.eaaf.modules.pvp2.PVPEventConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; 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.data.IIdentityLink; import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameterDecorator; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; @@ -45,7 +49,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * */ @Service("MOAReversionLogger") -public class MOAReversionLogger { +public class MOAReversionLogger implements IRevisionLogger { @Autowired protected AuthConfiguration authConfig; @@ -60,8 +64,8 @@ public class MOAReversionLogger { MOAIDEventConstants.TRANSACTION_DESTROYED, MOAIDEventConstants.TRANSACTION_ERROR, MOAIDEventConstants.TRANSACTION_IP, - MOAIDEventConstants.AUTHPROTOCOL_TYPE, - MOAIDEventConstants.AUTHPROTOCOL_PVP_METADATA, + IRevisionLogger.AUTHPROTOCOL_TYPE, + PVPEventConstants.AUTHPROTOCOL_PVP_METADATA, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION, @@ -91,6 +95,12 @@ public class MOAReversionLogger { MOAIDEventConstants.AUTHPROCESS_PEPS_RECEIVED, MOAIDEventConstants.AUTHPROCESS_PEPS_RECEIVED_ERROR, MOAIDEventConstants.AUTHPROCESS_PEPS_IDL_RECEIVED, + + MOAIDEventConstants.AUTHPROCESS_EIDAS_AT_CONNECTOR_MDS_VALID, + MOAIDEventConstants.AUTHPROCESS_EIDAS_AT_CONNECTOR_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_EIDAS_AT_CONNECTOR_RECEIVED_ERROR, + MOAIDEventConstants.AUTHPROCESS_EIDAS_AT_CONNECTOR_REQUESTED, + MOAIDEventConstants.AUTHPROCESS_EIDAS_AT_CONNECTOR_SELECTED, MOAIDEventConstants.AUTHPROCESS_FOREIGN_FOUND, MOAIDEventConstants.AUTHPROCESS_FOREIGN_SZRGW_RECEIVED, @@ -107,13 +117,20 @@ public class MOAReversionLogger { ); - public void logEvent(IOAAuthParameters oaConfig, + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.advancedlogging.IRevisionLogger#logEvent(at.gv.egovernment.moa.id.commons.api.IOAAuthParameters, int, java.lang.String) + */ + @Override + public void logEvent(ISPConfiguration oaConfig, int eventCode, String message) { if (selectOASpecificEventCodes(oaConfig).contains(eventCode)) MOAIDEventLog.logEvent(MOAIDEventLog.createNewEvent(new Date().getTime(), eventCode, message)); } - public void logEvent(IOAAuthParameters oaConfig, IRequest pendingRequest, + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.advancedlogging.IRevisionLogger#logEvent(at.gv.egovernment.moa.id.commons.api.IOAAuthParameters, at.gv.egiz.eaaf.core.api.IRequest, int) + */ + public void logEvent(ISPConfiguration oaConfig, IRequest pendingRequest, int eventCode) { if (selectOASpecificEventCodes(oaConfig).contains(eventCode)) MOAIDEventLog.logEvent(MOAIDEventLog.createNewEvent(new Date().getTime(), eventCode, @@ -122,6 +139,9 @@ public class MOAReversionLogger { } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.advancedlogging.IRevisionLogger#logEvent(at.gv.egovernment.moa.id.commons.api.IOAAuthParameters, at.gv.egiz.eaaf.core.api.IRequest, int, java.lang.String) + */ public void logEvent(IOAAuthParameters oaConfig, IRequest pendingRequest, int eventCode, String message) { if (selectOASpecificEventCodes(oaConfig).contains(eventCode)) @@ -133,37 +153,37 @@ public class MOAReversionLogger { } - /** - * @param sessionCreated - * @param uniqueSessionIdentifier + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.advancedlogging.IRevisionLogger#logEvent(int, java.lang.String) */ + @Override public void logEvent(int eventCode, String message) { MOAIDEventLog.logEvent(MOAIDEventLog.createNewEvent(new Date().getTime(), eventCode, message)); } - /** - * @param sessionCreated - * @param uniqueSessionIdentifier + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.advancedlogging.IRevisionLogger#logEvent(java.lang.String, java.lang.String, int, java.lang.String) */ + @Override public void logEvent(String sessionID, String transactionID, int eventCode, String message) { MOAIDEventLog.logEvent(MOAIDEventLog.createNewEvent(new Date().getTime(), eventCode, message, sessionID, transactionID)); } - /** - * @param sessionCreated - * @param uniqueSessionIdentifier + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.advancedlogging.IRevisionLogger#logEvent(java.lang.String, java.lang.String, int) */ + @Override public void logEvent(String sessionID, String transactionID, int eventCode) { MOAIDEventLog.logEvent(MOAIDEventLog.createNewEvent(new Date().getTime(), eventCode, sessionID, transactionID)); } - /** - * @param errorRequest - * @param transactionError + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.advancedlogging.IRevisionLogger#logEvent(at.gv.egiz.eaaf.core.api.IRequest, int) */ + @Override public void logEvent(IRequest pendingRequest, int eventCode) { MOAIDEventLog.logEvent(MOAIDEventLog.createNewEvent(new Date().getTime(), eventCode, pendingRequest.getUniqueSessionIdentifier(), @@ -171,8 +191,12 @@ public class MOAReversionLogger { } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.advancedlogging.IRevisionLogger#logEvent(at.gv.egiz.eaaf.core.api.IRequest, int, java.lang.String) + */ + @Override public void logEvent(IRequest pendingRequest, int eventCode, String message) { - logEvent(pendingRequest.getOnlineApplicationConfiguration(), + logEvent(pendingRequest.getServiceProviderConfiguration(OAAuthParameterDecorator.class), pendingRequest, eventCode, message); } @@ -232,12 +256,13 @@ public class MOAReversionLogger { } - private List<Integer> selectOASpecificEventCodes(IOAAuthParameters oaConfig) { + private List<Integer> selectOASpecificEventCodes(ISPConfiguration oaConfig) { List<Integer> OASpecificEventCodes = null; - if (oaConfig != null && oaConfig.getReversionsLoggingEventCodes() != null) - OASpecificEventCodes = oaConfig.getReversionsLoggingEventCodes(); + if (oaConfig != null && oaConfig instanceof IOAAuthParameters && + ((IOAAuthParameters)oaConfig).getReversionsLoggingEventCodes() != null) { + OASpecificEventCodes = ((IOAAuthParameters)oaConfig).getReversionsLoggingEventCodes(); - else + } else OASpecificEventCodes = getDefaulttReversionsLoggingEventCodes(); return OASpecificEventCodes; 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 72aef5fed..f642cddc7 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 @@ -43,22 +43,25 @@ import org.springframework.transaction.annotation.Transactional; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandator; import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; -import at.gv.egovernment.moa.id.auth.exception.BKUException; -import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.logging.IStatisticLogger; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionWrapper; import at.gv.egovernment.moa.id.auth.exception.ServiceException; import at.gv.egovernment.moa.id.client.SZRGWClientException; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; 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.data.IAuthenticationSession; import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; +import at.gv.egovernment.moa.id.commons.api.exceptions.BKUException; import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MISSimpleClientException; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.commons.db.dao.statistic.StatisticLog; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameterDecorator; +import at.gv.egovernment.moa.id.data.IMOAAuthData; +import at.gv.egovernment.moa.id.moduls.SSOManager; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -91,7 +94,9 @@ public class StatisticLogger implements IStatisticLogger{ private EntityManager entityManager; - public void testConnection() throws Exception { + @Override + //TODO: update tests!!!! + public void internalTesting() throws Exception { Date expioredate = new Date(new Date().getTime() - 120); Query query = entityManager.createNamedQuery("getAllEntriesNotBeforeTimeStamp"); query.setParameter("timeout", expioredate); @@ -105,7 +110,7 @@ public class StatisticLogger implements IStatisticLogger{ if ( authConfig.isAdvancedLoggingActive() && protocolRequest != null && authData != null) { IOAAuthParameters dbOA = null; - dbOA = protocolRequest.getOnlineApplicationConfiguration(); + dbOA = protocolRequest.getServiceProviderConfiguration(OAAuthParameterDecorator.class); if (dbOA == null) { Logger.warn("Advanced logging failed: OA can not be found in database."); @@ -128,88 +133,95 @@ public class StatisticLogger implements IStatisticLogger{ Logger.warn("Can not extract some information for StatisticLogger.", e); } - dblog.setOatarget(authData.getBPKType()); - - - boolean isFederatedAuthentication = protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE) != null; - dblog.setInterfederatedSSOSession(isFederatedAuthentication); - - if (isFederatedAuthentication) { - dblog.setBkutype(IOAAuthParameters.INDERFEDERATEDIDP); - dblog.setBkuurl(protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_ENTITYID, String.class)); - - } else { - dblog.setBkuurl(authData.getBkuURL()); - dblog.setBkutype(findBKUType(authData.getBkuURL(), dbOA)); - - } - dblog.setProtocoltype(protocolRequest.requestedModule()); dblog.setProtocolsubtype(protocolRequest.requestedAction()); dblog.setSsosession(isSSOSession); - //log MandateInforamtion - if (authData.isUseMandate()) { - dblog.setMandatelogin(authData.isUseMandate()); + if (authData instanceof IMOAAuthData) { + IMOAAuthData moaAuthData = (IMOAAuthData) authData; + dblog.setOatarget(moaAuthData.getBPKType()); + + boolean isFederatedAuthentication = protocolRequest.getRawData(SSOManager.DATAID_INTERFEDERATIOIDP_RESPONSE) != null; + dblog.setInterfederatedSSOSession(isFederatedAuthentication); - IMISMandate mandate = authData.getMISMandate(); - if (mandate != null) { + if (isFederatedAuthentication) { + dblog.setBkutype(IOAAuthParameters.INDERFEDERATEDIDP); + dblog.setBkuurl(protocolRequest.getRawData(SSOManager.DATAID_INTERFEDERATIOIDP_ENTITYID, String.class)); - if (MiscUtil.isNotEmpty(mandate.getProfRep())) { - dblog.setMandatetype(mandate.getProfRep()); - dblog.setPv(true); - dblog.setPvOID(mandate.getProfRep()); - - } else { - dblog.setPv(false); - } + } else if (moaAuthData.isForeigner()) { + dblog.setBkutype(IOAAuthParameters.EIDAS); - InputStream is = null; - try { - is = new ByteArrayInputStream(mandate.getMandate()); + } else { + dblog.setBkuurl(moaAuthData.getBkuURL()); + dblog.setBkutype(findBKUType(moaAuthData.getBkuURL(), dbOA)); + + } + + //log MandateInforamtion + if (moaAuthData.isUseMandate()) { + dblog.setMandatelogin(moaAuthData.isUseMandate()); + + IMISMandate mandate = moaAuthData.getMISMandate(); + if (mandate != null) { - JAXBContext jc = JAXBContext.newInstance(Mandate.class); - Unmarshaller u = jc.createUnmarshaller(); - Object mismandateobj = u.unmarshal(is); + if (MiscUtil.isNotEmpty(mandate.getProfRep())) { + dblog.setMandatetype(mandate.getProfRep()); + dblog.setPv(true); + dblog.setPvOID(mandate.getProfRep()); + + } else { + dblog.setPv(false); + } - if (mismandateobj != null && mismandateobj instanceof Mandate) { - Mandate mismandate = (Mandate) mismandateobj; + InputStream is = null; + try { + is = new ByteArrayInputStream(mandate.getMandate()); - if (MiscUtil.isEmpty(mandate.getProfRep())) - dblog.setMandatetype(mismandate.getAnnotation()); + JAXBContext jc = JAXBContext.newInstance(Mandate.class); + Unmarshaller u = jc.createUnmarshaller(); + Object mismandateobj = u.unmarshal(is); - Mandator mandator = mismandate.getMandator(); - CorporateBodyType corp = mandator.getCorporateBody(); - if (corp != null) { - dblog.setMandatortype(MANTATORTYPE_JUR); + if (mismandateobj != null && mismandateobj instanceof Mandate) { + Mandate mismandate = (Mandate) mismandateobj; + + if (MiscUtil.isEmpty(mandate.getProfRep())) + dblog.setMandatetype(mismandate.getAnnotation()); + + Mandator mandator = mismandate.getMandator(); + CorporateBodyType corp = mandator.getCorporateBody(); + if (corp != null) { + dblog.setMandatortype(MANTATORTYPE_JUR); + + } else { + dblog.setMandatortype(MANTATORTYPE_NAT); + } + } else { - dblog.setMandatortype(MANTATORTYPE_NAT); + Logger.warn("Advancted logging can not unmarshall MISMandate"); } - - - } else { - Logger.warn("Advancted logging can not unmarshall MISMandate"); - } - } catch (JAXBException e) { - Logger.warn("Advancted logging can not parse mandate.", e); - - } finally { - if (is!=null) { - try { - is.close(); - - } catch (IOException e) { - Logger.warn("Close InputStream failed." , e); - + } catch (JAXBException e) { + Logger.warn("Advancted logging can not parse mandate.", e); + + } finally { + if (is!=null) { + try { + is.close(); + + } catch (IOException e) { + Logger.warn("Close InputStream failed." , e); + + } } } - } - } - } - + } + } + + } else + Logger.info("'AuthData' is NOT of type 'IMOAAuthData'. StatisticLogger logs only basic infos"); + try { entityManager.persist(dblog); @@ -258,13 +270,13 @@ public class StatisticLogger implements IStatisticLogger{ dblog.setTimestamp(new Date()); - dblog.setOaurlprefix(getMessageWithMaxLength(errorRequest.getOAURL(), MAXOAIDENTIFIER_LENGTH)); + dblog.setOaurlprefix(getMessageWithMaxLength(errorRequest.getSPEntityId(), MAXOAIDENTIFIER_LENGTH)); dblog.setProtocoltype(errorRequest.requestedModule()); dblog.setProtocolsubtype(errorRequest.requestedAction()); generateErrorLogFormThrowable(throwable, dblog); - IOAAuthParameters dbOA = errorRequest.getOnlineApplicationConfiguration(); + IOAAuthParameters dbOA = errorRequest.getServiceProviderConfiguration(OAAuthParameterDecorator.class); if (dbOA != null) { dblog.setOaurlprefix(getMessageWithMaxLength(dbOA.getPublicURLPrefix(), MAXOAIDENTIFIER_LENGTH)); dblog.setOafriendlyName(dbOA.getFriendlyName()); @@ -290,7 +302,9 @@ public class StatisticLogger implements IStatisticLogger{ } else { Logger.debug("Use MOA session information from pending-req for ErrorLogging"); - moasession = errorRequest.getMOASession(); + moasession = (IAuthenticationSession) errorRequest.getSessionData(AuthenticationSessionWrapper.class); + + } @@ -383,45 +397,47 @@ public class StatisticLogger implements IStatisticLogger{ private String findBKUType(String bkuURL, IOAAuthParameters dbOA) { - if (dbOA != null) { - if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameter.HANDYBKU))) - return IOAAuthParameters.HANDYBKU; - - if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameter.LOCALBKU))) - return IOAAuthParameters.LOCALBKU; - - if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameter.THIRDBKU))) - return IOAAuthParameters.THIRDBKU; - } - - Logger.trace("Staticic Log search BKUType from DefaultBKUs"); - - try { - if (bkuURL.equals(authConfig.getDefaultBKUURL(IOAAuthParameters.THIRDBKU))) - return IOAAuthParameters.THIRDBKU; + if (bkuURL != null) { + if (dbOA != null) { + if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameterDecorator.HANDYBKU))) + return IOAAuthParameters.HANDYBKU; + + if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameterDecorator.LOCALBKU))) + return IOAAuthParameters.LOCALBKU; + + if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameterDecorator.THIRDBKU))) + return IOAAuthParameters.THIRDBKU; + } - if (bkuURL.equals(authConfig.getDefaultBKUURL(IOAAuthParameters.LOCALBKU))) + Logger.trace("Staticic Log search BKUType from DefaultBKUs"); + + try { + if (bkuURL.equals(authConfig.getDefaultBKUURL(IOAAuthParameters.THIRDBKU))) + return IOAAuthParameters.THIRDBKU; + + if (bkuURL.equals(authConfig.getDefaultBKUURL(IOAAuthParameters.LOCALBKU))) + return IOAAuthParameters.LOCALBKU; + + if (bkuURL.equals(authConfig.getDefaultBKUURL(IOAAuthParameters.HANDYBKU))) + return IOAAuthParameters.HANDYBKU; + + } catch (ConfigurationException e) { + Logger.info("Advanced Logging: Default BKUs read failed"); + } + + Logger.debug("Staticic Log search BKUType from generneric Parameters"); + + if (bkuURL.endsWith(GENERIC_LOCALBKU)) { + Logger.debug("BKUURL " + bkuURL + " is mapped to " + IOAAuthParameters.LOCALBKU); return IOAAuthParameters.LOCALBKU; + } - if (bkuURL.equals(authConfig.getDefaultBKUURL(IOAAuthParameters.HANDYBKU))) + if (bkuURL.startsWith(GENERIC_HANDYBKU)) { + Logger.debug("BKUURL " + bkuURL + " is mapped to " + IOAAuthParameters.HANDYBKU); return IOAAuthParameters.HANDYBKU; - - } catch (ConfigurationException e) { - Logger.info("Advanced Logging: Default BKUs read failed"); - } - - Logger.debug("Staticic Log search BKUType from generneric Parameters"); - - if (bkuURL.endsWith(GENERIC_LOCALBKU)) { - Logger.debug("BKUURL " + bkuURL + " is mapped to " + IOAAuthParameters.LOCALBKU); - return IOAAuthParameters.LOCALBKU; + } } - if (bkuURL.startsWith(GENERIC_HANDYBKU)) { - Logger.debug("BKUURL " + bkuURL + " is mapped to " + IOAAuthParameters.HANDYBKU); - return IOAAuthParameters.HANDYBKU; - } - Logger.debug("BKUURL " + bkuURL + " is mapped to " + IOAAuthParameters.AUTHTYPE_OTHERS); return IOAAuthParameters.AUTHTYPE_OTHERS; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/TransactionIDUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/TransactionIDUtils.java deleted file mode 100644 index 0b066f3b9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/TransactionIDUtils.java +++ /dev/null @@ -1,101 +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.advancedlogging; - - -import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.commons.api.IRequest; - -/** - * @author tlenz - * - */ -public class TransactionIDUtils { - - /** - * Set all MDC variables from pending request to this threat context<br> - * These includes SessionID, TransactionID, and unique service-provider identifier - * - * @param pendingRequest - */ - public static void setAllLoggingVariables(IRequest pendingRequest) { - setTransactionId(pendingRequest.getUniqueTransactionIdentifier()); - setSessionId(pendingRequest.getUniqueSessionIdentifier()); - setServiceProviderId(pendingRequest.getOnlineApplicationConfiguration().getPublicURLPrefix()); - - } - - /** - * Remove all MDC variables from this threat context - * - */ - public static void removeAllLoggingVariables() { - removeSessionId(); - removeTransactionId(); - removeServiceProviderId(); - - } - - - public static void setServiceProviderId(String oaUniqueId) { - org.apache.log4j.MDC.put(MOAIDAuthConstants.MDC_SERVICEPROVIDER_ID, oaUniqueId); - org.slf4j.MDC.put(MOAIDAuthConstants.MDC_SERVICEPROVIDER_ID, oaUniqueId); - - } - - public static void removeServiceProviderId() { - org.apache.log4j.MDC.remove(MOAIDAuthConstants.MDC_SERVICEPROVIDER_ID); - org.slf4j.MDC.remove(MOAIDAuthConstants.MDC_SERVICEPROVIDER_ID); - - } - - public static void setTransactionId(String pendingRequestID) { - org.apache.log4j.MDC.put(MOAIDAuthConstants.MDC_TRANSACTION_ID, - "TID-" + pendingRequestID); - org.slf4j.MDC.put(MOAIDAuthConstants.MDC_TRANSACTION_ID, - "TID-" + pendingRequestID); - - } - - public static void removeTransactionId() { - org.apache.log4j.MDC.remove(MOAIDAuthConstants.MDC_TRANSACTION_ID); - org.slf4j.MDC.remove(MOAIDAuthConstants.MDC_TRANSACTION_ID); - - } - - public static void setSessionId(String uniqueSessionId) { - org.apache.log4j.MDC.put(MOAIDAuthConstants.MDC_SESSION_ID, - "SID-" + uniqueSessionId); - org.slf4j.MDC.put(MOAIDAuthConstants.MDC_SESSION_ID, - "SID-" + uniqueSessionId); - - } - - public static void removeSessionId() { - org.apache.log4j.MDC.remove(MOAIDAuthConstants.MDC_SESSION_ID); - org.slf4j.MDC.remove(MOAIDAuthConstants.MDC_SESSION_ID); - - } - - -} 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 34d0d4be1..c684e1ac2 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 @@ -12,14 +12,14 @@ 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; +import at.gv.egiz.eaaf.core.api.data.ExceptionContainer; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.ProcessExecutionException; +import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.data.ExceptionContainer; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; 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 deleted file mode 100644 index 6f98357e2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IDestroyableObject.java +++ /dev/null @@ -1,36 +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.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/auth/IGarbageCollectorProcessing.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IGarbageCollectorProcessing.java deleted file mode 100644 index 27d142f2c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IGarbageCollectorProcessing.java +++ /dev/null @@ -1,36 +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.auth; - -/** - * @author tlenz - * - */ -public interface IGarbageCollectorProcessing { - - /** - * This method gets executed by the MOA garbage collector at regular intervals. - * - */ - public void runGarbageCollector(); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IPostStartupInitializable.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IPostStartupInitializable.java deleted file mode 100644 index d918be463..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/IPostStartupInitializable.java +++ /dev/null @@ -1,41 +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.auth; - - -/** - * - * @author tlenz - * - * Interface initialize a Object when the MOA-ID-Auth start-up process is fully completed - * - */ -public interface IPostStartupInitializable { - - /** - * This method is called once when MOA-ID-Auth start-up process is fully completed - * - */ - public void executeAfterStartup(); - -} 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 index 52e30a2f0..f88267ad7 100644 --- 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 @@ -33,6 +33,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Service; +import at.gv.egiz.eaaf.core.api.IGarbageCollectorProcessing; import at.gv.egovernment.moa.logging.Logger; @Service("MOAGarbageCollector") 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 d09aac0f4..66093b851 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 @@ -32,12 +32,12 @@ import javax.activation.MailcapCommandMap; import org.springframework.web.context.support.GenericWebApplicationContext; +import at.gv.egiz.eaaf.core.impl.utils.Random; 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.ConfigurationProviderImpl; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -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.spss.MOAException; 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 cc716f9f8..2c14af463 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 @@ -23,72 +23,71 @@ package at.gv.egovernment.moa.id.auth.builder; import java.io.IOException; -import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.security.PrivateKey; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.Date; +import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Map; +import java.util.Map.Entry; -import javax.naming.ldap.LdapName; -import javax.naming.ldap.Rdn; +import javax.annotation.PostConstruct; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeQuery; -import org.opensaml.saml2.core.Response; -import org.opensaml.ws.soap.common.SOAPException; -import org.opensaml.xml.XMLObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IAuthProcessDataContainer; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFBuilderException; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFParserException; +import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.exceptions.XPathException; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; +import at.gv.egiz.eaaf.core.impl.idp.auth.builder.AbstractAuthenticationDataBuilder; +import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BPKBuilder; +import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionWrapper; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.auth.exception.DynamicOABuildException; -import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; 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.data.ExtendedSAMLAttribute; import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession; -import at.gv.egovernment.moa.id.commons.api.data.IIdentityLink; import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; import at.gv.egovernment.moa.id.commons.api.data.IVerifiyXMLSignatureResponse; 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.api.exceptions.SessionDataStorageException; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; -import at.gv.egovernment.moa.id.data.AuthenticationData; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameterDecorator; import at.gv.egovernment.moa.id.data.AuthenticationRoleFactory; -import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; -import at.gv.egovernment.moa.id.data.Pair; +import at.gv.egovernment.moa.id.data.MOAAuthenticationData; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; -import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; +import at.gv.egovernment.moa.id.util.LoALevelMapper; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.egovernment.moa.util.XPathUtils; import at.gv.util.client.szr.SZRClient; import at.gv.util.config.EgovUtilPropertiesConfiguration; import at.gv.util.wsdl.szr.SZRException; @@ -100,30 +99,57 @@ import iaik.x509.X509Certificate; * */ @Service("AuthenticationDataBuilder") -public class AuthenticationDataBuilder extends MOAIDAuthConstants { +public class AuthenticationDataBuilder extends AbstractAuthenticationDataBuilder { + public static final String CONFIGURATION_PROP_FOREIGN_BPK_ENC_KEYS = "configuration.foreignsectors.pubkey"; + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; @Autowired protected AuthConfiguration authConfig; - @Autowired private AttributQueryBuilder attributQueryBuilder; - @Autowired private SAMLVerificationEngineSP samlVerificationEngine; - @Autowired(required=true) private MOAMetadataProvider metadataProvider; + @Autowired protected LoALevelMapper loaLevelMapper; + private Map<String, X509Certificate> encKeyMap = new HashMap<String, X509Certificate>(); - public IAuthData buildAuthenticationData(IRequest pendingReq, - IAuthenticationSession session) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { - return buildAuthenticationData(pendingReq, session, pendingReq.getOnlineApplicationConfiguration()); - + @PostConstruct + private void initialize() { + Map<String, String> pubKeyMap = authConfig.getBasicMOAIDConfigurationWithPrefix(CONFIGURATION_PROP_FOREIGN_BPK_ENC_KEYS); + for (Entry<String, String> el : pubKeyMap.entrySet()) { + try { + encKeyMap.put(el.getKey(), new X509Certificate(Base64Utils.decode(el.getValue(), false))); + Logger.info("Load foreign bPK encryption certificate for sector: " + el.getKey()); + + } catch (Exception e) { + Logger.warn("Can NOT load foreign bPK encryption certificate for sector: \" + el.getKey()", e); + + } + + } } - public IAuthData buildAuthenticationData(IRequest pendingReq, - IAuthenticationSession session, IOAAuthParameters oaParam) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { - AuthenticationData authdata = null; + @Override + public IAuthData buildAuthenticationData(IRequest pendingReq) throws EAAFAuthenticationException { + try { + return buildAuthenticationData(pendingReq, + pendingReq.getSessionData(AuthenticationSessionWrapper.class), + pendingReq.getServiceProviderConfiguration(OAAuthParameterDecorator.class)); + + } catch (ConfigurationException | BuildException | WrongParametersException | DynamicOABuildException | EAAFBuilderException e) { + Logger.warn("Can not build authentication data from session information"); + throw new EAAFAuthenticationException("builder.11", new Object[]{}, e); + + } + + } + + private IAuthData buildAuthenticationData(IRequest pendingReq, + IAuthenticationSession session, IOAAuthParameters oaParam) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException, EAAFBuilderException { + MOAAuthenticationData authdata = null; //only needed for SAML1 legacy support try { //check if SAML1 authentication module is in Classpath Class<?> saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); - IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); + //IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); + IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").getConstructor(LoALevelMapper.class).newInstance(loaLevelMapper); if (saml1RequstTemplate != null && saml1RequstTemplate.isInstance(pendingReq)) { //request is SAML1 --> invoke SAML1 protocol specific methods @@ -134,19 +160,19 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, session.getExtendedSAMLAttributesOA()); } - authdata = (AuthenticationData) saml1authdata; + authdata = (MOAAuthenticationData) saml1authdata; } else { - authdata = new AuthenticationData(); + authdata = new MOAAuthenticationData(loaLevelMapper); } } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { - authdata = new AuthenticationData(); + authdata = new MOAAuthenticationData(loaLevelMapper); } - OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getSPEntityId(), pendingReq.requestedModule()); //reuse authentication information in case of service-provider reauthentication if (activeOA != null) { authdata.setSessionIndex(activeOA.getAssertionSessionID()); @@ -160,14 +186,14 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { if (oaParam.isSTORKPVPGateway()) oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, pendingReq); - Boolean isMinimalFrontChannelResp = pendingReq.getGenericData( - PVPTargetConfiguration.DATAID_INTERFEDERATION_MINIMAL_FRONTCHANNEL_RESP, Boolean.class); + Boolean isMinimalFrontChannelResp = pendingReq.getRawData( + MOAIDAuthConstants.DATAID_INTERFEDERATION_MINIMAL_FRONTCHANNEL_RESP, Boolean.class); if (isMinimalFrontChannelResp != null && isMinimalFrontChannelResp) { //only set minimal response attributes authdata.setQAALevel( - pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_QAALEVEL, String.class)); + pendingReq.getRawData(MOAIDAuthConstants.DATAID_INTERFEDERATION_QAALEVEL, String.class)); authdata.setBPK( - pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_NAMEID, String.class)); + pendingReq.getRawData(MOAIDAuthConstants.DATAID_INTERFEDERATION_NAMEID, String.class)); } else { //build AuthenticationData from MOASession @@ -177,173 +203,15 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { return authdata; } - - /** - * Get PVP authentication attributes by using a SAML2 AttributeQuery - * - * @param reqQueryAttr List of PVP attributes which are requested - * @param userNameID SAML2 UserNameID of the user for which attributes are requested - * @param idpConfig Configuration of the IDP, which is requested - * @return - * @return PVP attribute DAO, which contains all received information - * @throws MOAIDException - */ - public AssertionAttributeExtractor getAuthDataFromAttributeQuery(List<Attribute> reqQueryAttr, - String userNameID, IOAAuthParameters idpConfig ) throws MOAIDException{ - String idpEnityID = idpConfig.getPublicURLPrefix(); - - try { - Logger.debug("Starting AttributeQuery process ..."); - //collect attributes by using BackChannel communication - String endpoint = idpConfig.getIDPAttributQueryServiceURL(); - if (MiscUtil.isEmpty(endpoint)) { - Logger.error("No AttributeQueryURL for interfederationIDP " + idpEnityID); - throw new ConfigurationException("config.26", new Object[]{idpEnityID}); - - } - - //build attributQuery request - AttributeQuery query = attributQueryBuilder.buildAttributQueryRequest(userNameID, endpoint, reqQueryAttr); - - //build SOAP request - List<XMLObject> xmlObjects = MOASAMLSOAPClient.send(endpoint, query); - - if (xmlObjects.size() == 0) { - Logger.error("Receive emptry AttributeQuery response-body."); - throw new AttributQueryException("auth.27", - new Object[]{idpEnityID, "Receive emptry AttributeQuery response-body."}); - - } - - Response intfResp; - if (xmlObjects.get(0) instanceof Response) { - intfResp = (Response) xmlObjects.get(0); - - //validate PVP 2.1 response - try { - samlVerificationEngine.verifyIDPResponse(intfResp, - TrustEngineFactory.getSignatureKnownKeysTrustEngine( - metadataProvider)); - - //create assertion attribute extractor from AttributeQuery response - return new AssertionAttributeExtractor(intfResp); - - } catch (Exception e) { - Logger.warn("PVP 2.1 assertion validation FAILED.", e); - throw new AssertionValidationExeption("auth.27", - new Object[]{idpEnityID, e.getMessage()}, e); - } - - } else { - Logger.error("Receive AttributeQuery response-body include no PVP 2.1 response"); - throw new AttributQueryException("auth.27", - new Object[]{idpEnityID, "Receive AttributeQuery response-body include no PVP 2.1 response"}); - - } - - } catch (SOAPException e) { - throw new BuildException("builder.06", null, e); - - } catch (SecurityException e) { - throw new BuildException("builder.06", null, e); - - } catch (org.opensaml.xml.security.SecurityException e1) { - throw new BuildException("builder.06", null, e1); - - } - } - - private void buildAuthDataFormMOASession(AuthenticationData authData, IAuthenticationSession session, - IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { - - Collection<String> includedToGenericAuthData = null; - if (session.getGenericSessionDataStorage() != null && - !session.getGenericSessionDataStorage().isEmpty()) - includedToGenericAuthData = session.getGenericSessionDataStorage().keySet(); - else - includedToGenericAuthData = new ArrayList<String>(); - - try { - //#################################################### - //set general authData info's - authData.setIssuer(protocolRequest.getAuthURL()); - authData.setSsoSession(protocolRequest.needSingleSignOnFunctionality()); - authData.setBaseIDTransferRestrication(oaParam.hasBaseIdTransferRestriction()); - - - //#################################################### - //parse user info's from identityLink - IIdentityLink idlFromPVPAttr = null; - IIdentityLink identityLink = session.getIdentityLink(); - if (identityLink != null) { - parseBasicUserInfosFromIDL(authData, identityLink, includedToGenericAuthData); - - } else { - // identityLink is not direct in MOASession - String pvpAttrIDL = session.getGenericDataFromSession(PVPConstants.EID_IDENTITY_LINK_NAME, String.class); - //find PVP-Attr. which contains the IdentityLink - if (MiscUtil.isNotEmpty(pvpAttrIDL)) { - Logger.debug("Find PVP-Attr: " + PVPConstants.EID_IDENTITY_LINK_FRIENDLY_NAME - + " --> Parse basic user info's from that attribute."); - InputStream idlStream = null; - try { - idlStream = Base64Utils.decodeToStream(pvpAttrIDL, false); - idlFromPVPAttr = new IdentityLinkAssertionParser(idlStream).parseIdentityLink(); - parseBasicUserInfosFromIDL(authData, idlFromPVPAttr, includedToGenericAuthData); - - } catch (ParseException e) { - Logger.error("Received IdentityLink is not valid", e); - - } catch (Exception e) { - Logger.error("Received IdentityLink is not valid", e); - - } finally { - try { - includedToGenericAuthData.remove(PVPConstants.EID_IDENTITY_LINK_NAME); - if (idlStream != null) - idlStream.close(); - - } catch (IOException e) { - Logger.fatal("Close InputStream FAILED.", e); - - } - - } - - } - - //if no basic user info's are set yet, parse info's single PVP-Attributes - if (MiscUtil.isEmpty(authData.getFamilyName())) { - Logger.debug("No IdentityLink found or not parseable --> Parse basic user info's from single PVP-Attributes."); - authData.setFamilyName(session.getGenericDataFromSession(PVPConstants.PRINCIPAL_NAME_NAME, String.class)); - authData.setGivenName(session.getGenericDataFromSession(PVPConstants.GIVEN_NAME_NAME, String.class)); - authData.setDateOfBirth(session.getGenericDataFromSession(PVPConstants.BIRTHDATE_NAME, String.class)); - authData.setIdentificationValue(session.getGenericDataFromSession(PVPConstants.EID_SOURCE_PIN_NAME, String.class)); - authData.setIdentificationType(session.getGenericDataFromSession(PVPConstants.EID_SOURCE_PIN_TYPE_NAME, String.class)); - - //remove corresponding keys from genericSessionData if exists - includedToGenericAuthData.remove(PVPConstants.PRINCIPAL_NAME_NAME); - includedToGenericAuthData.remove(PVPConstants.GIVEN_NAME_NAME); - includedToGenericAuthData.remove(PVPConstants.BIRTHDATE_NAME); - includedToGenericAuthData.remove(PVPConstants.EID_SOURCE_PIN_NAME); - includedToGenericAuthData.remove(PVPConstants.EID_SOURCE_PIN_TYPE_NAME); - } - - } - if (authData.getIdentificationType() != null && - !authData.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - Logger.trace("IdentificationType is not a baseID --> clear it. "); - authData.setBPK(authData.getIdentificationValue()); - authData.setBPKType(authData.getIdentificationType()); - - authData.setIdentificationValue(null); - authData.setIdentificationType(null); - - } + private void buildAuthDataFormMOASession(MOAAuthenticationData authData, IAuthenticationSession session, + IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException, EAAFBuilderException { + try { + //generate basic authentication data + generateBasicAuthData(authData, protocolRequest, session); - //#################################################### + // #### generate MOA-ID specific authentication data ###### //set BKU URL includedToGenericAuthData.remove(PVPConstants.EID_CCS_URL_NAME); if (MiscUtil.isNotEmpty(session.getBkuURL())) @@ -355,33 +223,53 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { //TODO: fully switch from STORK QAA to eIDAS LoA //#################################################### //set QAA level - includedToGenericAuthData.remove(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME); - if (MiscUtil.isNotEmpty(session.getQAALevel())) - authData.setQAALevel(session.getQAALevel()); + if (MiscUtil.isNotEmpty(authData.getEIDASQAALevel())) { + Logger.debug("Find eIDAS LoA. Map it to STORK QAA"); + authData.setQAALevel(loaLevelMapper.mapeIDASQAAToSTORKQAA(authData.getEIDASQAALevel())); + + } else { + Logger.info("Find NO eIDAS Loa. Starting STORK QAA processing as backup ... "); - else { - String qaaLevel = session.getGenericDataFromSession(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME, String.class); - if (MiscUtil.isNotEmpty(qaaLevel)) { - Logger.debug("Find PVP-Attr: " + PVPConstants.EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME - + " --> Parse QAA-Level from that attribute."); - - if (qaaLevel.startsWith(PVPConstants.STORK_QAA_PREFIX)) { - authData.setQAALevel(qaaLevel); - - } else { - Logger.debug("Found PVP QAA level. QAA mapping process starts ... "); - String mappedQAA = PVPtoSTORKMapper.getInstance().mapToQAALevel(qaaLevel); - if (MiscUtil.isNotEmpty(mappedQAA)) - authData.setQAALevel(mappedQAA); - + + includedToGenericAuthData.remove(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME); + String currentLoA = null; + if (MiscUtil.isNotEmpty(session.getQAALevel())) + currentLoA = session.getQAALevel(); + else { + currentLoA = session.getGenericDataFromSession(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME, String.class); + if (MiscUtil.isNotEmpty(currentLoA)) { + Logger.debug("Find PVP-Attr '" + PVPConstants.EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME + "':" + currentLoA + + " --> Parse QAA-Level from that attribute."); + } } + + if (MiscUtil.isNotEmpty(currentLoA)) { + if (currentLoA.startsWith(PVPConstants.STORK_QAA_PREFIX)) { + authData.setQAALevel(currentLoA); + authData.seteIDASLoA(loaLevelMapper.mapSTORKQAAToeIDASQAA(currentLoA)); + + } else if (currentLoA.startsWith(EAAFConstants.EIDAS_LOA_PREFIX)) { + authData.setQAALevel(loaLevelMapper.mapeIDASQAAToSTORKQAA(currentLoA)); + authData.seteIDASLoA(currentLoA); + + } else { + Logger.debug("Found PVP SecClass. QAA mapping process starts ... "); + String mappedStorkQAA = loaLevelMapper.mapSecClassToQAALevel(currentLoA); + if (MiscUtil.isNotEmpty(mappedStorkQAA)) { + authData.setQAALevel(mappedStorkQAA); + authData.seteIDASLoA(loaLevelMapper.mapSTORKQAAToeIDASQAA(mappedStorkQAA)); + + } + } + } } //if no QAA level is set in MOASession then set default QAA level - if (MiscUtil.isEmpty(authData.getQAALevel())) { - Logger.info("No QAA level found. Set to default level " + PVPConstants.STORK_QAA_PREFIX + "1"); + if (MiscUtil.isEmpty(authData.getEIDASQAALevel())) { + Logger.info("No QAA level found. Set to default level " + EAAFConstants.EIDAS_LOA_LOW); authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + "1"); + authData.seteIDASLoA(EAAFConstants.EIDAS_LOA_LOW); } @@ -433,65 +321,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } - - //#################################################### - //set isForeigner flag - //TODO: change to new eIDAS-token attribute identifier - if (session.getGenericDataFromSession(PVPConstants.EID_STORK_TOKEN_NAME) != null) { - Logger.debug("Find PVP-Attr: " + PVPConstants.EID_STORK_TOKEN_FRIENDLY_NAME - + " --> Set 'isForeigner' flag to TRUE"); - authData.setForeigner(true); - - } else { - authData.setForeigner(session.isForeigner()); - - } - - - //#################################################### - //set citizen country-code - includedToGenericAuthData.remove(PVPConstants.EID_ISSUING_NATION_NAME); - String pvpCCCAttr = session.getGenericDataFromSession(PVPConstants.EID_ISSUING_NATION_NAME, String.class); - if (MiscUtil.isNotEmpty(pvpCCCAttr)) { - authData.setCcc(pvpCCCAttr); - Logger.debug("Find PVP-Attr: " + PVPConstants.EID_ISSUING_NATION_FRIENDLY_NAME); - - } else { - if (authData.isForeigner()) { - try { - if (authData.getSignerCertificate() != null) { - //TODO: replace with TSL lookup when TSL is ready! - X509Certificate certificate = new X509Certificate(authData.getSignerCertificate()); - if (certificate != null) { - LdapName ln = new LdapName(certificate.getIssuerDN() - .getName()); - for (Rdn rdn : ln.getRdns()) { - if (rdn.getType().equalsIgnoreCase("C")) { - Logger.info("C is: " + rdn.getValue()); - authData.setCcc(rdn.getValue().toString()); - break; - } - } - } - - } else - Logger.warn("NO PVP-Attr: " + PVPConstants.EID_ISSUING_NATION_NAME - + " and NO SignerCertificate in MOASession -->" - + " Can NOT extract citizen-country of foreign person."); - - - } catch (Exception e) { - Logger.error("Failed to extract country code from certificate with message: " + e.getMessage()); - - } - - } else { - authData.setCcc(COUNTRYCODE_AUSTRIA); - - } - } - - + //#################################################### //set max. SSO session time includedToGenericAuthData.remove(AuthenticationSessionStorageConstants.FEDERATION_RESPONSE_VALIDE_TO); @@ -620,11 +450,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { includedToGenericAuthData.remove(PVPConstants.MANDATE_PROF_REP_OID_NAME); } } - - - - - + //#################################################### // set bPK and IdentityLink for Organwalter --> // Organwalter has a special bPK is received from MIS @@ -634,111 +460,14 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { authData.setBPK(misMandate.getOWbPK()); authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); Logger.trace("Authenticated User is OW: " + misMandate.getOWbPK()); - - - //TODO: check in case of mandates for business services - if (identityLink != null) - authData.setIdentityLink(identityLink); - - else if (idlFromPVPAttr != null){ - authData.setIdentityLink(idlFromPVPAttr); - Logger.debug("Set IdentityLink received from federated IDP for Organwalter"); - - } else - Logger.info("Can NOT set Organwalter IdentityLink. Msg: No IdentityLink found"); - - + //set bPK and IdenityLink for all other - } else { - //build bPK - String pvpbPKValue = getbPKValueFromPVPAttribute(session); - String pvpbPKTypeAttr = getbPKTypeFromPVPAttribute(session); - Pair<String, String> pvpEncbPKAttr = getEncryptedbPKFromPVPAttribute(session, authData, oaParam); - - //check if a unique ID for this citizen exists - if (MiscUtil.isEmpty(authData.getIdentificationValue()) && - MiscUtil.isEmpty(pvpbPKValue) && MiscUtil.isEmpty(authData.getBPK()) && - pvpEncbPKAttr == null) { - Logger.info("Can not build authData, because moaSession include no bPK, encrypted bPK or baseID"); - throw new MOAIDException("builder.08", new Object[]{"No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME - + " or " + PVPConstants.ENC_BPK_LIST_FRIENDLY_NAME}); - - } - - // baseID is in MOASesson --> calculate bPK directly - if (MiscUtil.isNotEmpty(authData.getIdentificationValue())) { - Logger.debug("Citizen baseID is in MOASession --> calculate bPK from this."); - Pair<String, String> result = buildOAspecificbPK(protocolRequest, oaParam, authData); - authData.setBPK(result.getFirst()); - authData.setBPKType(result.getSecond()); - - //check if bPK already added to AuthData matches OA - } else if (MiscUtil.isNotEmpty(authData.getBPK()) - && matchsReceivedbPKToOnlineApplication(oaParam, authData.getBPKType()) ) { - Logger.debug("Correct bPK is already included in AuthData."); - - //check if bPK received by PVP-Attribute matches OA - } else if (MiscUtil.isNotEmpty(pvpbPKValue) && - matchsReceivedbPKToOnlineApplication(oaParam, pvpbPKTypeAttr)) { - Logger.debug("Receive correct bPK from PVP-Attribute"); - authData.setBPK(pvpbPKValue); - authData.setBPKType(pvpbPKTypeAttr); - - //check if decrypted bPK exists - } else if (pvpEncbPKAttr != null) { - Logger.debug("Receive bPK as encrypted bPK and decryption was possible."); - authData.setBPK(pvpEncbPKAttr.getFirst()); - authData.setBPKType(pvpEncbPKAttr.getSecond()); + Logger.debug("User is an OW. Set original IDL into authdata ... "); + authData.setIdentityLink(session.getIdentityLink()); - //ask SZR to get bPK - } else { - String notValidbPK = authData.getBPK(); - String notValidbPKType = authData.getBPKType(); - if (MiscUtil.isEmpty(notValidbPK) && - MiscUtil.isEmpty(notValidbPKType)) { - notValidbPK = pvpbPKValue; - notValidbPKType = pvpbPKTypeAttr; - - if (MiscUtil.isEmpty(notValidbPK) && - MiscUtil.isEmpty(notValidbPKType)) { - Logger.fatal("No bPK in MOASession. THIS error should not occur any more."); - throw new NullPointerException("No bPK in MOASession. THIS error should not occur any more."); - } - } - - Pair<String, String> baseIDFromSZR = getbaseIDFromSZR(authData, notValidbPK, notValidbPKType); - if (baseIDFromSZR != null) { - Logger.info("Receive citizen baseID from SRZ. Authentication can be completed"); - authData.setIdentificationValue(baseIDFromSZR.getFirst()); - authData.setIdentificationType(baseIDFromSZR.getSecond()); - Pair<String, String> result = buildOAspecificbPK(protocolRequest, oaParam, authData); - authData.setBPK(result.getFirst()); - authData.setBPKType(result.getSecond()); - - } else { - Logger.warn("Can not build authData, because moaSession include no valid bPK, encrypted bPK or baseID"); - throw new MOAIDException("builder.08", new Object[]{"No valid " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME - + " or " + PVPConstants.ENC_BPK_LIST_FRIENDLY_NAME}); - - } - } - - //build IdentityLink - if (identityLink != null) - authData.setIdentityLink(buildOAspecificIdentityLink(oaParam, identityLink, authData.getBPK(), authData.getBPKType())); - else if (idlFromPVPAttr != null) { - authData.setIdentityLink(buildOAspecificIdentityLink(oaParam, idlFromPVPAttr, authData.getBPK(), authData.getBPKType())); - Logger.debug("Set IdentityLink received from federated IDP"); - } else { - Logger.info("Can NOT set IdentityLink. Msg: No IdentityLink found"); - - } - } - + } //################################################################### //set PVP role attribute (implemented for ISA 1.18 action) @@ -786,6 +515,9 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } + //build foreign bPKs + generateForeignbPK(authData, oaParam.foreignbPKSectorsRequested()); + //#################################################################### //copy all generic authentication information, which are not processed before to authData Iterator<String> copyInterator = includedToGenericAuthData.iterator(); @@ -794,13 +526,13 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { try { authData.setGenericData(elementKey, session.getGenericDataFromSession(elementKey)); - } catch (SessionDataStorageException e) { + } catch (EAAFStorageException e) { Logger.warn("Can not add generic authData with key:" + elementKey, e); } } - } catch (BuildException e) { + } catch (EAAFBuilderException e) { throw e; } catch (Throwable ex) { @@ -809,38 +541,6 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } - - /** - * Check a bPK-Type against a Service-Provider configuration <br> - * If bPK-Type is <code>null</code> the result is <code>false</code>. - * - * @param oaParam Service-Provider configuration, never null - * @param bPKType bPK-Type to check - * @return true, if bPK-Type matchs to Service-Provider configuration, otherwise false - * @throws ConfigurationException - */ - private boolean matchsReceivedbPKToOnlineApplication(IOAAuthParameters oaParam, String bPKType) throws ConfigurationException { - return oaParam.getAreaSpecificTargetIdentifier().equals(bPKType); - - } - - private void parseBasicUserInfosFromIDL(AuthenticationData authData, IIdentityLink identityLink, Collection<String> includedGenericSessionData) { - //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO - authData.setIdentificationValue(identityLink.getIdentificationValue()); - authData.setIdentificationType(identityLink.getIdentificationType()); - - authData.setGivenName(identityLink.getGivenName()); - authData.setFamilyName(identityLink.getFamilyName()); - authData.setDateOfBirth(identityLink.getDateOfBirth()); - - //remove corresponding keys from genericSessionData if exists - includedGenericSessionData.remove(PVPConstants.PRINCIPAL_NAME_NAME); - includedGenericSessionData.remove(PVPConstants.GIVEN_NAME_NAME); - includedGenericSessionData.remove(PVPConstants.BIRTHDATE_NAME); - includedGenericSessionData.remove(PVPConstants.EID_SOURCE_PIN_NAME); - includedGenericSessionData.remove(PVPConstants.EID_SOURCE_PIN_TYPE_NAME); - - } /** * @param authData @@ -848,7 +548,8 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { * @param notValidbPKType * @return */ - private Pair<String, String> getbaseIDFromSZR(AuthenticationData authData, String notValidbPK, + @Override + protected Pair<String, String> getbaseIDFromSZR(AuthenticationData authData, String notValidbPK, String notValidbPKType) { try { EgovUtilPropertiesConfiguration eGovClientsConfig = authConfig.geteGovUtilsConfig(); @@ -903,7 +604,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { * MOASession as 'GenericData' <br> <pre><code>session.getGenericDataFromSession(PVPConstants.ENC_BPK_LIST_NAME, String.class)</code></pre> * to <code>authData</code> * - * @param session MOASession, but never null + * @param authProcessDataContainer MOASession, but never null * @param authData AuthenticationData DAO * @param spConfig Service-Provider configuration * @@ -911,194 +612,123 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { * or <code>null</code> if no attribute exists or can not decrypted * @throws ConfigurationException */ - private Pair<String, String> getEncryptedbPKFromPVPAttribute(IAuthenticationSession session, - AuthenticationData authData, IOAAuthParameters spConfig) throws ConfigurationException { - //set List of encrypted bPKs to authData DAO - String pvpEncbPKListAttr = session.getGenericDataFromSession(PVPConstants.ENC_BPK_LIST_NAME, String.class); - if (MiscUtil.isNotEmpty(pvpEncbPKListAttr)) { - List<String> encbPKList = Arrays.asList(pvpEncbPKListAttr.split(";")); - authData.setEncbPKList(encbPKList); - - //check if one of this encrypted bPK could be decrypt for this Service-Provider - for (String fullEncbPK : encbPKList) { - int index = fullEncbPK.indexOf("|"); - if (index >= 0) { - String encbPK = fullEncbPK.substring(index+1); - String second = fullEncbPK.substring(0, index); - int secIndex = second.indexOf("+"); - if (secIndex >= 0) { - String oaTargetId = spConfig.getAreaSpecificTargetIdentifier(); - if (oaTargetId.startsWith(MOAIDAuthConstants.PREFIX_CDID)) { - String publicServiceShortTarget = oaTargetId.substring(MOAIDAuthConstants.PREFIX_CDID.length()); - if (publicServiceShortTarget.equals(second.substring(secIndex+1))) { - Logger.debug("Found encrypted bPK for online-application " - + spConfig.getPublicURLPrefix() - + " Start decryption process ..."); - PrivateKey privKey = spConfig.getBPKDecBpkDecryptionKey(); - if (privKey != null) { - try { - String bPK = BPKBuilder.decryptBPK(encbPK, publicServiceShortTarget, privKey); - if (MiscUtil.isNotEmpty(bPK)) { - Logger.info("bPK decryption process finished successfully."); - return Pair.newInstance(bPK, oaTargetId); - - } else { - Logger.error("bPK decryption FAILED."); - + @Override + protected Pair<String, String> getEncryptedbPKFromPVPAttribute(IAuthProcessDataContainer authProcessDataContainer, + AuthenticationData authData, ISPConfiguration spConfig) throws EAAFBuilderException { + //set List of encrypted bPKs to authData DAO + if (authData instanceof MOAAuthenticationData && + spConfig instanceof IOAAuthParameters) { + + String pvpEncbPKListAttr = authProcessDataContainer.getGenericDataFromSession(PVPConstants.ENC_BPK_LIST_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpEncbPKListAttr)) { + List<String> encbPKList = Arrays.asList(pvpEncbPKListAttr.split(";")); + ((MOAAuthenticationData) authData).setEncbPKList(encbPKList); + + //check if one of this encrypted bPK could be decrypt for this Service-Provider + for (String fullEncbPK : encbPKList) { + int index = fullEncbPK.indexOf("|"); + if (index >= 0) { + String encbPK = fullEncbPK.substring(index+1); + String second = fullEncbPK.substring(0, index); + int secIndex = second.indexOf("+"); + if (secIndex >= 0) { + String oaTargetId = spConfig.getAreaSpecificTargetIdentifier(); + if (oaTargetId.startsWith(MOAIDAuthConstants.PREFIX_CDID)) { + String publicServiceShortTarget = oaTargetId.substring(MOAIDAuthConstants.PREFIX_CDID.length()); + if (publicServiceShortTarget.equals(second.substring(secIndex+1))) { + Logger.debug("Found encrypted bPK for online-application " + + spConfig.getUniqueIdentifier() + + " Start decryption process ..."); + PrivateKey privKey = ((IOAAuthParameters) spConfig).getBPKDecBpkDecryptionKey(); + if (privKey != null) { + try { + String bPK = BPKBuilder.decryptBPK(encbPK, publicServiceShortTarget, privKey); + if (MiscUtil.isNotEmpty(bPK)) { + Logger.info("bPK decryption process finished successfully."); + return Pair.newInstance(bPK, oaTargetId); + + } else { + Logger.error("bPK decryption FAILED."); + + } + } catch (EAAFBuilderException e) { + Logger.error("bPK decryption FAILED.", e); + } - } catch (BuildException e) { - Logger.error("bPK decryption FAILED.", e); - } + } else { + Logger.info("bPK decryption FAILED, because no valid decryption key is found."); + + } } else { - Logger.info("bPK decryption FAILED, because no valid decryption key is found."); + Logger.info("Found encrypted bPK but " + + "encrypted bPK target does not match to online-application target"); - } + } } else { - Logger.info("Found encrypted bPK but " + - "encrypted bPK target does not match to online-application target"); + Logger.info("Encrypted bPKs are only allowed for public services with prefix: " + MOAIDAuthConstants.PREFIX_CDID + + " BUT oaTarget is " + oaTargetId); } - - } else { - Logger.info("Encrypted bPKs are only allowed for public services with prefix: " + MOAIDAuthConstants.PREFIX_CDID - + " BUT oaTarget is " + oaTargetId); - - } - } - } - } - } - - return null; - } - - /** - * Get bPK from PVP Attribute 'BPK_NAME', which could be exist in - * MOASession as 'GenericData' <br> <pre><code>session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class)</code></pre> - * - * @param session MOASession, but never null - * @return bPK, which was received by PVP-Attribute, or <code>null</code> if no attribute exists - */ - private String getbPKValueFromPVPAttribute(IAuthenticationSession session) { - String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class); - if (MiscUtil.isNotEmpty(pvpbPKValueAttr)) { - - //fix a wrong bPK-value prefix, which was used in some PVP Standardportal implementations - if (pvpbPKValueAttr.startsWith("bPK:")) { - Logger.warn("Attribute " + PVPConstants.BPK_NAME - + " contains a not standardize prefix! Staring attribute value correction process ..."); - pvpbPKValueAttr = pvpbPKValueAttr.substring("bPK:".length()); - - } - - String[] spitted = pvpbPKValueAttr.split(":"); - if (spitted.length != 2) { - Logger.warn("Attribute " + PVPConstants.BPK_NAME + " has a wrong encoding and can NOT be USED!" - + " Value:" + pvpbPKValueAttr); - return null; - + } + } + } } - Logger.debug("Find PVP-Attr: " + PVPConstants.BPK_FRIENDLY_NAME); - return spitted[1]; - } + } else + Logger.warn("AuthData: " + authData.getClass().getName() + " or spConfig: " + spConfig.getClass().getName() + + " are not MOAID data-objects"); return null; } - /** - * Get bPK-Type from PVP Attribute 'EID_SECTOR_FOR_IDENTIFIER_NAME', which could be exist in - * MOASession as 'GenericData' <br> <pre><code>session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)</code></pre> - * - * @param session MOASession, but never null - * @return bPKType, which was received by PVP-Attribute, or <code>null</code> if no attribute exists - */ - private String getbPKTypeFromPVPAttribute(IAuthenticationSession session) { - String pvpbPKTypeAttr = session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class); - if (MiscUtil.isNotEmpty(pvpbPKTypeAttr)) { - - //fix a wrong bPK-Type encoding, which was used in some PVP Standardportal implementations - if (pvpbPKTypeAttr.startsWith(Constants.URN_PREFIX_CDID) && - !pvpbPKTypeAttr.substring(Constants.URN_PREFIX_CDID.length(), - Constants.URN_PREFIX_CDID.length() + 1).equals("+")) { - Logger.warn("Receive uncorrect encoded bBKType attribute " + pvpbPKTypeAttr + " Starting attribute value correction ... "); - pvpbPKTypeAttr = Constants.URN_PREFIX_CDID + "+" + pvpbPKTypeAttr.substring(Constants.URN_PREFIX_CDID.length() + 1); - - } - Logger.debug("Find PVP-Attr: " + PVPConstants.EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME); - return pvpbPKTypeAttr; - } - - return null; - - - /* - * INFO: This code could be used to extract the bPKType from 'PVPConstants.BPK_NAME', - * because the prefix of BPK_NAME attribute contains the postfix of the bPKType - * - * Now, all PVP Standardportals should be able to send 'EID_SECTOR_FOR_IDENTIFIER' - * PVP attributes - */ -// String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class); -// String[] spitted = pvpbPKValueAttr.split(":"); -// if (MiscUtil.isEmpty(authData.getBPKType())) { -// Logger.debug("PVP assertion contains NO bPK/wbPK target attribute. " + -// "Starting target extraction from bPK/wbPK prefix ..."); -// //exract bPK/wbPK type from bpk attribute value prefix if type is -// //not transmitted as single attribute -// Pattern pattern = Pattern.compile("[a-zA-Z]{2}(-[a-zA-Z]+)?"); -// Matcher matcher = pattern.matcher(spitted[0]); -// if (matcher.matches()) { -// //find public service bPK -// authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + spitted[0]); -// Logger.debug("Found bPK prefix. Set target to " + authData.getBPKType()); -// -// } else { -// //find business service wbPK -// authData.setBPKType(Constants.URN_PREFIX_WBPK+ "+" + spitted[0]); -// Logger.debug("Found wbPK prefix. Set target to " + authData.getBPKType()); -// -// } -// } - - } + @Override + protected IIdentityLink buildOAspecificIdentityLink(ISPConfiguration spConfig, IIdentityLink idl, String bPK, String bPKType) throws EAAFConfigurationException, XPathException, DOMException, EAAFParserException { + if (spConfig.hasBaseIdTransferRestriction()) { + try { + Element idlassertion = idl.getSamlAssertion(); + + //set bpk/wpbk; + Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); + prIdentification.getFirstChild().setNodeValue(bPK); - private IIdentityLink buildOAspecificIdentityLink(IOAAuthParameters oaParam, IIdentityLink idl, String bPK, String bPKType) throws MOAIDException { - if (oaParam.hasBaseIdTransferRestriction()) { - Element idlassertion = idl.getSamlAssertion(); - //set bpk/wpbk; - Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - prIdentification.getFirstChild().setNodeValue(bPK); - //set bkp/wpbk type - Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); - prIdentificationType.getFirstChild().setNodeValue(bPKType); + //set bkp/wpbk type + Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); + prIdentificationType.getFirstChild().setNodeValue(bPKType); - IdentityLinkAssertionParser idlparser = new IdentityLinkAssertionParser(idlassertion); - IIdentityLink businessServiceIdl = idlparser.parseIdentityLink(); + IdentityLinkAssertionParser idlparser = new IdentityLinkAssertionParser(idlassertion); + IIdentityLink businessServiceIdl = idlparser.parseIdentityLink(); - //resign IDL - IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); - Element resignedilAssertion; - - if (authConfig.isIdentityLinkResigning()) { - resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion(), authConfig.getIdentityLinkResigningKey()); - } else { - resignedilAssertion = businessServiceIdl.getSamlAssertion(); + //resign IDL + IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); + Element resignedilAssertion; + + if (authConfig.isIdentityLinkResigning()) { + resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion(), authConfig.getIdentityLinkResigningKey()); + } else { + resignedilAssertion = businessServiceIdl.getSamlAssertion(); + } + + IdentityLinkAssertionParser resignedIDLParser = new IdentityLinkAssertionParser(resignedilAssertion); + return resignedIDLParser.parseIdentityLink(); + + } catch (MOAIDException e) { + Logger.warn("Can not build OA specific IDL. Reason: " + e.getMessage(), e); + throw new EAAFParserException("TODO", null, e); + } - IdentityLinkAssertionParser resignedIDLParser = new IdentityLinkAssertionParser(resignedilAssertion); - return resignedIDLParser.parseIdentityLink(); } else return idl; - - - } - - - private Pair<String, String> buildOAspecificbPK(IRequest pendingReq, IOAAuthParameters oaParam, AuthenticationData authData) throws BuildException, ConfigurationException { + + } + + + @Override + protected Pair<String, String> buildOAspecificbPK(IRequest pendingReq, AuthenticationData authData) throws EAAFBuilderException { + ISPConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); String baseID = authData.getIdentificationValue(); String baseIDType = authData.getIdentificationType(); @@ -1140,4 +770,58 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } + private void generateForeignbPK(MOAAuthenticationData authData, List<String> foreignSectors) { + if (foreignSectors != null && !foreignSectors.isEmpty()) { + Logger.debug("Sectors for foreign bPKs are configurated. Starting foreign bPK generation ... "); + for (String foreignSector : foreignSectors) { + Logger.trace("Process sector: " + foreignSector + " ... "); + if (encKeyMap.containsKey(foreignSector)) { + try { + String sector = null; + //splitt sector into VKZ and target + if (foreignSector.startsWith("wbpk")) { + Logger.trace("Find foreign private sector " + foreignSector); + sector = Constants.URN_PREFIX + ":" + foreignSector; + + } else { + String[] split = foreignSector.split("+"); + if (split.length != 2) { + Logger.warn("Foreign sector: " + foreignSector + " looks WRONG. IGNORE IT!"); + + } else { + Logger.trace("Find foreign public sector. VKZ: " + split[0] + " Target: " + split[1]); + sector = Constants.URN_PREFIX_CDID + "+" + split[1]; + + } + + } + + if (sector != null) { + Pair<String, String> bpk = new BPKBuilder().generateAreaSpecificPersonIdentifier( + authData.getIdentificationValue(), + authData.getIdentificationType(), + sector); + String foreignbPK = BPKBuilder.encryptBPK(bpk.getFirst(), bpk.getSecond(), encKeyMap.get(foreignSector).getPublicKey()); + authData.getEncbPKList().add("(" + foreignSector + "|" + foreignbPK + ")"); + Logger.debug("Foreign bPK for sector: " + foreignSector + " created."); + + } + + } catch (Exception e) { + Logger.warn("Foreign bPK generation FAILED for sector: " + foreignSector, e); + + } + + } else { + Logger.info("NO encryption cerfificate FOUND in configuration for sector: " + foreignSector); + Logger.info("Foreign bPK for sector: " + foreignSector + " is NOT possible"); + + } + } + + } else + Logger.debug("No foreign bPKs required for this service provider"); + + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java deleted file mode 100644 index a7f6e873f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java +++ /dev/null @@ -1,359 +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. - ******************************************************************************/ -/* - * 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.auth.builder; - -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.text.SimpleDateFormat; -import java.util.Date; - -import javax.crypto.BadPaddingException; -import javax.crypto.Cipher; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; - -import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.data.Pair; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Base64Utils; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * Builder for the bPK, as defined in - * <code>"Ableitung f¨r die bereichsspezifische Personenkennzeichnung"</code> - * version <code>1.0.1</code> from <code>"reference.e-government.gv.at"</code>. - * - * @author Paul Schamberger - * @version $Id$ - */ -public class BPKBuilder { - - /** - * Calculates an area specific unique person-identifier from a baseID - * - * @param baseID baseId from user but never null - * @param targetIdentifier target identifier for area specific identifier calculation but never null - * @return Pair<unique person identifier for this target, targetArea> but never null - * @throws BuildException if some input data are not valid - */ - public Pair<String, String> generateAreaSpecificPersonIdentifier(String baseID, String targetIdentifier) throws BuildException{ - return generateAreaSpecificPersonIdentifier(baseID, Constants.URN_PREFIX_BASEID, targetIdentifier); - - } - - /** - * Calculates an area specific unique person-identifier from an unique identifier with a specific type - * - * @param baseID baseId from user but never null - * @param baseIdType Type of the baseID but never null - * @param targetIdentifier target identifier for area specific identifier calculation but never null - * @return Pair<unique person identifier for this target, targetArea> but never null - * @throws BuildException if some input data are not valid - */ - public Pair<String, String> generateAreaSpecificPersonIdentifier(String baseID, String baseIdType, String targetIdentifier) throws BuildException{ - if (MiscUtil.isEmpty(baseID)) - throw new BuildException("builder.00", new Object[]{"baseID is empty or null"}); - - if (MiscUtil.isEmpty(baseIdType)) - throw new BuildException("builder.00", new Object[]{"the type of baseID is empty or null"}); - - if (MiscUtil.isEmpty(targetIdentifier)) - throw new BuildException("builder.00", new Object[]{"OA specific target identifier is empty or null"}); - - if (baseIdType.equals(Constants.URN_PREFIX_BASEID)) { - Logger.trace("Find baseID. Starting unique identifier caluclation for this target"); - - if (targetIdentifier.startsWith(MOAIDAuthConstants.PREFIX_CDID) || - targetIdentifier.startsWith(MOAIDAuthConstants.PREFIX_WPBK) || - targetIdentifier.startsWith(MOAIDAuthConstants.PREFIX_STORK)) { - Logger.trace("Calculate bPK, wbPK, or STORK identifier for target: " + targetIdentifier); - return Pair.newInstance(calculatebPKwbPK(baseID + "+" + targetIdentifier), targetIdentifier); - - } else if (targetIdentifier.startsWith(MOAIDAuthConstants.PREFIX_EIDAS)) { - Logger.trace("Calculate eIDAS identifier for target: " + targetIdentifier); - String[] splittedTarget = targetIdentifier.split("\\+"); - String cititzenCountryCode = splittedTarget[1]; - String eIDASOutboundCountry = splittedTarget[2]; - - if (cititzenCountryCode.equalsIgnoreCase(eIDASOutboundCountry)) { - Logger.warn("Suspect configuration FOUND!!! CitizenCountry equals DestinationCountry"); - - } - return buildeIDASIdentifer(baseID, baseIdType, cititzenCountryCode, eIDASOutboundCountry); - - - } else - throw new BuildException("builder.00", - new Object[]{"Target identifier: " + targetIdentifier + " is NOT allowed or unknown"}); - - } else { - Logger.trace("BaseID is not of type " + Constants.URN_PREFIX_BASEID + ". Check type against requested target ..."); - if (baseIdType.equals(targetIdentifier)) { - Logger.debug("Unique identifier is already area specific. Is nothing todo"); - return Pair.newInstance(baseID, targetIdentifier); - - } else { - Logger.warn("Get unique identifier for target: " + baseIdType + " but target: " + targetIdentifier + " is required!"); - throw new BuildException("builder.00", - new Object[]{"Get unique identifier for target: " + baseIdType + " but target: " + targetIdentifier + " is required"}); - - } - } - } - - - /** - * Builds the storkeid from the given parameters. - * - * @param baseID baseID of the citizen - * @param baseIDType Type of the baseID - * @param sourceCountry CountryCode of that country, which build the eIDAs ID - * @param destinationCountry CountryCode of that country, which receives the eIDAs ID - * - * @return Pair<eIDAs, bPKType> in a BASE64 encoding - * @throws BuildException if an error occurs on building the wbPK - */ - private Pair<String, String> buildeIDASIdentifer(String baseID, String baseIDType, String sourceCountry, String destinationCountry) - throws BuildException { - String bPK = null; - String bPKType = null; - - // check if we have been called by public sector application - if (baseIDType.startsWith(Constants.URN_PREFIX_BASEID)) { - bPKType = Constants.URN_PREFIX_EIDAS + "+" + sourceCountry + "+" + destinationCountry; - Logger.debug("Building eIDAS identification from: [identValue]+" + bPKType); - bPK = calculatebPKwbPK(baseID + "+" + bPKType); - - } else { // if not, sector identification value is already calculated by BKU - Logger.debug("eIDAS eIdentifier already provided by BKU"); - bPK = baseID; - } - - if ((MiscUtil.isEmpty(bPK) || - MiscUtil.isEmpty(sourceCountry) || - MiscUtil.isEmpty(destinationCountry))) { - throw new BuildException("builder.00", - new Object[]{"eIDAS-ID", "Unvollständige Parameterangaben: identificationValue=" + - bPK + ", Zielland=" + destinationCountry + ", Ursprungsland=" + sourceCountry}); - } - - Logger.debug("Building eIDAS identification from: " + sourceCountry+"/"+destinationCountry+"/" + "[identValue]"); - String eIdentifier = sourceCountry + "/" + destinationCountry + "/" + bPK; - - return Pair.newInstance(eIdentifier, bPKType); - } - -// /** -// * Builds the bPK from the given parameters. -// * -// * @param identificationValue Base64 encoded "Stammzahl" -// * @param target "Bereich lt. Verordnung des BKA" -// * @return bPK in a BASE64 encoding -// * @throws BuildException if an error occurs on building the bPK -// */ -// private String buildBPK(String identificationValue, String target) -// throws BuildException { -// -// if ((identificationValue == null || -// identificationValue.length() == 0 || -// target == null || -// target.length() == 0)) { -// throw new BuildException("builder.00", -// new Object[]{"BPK", "Unvollständige Parameterangaben: identificationValue=" + -// identificationValue + ",target=" + target}); -// } -// String basisbegriff; -// if (target.startsWith(Constants.URN_PREFIX_CDID + "+")) -// basisbegriff = identificationValue + "+" + target; -// else -// basisbegriff = identificationValue + "+" + Constants.URN_PREFIX_CDID + "+" + target; -// -// return calculatebPKwbPK(basisbegriff); -// } -// -// /** -// * Builds the wbPK from the given parameters. -// * -// * @param identificationValue Base64 encoded "Stammzahl" -// * @param registerAndOrdNr type of register + "+" + number in register. -// * @return wbPK in a BASE64 encoding -// * @throws BuildException if an error occurs on building the wbPK -// */ -// private String buildWBPK(String identificationValue, String registerAndOrdNr) -// throws BuildException { -// -// if ((identificationValue == null || -// identificationValue.length() == 0 || -// registerAndOrdNr == null || -// registerAndOrdNr.length() == 0)) { -// throw new BuildException("builder.00", -// new Object[]{"wbPK", "Unvollständige Parameterangaben: identificationValue=" + -// identificationValue + ",Register+Registernummer=" + registerAndOrdNr}); -// } -// -// String basisbegriff; -// if (registerAndOrdNr.startsWith(Constants.URN_PREFIX_WBPK + "+")) -// basisbegriff = identificationValue + "+" + registerAndOrdNr; -// else -// basisbegriff = identificationValue + "+" + Constants.URN_PREFIX_WBPK + "+" + registerAndOrdNr; -// -// return calculatebPKwbPK(basisbegriff); -// } -// -// private String buildbPKorwbPK(String baseID, String bPKorwbPKTarget) throws BuildException { -// if (MiscUtil.isEmpty(baseID) || -// !(bPKorwbPKTarget.startsWith(Constants.URN_PREFIX_CDID + "+") || -// bPKorwbPKTarget.startsWith(Constants.URN_PREFIX_WBPK + "+") || -// bPKorwbPKTarget.startsWith(Constants.URN_PREFIX_STORK + "+")) ) { -// throw new BuildException("builder.00", -// new Object[]{"bPK/wbPK", "bPK or wbPK target " + bPKorwbPKTarget -// + " has an unkown prefix."}); -// -// } -// -// return calculatebPKwbPK(baseID + "+" + bPKorwbPKTarget); -// -// } - - public static String encryptBPK(String bpk, String target, PublicKey publicKey) throws BuildException { - MiscUtil.assertNotNull(bpk, "BPK"); - MiscUtil.assertNotNull(publicKey, "publicKey"); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); - if (target.startsWith(Constants.URN_PREFIX_CDID + "+")) - target = target.substring((Constants.URN_PREFIX_CDID + "+").length()); - - String input = "V1::urn:publicid:gv.at:cdid+" + target + "::" - + bpk + "::" - + sdf.format(new Date()); - System.out.println(input); - byte[] result; - try { - byte[] inputBytes = input.getBytes("ISO-8859-1"); - result = encrypt(inputBytes, publicKey); - return new String(Base64Utils.encode(result, "ISO-8859-1")).replaceAll("\r\n", ""); - - } catch (Exception e) { - throw new BuildException("bPK encryption FAILED", null, e); - } - } - - public static String decryptBPK(String encryptedBpk, String target, PrivateKey privateKey) throws BuildException { - MiscUtil.assertNotEmpty(encryptedBpk, "Encrypted BPK"); - MiscUtil.assertNotNull(privateKey, "Private key"); - String decryptedString; - try { - byte[] encryptedBytes = Base64Utils.decode(encryptedBpk, false, "ISO-8859-1"); - byte[] decryptedBytes = decrypt(encryptedBytes, privateKey); - decryptedString = new String(decryptedBytes, "ISO-8859-1"); - - } catch (Exception e) { - throw new BuildException("bPK decryption FAILED", null, e); - } - String tmp = decryptedString.substring(decryptedString.indexOf('+') + 1); - String sector = tmp.substring(0, tmp.indexOf("::")); - tmp = tmp.substring(tmp.indexOf("::") + 2); - String bPK = tmp.substring(0, tmp.indexOf("::")); - - if (target.startsWith(Constants.URN_PREFIX_CDID + "+")) - target = target.substring((Constants.URN_PREFIX_CDID + "+").length()); - - if (target.equals(sector)) - return bPK; - - else { - Logger.error("Decrypted bPK does not match to request bPK target."); - return null; - } - } - - private String calculatebPKwbPK(String basisbegriff) throws BuildException { - try { - MessageDigest md = MessageDigest.getInstance("SHA-1"); - byte[] hash = md.digest(basisbegriff.getBytes("ISO-8859-1")); - String hashBase64 = Base64Utils.encode(hash); - return hashBase64; - - } catch (Exception ex) { - throw new BuildException("builder.00", new Object[]{"bPK/wbPK", ex.toString()}, ex); - } - - } - - private static byte[] encrypt(byte[] inputBytes, PublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { - byte[] result; - Cipher cipher = null; - try { - cipher = Cipher.getInstance("RSA/ECB/OAEPPadding"); // try with bouncycastle - } catch(NoSuchAlgorithmException e) { - cipher = Cipher.getInstance("RSA/ECB/OAEP"); // try with iaik provider - } - cipher.init(Cipher.ENCRYPT_MODE, publicKey); - result = cipher.doFinal(inputBytes); - - return result; - } - - private static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey) - throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{ - byte[] result; - Cipher cipher = null; - try { - cipher = Cipher.getInstance("RSA/ECB/OAEPPadding"); // try with bouncycastle - } catch(NoSuchAlgorithmException e) { - cipher = Cipher.getInstance("RSA/ECB/OAEP"); // try with iaik provider - } - cipher.init(Cipher.DECRYPT_MODE, privateKey); - result = cipher.doFinal(encryptedBytes); - return result; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilder.java index 4c4af4239..399ecc022 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilder.java @@ -50,11 +50,12 @@ import java.text.MessageFormat; import java.util.Calendar; import java.util.List; +import at.gv.egiz.eaaf.core.api.IRequest; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; 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.config.TargetToSectorNameMapper; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameterDecorator; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DateTimeUtils; import at.gv.egovernment.moa.util.MiscUtil; @@ -185,12 +186,12 @@ public class CreateXMLSignatureRequestBuilder implements Constants { } public static String buildForeignIDTextToBeSigned(String subject, IRequest pendingReq) throws ConfigurationException { - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + IOAAuthParameters oaParam = pendingReq.getServiceProviderConfiguration(OAAuthParameterDecorator.class); String target = null; String sectorName = null; - String saml1Target = pendingReq.getGenericData( + String saml1Target = pendingReq.getRawData( MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, String.class); if (MiscUtil.isNotEmpty(saml1Target)) { target = saml1Target; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DataURLBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DataURLBuilder.java deleted file mode 100644 index c78361eda..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DataURLBuilder.java +++ /dev/null @@ -1,109 +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. - ******************************************************************************/ -/* - * 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.auth.builder; - -import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; - -/** - * Builds a DataURL parameter meant for the security layer implementation - * to respond to. - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class DataURLBuilder { - - /** - * Constructor for DataURLBuilder. - */ - public DataURLBuilder() { - super(); - } - - /** - * Constructs a data URL for <code>VerifyIdentityLink</code> or <code>VerifyAuthenticationBlock</code>, - * including the <code>MOASessionID</code> as a parameter. - * - * @param authBaseURL base URL (context path) of the MOA ID Authentication component, - * including a trailing <code>'/'</code> - * @param authServletName request part of the data URL - * @param sessionID sessionID to be included in the dataURL - * @return String - */ - public String buildDataURL(String authBaseURL, String authServletName, String sessionID) { - String dataURL; - if (!authBaseURL.endsWith("/")) - authBaseURL += "/"; - - if (authServletName.startsWith("/")) - authServletName = authServletName.substring(1); - - dataURL = authBaseURL + authServletName; - - dataURL = addParameter(dataURL, MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, sessionID); - return dataURL; - } - - /** - * Method addParameter. - * @param urlString represents the url - * @param paramname is the parameter to be added - * @param value is the value of that parameter - * @return String - */ - private String addParameter(String urlString, String paramname, String value) { - String url = urlString; - if (paramname != null) { - if (url.indexOf("?") < 0) - url += "?"; - else - url += "&"; - url += paramname + "=" + value; - } - return url; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DynamicOAAuthParameterBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DynamicOAAuthParameterBuilder.java index fc5489673..e600505a2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DynamicOAAuthParameterBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/DynamicOAAuthParameterBuilder.java @@ -27,12 +27,12 @@ import java.util.List; import org.opensaml.saml2.core.Attribute; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.data.PVPAttributeDefinitions; import at.gv.egovernment.moa.id.auth.exception.DynamicOABuildException; 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.config.auth.data.DynamicOAAuthParameters; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; @@ -50,7 +50,7 @@ public class DynamicOAAuthParameterBuilder { for (Attribute attr : reqAttributes) { //get Target or BusinessService from request - if (attr.getName().equals(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME)) { + if (attr.getName().equals(PVPAttributeDefinitions.EID_SECTOR_FOR_IDENTIFIER_NAME)) { String attrValue = attr.getAttributeValues().get(0).getDOM().getTextContent(); if (attrValue.startsWith(Constants.URN_PREFIX_CDID)) { //dynamicOA.setBusinessService(false); @@ -88,7 +88,6 @@ public class DynamicOAAuthParameterBuilder { DynamicOAAuthParameters dynOAParams = new DynamicOAAuthParameters(); dynOAParams.setApplicationID(oaParam.getPublicURLPrefix()); - dynOAParams.setHasBaseIdProcessingRestriction(oaParam.hasBaseIdInternalProcessingRestriction()); dynOAParams.setHasBaseIdTransfergRestriction(oaParam.hasBaseIdTransferRestriction()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/MOAIDSubjectNameIdGenerator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/MOAIDSubjectNameIdGenerator.java new file mode 100644 index 000000000..3dfba9cca --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/MOAIDSubjectNameIdGenerator.java @@ -0,0 +1,115 @@ +package at.gv.egovernment.moa.id.auth.builder; + +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.w3c.dom.Element; + +import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; +import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; +import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFBuilderException; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BPKBuilder; +import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +import at.gv.egiz.eaaf.modules.pvp2.idp.api.builder.ISubjectNameIdGenerator; +import at.gv.egiz.eaaf.modules.pvp2.idp.exception.ResponderErrorException; +import at.gv.egovernment.moa.id.data.IMOAAuthData; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; +import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.Constants; + +@Service("MOASAML2SubjectNameIDGenerator") +public class MOAIDSubjectNameIdGenerator implements ISubjectNameIdGenerator { + + @Override + public Pair<String, String> generateSubjectNameId(IAuthData authData, ISPConfiguration spConfig) throws PVP2Exception { + //build nameID and nameID Format from moasessio + if (authData instanceof IMOAAuthData && + ((IMOAAuthData)authData).isUseMandate()) { + String bpktype = null; + String bpk = null; + + Element mandate = ((IMOAAuthData)authData).getMandate(); + if(mandate != null) { + Logger.debug("Read mandator bPK|baseID from full-mandate ... "); + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAvailableException(); + } + CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); + PhysicalPersonType pysicalperson = mandateObject.getMandator().getPhysicalPerson(); + + IdentificationType id; + if(corporation != null && corporation.getIdentification().size() > 0) + id = corporation.getIdentification().get(0); + + + else if (pysicalperson != null && pysicalperson.getIdentification().size() > 0) + id = pysicalperson.getIdentification().get(0); + + else { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAvailableException(); + } + + bpktype = id.getType(); + bpk = id.getValue().getValue(); + + } else { + Logger.debug("Read mandator bPK|baseID from PVP attributes ... "); + bpk = authData.getGenericData(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME, String.class); + bpktype = authData.getGenericData(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME, String.class); + + if (StringUtils.isEmpty(bpk)) { + //no sourcePin is included --> search for bPK + bpk = authData.getGenericData(PVPConstants.MANDATE_NAT_PER_BPK_NAME, String.class); + + try { + if (bpk.contains(":")) + bpk = bpk.split(":")[1]; + + } catch (Exception e) { + Logger.warn("Can not split bPK from mandator attribute!", e); + + } + + //set bPK-Type from configuration, because it MUST be equal to service-provider type + bpktype = spConfig.getAreaSpecificTargetIdentifier(); + + } else { + //sourcePin is include --> check sourcePinType + if (StringUtils.isEmpty(bpktype)) + bpktype = Constants.URN_PREFIX_BASEID; + + } + } + + if (StringUtils.isEmpty(bpk) || StringUtils.isEmpty(bpktype)) { + throw new NoMandateDataAvailableException(); + + } + + if (bpktype.equals(Constants.URN_PREFIX_BASEID)) { + try { + return new BPKBuilder().generateAreaSpecificPersonIdentifier(bpk, spConfig.getAreaSpecificTargetIdentifier()); + + } catch (EAAFBuilderException e) { + Logger.warn("Can NOT generate SubjectNameId." , e); + throw new ResponderErrorException("pvp2.01", null); + + } + + } else + return Pair.newInstance(bpk, bpktype); + + } else + return Pair.newInstance(authData.getBPK(), authData.getBPKType()); + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SignatureVerificationUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SignatureVerificationUtils.java index 9ca15c76f..27d983785 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SignatureVerificationUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SignatureVerificationUtils.java @@ -22,6 +22,8 @@ */ package at.gv.egovernment.moa.id.auth.builder; +import java.util.List; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -74,10 +76,15 @@ public class SignatureVerificationUtils { } } - public IVerifiyXMLSignatureResponse verify(byte[] signature, String trustProfileID) throws MOAIDException { + public IVerifiyXMLSignatureResponse verify(byte[] signature, String trustProfileID) throws MOAIDException { + return verify(signature, trustProfileID, null); + + } + + public IVerifiyXMLSignatureResponse verify(byte[] signature, String trustProfileID, List<String> verifyTransformsInfoProfileID) throws MOAIDException { try { //build signature-verification request - Element domVerifyXMLSignatureRequest = build(signature, trustProfileID); + Element domVerifyXMLSignatureRequest = build(signature, trustProfileID, verifyTransformsInfoProfileID); //send signature-verification to MOA-SP Element domVerifyXMLSignatureResponse = SignatureVerificationInvoker.getInstance() @@ -112,7 +119,7 @@ public class SignatureVerificationUtils { * * @throws ParseException */ - private Element build(byte[] signature, String trustProfileID) + private Element build(byte[] signature, String trustProfileID, List<String> verifyTransformsInfoProfileID) throws ParseException { try { @@ -153,6 +160,20 @@ public class SignatureVerificationUtils { requestElem_.appendChild(signatureManifestCheckParamsElem); signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "false"); + //verify transformations + if (verifyTransformsInfoProfileID != null && !verifyTransformsInfoProfileID.isEmpty()) { + Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo"); + signatureManifestCheckParamsElem.appendChild(referenceInfoElem); + for (String element : verifyTransformsInfoProfileID) { + Element verifyTransformsInfoProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfileID"); + referenceInfoElem.appendChild(verifyTransformsInfoProfileIDElem); + verifyTransformsInfoProfileIDElem.appendChild(requestDoc_.createTextNode(element)); + + } + } + + + //hashinput data Element returnHashInputDataElem = requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData"); requestElem_.appendChild(returnHashInputDataElem); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java index 94651915e..cadaec2a0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java @@ -40,18 +40,22 @@ import java.io.Serializable; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.util.ArrayList; +import java.util.Collections; import java.util.Date; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import org.apache.commons.collections4.map.HashedMap; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egovernment.moa.id.commons.api.data.AuthProzessDataConstants; import at.gv.egovernment.moa.id.commons.api.data.ExtendedSAMLAttribute; import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession; -import at.gv.egovernment.moa.id.commons.api.data.IIdentityLink; import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; import at.gv.egovernment.moa.id.commons.api.data.IVerifiyXMLSignatureResponse; -import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.MiscUtil; @@ -65,7 +69,7 @@ import iaik.x509.X509Certificate; * @author Thomas Lenz * */ -public class AuthenticationSession implements Serializable, IAuthenticationSession { +public class AuthenticationSession implements Serializable, IAuthenticationSession, AuthProzessDataConstants { /** * @@ -232,13 +236,17 @@ public class AuthenticationSession implements Serializable, IAuthenticationSessi */ @Override public X509Certificate getSignerCertificate() { - try { - return new X509Certificate(signerCertificate); - } - catch (CertificateException e) { - Logger.warn("Signer certificate can not be loaded from session database!", e); - return null; + if (signerCertificate != null && signerCertificate.length > 0) { + try { + return new X509Certificate(signerCertificate); + } + catch (CertificateException e) { + Logger.warn("Signer certificate can not be loaded from session database!", e); + + } } + + return null; } /* (non-Javadoc) @@ -274,7 +282,7 @@ public class AuthenticationSession implements Serializable, IAuthenticationSessi * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getSessionID() */ @Override - public String getSessionID() { + public String getSSOSessionID() { return sessionID; } @@ -290,7 +298,7 @@ public class AuthenticationSession implements Serializable, IAuthenticationSessi * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setSessionID(java.lang.String) */ @Override - public void setSessionID(String sessionId) { + public void setSSOSessionID(String sessionId) { this.sessionID = sessionId; } @@ -615,17 +623,17 @@ public class AuthenticationSession implements Serializable, IAuthenticationSessi * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setGenericDataToSession(java.lang.String, java.lang.Object) */ @Override - public void setGenericDataToSession(String key, Object object) throws SessionDataStorageException { + public void setGenericDataToSession(String key, Object object) throws EAAFStorageException { if (MiscUtil.isEmpty(key)) { Logger.warn("Generic session-data can not be stored with a 'null' key"); - throw new SessionDataStorageException("Generic session-data can not be stored with a 'null' key", null); + throw new EAAFStorageException("Generic session-data can not be stored with a 'null' key"); } if (object != null) { if (!Serializable.class.isInstance(object)) { Logger.warn("Generic session-data can only store objects which implements the 'Seralizable' interface"); - throw new SessionDataStorageException("Generic session-data can only store objects which implements the 'Seralizable' interface", null); + throw new EAAFStorageException("Generic session-data can only store objects which implements the 'Seralizable' interface"); } } @@ -636,5 +644,35 @@ public class AuthenticationSession implements Serializable, IAuthenticationSessi Logger.trace("Add generic session-data with key:" + key + " to session."); genericSessionDataStorate.put(key, object); + } + + @Override + public Map<String, Object> getKeyValueRepresentationFromAuthSession() { + Map<String, Object> result = new HashMap<String, Object>(); + result.put(FLAG_IS_AUTHENTICATED, isAuthenticated()); + + result.put(FLAG_IS_FOREIGNER, isForeigner()); + result.put(FLAG_IS_ORGANWALTER, isOW()); + result.put(FLAG_SAMLATTRIBUTEGEBEORWBPK, samlAttributeGebeORwbpk); + result.put(FLAG_USE_MANDATE, isMandateUsed()); + + result.put(VALUE_AUTHBLOCK, getAuthBlock()); + result.put(VALUE_AUTNBLOCKTOKKEN, getAuthBlockTokken()); + result.put(VALUE_BKUURL, getBkuURL()); + result.put(VALUE_EXTENTEDSAMLATTRAUTH, getExtendedSAMLAttributesAUTH()); + result.put(VALUE_EXTENTEDSAMLATTROA, getExtendedSAMLAttributesOA()); + result.put(VALUE_IDENTITYLINK, getIdentityLink()); + result.put(VALUE_ISSUEINSTANT, getIssueInstant()); + result.put(VALUE_MISMANDATE, getMISMandate()); + result.put(VALUE_MISREFVALUE, getMandateReferenceValue()); + result.put(VALUE_MISSESSIONID, getMISSessionID()); + result.put(VALUE_QAALEVEL, getQAALevel()); + result.put(VALUE_SIGNER_CERT, getSignerCertificate()); + result.put(VALUE_VERIFYSIGRESP, getXMLVerifySignatureResponse()); + + for (Entry<String, Object> el : genericSessionDataStorate.entrySet()) + result.put(GENERIC_PREFIX + el.getKey(), el.getValue()); + + return Collections.unmodifiableMap(result); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionWrapper.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionWrapper.java index 5419e8ae0..aea6f26fb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionWrapper.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionWrapper.java @@ -25,77 +25,36 @@ package at.gv.egovernment.moa.id.auth.data; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; +import java.util.Collections; import java.util.List; import java.util.Map; +import at.gv.egiz.eaaf.core.api.idp.auth.ISSOManager; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.AuthProcessDataWrapper; import at.gv.egovernment.moa.id.commons.api.data.AuthProzessDataConstants; import at.gv.egovernment.moa.id.commons.api.data.ExtendedSAMLAttribute; import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession; -import at.gv.egovernment.moa.id.commons.api.data.IIdentityLink; import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; import at.gv.egovernment.moa.id.commons.api.data.IVerifiyXMLSignatureResponse; -import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; import iaik.x509.X509Certificate; /** * @author tlenz * */ -public class AuthenticationSessionWrapper implements IAuthenticationSession, AuthProzessDataConstants { +public class AuthenticationSessionWrapper extends AuthProcessDataWrapper implements IAuthenticationSession, AuthProzessDataConstants { - - private Map<String, Object> sessionData; /** * @param genericDataStorage */ public AuthenticationSessionWrapper(Map<String, Object> genericDataStorage) { - this.sessionData = genericDataStorage; - } - - private <T> T wrapStringObject(String key, Object defaultValue, Class<T> clazz) { - if (MiscUtil.isNotEmpty(key)) { - Object obj = sessionData.get(key); - if (obj != null && clazz.isInstance(obj)) - return (T) obj; - } + super(genericDataStorage); - if (defaultValue == null) - return null; - - else if (clazz.isInstance(defaultValue)) - return (T)defaultValue; - - else { - Logger.error("DefaultValue: " + defaultValue.getClass().getName() + " is not of Type:" + clazz.getName()); - throw new IllegalStateException("DefaultValue: " + defaultValue.getClass().getName() + " is not of Type:" + clazz.getName()); - - } } + - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isAuthenticated() - */ - @Override - public boolean isAuthenticated() { - return wrapStringObject(FLAG_IS_AUTHENTICATED, false, Boolean.class); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setAuthenticated(boolean) - */ - @Override - public void setAuthenticated(boolean authenticated) { - sessionData.put(FLAG_IS_AUTHENTICATED, authenticated); - - } - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getSignerCertificate() */ @@ -130,7 +89,7 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut @Override public void setSignerCertificate(X509Certificate signerCertificate) { try { - sessionData.put(VALUE_SIGNER_CERT, signerCertificate.getEncoded()); + authProcessData.put(VALUE_SIGNER_CERT, signerCertificate.getEncoded()); }catch (CertificateEncodingException e) { Logger.warn("Signer certificate can not be stored to session database!", e); @@ -139,38 +98,20 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut } /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getIdentityLink() - */ - @Override - public IIdentityLink getIdentityLink() { - return wrapStringObject(VALUE_IDENTITYLINK, null, IIdentityLink.class); - - } - - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getSessionID() */ @Override - public String getSessionID() { - return wrapStringObject(VALUE_SESSIONID, null, String.class); + public String getSSOSessionID() { + return wrapStringObject(ISSOManager.AUTH_DATA_SSO_SESSIONID, null, String.class); } /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setIdentityLink(at.gv.egovernment.moa.id.auth.data.IdentityLink) - */ - @Override - public void setIdentityLink(IIdentityLink identityLink) { - sessionData.put(VALUE_IDENTITYLINK, identityLink); - - } - - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setSessionID(java.lang.String) */ @Override - public void setSessionID(String sessionId) { - sessionData.put(VALUE_SESSIONID, sessionId); + public void setSSOSessionID(String sessionId) { + authProcessData.put(ISSOManager.AUTH_DATA_SSO_SESSIONID, sessionId); } @@ -187,7 +128,7 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut */ @Override public void setBkuURL(String bkuURL) { - sessionData.put(VALUE_BKUURL, bkuURL); + authProcessData.put(VALUE_BKUURL, bkuURL); } @@ -204,7 +145,7 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut */ @Override public void setAuthBlock(String authBlock) { - sessionData.put(VALUE_AUTHBLOCK, authBlock); + authProcessData.put(VALUE_AUTHBLOCK, authBlock); } @@ -221,7 +162,7 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut */ @Override public void setExtendedSAMLAttributesAUTH(List<ExtendedSAMLAttribute> extendedSAMLAttributesAUTH) { - sessionData.put(VALUE_EXTENTEDSAMLATTRAUTH, extendedSAMLAttributesAUTH); + authProcessData.put(VALUE_EXTENTEDSAMLATTRAUTH, extendedSAMLAttributesAUTH); } @@ -238,7 +179,7 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut */ @Override public void setExtendedSAMLAttributesOA(List<ExtendedSAMLAttribute> extendedSAMLAttributesOA) { - sessionData.put(VALUE_EXTENTEDSAMLATTROA, extendedSAMLAttributesOA); + authProcessData.put(VALUE_EXTENTEDSAMLATTROA, extendedSAMLAttributesOA); } @@ -255,24 +196,7 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut */ @Override public void setSAMLAttributeGebeORwbpk(boolean samlAttributeGebeORwbpk) { - sessionData.put(FLAG_SAMLATTRIBUTEGEBEORWBPK, samlAttributeGebeORwbpk); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getIssueInstant() - */ - @Override - public String getIssueInstant() { - return wrapStringObject(VALUE_ISSUEINSTANT, null, String.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setIssueInstant(java.lang.String) - */ - @Override - public void setIssueInstant(String issueInstant) { - sessionData.put(VALUE_ISSUEINSTANT, issueInstant); + authProcessData.put(FLAG_SAMLATTRIBUTEGEBEORWBPK, samlAttributeGebeORwbpk); } @@ -289,28 +213,11 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut } /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setUseMandates(boolean) - */ - @Override - public void setUseMandates(boolean useMandates) { - sessionData.put(FLAG_USE_MANDATE, useMandates); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isMandateUsed() - */ - @Override - public boolean isMandateUsed() { - return wrapStringObject(FLAG_USE_MANDATE, false, Boolean.class); - } - - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setMISSessionID(java.lang.String) */ @Override public void setMISSessionID(String misSessionID) { - sessionData.put(VALUE_MISSESSIONID, misSessionID); + authProcessData.put(VALUE_MISSESSIONID, misSessionID); } @@ -335,24 +242,7 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut */ @Override public void setMandateReferenceValue(String mandateReferenceValue) { - sessionData.put(VALUE_MISREFVALUE, mandateReferenceValue); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isForeigner() - */ - @Override - public boolean isForeigner() { - return wrapStringObject(FLAG_IS_FOREIGNER, false, Boolean.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setForeigner(boolean) - */ - @Override - public void setForeigner(boolean isForeigner) { - sessionData.put(FLAG_IS_FOREIGNER, isForeigner); + authProcessData.put(VALUE_MISREFVALUE, mandateReferenceValue); } @@ -369,7 +259,7 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut */ @Override public void setXMLVerifySignatureResponse(IVerifiyXMLSignatureResponse xMLVerifySignatureResponse) { - sessionData.put(VALUE_VERIFYSIGRESP, xMLVerifySignatureResponse); + authProcessData.put(VALUE_VERIFYSIGRESP, xMLVerifySignatureResponse); } @@ -386,27 +276,10 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut */ @Override public void setMISMandate(IMISMandate mandate) { - sessionData.put(VALUE_MISMANDATE, mandate); + authProcessData.put(VALUE_MISMANDATE, mandate); } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#isOW() - */ - @Override - public boolean isOW() { - return wrapStringObject(FLAG_IS_ORGANWALTER, false, Boolean.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setOW(boolean) - */ - @Override - public void setOW(boolean isOW) { - sessionData.put(FLAG_IS_ORGANWALTER, isOW); - - } - + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getAuthBlockTokken() */ @@ -420,73 +293,14 @@ public class AuthenticationSessionWrapper implements IAuthenticationSession, Aut */ @Override public void setAuthBlockTokken(String authBlockTokken) { - sessionData.put(VALUE_AUTNBLOCKTOKKEN, authBlockTokken); - - } + authProcessData.put(VALUE_AUTNBLOCKTOKKEN, authBlockTokken); - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getQAALevel() - */ - @Override - public String getQAALevel() { - return wrapStringObject(VALUE_QAALEVEL, null, String.class); } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setQAALevel(java.lang.String) - */ @Override - public void setQAALevel(String qAALevel) { - sessionData.put(VALUE_QAALEVEL, qAALevel); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getSessionCreated() - */ - @Override - public Date getSessionCreated() { - return wrapStringObject(VALUE_CREATED, null, Date.class); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getGenericSessionDataStorage() - */ - @Override - public Map<String, Object> getGenericSessionDataStorage() { - Map<String, Object> result = new HashMap<String, Object>(); - for (String el : sessionData.keySet()) { - if (el.startsWith(GENERIC_PREFIX)) - result.put(el.substring(GENERIC_PREFIX.length()), sessionData.get(el)); - - } + public Map<String, Object> getKeyValueRepresentationFromAuthSession() { + return Collections.unmodifiableMap(authProcessData); - return result; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getGenericDataFromSession(java.lang.String) - */ - @Override - public Object getGenericDataFromSession(String key) { - return sessionData.get(GENERIC_PREFIX + key); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#getGenericDataFromSession(java.lang.String, java.lang.Class) - */ - @Override - public <T> T getGenericDataFromSession(String key, Class<T> clazz) { - return wrapStringObject(GENERIC_PREFIX + key, null, clazz); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IAuthenticationSession#setGenericDataToSession(java.lang.String, java.lang.Object) - */ - @Override - public void setGenericDataToSession(String key, Object object) throws SessionDataStorageException { - sessionData.put(GENERIC_PREFIX + key, object); - } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/IdentityLink.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/IdentityLink.java deleted file mode 100644 index 2690bc2cc..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/IdentityLink.java +++ /dev/null @@ -1,312 +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. - ******************************************************************************/ -/* - * 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.auth.data; - -import java.io.IOException; -import java.io.Serializable; -import java.security.PublicKey; - -import javax.xml.transform.TransformerException; - -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.commons.api.data.IIdentityLink; -import at.gv.egovernment.moa.util.DOMUtils; - - -/** - * Data contained in an identity link issued by BMI, relevant to the MOA ID component. - * <br><code>"IdentityLink"</code> is the translation of <code>"Personenbindung"</code>. - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class IdentityLink implements Serializable, IIdentityLink{ - - private static final long serialVersionUID = 1L; - - /** - * <code>"identificationValue"</code> is the translation of <code>"Stammzahl"</code>. - */ - private String identificationValue; - /** - * <code>"identificationType"</code> type of the identificationValue in the IdentityLink. - */ - private String identificationType; - /** - * first name - */ - private String givenName; - /** - * family name - */ - private String familyName; - - /** - * The name as (givenName + familyName) - */ - private String name; - /** - * date of birth - */ - private String dateOfBirth; - /** - * the original saml:Assertion-Element - */ - private Element samlAssertion; - /** - * the serializes saml:Assertion - */ - private String serializedSamlAssertion; - /** - * Element /saml:Assertion/saml:AttributeStatement/saml:Subject/saml:SubjectConfirmation/saml:SubjectConfirmationData/pr:Person - */ - private Element prPerson; - /** - * we need for each dsig:Reference Element all - * transformation elements - */ - private Element[] dsigReferenceTransforms; - - /** - * The issuing time of the identity link SAML assertion. - */ - private String issueInstant; - - /** - * we need all public keys stored in - * the identity link - */ - private PublicKey[] publicKey; - - /** - * Constructor for IdentityLink - */ - public IdentityLink() { - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getDateOfBirth() - */ - @Override -public String getDateOfBirth() { - return dateOfBirth; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getFamilyName() - */ - @Override -public String getFamilyName() { - return familyName; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getGivenName() - */ - @Override -public String getGivenName() { - return givenName; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getName() - */ - @Override -public String getName() { - if (name == null) { - name = givenName + " " + familyName; - } - return name; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getIdentificationValue() - */ - @Override -public String getIdentificationValue() { - return identificationValue; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getIdentificationType() - */ - @Override - public String getIdentificationType() { - return identificationType; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setDateOfBirth(java.lang.String) - */ - @Override -public void setDateOfBirth(String dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setFamilyName(java.lang.String) - */ - @Override -public void setFamilyName(String familyName) { - this.familyName = familyName; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setGivenName(java.lang.String) - */ - @Override -public void setGivenName(String givenName) { - this.givenName = givenName; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setIdentificationValue(java.lang.String) - */ - @Override -public void setIdentificationValue(String identificationValue) { - this.identificationValue = identificationValue; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setIdentificationType(java.lang.String) - */ - @Override - public void setIdentificationType(String identificationType) { - this.identificationType = identificationType; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getSamlAssertion() - */ - @Override -public Element getSamlAssertion() { - return samlAssertion; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getSerializedSamlAssertion() - */ - @Override -public String getSerializedSamlAssertion() { - return serializedSamlAssertion; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setSamlAssertion(org.w3c.dom.Element) - */ - @Override -public void setSamlAssertion(Element samlAssertion) throws TransformerException, IOException { - this.samlAssertion = samlAssertion; - this.serializedSamlAssertion = DOMUtils.serializeNode(samlAssertion); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getDsigReferenceTransforms() - */ - @Override -public Element[] getDsigReferenceTransforms() { - return dsigReferenceTransforms; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setDsigReferenceTransforms(org.w3c.dom.Element[]) - */ - @Override -public void setDsigReferenceTransforms(Element[] dsigReferenceTransforms) { - this.dsigReferenceTransforms = dsigReferenceTransforms; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getPublicKey() - */ - @Override -public PublicKey[] getPublicKey() { - return publicKey; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setPublicKey(java.security.PublicKey[]) - */ - @Override -public void setPublicKey(PublicKey[] publicKey) { - this.publicKey = publicKey; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getPrPerson() - */ - @Override -public Element getPrPerson() { - return prPerson; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setPrPerson(org.w3c.dom.Element) - */ - @Override -public void setPrPerson(Element prPerson) { - this.prPerson = prPerson; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#getIssueInstant() - */ - @Override -public String getIssueInstant() { - return issueInstant; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.auth.data.IIdentityLink#setIssueInstant(java.lang.String) - */ - @Override -public void setIssueInstant(String issueInstant) { - this.issueInstant = issueInstant; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/BKUException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/BKUException.java deleted file mode 100644 index ffbb6a19e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/BKUException.java +++ /dev/null @@ -1,59 +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.auth.exception; - -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; - -public class BKUException extends MOAIDException { - - private static final long serialVersionUID = -4646544256490397419L; - - private String bkuErrorCode; - private String bkuErrorMessage; - - public BKUException(String messageId, Object[] parameters, - String bkuErrorCode, String bkuErrorMessage) { - super(messageId, parameters); - - this.bkuErrorCode = bkuErrorCode; - this.bkuErrorMessage = bkuErrorMessage; - } - - - /** - * @return the bkuErrorCode - */ - public String getBkuErrorCode() { - return bkuErrorCode; - } - - - /** - * @return the bkuErrorMessage - */ - public String getBkuErrorMessage() { - return bkuErrorMessage; - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/InvalidProtocolRequestException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/InvalidProtocolRequestException.java deleted file mode 100644 index c6b8a4b6e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/InvalidProtocolRequestException.java +++ /dev/null @@ -1,49 +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.auth.exception; - -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; - -/** - * @author tlenz - * - */ -public class InvalidProtocolRequestException extends MOAIDException { - - /** - * - */ - private static final long serialVersionUID = -7866198705324084601L; - - /** - * @param messageId - * @param parameters - */ - public InvalidProtocolRequestException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - public InvalidProtocolRequestException(String messageId, Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } -} 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 deleted file mode 100644 index ab3d2cae2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MISSimpleClientException.java +++ /dev/null @@ -1,94 +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.
- ******************************************************************************/
-/*
- * 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.auth.exception;
-
-import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException;
-
-public class MISSimpleClientException extends MOAIDException {
-
- private static final long serialVersionUID = 1L;
-
- private String misErrorCode;
- private String misErrorMessage;
-
- public MISSimpleClientException() {
- super("UNDEFINED ERROR", null);
- }
-
- public MISSimpleClientException(String message) {
- super(message, null);
- }
-
- public MISSimpleClientException(String message, String code, String text) {
- super(message, new Object[] { code , text });
- this.misErrorMessage = text;
- this.misErrorCode = code;
- }
-
- public MISSimpleClientException(String message, Throwable cause) {
- super(message, null, cause);
- }
-
- public MISSimpleClientException(String message, Object[] params, Throwable cause) {
- super(message, params, cause);
- }
-
- /**
- * @return the bkuErrorCode
- */
- public String getMISErrorCode() {
- return misErrorCode;
- }
-
-
- /**
- * @return the bkuErrorMessage
- */
- public String getMISErrorMessage() {
- return misErrorMessage;
- }
-}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ProtocolNotActiveException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ProtocolNotActiveException.java deleted file mode 100644 index 2d09384a3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ProtocolNotActiveException.java +++ /dev/null @@ -1,46 +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.auth.exception; - -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; - -/** - * @author tlenz - * - */ -public class ProtocolNotActiveException extends MOAIDException { - - /** - * - */ - private static final long serialVersionUID = 1832697083163940710L; - - /** - * @param messageId - * @param parameters - */ - public ProtocolNotActiveException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java index d5ca89656..d2d39e9e6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java @@ -52,10 +52,7 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.auth.exception.ServiceException; -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.api.ConnectionParameterInterface; -import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.spss.MOAException; import at.gv.egovernment.moa.spss.api.SignatureVerificationService; import at.gv.egovernment.moa.spss.api.cmsverify.VerifyCMSSignatureRequest; @@ -64,7 +61,6 @@ import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureRequestParser; import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureResponseBuilder; import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; -import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moaspss.logging.Logger; /** @@ -93,22 +89,22 @@ public class SignatureVerificationInvoker { } private SignatureVerificationInvoker() { - try { - AuthConfiguration authConfigProvider = AuthConfigurationProviderFactory.getInstance(); - ConnectionParameterInterface authConnParam = authConfigProvider.getMoaSpConnectionParameter(); +// try { +// AuthConfiguration authConfigProvider = AuthConfigurationProviderFactory.getInstance(); +// ConnectionParameterInterface authConnParam = authConfigProvider.getMoaSpConnectionParameter(); - if (authConnParam != null && MiscUtil.isNotEmpty(authConnParam.getUrl())) { - - - } else { +// if (authConnParam != null && MiscUtil.isNotEmpty(authConnParam.getUrl())) { +// +// +// } else { svs = SignatureVerificationService.getInstance(); - } +// } - } catch (ConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } +// } catch (ConfigurationException e) { +// // TODO Auto-generated catch block +// e.printStackTrace(); +// } } @@ -144,35 +140,34 @@ public class SignatureVerificationInvoker { protected Element doCall(QName serviceName, Element request) throws ServiceException { ConnectionParameterInterface authConnParam = null; try { - AuthConfiguration authConfigProvider = AuthConfigurationProviderFactory.getInstance(); - authConnParam = authConfigProvider.getMoaSpConnectionParameter(); - //If the ConnectionParameter do NOT exist, we try to get the api to work.... - if (authConnParam != null && MiscUtil.isNotEmpty(authConnParam.getUrl())) { - - throw new ServiceException("service.00", new Object[]{"MOA-SP connection via Web-Service is not allowed any more!!!!!!"}); -// Service service = ServiceFactory.newInstance().createService(serviceName); -// Call call = service.createCall(); -// SOAPBodyElement body = new SOAPBodyElement(request); -// SOAPBodyElement[] params = new SOAPBodyElement[] { body }; -// Vector responses; -// SOAPBodyElement response; +// AuthConfiguration authConfigProvider = AuthConfigurationProviderFactory.getInstance(); +// authConnParam = authConfigProvider.getMoaSpConnectionParameter(); +// //If the ConnectionParameter do NOT exist, we try to get the api to work.... +// if (authConnParam != null && MiscUtil.isNotEmpty(authConnParam.getUrl())) { // -// Logger.debug("Connecting using auth url: " + authConnParam.getUrl() + ", service " + serviceName.getNamespaceURI() + " : " + serviceName.getLocalPart() + " : "+ serviceName.getPrefix()); -// call.setTargetEndpointAddress(authConnParam.getUrl()); -// responses = (Vector) call.invoke(serviceName, params); -// Logger.debug("Got responses: " + responses.size()); // TODO handle axis 302 response when incorrect service url is used -// response = (SOAPBodyElement) responses.get(0); -// return response.getAsDOM(); - } - else { - VerifyXMLSignatureRequest vsrequest = new VerifyXMLSignatureRequestParser().parse(request); - +// throw new ServiceException("service.00", new Object[]{"MOA-SP connection via Web-Service is not allowed any more!!!!!!"}); +//// Service service = ServiceFactory.newInstance().createService(serviceName); +//// Call call = service.createCall(); +//// SOAPBodyElement body = new SOAPBodyElement(request); +//// SOAPBodyElement[] params = new SOAPBodyElement[] { body }; +//// Vector responses; +//// SOAPBodyElement response; +//// +//// Logger.debug("Connecting using auth url: " + authConnParam.getUrl() + ", service " + serviceName.getNamespaceURI() + " : " + serviceName.getLocalPart() + " : "+ serviceName.getPrefix()); +//// call.setTargetEndpointAddress(authConnParam.getUrl()); +//// responses = (Vector) call.invoke(serviceName, params); +//// Logger.debug("Got responses: " + responses.size()); // TODO handle axis 302 response when incorrect service url is used +//// response = (SOAPBodyElement) responses.get(0); +//// return response.getAsDOM(); +// } +// else { + VerifyXMLSignatureRequest vsrequest = new VerifyXMLSignatureRequestParser().parse(request); VerifyXMLSignatureResponse vsresponse = svs.verifyXMLSignature(vsrequest); - Document result = new VerifyXMLSignatureResponseBuilder().build(vsresponse); - + Document result = new VerifyXMLSignatureResponseBuilder(true).build(vsresponse); + //Logger.setHierarchy("moa.id.auth"); return result.getDocumentElement(); - } +// } } catch (Exception ex) { if (authConnParam != null) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java deleted file mode 100644 index ec6dbc951..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java +++ /dev/null @@ -1,229 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.fileupload.FileItem;
-import org.apache.commons.fileupload.FileItemFactory;
-import org.apache.commons.fileupload.FileUploadException;
-import org.apache.commons.fileupload.disk.DiskFileItemFactory;
-import org.apache.commons.fileupload.servlet.ServletFileUpload;
-import org.apache.commons.lang3.ArrayUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
-import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
-import at.gv.egovernment.moa.id.commons.api.AuthConfiguration;
-import at.gv.egovernment.moa.id.commons.api.IRequest;
-import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession;
-import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException;
-import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
-import at.gv.egovernment.moa.id.moduls.IRequestStorage;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-import at.gv.egovernment.moa.id.process.springweb.MoaIdTask;
-import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController;
-import at.gv.egovernment.moa.logging.Logger;
-
-/**
- * Task based counterpart to {@link AuthServlet}, providing the same utility methods (error handling, parameter parsing
- * etc.).</p> The code has been taken from {@link AuthServlet}.
- */
-public abstract class AbstractAuthServletTask extends MoaIdTask {
-
- @Autowired protected IRequestStorage requestStoreage;
- //@Autowired protected IAuthenticationSessionStoreage authenticatedSessionStorage;
- @Autowired protected MOAReversionLogger revisionsLogger;
- @Autowired protected AuthConfiguration authConfig;
-
- protected static final String ERROR_CODE_PARAM = "errorid";
-
- protected IRequest pendingReq = null;
- protected IAuthenticationSession moasession = null;
-
- public abstract void execute(ExecutionContext executionContext, HttpServletRequest request,
- HttpServletResponse response) throws TaskExecutionException;
-
-
- protected final IRequest internalExecute(IRequest pendingReq, ExecutionContext executionContext, HttpServletRequest request,
- HttpServletResponse response) throws TaskExecutionException {
- //set pending-request object
- this.pendingReq = pendingReq;
-
- //execute task specific action
- execute(executionContext, request, response);
-
- //return pending-request object
- return this.pendingReq;
- }
-
-
- /**
- * Default initialization loads the MOASession object from database
- *
- * @param req
- * @param executionContext
- * @throws MOAIDException
- * @throws MOADatabaseException
- */
- protected void defaultTaskInitialization(HttpServletRequest req, ExecutionContext executionContext) throws MOAIDException, MOADatabaseException {
- Logger.trace("Get MOASessionData object from pendingReq:" + pendingReq.getRequestID());
- moasession = pendingReq.getMOASession();
-
- }
-
- /**
- * Redirect the authentication process to protocol specific finalization endpoint.
- *
- * @param pendingReq Actually processed protocol specific authentication request
- * @param httpResp
- */
- protected void performRedirectToProtocolFinialization(IRequest pendingReq, HttpServletResponse httpResp) {
- performRedirectToItself(pendingReq, httpResp, AbstractAuthProtocolModulController.FINALIZEPROTOCOL_ENDPOINT);
-
- }
-
- /**
- * Redirect the authentication process to MOA-ID-Auth itself
- *
- * @param pendingReq Actually processed protocol specific authentication request
- * @param httpResp
- * @param moaIDEndPoint Servlet EndPoint that should receive the redirect
- */
- protected void performRedirectToItself(IRequest pendingReq, HttpServletResponse httpResp, String moaIDEndPoint) {
- String redirectURL = new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(),
- moaIDEndPoint, pendingReq.getRequestID());
-
- httpResp.setContentType("text/html");
- httpResp.setStatus(302);
- httpResp.addHeader("Location", redirectURL);
- Logger.debug("REDIRECT TO: " + redirectURL);
-
- }
-
-
- /**
- * Parses the request input stream for parameters, assuming parameters are
- * encoded UTF-8 (no standard exists how browsers should encode them).
- *
- * @param req
- * servlet request
- *
- * @return mapping parameter name -> value
- *
- * @throws IOException
- * if parsing request parameters fails.
- *
- * @throws FileUploadException
- * if parsing request parameters fails.
- */
- protected Map<String, String> getParameters(HttpServletRequest req) throws IOException,
- FileUploadException {
-
- Map<String, String> parameters = new HashMap<String, String>();
-
- if (ServletFileUpload.isMultipartContent(req)) {
- // request is encoded as mulitpart/form-data
- FileItemFactory factory = new DiskFileItemFactory();
- ServletFileUpload upload = null;
- upload = new ServletFileUpload(factory);
- List items = null;
- items = upload.parseRequest(req);
- for (int i = 0; i < items.size(); i++) {
- FileItem item = (FileItem) items.get(i);
- if (item.isFormField()) {
- // Process only form fields - no file upload items
- String logString = item.getString("UTF-8");
-
- // TODO use RegExp
- String startS = "<pr:Identification><pr:Value>";
- String endS = "</pr:Value><pr:Type>urn:publicid:gv.at:baseid</pr:Type>";
- String logWithMaskedBaseid = logString;
- int start = logString.indexOf(startS);
- if (start > -1) {
- int end = logString.indexOf(endS);
- if (end > -1) {
- logWithMaskedBaseid = logString.substring(0, start);
- logWithMaskedBaseid += startS;
- logWithMaskedBaseid += "xxxxxxxxxxxxxxxxxxxxxxxx";
- logWithMaskedBaseid += logString.substring(end,
- logString.length());
- }
- }
- parameters
- .put(item.getFieldName(), item.getString("UTF-8"));
- Logger.debug("Processed multipart/form-data request parameter: \nName: "
- + item.getFieldName()
- + "\nValue: "
- + logWithMaskedBaseid);
- }
- }
- }
-
- else {
- Iterator<Entry<String, String[]>> requestParamIt = req.getParameterMap().entrySet().iterator();
- while (requestParamIt.hasNext()) {
- Entry<String, String[]> entry = requestParamIt.next();
- String key = entry.getKey();
- String[] values = entry.getValue();
- // take the last value from the value array since the legacy code above also does it this way
- parameters.put(key, ArrayUtils.isEmpty(values) ? null : values[values.length-1]);
- }
-
- }
-
- return parameters;
- }
-
- /**
- * Reads bytes up to a delimiter, consuming the delimiter.
- *
- * @param in
- * input stream
- * @param delimiter
- * delimiter character
- * @return String constructed from the read bytes
- * @throws IOException
- */
- protected String readBytesUpTo(InputStream in, char delimiter)
- throws IOException {
- ByteArrayOutputStream bout = new ByteArrayOutputStream();
- boolean done = false;
- int b;
- while (!done && (b = in.read()) >= 0) {
- if (b == delimiter)
- done = true;
- else
- bout.write(b);
- }
- return bout.toString();
- }
-
- /**
- * Adds a parameter to a URL.
- *
- * @param url
- * the URL
- * @param paramname
- * parameter name
- * @param paramvalue
- * parameter value
- * @return the URL with parameter added
- */
- protected static String addURLParameter(String url, String paramname,
- String paramvalue) {
- String param = paramname + "=" + paramvalue;
- if (url.indexOf("?") < 0)
- return url + "?" + param;
- else
- return url + "&" + param;
- }
-}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java deleted file mode 100644 index 8983403d8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AuthModule.java +++ /dev/null @@ -1,42 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules; - -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.process.model.ProcessDefinition; - -/** - * Provides metadata of a certain module. Uses for module discovery and process selection. - */ -public interface AuthModule { - - /** - * Returns the priority of the module. The priority defines the order of the respective module within the chain of - * discovered modules. Higher priorized modules are asked before lower priorized modules for a process that they can - * handle. - * <p/> - * Internal default modules are priorized neutral ({@code 0}. Use a higher priority ({@code 1...Integer.MAX_VALUE}) - * in order to have your module(s) priorized or a lower priority ({@code Integer.MIN_VALUE...-1}) in order to put - * your modules behind default modules. - * - * @return the priority of the module. - */ - int getPriority(); - - /** - * Selects a process (description), referenced by its unique id, which is able to perform authentication with the - * given {@link ExecutionContext}. Returns {@code null} if no appropriate process (description) was available within - * this module. - * - * @param context - * an ExecutionContext for a process. - * @return the process-ID of a process which is able to work with the given ExecutionContext, or {@code null}. - */ - String selectProcess(ExecutionContext context); - - /** - * Returns the an Array of {@link ProcessDefinition}s of the processes included in this module. - * - * @return an array of resource uris of the processes included in this module. - */ - String[] getProcessDefinitions(); - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java index 90795a416..48d652671 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java @@ -22,8 +22,9 @@ */ package at.gv.egovernment.moa.id.auth.modules; +import at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; /** * @author tlenz diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/SingleSignOnConsentsModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/SingleSignOnConsentsModuleImpl.java index d64126de6..b624e13ef 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/SingleSignOnConsentsModuleImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/SingleSignOnConsentsModuleImpl.java @@ -22,7 +22,8 @@ */ package at.gv.egovernment.moa.id.auth.modules; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.auth.modules.AuthModule; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; /** * @author tlenz diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/TaskExecutionException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/TaskExecutionException.java deleted file mode 100644 index 1128cbab3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/TaskExecutionException.java +++ /dev/null @@ -1,75 +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.auth.modules; - -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ -public class TaskExecutionException extends ProcessExecutionException { - - private static final long serialVersionUID = 1L; - Throwable originalException = null; - String pendingRequestID = null; - - /** - * @param message - * @param cause - */ - public TaskExecutionException(IRequest pendingReq, String message, Throwable cause) { - super(message, cause); - this.originalException = cause; - - if (MiscUtil.isNotEmpty(pendingReq.getRequestID())) - this.pendingRequestID = pendingReq.getRequestID(); - - } - - /** - * Get the original internal exception from task - * - * @return the originalException - */ - public Throwable getOriginalException() { - return originalException; - - } - - /** - * Get the pending-request ID of that request, which was processed when the exception occurs - * - * @return the pendingRequestID - */ - public String getPendingRequestID() { - return pendingRequestID; - } - - - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java index 42789d01d..0336cb370 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java @@ -30,10 +30,11 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import org.springframework.stereotype.Component; -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -56,7 +57,7 @@ public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { while(reqParamNames.hasMoreElements()) { String paramName = reqParamNames.nextElement(); if (MiscUtil.isNotEmpty(paramName) && - !MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID.equalsIgnoreCase(paramName)) + !EAAFConstants.PROCESS_ENGINE_PENDINGREQUESTID.equalsIgnoreCase(paramName)) executionContext.put(paramName, StringEscapeUtils.escapeHtml(request.getParameter(paramName))); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateSSOConsentsTaskImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateSSOConsentsTaskImpl.java index 1c26ff5ec..375b144d7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateSSOConsentsTaskImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateSSOConsentsTaskImpl.java @@ -29,15 +29,15 @@ import org.apache.commons.lang.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; @@ -78,13 +78,8 @@ public class EvaluateSSOConsentsTaskImpl extends AbstractAuthServletTask { //defaultTaskInitialization(request, executionContext); //check SSO session cookie and MOASession object - String ssoId = ssoManager.getSSOSessionID(request); - boolean isValidSSOSession = ssoManager.isValidSSOSession(ssoId, pendingReq); - - //load MOA SSO-session from database - AuthenticationSession ssoMOSSession = authenticatedSessionStorage.getInternalSSOSession(pendingReq.getInternalSSOSessionIdentifier()); - - if (!(isValidSSOSession && ssoMOSSession.isAuthenticated() )) { + String ssoId = ssoManager.getSSOSessionID(request); + if (!(ssoManager.isValidSSOSession(ssoId, pendingReq))) { Logger.info("Single Sign-On consents evaluator found NO valid SSO session. Stopping authentication process ..."); throw new AuthenticationException("auth.30", null); @@ -92,21 +87,23 @@ public class EvaluateSSOConsentsTaskImpl extends AbstractAuthServletTask { //Log consents evaluator event to revisionslog revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_FINISHED, String.valueOf(ssoConsents)); - - //Populate this pending request with SSO session information - pendingReq.populateMOASessionWithSSOInformation(ssoMOSSession); - - + //user allow single sign-on authentication if (ssoConsents) { - + //load MOA SSO-session from database + AuthenticationSession ssoMOSSession = authenticatedSessionStorage.getInternalSSOSession(pendingReq.getInternalSSOSessionIdentifier()); + + + //Populate this pending request with SSO session information + pendingReq.setRawDataToTransaction(ssoMOSSession.getKeyValueRepresentationFromAuthSession());; + //authenticate pending-request pendingReq.setAuthenticated(true); pendingReq.setAbortedByUser(false); } else { //user deny single sign-on authentication - Logger.debug("User deny the Single Sign-On authentication for SP: " + pendingReq.getOAURL()); + Logger.debug("User deny the Single Sign-On authentication for SP: " + pendingReq.getSPEntityId()); pendingReq.setAbortedByUser(true); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java deleted file mode 100644 index 4eff0fcf5..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java +++ /dev/null @@ -1,79 +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.auth.modules.internal.tasks; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.stereotype.Component; - -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -@Component("FinalizeAuthenticationTask") -public class FinalizeAuthenticationTask extends AbstractAuthServletTask { - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public void execute(ExecutionContext executionContext, - HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - - try { - defaultTaskInitialization(request, executionContext); - - //set MOASession to authenticated - moasession.setAuthenticated(true); - - //set pending request to authenticated - pendingReq.setAuthenticated(true); - requestStoreage.storePendingRequest(pendingReq); - - Logger.info("AuthProcess finished. Redirect to Protocol Dispatcher."); - performRedirectToProtocolFinialization(pendingReq, response); - - } catch (MOAIDException e) { - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } catch (Exception e) { - Logger.warn("FinalizeAuthenticationTask has an internal error", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } finally { - executionContext.remove(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID); - - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java index 710008714..98e632bd8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java @@ -28,18 +28,18 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; import at.gv.egovernment.moa.id.auth.frontend.builder.SPSpecificGUIBuilderConfigurationWithDBLoad; -import at.gv.egovernment.moa.id.auth.frontend.exception.GUIBuildException; -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.auth.servlet.GeneralProcessEngineSignalController; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.logging.Logger; /** @@ -58,14 +58,13 @@ public class GenerateBKUSelectionFrameTask extends AbstractAuthServletTask { public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { try { - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUSELECTION_INIT); + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUSELECTION_INIT); //load Parameters from OnlineApplicationConfiguration - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + ISPConfiguration oaParam = pendingReq.getServiceProviderConfiguration(); if (oaParam == null) { - throw new AuthenticationException("auth.00", new Object[] { pendingReq.getOAURL() }); + throw new AuthenticationException("auth.00", new Object[] { pendingReq.getSPEntityId() }); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateSSOConsentEvaluatorFrameTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateSSOConsentEvaluatorFrameTask.java index 475009cf2..3c364e924 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateSSOConsentEvaluatorFrameTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateSSOConsentEvaluatorFrameTask.java @@ -28,16 +28,16 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import at.gv.egiz.eaaf.core.api.gui.IGUIBuilderConfiguration; +import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; import at.gv.egovernment.moa.id.auth.frontend.builder.SPSpecificGUIBuilderConfigurationWithDBLoad; -import at.gv.egovernment.moa.id.auth.frontend.exception.GUIBuildException; -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.auth.servlet.GeneralProcessEngineSignalController; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.logging.Logger; /** @@ -57,9 +57,7 @@ public class GenerateSSOConsentEvaluatorFrameTask extends AbstractAuthServletTas @Override public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { - try { - //perform default task initialization - defaultTaskInitialization(request, executionContext); + try { //set authenticated flag to false, because user consents is required pendingReq.setAuthenticated(false); @@ -76,8 +74,7 @@ public class GenerateSSOConsentEvaluatorFrameTask extends AbstractAuthServletTas guiBuilder.build(response, config, "SendAssertion-Evaluation"); //Log consents evaluator event to revisionslog - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_START); + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_START); } catch (GUIBuildException e) { Logger.warn("Can not build GUI:'SendAssertion-Evaluation'. Msg:" + e.getMessage()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java deleted file mode 100644 index c1d02a029..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java +++ /dev/null @@ -1,108 +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.auth.modules.internal.tasks; - -import java.util.Set; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.id.process.ExecutionContextImpl; -import at.gv.egovernment.moa.id.process.ProcessEngine; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -@Component("RestartAuthProzessManagement") -public class RestartAuthProzessManagement extends AbstractAuthServletTask { - - @Autowired ProcessEngine processEngine; - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) - */ - @Override - public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) - throws TaskExecutionException { - try { - //create a new execution context and copy all elements to new context - ExecutionContext newec = new ExecutionContextImpl(); - Set<String> entries = executionContext.keySet(); - for (String key : entries) { - newec.put(key, executionContext.get(key)); - - } - - Logger.debug("Select new auth.-process and restart restart process-engine ... "); - - // select and create new process instance - String processDefinitionId = ModuleRegistration.getInstance().selectProcess(newec); - if (processDefinitionId == null) { - Logger.warn("No suitable authentication process found for SessionID " + pendingReq.getRequestID()); - throw new MOAIDException("process.02", new Object[] { pendingReq.getRequestID() }); - } - - String processInstanceId = processEngine.createProcessInstance(processDefinitionId, newec); - - // keep process instance id in moa session - ((RequestImpl)pendingReq).setProcessInstanceId(processInstanceId); - - // make sure pending request has been persisted before running the process - try { - requestStoreage.storePendingRequest(pendingReq); - - } catch (MOAIDException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { pendingReq.getRequestID() }); - - } - - Logger.info("Restart process-engine with auth.process:" + processDefinitionId); - - // start process - processEngine.start(pendingReq); - - - } catch (MOAIDException e) { - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } catch (Exception e) { - Logger.warn("RestartAuthProzessManagement has an internal error", e); - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/UserRestrictionTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/UserRestrictionTask.java new file mode 100644 index 000000000..acaf21682 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/UserRestrictionTask.java @@ -0,0 +1,86 @@ +package at.gv.egovernment.moa.id.auth.modules.internal.tasks; + +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; + +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.TaskExecutionException; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BPKBuilder; +import at.gv.egiz.eaaf.core.impl.idp.auth.modules.AbstractAuthServletTask; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionWrapper; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; +import at.gv.egovernment.moa.id.config.auth.data.UserWhitelistStore; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +public class UserRestrictionTask extends AbstractAuthServletTask { + + public static final String CONFIG_PROPS_SP_LIST = "configuration.restrictions.sp.entityIds"; + public static final String CONFIG_PROPS_CSV_USER_FILE = "configuration.restrictions.sp.users.url"; + public static final String CONFIG_PROPS_CSV_USER_SECTOR = "configuration.restrictions.sp.users.sector"; + + @Autowired(required=true) UserWhitelistStore whitelist; + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try { + String spEntityId = pendingReq.getServiceProviderConfiguration().getUniqueIdentifier(); + List<String> restrictedSPs = KeyValueUtils.getListOfCSVValues(authConfig.getBasicConfiguration(CONFIG_PROPS_SP_LIST)); + if (restrictedSPs.contains(spEntityId)) { + Logger.debug("SP:" + spEntityId + " has a user restrication. Check users bPK ... "); + AuthenticationSessionWrapper moasession = pendingReq.getSessionData(AuthenticationSessionWrapper.class); + + //check if user idl is already loaded + if (moasession.getIdentityLink() == null) { + Logger.warn("PendingRequest contains NO IdentityLink. User restrictation NOT possible!"); + throw new MOAIDException("process.03", null); + + } + + //calculate whitelist bPK for current user + String bpkTarget = authConfig.getBasicConfiguration(CONFIG_PROPS_CSV_USER_SECTOR); + if (MiscUtil.isEmpty(bpkTarget)) { + Logger.info("NO bPK sector for user whitelist in configuration"); + throw new MOAIDException("config.05", new Object[] {CONFIG_PROPS_CSV_USER_SECTOR}); + + } + + Pair<String, String> pseudonym = new BPKBuilder().generateAreaSpecificPersonIdentifier( + moasession.getIdentityLink().getIdentificationValue(), + moasession.getIdentityLink().getIdentificationType(), + bpkTarget); + + + //check if user's bPK is whitelisted + if (!whitelist.isUserbPKInWhitelistDynamic(pseudonym.getFirst())) { + Logger.info("User's bPK is not whitelisted. Authentication process stops ..."); + Logger.trace("User's bPK: " + pseudonym.getFirst()); + throw new MOAIDException("auth.35", null); + + } + + Logger.debug("User was found in whitelist. Continue authentication process ... "); + + } else + Logger.trace("SP: " + spEntityId + " has no user restrication."); + + + } catch (MOAIDException e) { + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } catch (Exception e) { + Logger.warn("RestartAuthProzessManagement has an internal error", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java deleted file mode 100644 index 9c950366c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/registration/ModuleRegistration.java +++ /dev/null @@ -1,149 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.registration; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.ServiceLoader; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.core.io.Resource; - -import at.gv.egovernment.moa.id.auth.modules.AuthModule; -import at.gv.egovernment.moa.id.process.ProcessDefinitionParserException; -import at.gv.egovernment.moa.id.process.ProcessEngine; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; - -/** - * This class handles registering modules. The modules are detected either with - * the ServiceLoader mechanism or via Spring. All detected modules are ranked - * according to their priority. - */ -public class ModuleRegistration { - - private static ModuleRegistration instance = new ModuleRegistration(); - - private List<AuthModule> priorizedModules = new ArrayList<>(); - - @Autowired - private ApplicationContext ctx; - - @Autowired - private ProcessEngine processEngine; - - private Logger log = LoggerFactory.getLogger(getClass()); - - public static ModuleRegistration getInstance() { - return instance; - } - - private ModuleRegistration() { - } - - @PostConstruct - private void init() { - // load modules via the ServiceLoader - initServiceLoaderModules(); - - // load modules via Spring - initSpringModules(); - - // order modules according to their priority - sortModules(); - } - - /** - * Discovers modules which use the ServiceLoader mechanism. - */ - private void initServiceLoaderModules() { - log.info("Looking for auth modules."); - ServiceLoader<AuthModule> loader = ServiceLoader.load(AuthModule.class); - Iterator<AuthModule> modules = loader.iterator(); - while (modules.hasNext()) { - AuthModule module = modules.next(); - log.info("Detected module {}", module.getClass().getName()); - registerModuleProcessDefinitions(module); - priorizedModules.add(module); - } - } - - /** - * Discovers modules which use Spring. - */ - private void initSpringModules() { - log.debug("Discovering Spring modules."); - Map<String, AuthModule> modules = ctx.getBeansOfType(AuthModule.class); - for (AuthModule module : modules.values()) { - registerModuleProcessDefinitions(module); - priorizedModules.add(module); - } - } - - /** - * Registers the resource uris for the module. - * - * @param module - * the module. - */ - private void registerModuleProcessDefinitions(AuthModule module) { - for (String uri : module.getProcessDefinitions()) { - Resource resource = ctx.getResource(uri); - if (resource.isReadable()) { - log.info("Registering process definition '{}'.", uri); - try (InputStream processDefinitionInputStream = resource.getInputStream()) { - processEngine.registerProcessDefinition(processDefinitionInputStream); - } catch (IOException e) { - log.error("Process definition '{}' could NOT be read.", uri, e); - } catch (ProcessDefinitionParserException e) { - log.error("Error while parsing process definition '{}'", uri, e); - } - } else { - log.error("Process definition '{}' cannot be read.", uri); - } - } - } - - /** - * Order the modules in descending order according to their priority. - */ - private void sortModules() { - Collections.sort(priorizedModules, new Comparator<AuthModule>() { - @Override - public int compare(AuthModule thisAuthModule, AuthModule otherAuthModule) { - int thisOrder = thisAuthModule.getPriority(); - int otherOrder = otherAuthModule.getPriority(); - return (thisOrder < otherOrder ? 1 : (thisOrder == otherOrder ? 0 : -1)); - } - }); - } - - /** - * Returns the process description id of the first process, in the highest ranked - * module, which is able to work with the given execution context. - * - * @param context - * the {@link ExecutionContext}. - * @return the process id or {@code null} - */ - public String selectProcess(ExecutionContext context) { - for (AuthModule module : priorizedModules) { - String id = module.selectProcess(context); - if (StringUtils.isNotEmpty(id)) { - log.debug("Process with id '{}' selected, for context '{}'.", id, context); - return id; - } - } - log.info("No process is able to handle context '{}'.", context); - return null; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParser.java index 8f7364f62..3ff22b84d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/IdentityLinkAssertionParser.java @@ -58,15 +58,15 @@ import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.traversal.NodeIterator; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.IdentityLink; +import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; +import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; import at.gv.egovernment.moa.id.auth.exception.ECDSAConverterException; import at.gv.egovernment.moa.id.auth.exception.ParseException; -import at.gv.egovernment.moa.id.commons.api.data.IIdentityLink; import at.gv.egovernment.moa.id.util.ECDSAKeyValueConverter; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.egovernment.moa.util.XPathUtils; /** * Parses an identity link <code><saml:Assertion></code> @@ -259,7 +259,7 @@ public class IdentityLinkAssertionParser { public IIdentityLink parseIdentityLink() throws ParseException { IIdentityLink identityLink; - try { + try { identityLink = new IdentityLink(); identityLink.setSamlAssertion(assertionElem); identityLink.setIssueInstant(assertionElem.getAttribute(ISSUE_INSTANT_ATTR)); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java index b2db8d5a2..ead80b117 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java @@ -30,19 +30,20 @@ import org.apache.commons.lang.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; 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.data.IAuthenticationSession; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.StringUtils; @@ -59,7 +60,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ String useMandate, String ccc, HttpServletRequest req, - IRequest protocolReq) throws WrongParametersException, MOAIDException { + IRequest protocolReq) throws WrongParametersException, MOAIDException, EAAFException { String resultTargetFriendlyName = null; String resultTarget = null; @@ -96,10 +97,10 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ //load OnlineApplication configuration - IOAAuthParameters oaParam = protocolReq.getOnlineApplicationConfiguration(); + IOAAuthParameters oaParam = protocolReq.getServiceProviderConfiguration(IOAAuthParameters.class); if (oaParam == null) throw new AuthenticationException("auth.00", - new Object[] { protocolReq.getOAURL() }); + new Object[] { protocolReq.getSPEntityId() }); // get target and target friendly name from config @@ -137,8 +138,8 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ resultTargetFriendlyName = targetFriendlyNameConfig; //set info's into request-context. (It's required to support SAML1 requested target parameters) - protocolReq.setGenericDataToSession(MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, resultTarget); - protocolReq.setGenericDataToSession( + protocolReq.setRawDataToTransaction(MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, resultTarget); + protocolReq.setRawDataToTransaction( MOAIDAuthConstants.AUTHPROCESS_DATA_TARGETFRIENDLYNAME, resultTargetFriendlyName); } else { @@ -185,7 +186,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ && MiscUtil.isNotEmpty(templateURLList.get(0)) ) { templateURL = FileUtils.makeAbsoluteURL( oaParam.getTemplateURL().get(0), - authConfig.getRootConfigFileDir()); + authConfig.getRootConfigFileDir()); Logger.info("No SL-Template in request, load SL-Template from OA configuration (URL: " + templateURL + ")"); } else if ( (defaulTemplateURLList.size() > 0) && MiscUtil.isNotEmpty(defaulTemplateURLList.get(0))) { @@ -205,7 +206,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ if (!ParamValidatorUtils.isValidTemplate(req, templateURL, oaParam.getTemplateURL())) throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12"); - protocolReq.setGenericDataToSession( + protocolReq.setRawDataToTransaction( MOAIDAuthConstants.AUTHPROCESS_DATA_SECURITYLAYERTEMPLATE, templateURL); @@ -227,7 +228,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ } public void parse(ExecutionContext ec, IAuthenticationSession moasession, HttpServletRequest req, IRequest pendingReq) - throws WrongParametersException, MOAIDException { + throws WrongParametersException, MOAIDException, EAAFException { //get Parameters from request String oaURL = (String) ec.get(PARAM_OA); @@ -236,18 +237,18 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ String useMandate = (String) ec.get(PARAM_USEMANDATE); String ccc = (String) ec.get(PARAM_CCC); - if (pendingReq.getOnlineApplicationConfiguration() != null && - pendingReq.getOnlineApplicationConfiguration().isOnlyMandateAllowed()) { - Logger.debug("Service " + pendingReq.getOnlineApplicationConfiguration().getPublicURLPrefix() + if (pendingReq.getServiceProviderConfiguration(IOAAuthParameters.class) != null && + pendingReq.getServiceProviderConfiguration(IOAAuthParameters.class).isOnlyMandateAllowed()) { + Logger.debug("Service " + pendingReq.getServiceProviderConfiguration(IOAAuthParameters.class).getPublicURLPrefix() + " only allows authentication with mandates. --> Set useMandate to TRUE."); - useMandate = String.valueOf(pendingReq.getOnlineApplicationConfiguration().isOnlyMandateAllowed()); + useMandate = String.valueOf(pendingReq.getServiceProviderConfiguration(IOAAuthParameters.class).isOnlyMandateAllowed()); } - oaURL = pendingReq.getOAURL(); + oaURL = pendingReq.getSPEntityId(); //only needed for SAML1 - String target = pendingReq.getGenericData("saml1_target", String.class); + String target = pendingReq.getRawData("saml1_target", String.class); parse(moasession, target, oaURL, bkuURL, templateURL, useMandate, ccc, req, pendingReq); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java index b54a43fff..c66353846 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java @@ -46,20 +46,22 @@ package at.gv.egovernment.moa.id.auth.parser; -import iaik.utils.Base64InputStream; -import iaik.x509.X509Certificate; - import java.io.ByteArrayInputStream; import java.io.InputStream; +import org.joda.time.DateTime; +import org.joda.time.format.ISODateTimeFormat; import org.w3c.dom.Element; +import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; +import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.commons.api.data.IVerifiyXMLSignatureResponse; import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.egovernment.moa.util.XPathUtils; +import at.gv.egovernment.moa.util.MiscUtil; +import iaik.utils.Base64InputStream; +import iaik.x509.X509Certificate; /** * Parses a <code><VerifyXMLSignatureResponse></code> returned by @@ -115,6 +117,9 @@ public class VerifyXMLSignatureResponseParser { private static final String CERTIFICATE_CHECK_CODE_XPATH = ROOT + MOA + "CertificateCheck/" + MOA + "Code"; + private static final String SIGNING_TIME_XPATH = + ROOT + MOA + "SigningTime"; + /** This is the root element of the XML-Document provided by the Security Layer Card*/ private Element verifyXMLSignatureResponse; @@ -200,7 +205,14 @@ public class VerifyXMLSignatureResponseParser { if (signatureManifestCheckCode != null) { respData.setSignatureManifestCheckCode(new Integer(signatureManifestCheckCode).intValue()); } - respData.setCertificateCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,CERTIFICATE_CHECK_CODE_XPATH,"")).intValue()); + respData.setCertificateCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,CERTIFICATE_CHECK_CODE_XPATH,"")).intValue()); + + String signingTimeElement = XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNING_TIME_XPATH,""); + if (MiscUtil.isNotEmpty(signingTimeElement)) { + DateTime datetime = ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(signingTimeElement); + respData.setSigningDateTime(datetime.toDate()); + + } } catch (Throwable t) { throw new ParseException("parser.01", null, t); 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 deleted file mode 100644 index f61b9a4da..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ /dev/null @@ -1,351 +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.auth.servlet; - -import java.io.IOException; -import java.io.PrintWriter; -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; -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.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; -import at.gv.egovernment.moa.id.auth.frontend.builder.DefaultGUIFormBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; -import at.gv.egovernment.moa.id.auth.frontend.exception.GUIBuildException; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -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.utils.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.data.ExceptionContainer; -import at.gv.egovernment.moa.id.moduls.IRequestStorage; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; -import at.gv.egovernment.moa.id.util.ErrorResponseUtils; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ -public abstract class AbstractController extends MOAIDAuthConstants { - - public static final String ERROR_CODE_PARAM = "errorid"; - - @Autowired protected IStatisticLogger statisticLogger; - @Autowired protected IRequestStorage requestStorage; - @Autowired protected ITransactionStorage transactionStorage; - @Autowired protected MOAReversionLogger revisionsLogger; - @Autowired protected AuthConfiguration authConfig; - @Autowired protected IGUIFormBuilder guiBuilder; - - @ExceptionHandler({MOAIDException.class}) - public void MOAIDExceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws IOException { - Logger.error(e.getMessage() , e); - internalMOAIDExceptionHandler(req, resp, e, true); - - } - - @ExceptionHandler({Exception.class}) - public void GenericExceptionHandler(HttpServletResponse resp, Exception exception) throws IOException { - Logger.error("Internel Server Error." , exception); - resp.setContentType(MediaType.HTML_UTF_8.toString()); - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + - "(Errorcode=9199" - +" | Description="+ StringEscapeUtils.escapeHtml(exception.getMessage()) + ")"); - return; - - } - - @ExceptionHandler({IOException.class}) - public void IOExceptionHandler(HttpServletResponse resp, Throwable exception) { - Logger.error("Internel Server Error." , exception); - resp.setContentType(MediaType.HTML_UTF_8.toString()); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - - } - - protected void handleError(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp, IRequest pendingReq) throws IOException { - - String pendingRequestID = null; - if (pendingReq != null) - pendingRequestID = pendingReq.getRequestID(); - - Throwable loggedException = null; - Throwable extractedException = extractOriginalExceptionFromProcessException(exceptionThrown); - - //extract pendingRequestID and originalException if it was a TaskExecutionException - if (extractedException instanceof TaskExecutionException) { - //set original exception - loggedException = ((TaskExecutionException) extractedException).getOriginalException(); - - //use TaskExecutionException directly, if no Original Exeception is included - if (loggedException == null) - loggedException = exceptionThrown; - - //set pending-request ID if it is set - String reqID = ((TaskExecutionException) extractedException).getPendingRequestID(); - if (MiscUtil.isNotEmpty(reqID)) - pendingRequestID = reqID; - - } else - loggedException = exceptionThrown; - - try { - //switch to protocol-finalize method to generate a protocol-specific error message - - //put exception into transaction store for redirect - String key = Random.nextLongRandom(); - if (pendingReq != null) { - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR); - transactionStorage.put(key, - new ExceptionContainer(pendingReq, loggedException),-1); - - } else { - transactionStorage.put(key, - new ExceptionContainer(null, loggedException),-1); - - } - - //build up redirect URL - String redirectURL = null; - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/"+AbstractAuthProtocolModulController.FINALIZEPROTOCOL_ENDPOINT - + "?" + ERROR_CODE_PARAM + "=" + key; - - //only add pending-request Id if it exists - if (MiscUtil.isNotEmpty(pendingRequestID)) - redirectURL += "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - return; - - } catch (Exception e) { - Logger.warn("Default error-handling FAILED. Exception can not be stored to Database.", e); - Logger.info("Switch to generic generic backup error-handling ... "); - handleErrorNoRedirect(loggedException, req, resp, true); - - } - - } - - /** - * Handles all exceptions with no pending request. - * Therefore, the error is written to the users browser - * - * @param throwable - * @param req - * @param resp - * @throws IOException - */ - protected void handleErrorNoRedirect(Throwable throwable, HttpServletRequest req, - HttpServletResponse resp, boolean writeExceptionToStatisticLog) throws IOException { - - //log Exception into statistic database - if (writeExceptionToStatisticLog) - statisticLogger.logErrorOperation(throwable); - - //write errror to console - logExceptionToTechnicalLog(throwable); - - //return error to Web browser - if (throwable instanceof MOAIDException || throwable instanceof ProcessExecutionException) - internalMOAIDExceptionHandler(req, resp, (Exception)throwable, false); - - else { - //write generic message for general exceptions - String msg = MOAIDMessageProvider.getInstance().getMessage("internal.00", null); - writeHTMLErrorResponse(req, resp, msg, "9199", (Exception) throwable); - - } - - } - - /** - * Write a Exception to the MOA-ID-Auth internal technical log - * - * @param loggedException Exception to log - */ - protected void logExceptionToTechnicalLog(Throwable loggedException) { - if (!( loggedException instanceof MOAIDException - || loggedException instanceof ProcessExecutionException )) { - Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); - - } else { - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { - Logger.warn(loggedException.getMessage(), loggedException); - - } else { - Logger.warn(loggedException.getMessage()); - - } - } - } - - private void writeBadRequestErrorResponse(HttpServletRequest req, HttpServletResponse resp, MOAIDException e) throws IOException { - ErrorResponseUtils utils = ErrorResponseUtils.getInstance(); - String code = utils.mapInternalErrorToExternalError( - ((InvalidProtocolRequestException)e).getMessageId()); - String descr = StringEscapeUtils.escapeHtml(e.getMessage()); - resp.setContentType(MediaType.HTML_UTF_8.toString()); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Protocol validation FAILED!" + - "(Errorcode=" + code + - " | Description=" + descr + ")"); - - } - - private void writeHTMLErrorResponse(HttpServletRequest req, HttpServletResponse httpResp, String msg, String errorCode, Exception error) throws IOException { - - try { - DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( - HTTPUtils.extractAuthURLFromRequest(req), - DefaultGUIFormBuilderConfiguration.VIEW_ERRORMESSAGE, - null); - - //add errorcode and errormessage - config.putCustomParameter("errorMsg", msg); - config.putCustomParameter("errorCode", errorCode); - - //add stacktrace if debug is enabled - if (Logger.isTraceEnabled()) { - config.putCustomParameter("stacktrace", getStacktraceFromException(error)); - - } - - guiBuilder.build(httpResp, config, "Error-Message"); - - } catch (GUIBuildException e) { - Logger.warn("Can not build error-message GUI.", e); - GenericExceptionHandler(httpResp, e); - - } - - } - - private void writeHTMLErrorResponse(HttpServletRequest req, HttpServletResponse httpResp, Exception error) throws IOException { - writeHTMLErrorResponse(req, httpResp, - error.getMessage(), - ErrorResponseUtils.getInstance().getResponseErrorCode(error), - error); - } - - - private String getStacktraceFromException(Exception ex) { - StringWriter errors = new StringWriter(); - ex.printStackTrace(new PrintWriter(errors)); - return errors.toString(); - - } - - /** - * Extracts a TaskExecutionException of a ProcessExecutionExeception Stacktrace. - * - * @param exception - * @return Return the latest TaskExecutionExecption if exists, otherwise the latest ProcessExecutionException - */ - private Throwable extractOriginalExceptionFromProcessException(Throwable exception) { - Throwable exholder = exception; - TaskExecutionException taskExc = null; - - while(exholder != null - && exholder instanceof ProcessExecutionException) { - ProcessExecutionException procExc = (ProcessExecutionException) exholder; - if (procExc.getCause() != null && - procExc.getCause() instanceof TaskExecutionException) { - taskExc = (TaskExecutionException) procExc.getCause(); - exholder = taskExc.getOriginalException(); - - } else - break; - - } - - if (taskExc == null) - return exholder; - - else - return taskExc; - } - - private void internalMOAIDExceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception e, boolean writeExceptionToStatisicLog) throws IOException { - if (e instanceof ProtocolNotActiveException) { - resp.getWriter().write(e.getMessage()); - resp.setContentType(MediaType.HTML_UTF_8.toString()); - resp.sendError(HttpServletResponse.SC_FORBIDDEN, StringEscapeUtils.escapeHtml(e.getMessage())); - - } else if (e instanceof AuthnRequestValidatorException) { - AuthnRequestValidatorException ex = (AuthnRequestValidatorException)e; - //log Error Message - if (writeExceptionToStatisicLog) - statisticLogger.logErrorOperation(ex, ex.getErrorRequest()); - - //write error message - writeBadRequestErrorResponse(req, resp, (MOAIDException) e); - - } else if (e instanceof InvalidProtocolRequestException) { - //send error response - writeBadRequestErrorResponse(req, resp, (MOAIDException) e); - - } else if (e instanceof ConfigurationException) { - //send HTML formated error message - writeHTMLErrorResponse(req, resp, (MOAIDException) e); - - } else if (e instanceof MOAIDException) { - //send HTML formated error message - writeHTMLErrorResponse(req, resp, e); - - } else if (e instanceof ProcessExecutionException) { - //send HTML formated error message - writeHTMLErrorResponse(req, resp, e); - - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractProcessEngineSignalController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractProcessEngineSignalController.java deleted file mode 100644 index 32f103ca7..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractProcessEngineSignalController.java +++ /dev/null @@ -1,86 +0,0 @@ -package at.gv.egovernment.moa.id.auth.servlet;
-
-import java.io.IOException;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.lang.StringEscapeUtils;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils;
-import at.gv.egovernment.moa.id.auth.exception.MOAIllegalStateException;
-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.process.ProcessEngine;
-import at.gv.egovernment.moa.logging.Logger;
-
-/**
- * Servlet that resumes a suspended process (in case of asynchronous tasks).
- *
- * @author tknall
- *
- */
-public abstract class AbstractProcessEngineSignalController extends AbstractController {
-
- @Autowired protected ProcessEngine processEngine;
-
- protected void signalProcessManagement(HttpServletRequest req, HttpServletResponse resp) throws IOException {
- String pendingRequestID = StringEscapeUtils.escapeHtml(getPendingRequestId(req));
- IRequest pendingReq = null;
- try {
- if (pendingRequestID == null) {
- throw new MOAIllegalStateException("process.03", new Object[]{"Unable to determine MOA pending-request id."});
-
- }
-
- pendingReq = requestStorage.getPendingRequest(pendingRequestID);
- if (pendingReq == null) {
- Logger.info("No PendingRequest with Id: " + pendingRequestID + " Maybe, a transaction timeout occure.");
- throw new MOAIDException("auth.28", new Object[]{pendingRequestID});
-
- }
-
- //change pending-request ID
- requestStorage.changePendingRequestID(pendingReq);
- pendingRequestID = pendingReq.getRequestID();
-
- // process instance is mandatory
- if (pendingReq.getProcessInstanceId() == null) {
- throw new MOAIllegalStateException("process.03", new Object[]{"MOA session does not provide process instance id."});
-
- }
-
- // wake up next task
- processEngine.signal(pendingReq);
-
- } catch (Exception ex) {
- handleError(null, ex, req, resp, pendingReq);
-
- } finally {
- //MOASessionDBUtils.closeSession();
- TransactionIDUtils.removeAllLoggingVariables();
-
- }
-
-
- }
-
- /**
- * Retrieves the current pending-request id from the HttpServletRequest parameter
- * {@link MOAIDAuthConstants#PARAM_TARGET_PENDINGREQUESTID}.
- * <p/>
- * Note that this class/method can be overwritten by modules providing their own strategy of retrieving the
- * respective pending-request id.
- *
- * @param request
- * The unterlying HttpServletRequest.
- * @return The current pending-request id.
- */
- public String getPendingRequestId(HttpServletRequest request) {
- return StringEscapeUtils.escapeHtml(request.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID));
-
- }
-
-}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java index 49145a850..18aa93cc9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java @@ -33,15 +33,16 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.IRequestStorage; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; +import at.gv.egiz.eaaf.core.impl.idp.controller.AbstractController; +import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; import at.gv.egovernment.moa.id.auth.frontend.builder.AbstractServiceProviderSpecificGUIFormBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; import at.gv.egovernment.moa.id.auth.frontend.builder.SPSpecificGUIBuilderConfigurationWithDBLoad; -import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.MOAIDConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.moduls.IRequestStorage; -import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -164,7 +165,7 @@ public class GUILayoutBuilderServlet extends AbstractController { private IRequest extractPendingRequest(HttpServletRequest req) { try { String pendingReqID = StringEscapeUtils.escapeHtml( - req.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); + req.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); if (MiscUtil.isNotEmpty(pendingReqID)) { IRequest pendingReq = requestStorage.getPendingRequest(pendingReqID); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GeneralProcessEngineSignalController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GeneralProcessEngineSignalController.java index dfa923558..87325989a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GeneralProcessEngineSignalController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GeneralProcessEngineSignalController.java @@ -31,6 +31,8 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import at.gv.egiz.eaaf.core.impl.idp.controller.AbstractProcessEngineSignalController; + /** * @author tlenz * 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 0397bd501..c39d78d8b 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 @@ -36,24 +36,27 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; +import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; +import at.gv.egiz.eaaf.core.impl.idp.controller.AbstractController; +import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.modules.pvp2.exception.NoMetadataInformationException; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; import at.gv.egovernment.moa.id.auth.frontend.builder.DefaultGUIFormBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.frontend.exception.GUIBuildException; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.data.ISLOInformationContainer; import at.gv.egovernment.moa.id.data.SLOInformationContainer; -import at.gv.egovernment.moa.id.moduls.AuthenticationManager; import at.gv.egovernment.moa.id.moduls.SSOManager; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NOSLOServiceDescriptorException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMetadataInformationException; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLEncoder; @@ -66,7 +69,7 @@ import at.gv.egovernment.moa.util.URLEncoder; public class IDPSingleLogOutServlet extends AbstractController { @Autowired SSOManager ssoManager; - @Autowired AuthenticationManager authManager; + @Autowired IAuthenticationManager authManager; @Autowired IAuthenticationSessionStoreage authenicationStorage; @Autowired SingleLogOutBuilder sloBuilder; @@ -127,6 +130,9 @@ public class IDPSingleLogOutServlet extends AbstractController { } catch (MOADatabaseException e) { handleErrorNoRedirect(e, req, resp, false); + } catch (EAAFException e) { + handleErrorNoRedirect(e, req, resp, false); + } return; @@ -135,10 +141,13 @@ public class IDPSingleLogOutServlet extends AbstractController { try { if (ssoManager.isValidSSOSession(ssoid, null)) { - AuthenticationSession authSession = authenicationStorage.getInternalMOASessionWithSSOID(ssoid); + String internalSSOId = authenicationStorage.getInternalSSOSessionWithSSOID(ssoid); - if(authSession != null) { - authManager.performSingleLogOut(req, resp, authSession, authURL); + if(MiscUtil.isNotEmpty(internalSSOId)) { + ISLOInformationContainer sloInfoContainer = authManager.performSingleLogOut(req, resp, null, internalSSOId); + + Logger.debug("Starting technical SLO process ... "); + sloBuilder.toTechnicalLogout(sloInfoContainer, req, resp, authURL); return; } @@ -154,16 +163,24 @@ public class IDPSingleLogOutServlet extends AbstractController { if (MiscUtil.isNotEmpty(restartProcess)) { Logger.info("Restart Single LogOut process after timeout ... "); try { - ISLOInformationContainer sloContainer = transactionStorage.get(restartProcess, SLOInformationContainer.class); + SLOInformationContainer sloContainer = transactionStorage.get(restartProcess, SLOInformationContainer.class); + if (sloContainer == null) { + Logger.info("No Single LogOut processing information with ID: " + restartProcess); + handleErrorNoRedirect(new MOAIDException("slo.03", null), req, resp, false); + return; + + } + if (sloContainer.hasFrontChannelOA()) sloContainer.putFailedOA("differntent OAs"); String redirectURL = null; - if (sloContainer.getSloRequest() != null) { + IRequest sloReq = sloContainer.getSloRequest(); + if (sloReq != null && sloReq instanceof PVPSProfilePendingRequest) { //send SLO response to SLO request issuer - SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(sloContainer.getSloRequest()); - LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, sloContainer.getSloRequest(), sloContainer.getSloFailedOAs()); - redirectURL = sloBuilder.getFrontChannelSLOMessageURL(sloService, message, req, resp, sloContainer.getSloRequest().getRequest().getRelayState()); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor((PVPSProfilePendingRequest)sloContainer.getSloRequest()); + LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, (PVPSProfilePendingRequest)sloContainer.getSloRequest(), sloContainer.getSloFailedOAs()); + redirectURL = sloBuilder.getFrontChannelSLOMessageURL(sloService, message, req, resp, ((PVPSProfilePendingRequest)sloContainer.getSloRequest()).getRequest().getRelayState()); } else { //print SLO information directly @@ -205,6 +222,9 @@ public class IDPSingleLogOutServlet extends AbstractController { } catch (MOAIDException e) { Logger.warn("Build SLO respone FAILED.", e); + } catch (EAAFException e) { + Logger.warn("Build SLO respone FAILED.", e); + } try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java index 8ef047300..0285dd75b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java @@ -56,13 +56,11 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egiz.eaaf.core.api.idp.auth.ISSOManager; +import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.moduls.AuthenticationManager; -import at.gv.egovernment.moa.id.moduls.SSOManager; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -71,9 +69,11 @@ import at.gv.egovernment.moa.util.MiscUtil; public class LogOutServlet { private static final String REDIRECT_URL = "redirect"; - @Autowired private SSOManager ssomanager; - @Autowired private AuthenticationManager authmanager; - @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; + @Autowired(required=true) private ISSOManager ssomanager; + //@Autowired(required=true) private IAuthenticationManager authmanager; + @Autowired(required=true) private IAuthenticationSessionStoreage authenticatedSessionStorage; + @Autowired(required=true) private AuthConfiguration authConfig; + @RequestMapping(value = "/LogOut", method = {RequestMethod.POST, RequestMethod.GET}) public void performLogOut(HttpServletRequest req, HttpServletResponse resp) throws IOException { @@ -81,10 +81,7 @@ public class LogOutServlet { String redirectUrl = (String) req.getParameter(REDIRECT_URL); - try { - //get SSO token from request - String ssoid = ssomanager.getSSOSessionID(req); - + try { if (MiscUtil.isEmpty(redirectUrl)) { //set default redirect Target Logger.debug("Set default RedirectURL back to MOA-ID-Auth"); @@ -92,7 +89,7 @@ public class LogOutServlet { } else { //return an error if RedirectURL is not a active Online-Applikation - IOAAuthParameters oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(redirectUrl); + IOAAuthParameters oa = authConfig.getServiceProviderConfiguration(redirectUrl, IOAAuthParameters.class); if (oa == null) { Logger.info("RedirctURL does not match to OA configuration. Set default RedirectURL back to MOA-ID-Auth"); redirectUrl = HTTPUtils.extractAuthURLFromRequest(req); @@ -101,23 +98,11 @@ public class LogOutServlet { } - if (ssomanager.isValidSSOSession(ssoid, null)) { - - //TODO: Single LogOut Implementation - - //delete SSO session and MOA session - AuthenticationSession moasessionid = authenticatedSessionStorage.getInternalMOASessionWithSSOID(ssoid); - authmanager.performOnlyIDPLogOut(moasessionid); - - Logger.info("User with SSO Id " + ssoid + " is logged out and get redirect to "+ redirectUrl); - } else { + if (ssomanager.destroySSOSessionOnIDPOnly(req, resp, null)) + Logger.info("User with SSO is logged out and get redirect to "+ redirectUrl); + else Logger.info("No active SSO session found. User is maybe logout already and get redirect to "+ redirectUrl); - - } - - //Remove SSO token - ssomanager.deleteSSOSessionID(req, resp); - + } catch (Exception e) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Request not allowed."); return; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java index a00de1da0..e5a8bb739 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java @@ -23,6 +23,7 @@ package at.gv.egovernment.moa.id.auth.servlet; import java.io.IOException; +import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -33,14 +34,14 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; +import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; import at.gv.egovernment.moa.id.auth.frontend.builder.DefaultGUIFormBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLEncoder; @@ -57,8 +58,9 @@ public class RedirectServlet { private static final String URL = "URL"; private static final String TARGET = "TARGET"; - @Autowired SSOManager ssoManager; - @Autowired IGUIFormBuilder guiBuilder; + @Autowired(required=true) SSOManager ssoManager; + @Autowired(required=true) IGUIFormBuilder guiBuilder; + @Autowired(required=true) private AuthConfiguration authConfig; @RequestMapping(value = "/RedirectServlet", method = RequestMethod.GET) public void performLogOut(HttpServletRequest req, HttpServletResponse resp) throws IOException { @@ -78,10 +80,13 @@ public class RedirectServlet { //url = URLDecoder.decode(url, "UTF-8"); - oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(url); + oa = authConfig.getServiceProviderConfiguration(url, IOAAuthParameters.class); String authURL = HTTPUtils.extractAuthURLFromRequest(req); - if (oa == null || !AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix().contains(authURL)) { + List<String> allowedPublicUrlPrefixes = authConfig.getPublicURLPrefix(); + + if ((oa == null && !checkRedirectToItself(url, allowedPublicUrlPrefixes)) + || !authConfig.getPublicURLPrefix().contains(authURL)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Parameters not valid"); return; @@ -166,5 +171,17 @@ public class RedirectServlet { } } + + private boolean checkRedirectToItself(String url, List<String> allowedPublicUrlPrefixes) { + if (url != null) { + for (String el : allowedPublicUrlPrefixes) { + if (url.startsWith(el)) + return true; + + } + } + + return false; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/UniqueSessionIdentifierInterceptor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/UniqueSessionIdentifierInterceptor.java index 466364adb..5aa3a691f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/UniqueSessionIdentifierInterceptor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/UniqueSessionIdentifierInterceptor.java @@ -25,14 +25,18 @@ package at.gv.egovernment.moa.id.auth.servlet.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; -import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.commons.MOAIDConstants; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.IRequestStorage; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.core.impl.utils.TransactionIDUtils; import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.util.MiscUtil; /** @@ -41,7 +45,9 @@ import at.gv.egovernment.moa.util.MiscUtil; */ public class UniqueSessionIdentifierInterceptor implements HandlerInterceptor { - @Autowired private SSOManager ssomanager; + @Autowired private IRequestStorage requestStorage; + @Autowired(required=false) private SSOManager ssomanager; + /* (non-Javadoc) * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) @@ -50,18 +56,35 @@ public class UniqueSessionIdentifierInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - //get SSO Cookie for Request - String ssoId = ssomanager.getSSOSessionID(request); + String uniqueSessionIdentifier = null; - //search for unique session identifier - String uniqueSessionIdentifier = ssomanager.getUniqueSessionIdentifier(ssoId); - if (MiscUtil.isEmpty(uniqueSessionIdentifier)) - uniqueSessionIdentifier = Random.nextRandom(); + //if SSOManager is available, search SessionIdentifier in SSO session + if (ssomanager != null) { + String ssoId = ssomanager.getSSOSessionID(request); + uniqueSessionIdentifier = ssomanager.getUniqueSessionIdentifier(ssoId); + + } - TransactionIDUtils.setSessionId(uniqueSessionIdentifier); - request.setAttribute(MOAIDConstants.UNIQUESESSIONIDENTIFIER, uniqueSessionIdentifier); + // search SessionIdentifier in PendingRequest if available + if (MiscUtil.isEmpty(uniqueSessionIdentifier)) { + String pendingReqId = StringEscapeUtils.escapeHtml4( + request.getParameter(EAAFConstants.PARAM_HTTP_TARGET_PENDINGREQUESTID)); + if (StringUtils.isNotEmpty(pendingReqId)) { + IRequest pendingReq = requestStorage.getPendingRequest(pendingReqId); + if (pendingReq != null) + uniqueSessionIdentifier = pendingReq.getUniqueSessionIdentifier(); + + } + } + + //if NO SSOSession and no PendingRequest create new SessionIdentifier + if (StringUtils.isEmpty(uniqueSessionIdentifier)) + uniqueSessionIdentifier = Random.nextHexRandom16(); + TransactionIDUtils.setSessionId(uniqueSessionIdentifier); + request.setAttribute(EAAFConstants.UNIQUESESSIONIDENTIFIER, uniqueSessionIdentifier); return true; + } /* (non-Javadoc) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/VHostUrlRewriteServletFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/VHostUrlRewriteServletFilter.java index 93d74d7ef..4dac390e6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/VHostUrlRewriteServletFilter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/VHostUrlRewriteServletFilter.java @@ -37,9 +37,9 @@ import javax.servlet.http.HttpServletRequest; import org.springframework.context.ApplicationContext; +import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; 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.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/WebFrontEndSecurityInterceptor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/WebFrontEndSecurityInterceptor.java index c8c6c1fb5..ee69b082b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/WebFrontEndSecurityInterceptor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/WebFrontEndSecurityInterceptor.java @@ -30,10 +30,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; +import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java new file mode 100644 index 000000000..604d224eb --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/IdentityLinkValidator.java @@ -0,0 +1,210 @@ +/******************************************************************************* + * 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. + ******************************************************************************/ +/* + * 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.auth.validator; + +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egiz.eaaf.core.impl.idp.auth.data.IdentityLink; +import at.gv.egiz.eaaf.core.impl.utils.XPathUtils; +import at.gv.egovernment.moa.id.auth.exception.ValidateException; +import at.gv.egovernment.moa.util.Constants; + +/** + * This class is used to validate an {@link IdentityLink} + * returned by the security layer + * + * @author Stefan Knirsch + * @version $Id$ + */ +public class IdentityLinkValidator implements Constants { + + // + // XPath namespace prefix shortcuts + // + /** Xpath prefix for reaching PersonData Namespaces */ + private static final String PDATA = PD_PREFIX + ":"; + /** Xpath prefix for reaching SAML Namespaces */ + private static final String SAML = SAML_PREFIX + ":"; + /** Xpath prefix for reaching XML-DSIG Namespaces */ + private static final String DSIG = DSIG_PREFIX + ":"; + /** Xpath prefix for reaching ECDSA Namespaces */ + private static final String ECDSA = ECDSA_PREFIX + ":"; + /** Xpath expression to the root element */ + private static final String ROOT = ""; + /** Xpath expression to the SAML:SubjectConfirmationData element */ + private static final String SAML_SUBJECT_CONFIRMATION_DATA_XPATH = + ROOT + + SAML + + "AttributeStatement/" + + SAML + + "Subject/" + + SAML + + "SubjectConfirmation/" + + SAML + + "SubjectConfirmationData"; +/** Xpath expression to the PersonData:Person element */ + private static final String PERSON_XPATH = + SAML_SUBJECT_CONFIRMATION_DATA_XPATH + "/" + PDATA + "Person"; + /** Xpath expression to the SAML:Attribute element */ + private static final String ATTRIBUTE_XPATH = + ROOT + SAML + "AttributeStatement/" + SAML + "Attribute"; +// /** Xpath expression to the SAML:AttributeName attribute */ +// private static final String ATTRIBUTE_NAME_XPATH = +// ROOT + SAML + "AttributeStatement/" + SAML + "Attribute/@AttributeName"; +// /** Xpath expression to the SAML:AttributeNamespace attribute */ +// private static final String ATTRIBUTE_NAMESPACE_XPATH = +// ROOT +// + SAML +// + "AttributeStatement/" +// + SAML +// + "Attribute/@AttributeNamespace"; +// /** Xpath expression to the SAML:AttributeValue element */ +// private static final String ATTRIBUTE_VALUE_XPATH = +// ROOT +// + SAML +// + "AttributeStatement/" +// + SAML +// + "Attribute/" +// + SAML +// + "AttributeValue"; + + /** Singleton instance. <code>null</code>, if none has been created. */ + private static IdentityLinkValidator instance; + + /** + * Constructor for a singleton IdentityLinkValidator. + * @return a new IdentityLinkValidator instance + * @throws ValidateException if no instance can be created + */ + public static synchronized IdentityLinkValidator getInstance() + throws ValidateException { + if (instance == null) { + instance = new IdentityLinkValidator(); + } + return instance; + } + + /** + * Method validate. Validates the {@link IdentityLink} + * @param identityLink The identityLink to validate + * @throws ValidateException on any validation error + */ + public void validate(IIdentityLink identityLink) throws ValidateException { + + Element samlAssertion = identityLink.getSamlAssertion(); + //Search the SAML:ASSERTION Object (A2.054) + if (samlAssertion == null) { + throw new ValidateException("validator.00", null); + } + + // Check how many saml:Assertion/saml:AttributeStatement/ + // saml:Subject/ saml:SubjectConfirmation/ + // saml:SubjectConfirmationData/pr:Person of type + // PhysicalPersonType exist (A2.056) + NodeList nl = XPathUtils.selectNodeList(samlAssertion, PERSON_XPATH); + // If we have just one Person-Element we don't need to check the attributes + int counterPhysicalPersonType = 0; + if (nl.getLength() > 1) + for (int i = 0; i < nl.getLength(); i++) { + String xsiType = + ((Element) nl.item(i)) + .getAttributeNodeNS( + "http://www.w3.org/2001/XMLSchema-instance", + "type") + .getNodeValue(); + // We have to check if xsiType contains "PhysicalPersonType" + // An equal-check will fail because of the Namespace-prefix of the attribute value + if (xsiType.indexOf("PhysicalPersonType") > -1) + counterPhysicalPersonType++; + } + if (counterPhysicalPersonType > 1) + throw new ValidateException("validator.01", null); + + //Check the SAML:ATTRIBUTES + nl = XPathUtils.selectNodeList(samlAssertion, ATTRIBUTE_XPATH); + for (int i = 0; i < nl.getLength(); i++) { + String attributeName = + XPathUtils.getAttributeValue( + (Element) nl.item(i), + "@AttributeName", + null); + String attributeNS = + XPathUtils.getAttributeValue( + (Element) nl.item(i), + "@AttributeNamespace", + null); + if (attributeName.equals("CitizenPublicKey")) { + + if (attributeNS.equals("http://www.buergerkarte.at/namespaces/personenbindung/20020506#") || + attributeNS.equals("urn:publicid:gv.at:namespaces:identitylink:1.2")) { + Element attributeValue = + (Element) XPathUtils.selectSingleNode((Element) nl.item(i),nSMap, SAML + "AttributeValue/" + DSIG + "RSAKeyValue"); + if (attributeValue==null) + attributeValue = + (Element) XPathUtils.selectSingleNode((Element)nl.item(i), nSMap, SAML + "AttributeValue/" + ECDSA + "ECDSAKeyValue"); + if (attributeValue==null) + attributeValue = + (Element) XPathUtils.selectSingleNode((Element)nl.item(i), nSMap, SAML + "AttributeValue/" + DSIG + "DSAKeyValue"); + if (attributeValue == null) + throw new ValidateException("validator.02", null); + + } + else + throw new ValidateException("validator.03", new Object [] {attributeNS} ); + } + else + throw new ValidateException("validator.04", new Object [] {attributeName} ); + } + + //Check if dsig:Signature exists + Element dsigSignature = (Element) XPathUtils.selectSingleNode(samlAssertion,ROOT + DSIG + "Signature"); + if (dsigSignature==null) throw new ValidateException("validator.05", new Object[] {"in der Personenbindung"}); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureRequestBuilder.java new file mode 100644 index 000000000..d1c67b06e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureRequestBuilder.java @@ -0,0 +1,408 @@ +/******************************************************************************* + * 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. + ******************************************************************************/ +/* + * 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.auth.validator; + +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; + +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse; +import at.gv.egovernment.moa.id.auth.exception.BuildException; +import at.gv.egovernment.moa.id.auth.exception.ParseException; +import at.gv.egovernment.moa.util.Base64Utils; +import at.gv.egovernment.moa.util.Constants; + +/** + * Builder for the <code><VerifyXMLSignatureRequestBuilder></code> structure + * used for sending the DSIG-Signature of the Security Layer card for validating to MOA-SP. + * + * @author Stefan Knirsch + * @version $Id$ + */ +public class VerifyXMLSignatureRequestBuilder { + + /** shortcut for XMLNS namespace URI */ + private static final String XMLNS_NS_URI = Constants.XMLNS_NS_URI; + /** shortcut for MOA namespace URI */ + private static final String MOA_NS_URI = Constants.MOA_NS_URI; + /** The DSIG-Prefix */ + private static final String DSIG = Constants.DSIG_PREFIX + ":"; + + /** The document containing the <code>VerifyXMLsignatureRequest</code> */ + private Document requestDoc_; + /** the <code>VerifyXMLsignatureRequest</code> root element */ + private Element requestElem_; + + + /** + * Builds the body for a <code>VerifyXMLsignatureRequest</code> including the root + * element and namespace declarations. + * + * @throws BuildException If an error occurs on building the document. + */ + public VerifyXMLSignatureRequestBuilder() throws BuildException { + try { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + requestDoc_ = docBuilder.newDocument(); + requestElem_ = requestDoc_.createElementNS(MOA_NS_URI, "VerifyXMLSignatureRequest"); + requestElem_.setAttributeNS(XMLNS_NS_URI, "xmlns", MOA_NS_URI); + requestElem_.setAttributeNS(XMLNS_NS_URI, "xmlns:" + Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); + requestDoc_.appendChild(requestElem_); + } catch (Throwable t) { + throw new BuildException( + "builder.00", + new Object[] {"VerifyXMLSignatureRequest", t.toString()}, + t); + } + } + + + /** + * Builds a <code><VerifyXMLSignatureRequest></code> + * from an IdentityLink with a known trustProfileID which + * has to exist in MOA-SP + * @param identityLink - The IdentityLink + * @param trustProfileID - a preconfigured TrustProfile at MOA-SP + * + * @return Element - The complete request as Dom-Element + * + * @throws ParseException + */ + public Element build(IIdentityLink identityLink, String trustProfileID) + throws ParseException + { + try { + // build the request + Element dateTimeElem = requestDoc_.createElementNS(MOA_NS_URI, "DateTime"); + requestElem_.appendChild(dateTimeElem); + Node dateTime = requestDoc_.createTextNode(identityLink.getIssueInstant()); + dateTimeElem.appendChild(dateTime); + Element verifiySignatureInfoElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo"); + requestElem_.appendChild(verifiySignatureInfoElem); + Element verifySignatureEnvironmentElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment"); + verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem); + Element base64ContentElem = requestDoc_.createElementNS(MOA_NS_URI, "Base64Content"); + verifySignatureEnvironmentElem.appendChild(base64ContentElem); + // insert the base64 encoded identity link SAML assertion + String serializedAssertion = identityLink.getSerializedSamlAssertion(); + String base64EncodedAssertion = Base64Utils.encode(serializedAssertion.getBytes("UTF-8")); + //replace all '\r' characters by no char. + StringBuffer replaced = new StringBuffer(); + for (int i = 0; i < base64EncodedAssertion.length(); i ++) { + char c = base64EncodedAssertion.charAt(i); + if (c != '\r') { + replaced.append(c); + } + } + base64EncodedAssertion = replaced.toString(); + Node base64Content = requestDoc_.createTextNode(base64EncodedAssertion); + base64ContentElem.appendChild(base64Content); + // specify the signature location + Element verifySignatureLocationElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation"); + verifiySignatureInfoElem.appendChild(verifySignatureLocationElem); + Node signatureLocation = requestDoc_.createTextNode(DSIG + "Signature"); + verifySignatureLocationElem.appendChild(signatureLocation); + // signature manifest params + Element signatureManifestCheckParamsElem = + requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams"); + requestElem_.appendChild(signatureManifestCheckParamsElem); + signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "false"); + // add the transforms + Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo"); + signatureManifestCheckParamsElem.appendChild(referenceInfoElem); + Element[] dsigTransforms = identityLink.getDsigReferenceTransforms(); + + for (int i = 0; i < dsigTransforms.length; i++) { + Element verifyTransformsInfoProfileElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfile"); + referenceInfoElem.appendChild(verifyTransformsInfoProfileElem); + verifyTransformsInfoProfileElem.appendChild(requestDoc_.importNode(dsigTransforms[i], true)); + } + Element returnHashInputDataElem = + requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData"); + requestElem_.appendChild(returnHashInputDataElem); + Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID"); + trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID)); + requestElem_.appendChild(trustProfileIDElem); + } catch (Throwable t) { + throw new ParseException("builder.00", + new Object[] { "VerifyXMLSignatureRequest (IdentityLink)" }, t); + } + + return requestElem_; + } + + /** + * Builds a <code><VerifyXMLSignatureRequest></code> + * from an IdentityLink with a known trustProfileID which + * has to exist in MOA-SP + * @param identityLink - The IdentityLink + * @param trustProfileID - a preconfigured TrustProfile at MOA-SP + * + * @return Element - The complete request as Dom-Element + * + * @throws ParseException + */ + public Element build(byte[]mandate, String trustProfileID) + throws ParseException + { + try { + // build the request +// Element dateTimeElem = requestDoc_.createElementNS(MOA_NS_URI, "DateTime"); +// requestElem_.appendChild(dateTimeElem); +// Node dateTime = requestDoc_.createTextNode(identityLink.getIssueInstant()); +// dateTimeElem.appendChild(dateTime); + Element verifiySignatureInfoElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo"); + requestElem_.appendChild(verifiySignatureInfoElem); + Element verifySignatureEnvironmentElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment"); + verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem); + Element base64ContentElem = requestDoc_.createElementNS(MOA_NS_URI, "Base64Content"); + verifySignatureEnvironmentElem.appendChild(base64ContentElem); + // insert the base64 encoded identity link SAML assertion + //String serializedAssertion = identityLink.getSerializedSamlAssertion(); + //String base64EncodedAssertion = Base64Utils.encode(mandate.getBytes("UTF-8")); + String base64EncodedAssertion = Base64Utils.encode(mandate); + //replace all '\r' characters by no char. + StringBuffer replaced = new StringBuffer(); + for (int i = 0; i < base64EncodedAssertion.length(); i ++) { + char c = base64EncodedAssertion.charAt(i); + if (c != '\r') { + replaced.append(c); + } + } + base64EncodedAssertion = replaced.toString(); + Node base64Content = requestDoc_.createTextNode(base64EncodedAssertion); + base64ContentElem.appendChild(base64Content); + // specify the signature location + Element verifySignatureLocationElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation"); + verifiySignatureInfoElem.appendChild(verifySignatureLocationElem); + Node signatureLocation = requestDoc_.createTextNode(DSIG + "Signature"); + verifySignatureLocationElem.appendChild(signatureLocation); + // signature manifest params + Element signatureManifestCheckParamsElem = + requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams"); + requestElem_.appendChild(signatureManifestCheckParamsElem); + signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "false"); +// // add the transforms +// Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo"); +// signatureManifestCheckParamsElem.appendChild(referenceInfoElem); +// Element[] dsigTransforms = identityLink.getDsigReferenceTransforms(); +// +// for (int i = 0; i < dsigTransforms.length; i++) { +// Element verifyTransformsInfoProfileElem = +// requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfile"); +// referenceInfoElem.appendChild(verifyTransformsInfoProfileElem); +// verifyTransformsInfoProfileElem.appendChild(requestDoc_.importNode(dsigTransforms[i], true)); +// } + Element returnHashInputDataElem = + requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData"); + requestElem_.appendChild(returnHashInputDataElem); + Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID"); + trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID)); + requestElem_.appendChild(trustProfileIDElem); + } catch (Throwable t) { + throw new ParseException("builder.00", + new Object[] { "VerifyXMLSignatureRequest (IdentityLink)" }, t); + } + + return requestElem_; + } + + + /** + * Builds a <code><VerifyXMLSignatureRequest></code> + * from the signed AUTH-Block with a known trustProfileID which + * has to exist in MOA-SP + * @param csr - signed AUTH-Block + * @param verifyTransformsInfoProfileID - allowed verifyTransformsInfoProfileID + * @param trustProfileID - a preconfigured TrustProfile at MOA-SP + * @return Element - The complete request as Dom-Element + * @throws ParseException + */ + public Element build( + CreateXMLSignatureResponse csr, + List<String> verifyTransformsInfoProfileID, + String trustProfileID) + throws BuildException { //samlAssertionObject + + try { + // build the request +// requestElem_.setAttributeNS(Constants.XMLNS_NS_URI, "xmlns:" +// + Constants.XML_PREFIX, Constants.XMLNS_NS_URI); + Element verifiySignatureInfoElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo"); + requestElem_.appendChild(verifiySignatureInfoElem); + Element verifySignatureEnvironmentElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment"); + verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem); + Element xmlContentElem = requestDoc_.createElementNS(MOA_NS_URI, "XMLContent"); + verifySignatureEnvironmentElem.appendChild(xmlContentElem); + xmlContentElem.setAttribute(Constants.XML_PREFIX + ":space", "preserve"); + // insert the SAML assertion + xmlContentElem.appendChild(requestDoc_.importNode(csr.getSamlAssertion(), true)); + // specify the signature location + Element verifySignatureLocationElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation"); + verifiySignatureInfoElem.appendChild(verifySignatureLocationElem); + Node signatureLocation = requestDoc_.createTextNode(DSIG + "Signature"); + verifySignatureLocationElem.appendChild(signatureLocation); + // signature manifest params + Element signatureManifestCheckParamsElem = + requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams"); + requestElem_.appendChild(signatureManifestCheckParamsElem); + signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "true"); + // add the transform profile IDs + Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo"); + signatureManifestCheckParamsElem.appendChild(referenceInfoElem); + +// for (int i = 0; i < verifyTransformsInfoProfileID.length; i++) { +// +// Element verifyTransformsInfoProfileIDElem = +// requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfileID"); +// referenceInfoElem.appendChild(verifyTransformsInfoProfileIDElem); +// verifyTransformsInfoProfileIDElem.appendChild( +// requestDoc_.createTextNode(verifyTransformsInfoProfileID[i])); +// } + + for (String element : verifyTransformsInfoProfileID) { + + Element verifyTransformsInfoProfileIDElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifyTransformsInfoProfileID"); + referenceInfoElem.appendChild(verifyTransformsInfoProfileIDElem); + verifyTransformsInfoProfileIDElem.appendChild( + requestDoc_.createTextNode(element)); + } + + Element returnHashInputDataElem = + requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData"); + requestElem_.appendChild(returnHashInputDataElem); + Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID"); + trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID)); + requestElem_.appendChild(trustProfileIDElem); + + } catch (Throwable t) { + throw new BuildException("builder.00", new Object[] { "VerifyXMLSignatureRequest" }, t); + } + + return requestElem_; + } + + /** + * Builds a <code><VerifyXMLSignatureRequest></code> + * from the signed data with a known trustProfileID which + * has to exist in MOA-SP + * @param csr - signed AUTH-Block + * @param trustProfileID - a preconfigured TrustProfile at MOA-SP + * @return Element - The complete request as Dom-Element + * @throws ParseException + */ + public Element buildDsig( + CreateXMLSignatureResponse csr, + String trustProfileID) + throws BuildException { //samlAssertionObject + + try { + // build the request +// requestElem_.setAttributeNS(Constants.XMLNS_NS_URI, "xmlns:" +// + Constants.XML_PREFIX, Constants.XMLNS_NS_URI); + + Element verifiySignatureInfoElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureInfo"); + requestElem_.appendChild(verifiySignatureInfoElem); + Element verifySignatureEnvironmentElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureEnvironment"); + verifiySignatureInfoElem.appendChild(verifySignatureEnvironmentElem); + + Element xmlContentElem = requestDoc_.createElementNS(MOA_NS_URI, "XMLContent"); + verifySignatureEnvironmentElem.appendChild(xmlContentElem); + xmlContentElem.setAttribute(Constants.XML_PREFIX + ":space", "preserve"); + + // insert the dsig:Signature + xmlContentElem.appendChild(requestDoc_.importNode(csr.getDsigSignature(), true)); + // specify the signature location + Element verifySignatureLocationElem = + requestDoc_.createElementNS(MOA_NS_URI, "VerifySignatureLocation"); + verifiySignatureInfoElem.appendChild(verifySignatureLocationElem); + Node signatureLocation = requestDoc_.createTextNode("/"+ DSIG + "Signature"); + verifySignatureLocationElem.appendChild(signatureLocation); + // signature manifest params + Element signatureManifestCheckParamsElem = + requestDoc_.createElementNS(MOA_NS_URI, "SignatureManifestCheckParams"); + requestElem_.appendChild(signatureManifestCheckParamsElem); + signatureManifestCheckParamsElem.setAttribute("ReturnReferenceInputData", "true"); + // add the transform profile IDs + Element referenceInfoElem = requestDoc_.createElementNS(MOA_NS_URI, "ReferenceInfo"); + signatureManifestCheckParamsElem.appendChild(referenceInfoElem); + + Element returnHashInputDataElem = + requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData"); + requestElem_.appendChild(returnHashInputDataElem); + Element trustProfileIDElem = requestDoc_.createElementNS(MOA_NS_URI, "TrustProfileID"); + + trustProfileIDElem.appendChild(requestDoc_.createTextNode(trustProfileID)); + requestElem_.appendChild(trustProfileIDElem); + + } catch (Throwable t) { + throw new BuildException("builder.00", new Object[] { "VerifyXMLSignatureRequest" }, t); + } + + return requestElem_; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java new file mode 100644 index 000000000..b9c15e75e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java @@ -0,0 +1,308 @@ +/******************************************************************************* + * 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. + ******************************************************************************/ +/* + * 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.auth.validator; + +import java.security.InvalidKeyException; +import java.security.PublicKey; +import java.security.interfaces.RSAPublicKey; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import at.gv.egiz.eaaf.core.api.idp.auth.data.IIdentityLink; +import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; +import at.gv.egovernment.moa.id.auth.exception.ValidateException; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egovernment.moa.id.commons.api.data.IVerifiyXMLSignatureResponse; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; +import at.gv.egovernment.moa.logging.Logger; +import iaik.asn1.structures.Name; +import iaik.security.ec.common.ECPublicKey; +import iaik.utils.RFC2253NameParserException; +import iaik.x509.X509Certificate; +import iaik.x509.X509ExtensionInitException; + +/** + * This class is used to validate an {@link VerifyXMLSignatureResponse} + * returned by MOA-SPSS + * + * @author Stefan Knirsch + * @version $Id$ + */ +public class VerifyXMLSignatureResponseValidator { + + /** Identification string for checking identity link */ + public static final String CHECK_IDENTITY_LINK = "IdentityLink"; + /** Identification string for checking authentication block */ + public static final String CHECK_AUTH_BLOCK = "AuthBlock"; + + /** Singleton instance. <code>null</code>, if none has been created. */ + private static VerifyXMLSignatureResponseValidator instance; + + /** + * Constructor for a singleton VerifyXMLSignatureResponseValidator. + */ + public static synchronized VerifyXMLSignatureResponseValidator getInstance() + throws ValidateException { + if (instance == null) { + instance = new VerifyXMLSignatureResponseValidator(); + } + return instance; + } + + /** + * Validates a {@link VerifyXMLSignatureResponse} returned by MOA-SPSS. + * + * @param verifyXMLSignatureResponse the <code><VerifyXMLSignatureResponse></code> + * @param identityLinkSignersSubjectDNNames subject names configured + * @param whatToCheck is used to identify whether the identityLink or the Auth-Block is validated + * @param oaParam specifies whether the validation result of the + * manifest has to be ignored (identityLink validation if + * the OA is a business service) or not + * @throws ValidateException on any validation error + * @throws ConfigurationException + */ + public void validate(IVerifiyXMLSignatureResponse verifyXMLSignatureResponse, + List<String> identityLinkSignersSubjectDNNames, + String whatToCheck, + IOAAuthParameters oaParam, + AuthConfiguration authConfig) + throws ValidateException, ConfigurationException { + + if (verifyXMLSignatureResponse.getSignatureCheckCode() != 0) + throw new ValidateException("validator.06", new Object[] {whatToCheck}); + + if (verifyXMLSignatureResponse.getCertificateCheckCode() != 0) { + String checkFailedReason =""; + if (verifyXMLSignatureResponse.getCertificateCheckCode() == 1) + checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.21", null); + if (verifyXMLSignatureResponse.getCertificateCheckCode() == 2) + checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.22", null); + if (verifyXMLSignatureResponse.getCertificateCheckCode() == 3) + checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.23", null); + if (verifyXMLSignatureResponse.getCertificateCheckCode() == 4) + checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.24", null); + if (verifyXMLSignatureResponse.getCertificateCheckCode() == 5) + checkFailedReason = MOAIDMessageProvider.getInstance().getMessage("validator.25", null); + +// TEST CARDS + if (whatToCheck.equals(CHECK_IDENTITY_LINK)) + throw new ValidateException("validator.07", new Object[] { checkFailedReason } ); + else + throw new ValidateException("validator.19", new Object[] { checkFailedReason } ); + } + + //check QC + if (authConfig.isCertifiacteQCActive() && + !whatToCheck.equals(CHECK_IDENTITY_LINK) && + !verifyXMLSignatureResponse.isQualifiedCertificate()) { + + //check if testcards are active and certificate has an extension for test credentials + if (oaParam.isTestCredentialEnabled()) { + boolean foundTestCredentialOID = false; + try { + X509Certificate signerCert = verifyXMLSignatureResponse.getX509certificate(); + + List<String> validOIDs = new ArrayList<String>(); + if (oaParam.getTestCredentialOIDs() != null) + validOIDs.addAll(oaParam.getTestCredentialOIDs()); + else + validOIDs.add(MOAIDAuthConstants.TESTCREDENTIALROOTOID); + + Set<String> extentsions = signerCert.getCriticalExtensionOIDs(); + extentsions.addAll(signerCert.getNonCriticalExtensionOIDs()); + Iterator<String> extit = extentsions.iterator(); + while(extit.hasNext()) { + String certOID = extit.next(); + for (String el : validOIDs) { + if (certOID.startsWith(el)) + foundTestCredentialOID = true; + } + } + + } catch (Exception e) { + Logger.warn("Test credential OID extraction FAILED.", e); + + } + //throw Exception if not TestCredentialOID is found + if (!foundTestCredentialOID) + throw new ValidateException("validator.72", null); + + } else + throw new ValidateException("validator.71", null); + } + + // if OA is type is business service the manifest validation result has + // to be ignored + boolean ignoreManifestValidationResult = false; + if (whatToCheck.equals(CHECK_IDENTITY_LINK)) + ignoreManifestValidationResult = (oaParam.hasBaseIdInternalProcessingRestriction()) ? true + : false; + + if (ignoreManifestValidationResult) { + Logger.debug("OA type is business service, thus ignoring DSIG manifest validation result"); + } else { + if (verifyXMLSignatureResponse.isXmlDSIGManigest()) + if (verifyXMLSignatureResponse.getXmlDSIGManifestCheckCode() != 0) + throw new ValidateException("validator.08", null); + } + + + // Check the signature manifest only when verifying the signed AUTHBlock + if (whatToCheck.equals(CHECK_AUTH_BLOCK)) { + if (verifyXMLSignatureResponse.getSignatureManifestCheckCode() > 0) { + throw new ValidateException("validator.50", null); + } + } + + //Check whether the returned X509 SubjectName is in the MOA-ID configuration or not + if (identityLinkSignersSubjectDNNames != null) { + String subjectDN = ""; + X509Certificate x509Cert = verifyXMLSignatureResponse.getX509certificate(); + try { + subjectDN = ((Name) x509Cert.getSubjectDN()).getRFC2253String(); + } + catch (RFC2253NameParserException e) { + throw new ValidateException("validator.17", null); + } + //System.out.println("subjectDN: " + subjectDN); + // check the authorisation to sign the identity link + if (!identityLinkSignersSubjectDNNames.contains(subjectDN)) { + // subject DN check failed, try OID check: + try { + if (x509Cert.getExtension(MOAIDAuthConstants.IDENTITY_LINK_SIGNER_OID) == null) { + throw new ValidateException("validator.18", new Object[] { subjectDN }); + } else { + Logger.debug("Identity link signer cert accepted for signing identity link: " + + "subjectDN check failed, but OID check successfully passed."); + } + } catch (X509ExtensionInitException e) { + throw new ValidateException("validator.49", null); + } + } else { + Logger.debug("Identity link signer cert accepted for signing identity link: " + + "subjectDN check successfully passed."); + } + + } + } + + /** + * Method validateCertificate. + * @param verifyXMLSignatureResponse The VerifyXMLSignatureResponse + * @param idl The Identitylink + * @throws ValidateException + */ + public void validateCertificate( + IVerifiyXMLSignatureResponse verifyXMLSignatureResponse, + IIdentityLink idl) + throws ValidateException { + + X509Certificate x509Response = verifyXMLSignatureResponse.getX509certificate(); + PublicKey[] pubKeysIdentityLink = (PublicKey[]) idl.getPublicKey(); + + PublicKey pubKeySignature = x509Response.getPublicKey(); + checkIDLAgainstSignatureCertificate(pubKeysIdentityLink, pubKeySignature); + + } + + + public void checkIDLAgainstSignatureCertificate( PublicKey[] pubKeysIdentityLink, PublicKey pubKeySignature) throws ValidateException { + boolean found = false; + for (int i = 0; i < pubKeysIdentityLink.length; i++) { + PublicKey idlPubKey = pubKeysIdentityLink[i]; + //compare RSAPublicKeys + if ((idlPubKey instanceof java.security.interfaces.RSAPublicKey) && + (pubKeySignature instanceof java.security.interfaces.RSAPublicKey)) { + + RSAPublicKey rsaPubKeySignature = (RSAPublicKey) pubKeySignature; + RSAPublicKey rsakey = (RSAPublicKey) pubKeysIdentityLink[i]; + + if (rsakey.getModulus().equals(rsaPubKeySignature.getModulus()) + && rsakey.getPublicExponent().equals(rsaPubKeySignature.getPublicExponent())) + found = true; + } + + //compare ECDSAPublicKeys + if( ( (idlPubKey instanceof java.security.interfaces.ECPublicKey) || + (idlPubKey instanceof ECPublicKey)) && + ( (pubKeySignature instanceof java.security.interfaces.ECPublicKey) || + (pubKeySignature instanceof ECPublicKey) ) ) { + + try { + ECPublicKey ecdsaPubKeySignature = new ECPublicKey(pubKeySignature.getEncoded()); + ECPublicKey ecdsakey = new ECPublicKey(pubKeysIdentityLink[i].getEncoded()); + + if(ecdsakey.equals(ecdsaPubKeySignature)) + found = true; + + } catch (InvalidKeyException e) { + Logger.warn("ECPublicKey can not parsed into a iaik.ECPublicKey", e); + throw new ValidateException("validator.09", null); + } + + + + } + +// Logger.debug("IDL-Pubkey=" + idl.getPublicKey()[i].getClass().getName() +// + " Resp-Pubkey=" + pubKeySignature.getClass().getName()); + + } + + if (!found) { + + throw new ValidateException("validator.09", null); + + } + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/utils/SZRGWClientUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/utils/SZRGWClientUtils.java index 4cca2e625..a9abc2c5f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/utils/SZRGWClientUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/utils/SZRGWClientUtils.java @@ -1,199 +1,200 @@ -/* - * 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.client.utils; - -import java.io.UnsupportedEncodingException; -import java.util.List; -import java.util.UUID; - -import org.opensaml.xml.util.XMLHelper; -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.client.SZRGWClient; -import at.gv.egovernment.moa.id.client.SZRGWClientException; -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.ConnectionParameterInterface; -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.utils.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.util.xsd.mis.MandateIdentifiers; -import at.gv.util.xsd.mis.Target; -import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest; -import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest.PEPSData; -import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; -import at.gv.util.xsd.srzgw.MISType; -import at.gv.util.xsd.srzgw.MISType.Filters; - -/** - * @author tlenz - * - */ -public class SZRGWClientUtils { - - /** - * Does the request to the SZR-GW. - * - * @param signature the signature - * @return the identity link - * @throws SZRGWClientException the sZRGW client exception - * @throws ConfigurationException the configuration exception - */ - public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, Element signature) throws SZRGWClientException, ConfigurationException { - return getIdentityLink(pendingReq, null, null, null, null, XMLHelper.nodeToString(signature), null); - } - - /** - * Does the request to the SZR-GW. - * - * @param PEPSIdentifier the pEPS identifier - * @param PEPSFirstname the pEPS firstname - * @param PEPSFamilyname the pEPS familyname - * @param PEPSDateOfBirth the pEPS date of birth - * @param signature XMLDSIG signature - * @return Identity link assertion - * @throws SZRGWClientException the sZRGW client exception - * @throws ConfigurationException the configuration exception - */ - public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String signature, String PEPSFiscalNumber) throws SZRGWClientException { - return getIdentityLink(pendingReq, PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, null, signature, null, null, null, null, null, null, null, PEPSFiscalNumber); - } - - /** - * SZR-GW Client interface. - * - * @param eIdentifier the e identifier - * @param givenName the given name - * @param lastName the last name - * @param dateOfBirth the date of birth - * @param citizenSignature the citizen signature - * @param representative the representative - * @param represented the represented - * @param mandate the mandate - * @return the identity link - * @throws SZRGWClientException the sZRGW client exception - */ - public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, String eIdentifier, - String givenName, String lastName, String dateOfBirth, String gender, - String citizenSignature, String representative, String represented, - String mandate, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { - return getIdentityLink(pendingReq, eIdentifier, givenName, lastName, dateOfBirth, gender, - citizenSignature, representative, represented, mandate, null, - null, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); - } - - /** - * Gets the identity link. - * - * @param citizenSignature the citizen signature - * @param representative the representative - * @param represented the represented - * @param mandate the mandate - * @param organizationAddress the organization address - * @param organizationType the organization type - * @return the identity link - * @throws SZRGWClientException - */ - public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, String citizenSignature, - String representative, String represented, String mandateContent, - String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { - return getIdentityLink(pendingReq, null, null, null, null, null, - citizenSignature, represented, representative, mandateContent, organizationAddress, - organizationType, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); - } - - public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String gender, String citizenSignature, String represented, String representative, String mandateContent, String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { - - try { - AuthConfiguration authConf = AuthConfigurationProviderFactory.getInstance(); - ConnectionParameterInterface connectionParameters = authConf.getForeignIDConnectionParameter(pendingReq.getOnlineApplicationConfiguration()); - - String requestID = UUID.randomUUID().toString(); - SZRGWClient client = new SZRGWClient(connectionParameters); - - CreateIdentityLinkRequest request = new CreateIdentityLinkRequest(); - request.setSignature(citizenSignature.getBytes("UTF-8")); - request.setReqID(requestID); - if(PEPSDateOfBirth!=null || PEPSFamilyname!=null || PEPSFirstname!=null || PEPSIdentifier!=null || representative!=null || represented!=null || mandateContent!=null || organizationAddress!=null || organizationType!=null) - { - PEPSData data = new PEPSData(); - data.setDateOfBirth(PEPSDateOfBirth); - data.setFamilyname(PEPSFamilyname); - data.setFirstname(PEPSFirstname); - data.setIdentifier(PEPSIdentifier); - - data.setFiscalNumber(PEPSFiscalNumber); - - data.setRepresentative(representative); - data.setRepresented(represented); - data.setMandateContent(mandateContent); - - data.setLegalPersonCanonicalRegisteredAddress(organizationAddress); - data.setLegalPersonTranslatableType(organizationType); - - request.setPEPSData(data); - } - if (null != mandateContent) { - MISType mis = new MISType(); - - Target targetObject = new Target(); - targetObject.setType(targetType); - targetObject.setValue(targetValue); - mis.setTarget(targetObject); - - mis.setOAFriendlyName(oaFriendlyName); - - Filters filterObject = new Filters(); - MandateIdentifiers mandateIds = new MandateIdentifiers(); - for(String current : filters) - mandateIds.getMandateIdentifier().add(current.trim()); - filterObject.setMandateIdentifiers(mandateIds); - mis.setFilters(filterObject); - - request.setMIS(mis); - } - - if (MiscUtil.isEmpty(connectionParameters.getUrl())) { - Logger.warn("SZR-Gateway Service URL is empty"); - throw new SZRGWClientException("service.07"); - } - - Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); - CreateIdentityLinkResponse response = client.sentCreateIDLRequest(request, connectionParameters.getUrl()); - return response; - - } - catch (ConfigurationException e) { - Logger.warn(e); - Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null )); - } catch (UnsupportedEncodingException e) { - Logger.warn(e); - } - - return null; - - } - -} +///* +// * 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.client.utils; +// +//import java.io.UnsupportedEncodingException; +//import java.util.List; +//import java.util.UUID; +// +//import org.opensaml.xml.util.XMLHelper; +//import org.w3c.dom.Element; +// +//import at.gv.egiz.eaaf.core.api.IRequest; +//import at.gv.egovernment.moa.id.client.SZRGWClient; +//import at.gv.egovernment.moa.id.client.SZRGWClientException; +//import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +//import at.gv.egovernment.moa.id.commons.api.ConnectionParameterInterface; +//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.utils.MOAIDMessageProvider; +//import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +//import at.gv.egovernment.moa.logging.Logger; +//import at.gv.egovernment.moa.util.MiscUtil; +//import at.gv.util.xsd.mis.MandateIdentifiers; +//import at.gv.util.xsd.mis.Target; +//import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest; +//import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest.PEPSData; +//import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; +//import at.gv.util.xsd.srzgw.MISType; +//import at.gv.util.xsd.srzgw.MISType.Filters; +// +///** +// * @author tlenz +// * +// */ +//public class SZRGWClientUtils { +// +// /** +// * Does the request to the SZR-GW. +// * +// * @param signature the signature +// * @return the identity link +// * @throws SZRGWClientException the sZRGW client exception +// * @throws ConfigurationException the configuration exception +// */ +// public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, Element signature) throws SZRGWClientException, ConfigurationException { +// return getIdentityLink(pendingReq, null, null, null, null, XMLHelper.nodeToString(signature), null); +// } +// +// /** +// * Does the request to the SZR-GW. +// * +// * @param PEPSIdentifier the pEPS identifier +// * @param PEPSFirstname the pEPS firstname +// * @param PEPSFamilyname the pEPS familyname +// * @param PEPSDateOfBirth the pEPS date of birth +// * @param signature XMLDSIG signature +// * @return Identity link assertion +// * @throws SZRGWClientException the sZRGW client exception +// * @throws ConfigurationException the configuration exception +// */ +// public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String signature, String PEPSFiscalNumber) throws SZRGWClientException { +// return getIdentityLink(pendingReq, PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, null, signature, null, null, null, null, null, null, null, PEPSFiscalNumber); +// } +// +// /** +// * SZR-GW Client interface. +// * +// * @param eIdentifier the e identifier +// * @param givenName the given name +// * @param lastName the last name +// * @param dateOfBirth the date of birth +// * @param citizenSignature the citizen signature +// * @param representative the representative +// * @param represented the represented +// * @param mandate the mandate +// * @return the identity link +// * @throws SZRGWClientException the sZRGW client exception +// */ +// public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, String eIdentifier, +// String givenName, String lastName, String dateOfBirth, String gender, +// String citizenSignature, String representative, String represented, +// String mandate, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { +// return getIdentityLink(pendingReq, eIdentifier, givenName, lastName, dateOfBirth, gender, +// citizenSignature, representative, represented, mandate, null, +// null, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); +// } +// +// /** +// * Gets the identity link. +// * +// * @param citizenSignature the citizen signature +// * @param representative the representative +// * @param represented the represented +// * @param mandate the mandate +// * @param organizationAddress the organization address +// * @param organizationType the organization type +// * @return the identity link +// * @throws SZRGWClientException +// */ +// public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, String citizenSignature, +// String representative, String represented, String mandateContent, +// String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { +// return getIdentityLink(pendingReq, null, null, null, null, null, +// citizenSignature, represented, representative, mandateContent, organizationAddress, +// organizationType, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); +// } +// +// public static CreateIdentityLinkResponse getIdentityLink(IRequest pendingReq, String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String gender, String citizenSignature, String represented, String representative, String mandateContent, String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { +// +// try { +// AuthConfiguration authConf = AuthConfigurationProviderFactory.getInstance(); +// ConnectionParameterInterface connectionParameters = authConf.getForeignIDConnectionParameter(pendingReq.getServiceProviderConfiguration(IOAAuthParameters.class)); +// +// String requestID = UUID.randomUUID().toString(); +// SZRGWClient client = new SZRGWClient(connectionParameters); +// +// CreateIdentityLinkRequest request = new CreateIdentityLinkRequest(); +// request.setSignature(citizenSignature.getBytes("UTF-8")); +// request.setReqID(requestID); +// if(PEPSDateOfBirth!=null || PEPSFamilyname!=null || PEPSFirstname!=null || PEPSIdentifier!=null || representative!=null || represented!=null || mandateContent!=null || organizationAddress!=null || organizationType!=null) +// { +// PEPSData data = new PEPSData(); +// data.setDateOfBirth(PEPSDateOfBirth); +// data.setFamilyname(PEPSFamilyname); +// data.setFirstname(PEPSFirstname); +// data.setIdentifier(PEPSIdentifier); +// +// data.setFiscalNumber(PEPSFiscalNumber); +// +// data.setRepresentative(representative); +// data.setRepresented(represented); +// data.setMandateContent(mandateContent); +// +// data.setLegalPersonCanonicalRegisteredAddress(organizationAddress); +// data.setLegalPersonTranslatableType(organizationType); +// +// request.setPEPSData(data); +// } +// if (null != mandateContent) { +// MISType mis = new MISType(); +// +// Target targetObject = new Target(); +// targetObject.setType(targetType); +// targetObject.setValue(targetValue); +// mis.setTarget(targetObject); +// +// mis.setOAFriendlyName(oaFriendlyName); +// +// Filters filterObject = new Filters(); +// MandateIdentifiers mandateIds = new MandateIdentifiers(); +// for(String current : filters) +// mandateIds.getMandateIdentifier().add(current.trim()); +// filterObject.setMandateIdentifiers(mandateIds); +// mis.setFilters(filterObject); +// +// request.setMIS(mis); +// } +// +// if (MiscUtil.isEmpty(connectionParameters.getUrl())) { +// Logger.warn("SZR-Gateway Service URL is empty"); +// throw new SZRGWClientException("service.07"); +// } +// +// Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); +// CreateIdentityLinkResponse response = client.sentCreateIDLRequest(request, connectionParameters.getUrl()); +// return response; +// +// } +// catch (ConfigurationException e) { +// Logger.warn(e); +// Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null )); +// } catch (UnsupportedEncodingException e) { +// Logger.warn(e); +// } +// +// return null; +// +// } +// +//} 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 8b0134f9c..f44ec756e 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,14 +46,17 @@ package at.gv.egovernment.moa.id.config; +import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Map; import java.util.Properties; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.impl.idp.conf.AbstractConfigurationImpl; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.initialize.EAAFDefaultSAML2Bootstrap; 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.protocols.pvp2x.config.MOADefaultBootstrap; import at.gv.egovernment.moa.logging.Logger; import at.gv.util.config.EgovUtilPropertiesConfiguration; @@ -65,14 +68,15 @@ import at.gv.util.config.EgovUtilPropertiesConfiguration; * @author Paul Ivancsics * @version $Id$ */ -public abstract class ConfigurationProviderImpl implements ConfigurationProvider{ +public abstract class ConfigurationProviderImpl extends AbstractConfigurationImpl implements ConfigurationProvider{ /** * Constructor + * @throws EAAFConfigurationException */ - public ConfigurationProviderImpl() { - - super(); + public ConfigurationProviderImpl(String configFilePath) throws EAAFConfigurationException { + super(configFilePath); + } private EgovUtilPropertiesConfiguration eGovUtilsConfig = null; @@ -117,26 +121,7 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider /** The default chaining mode. */ protected String defaultChainingMode = "pkix"; - - /** - * main configuration file directory name used to configure MOA-ID - */ - protected String rootConfigFileDir; - - - protected Properties configProp = null; - - /** - * Returns the main configuration file directory used to configure MOA-ID - * - * @return the directory - */ - public String getRootConfigFileDir() { - return rootConfigFileDir; - } - - public String getDefaultChainingMode() { return defaultChainingMode; } @@ -147,15 +132,17 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider * @return */ public Properties getDBConnectionConfiguration() { - return this.configProp; + return getFullConfigurationProperties(); + } /** * @param properties * @throws ConfigurationException * @throws org.opensaml.xml.ConfigurationException + * @throws MalformedURLException */ - public void initial(Properties props) throws ConfigurationException, org.opensaml.xml.ConfigurationException { + protected void initial(Properties props) throws ConfigurationException, org.opensaml.xml.ConfigurationException, MalformedURLException { //Initial Hibernate Framework Logger.trace("Initializing Hibernate framework."); try { @@ -174,7 +161,7 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider } // read Config Hibernate properties - configProp = new Properties(); + Properties configProp = new Properties(); for (Object key : props.keySet()) { String propPrefix = "configuration."; if (key.toString().startsWith(propPrefix+"hibernate")) { @@ -192,37 +179,7 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider statisticProps.put(propertyName, props.get(key.toString())); } } - -// // initialize hibernate -// synchronized (ConfigurationProviderImpl.class) { -// -// //Initial config Database -// // ConfigurationDBUtils.initHibernate(configProp); -// -// //initial MOAID Session Database -// Configuration config = new Configuration(); -// config.addAnnotatedClass(AssertionStore.class); -// config.addAnnotatedClass(AuthenticatedSessionStore.class); -// config.addAnnotatedClass(OASessionStore.class); -// config.addAnnotatedClass(OldSSOSessionIDStore.class); -// config.addAnnotatedClass(InterfederationSessionStore.class); -// //config.addAnnotatedClass(ProcessInstanceStore.class); -// config.addProperties(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."); -//// } -// -// } -// Logger.trace("Hibernate initialization finished."); - + } catch (ExceptionInInitializerError e) { throw new ConfigurationException("config.17", null, e); @@ -234,7 +191,7 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider //Initialize OpenSAML for STORK Logger.info("Starting initialization of OpenSAML..."); - MOADefaultBootstrap.bootstrap(); + EAAFDefaultSAML2Bootstrap.bootstrap(); //DefaultBootstrap.bootstrap(); Logger.debug("OpenSAML successfully initialized"); @@ -251,7 +208,7 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider if (!eGovUtilsConfigProp.isEmpty()) { Logger.info("Start eGovUtils client implementation configuration ..."); eGovUtilsConfig = - new EgovUtilPropertiesConfiguration(eGovUtilsConfigProp, rootConfigFileDir); + new EgovUtilPropertiesConfiguration(eGovUtilsConfigProp, getConfigurationRootDirectory().toURL().toString()); } this.generateActiveProfiles(props); @@ -291,5 +248,18 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider Logger.debug("Set active Spring-Profiles to: " + activeProfiles); return activeProfiles.toArray(new String[0]); } + + public String getRootConfigFileDir() throws ConfigurationException { + try { + return getConfigurationRootDirectory().toURL().toString(); + + } catch (MalformedURLException e) { + Logger.error("Can not read Config-Root Directory.", e); + throw new ConfigurationException("config.03", null, e); + + } + + + } } 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/OAAuthParameterDecorator.java index 5642861c5..a2dfeba2f 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/OAAuthParameterDecorator.java @@ -52,20 +52,19 @@ import java.security.PrivateKey; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; -import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import org.apache.commons.lang.SerializationUtils; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.MOAIDConstants; -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.commons.api.IStorkConfig; import at.gv.egovernment.moa.id.commons.api.data.BPKDecryptionParameters; @@ -75,8 +74,7 @@ import at.gv.egovernment.moa.id.commons.api.data.StorkAttribute; import at.gv.egovernment.moa.id.commons.api.data.StorkAttributeProviderPlugin; 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.commons.utils.KeyValueUtils; -import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper; +import at.gv.egovernment.moa.id.commons.validation.TargetValidator; import at.gv.egovernment.moa.id.data.EncryptedData; import at.gv.egovernment.moa.id.util.ConfigurationEncrytionUtil; import at.gv.egovernment.moa.logging.Logger; @@ -91,56 +89,24 @@ import at.gv.egovernment.moa.util.MiscUtil; * * @author Thomas Lenz */ -public class OAAuthParameter implements IOAAuthParameters, Serializable{ +public class OAAuthParameterDecorator implements IOAAuthParameters, Serializable{ - /** - * - */ private static final long serialVersionUID = -6522544229837934376L; - final public static String DEFAULT_KEYBOXIDENTIFIER = "SecureSignatureKeypair"; - private Map<String, String> oaConfiguration; - private List<String> targetAreasWithNoInteralBaseIdRestriction = new ArrayList<String>(); - private List<String> targetAreasWithNoBaseIdTransmissionRestriction = new ArrayList<String>(); + + private ISPConfiguration spConfiguration; + - public OAAuthParameter(final Map<String, String> oa, AuthConfiguration authConfig) { - this.oaConfiguration = oa; - - //set oa specific restrictions - targetAreasWithNoInteralBaseIdRestriction = KeyValueUtils.getListOfCSVValues( - authConfig.getBasicMOAIDConfiguration( - CONFIG_KEY_RESTRICTIONS_BASEID_INTERNAL, - MOAIDAuthConstants.PREFIX_CDID)); - - targetAreasWithNoBaseIdTransmissionRestriction = KeyValueUtils.getListOfCSVValues( - authConfig.getBasicMOAIDConfiguration( - CONFIG_KEY_RESTRICTIONS_BASEID_TRANSMISSION, - MOAIDAuthConstants.PREFIX_CDID)); - - if (Logger.isTraceEnabled()) { - Logger.trace("Internal policy for OA: " + getPublicURLPrefix()); - for (String el : targetAreasWithNoInteralBaseIdRestriction) - Logger.trace(" Allow baseID processing for prefix " + el); - for (String el : targetAreasWithNoBaseIdTransmissionRestriction) - Logger.trace(" Allow baseID transfer for prefix " + el); - - } - } + public OAAuthParameterDecorator(ISPConfiguration spConfiguration) { + this.spConfiguration = spConfiguration; + } - - public Map<String, String> getFullConfiguration() { - return Collections.unmodifiableMap(this.oaConfiguration); - } - - public String getConfigurationValue(String key) { - return this.oaConfiguration.get(key); - } - + @Override - public boolean hasBaseIdInternalProcessingRestriction() throws ConfigurationException { + public boolean hasBaseIdInternalProcessingRestriction() { String targetAreaIdentifier = getAreaSpecificTargetIdentifier(); - for (String el : targetAreasWithNoInteralBaseIdRestriction) { + for (String el : spConfiguration.getTargetsWithNoBaseIdInternalProcessingRestriction()) { if (targetAreaIdentifier.startsWith(el)) return false; @@ -150,9 +116,9 @@ public class OAAuthParameter implements IOAAuthParameters, Serializable{ } @Override - public boolean hasBaseIdTransferRestriction() throws ConfigurationException { + public boolean hasBaseIdTransferRestriction() { String targetAreaIdentifier = getAreaSpecificTargetIdentifier(); - for (String el : targetAreasWithNoBaseIdTransmissionRestriction) { + for (String el : spConfiguration.getTargetsWithNoBaseIdTransferRestriction()) { if (targetAreaIdentifier.startsWith(el)) return false; @@ -162,7 +128,7 @@ public class OAAuthParameter implements IOAAuthParameters, Serializable{ } @Override - public String getAreaSpecificTargetIdentifier() throws ConfigurationException { + public String getAreaSpecificTargetIdentifier() { if (getBusinessService()) return getIdentityLinkDomainIdentifier(); else @@ -185,8 +151,8 @@ public class OAAuthParameter implements IOAAuthParameters, Serializable{ */ //@Override private String getIdentityLinkDomainIdentifier() { - String type = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_BUSINESS_TYPE); - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_BUSINESS_VALUE); + String type = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_BUSINESS_TYPE); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_BUSINESS_VALUE); if (MiscUtil.isNotEmpty(type) && MiscUtil.isNotEmpty(value)) { if (MOAIDConstants.IDENIFICATIONTYPE_STORK.equals(type)) { return MOAIDConstants.PREFIX_STORK + "AT" + "+" + value; @@ -208,7 +174,7 @@ private String getIdentityLinkDomainIdentifier() { */ //@Override private String getIdentityLinkDomainIdentifierType() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_BUSINESS_TYPE); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_BUSINESS_TYPE); if (MiscUtil.isNotEmpty(value)) return MOAIDConfigurationConstants.BUSINESSSERVICENAMES.get(value); @@ -221,17 +187,17 @@ private String getIdentityLinkDomainIdentifierType() { */ //@Override private String getTarget() { - if (Boolean.parseBoolean(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_USE_OWN))) - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_OWN_TARGET); + if (Boolean.parseBoolean(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_USE_OWN))) + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_OWN_TARGET); else { - if (Boolean.parseBoolean(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_USE_SUB))) { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET) + if (Boolean.parseBoolean(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_USE_SUB))) { + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET) + "-" - + oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET_SUB); + + spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET_SUB); } else { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET); + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET); } } } @@ -241,11 +207,11 @@ private String getTarget() { */ //@Override private String getTargetFriendlyName() { - if (Boolean.parseBoolean(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_USE_OWN))) - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_OWN_NAME); + if (Boolean.parseBoolean(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_USE_OWN))) + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_OWN_NAME); else - return TargetToSectorNameMapper.getSectorNameViaTarget(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET)); + return TargetValidator.getTargetFriendlyName(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET)); } @@ -254,7 +220,7 @@ private String getTargetFriendlyName() { */ @Override public String getKeyBoxIdentifier() { - String keyBoxId = oaConfiguration.get( + String keyBoxId = spConfiguration.getConfigurationValue( MOAIDConfigurationConstants.SERVICE_AUTH_BKU_KEYBOXIDENTIFIER); if (MiscUtil.isNotEmpty(keyBoxId)) return keyBoxId; @@ -269,33 +235,33 @@ public String getKeyBoxIdentifier() { @Override public SAML1ConfigurationParameters getSAML1Parameter() { SAML1ConfigurationParameters returnValue = new SAML1ConfigurationParameters(); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_ENABLED)) + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_ENABLED)) returnValue.setActive( - Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_ENABLED))); + Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_ENABLED))); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_AUTHBLOCK)) + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_AUTHBLOCK)) returnValue.setProvideAuthBlock( - Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_AUTHBLOCK))); + Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_AUTHBLOCK))); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_IDL)) + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_IDL)) returnValue.setProvideIdl( - Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_IDL))); + Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_IDL))); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_BASEID)) + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_BASEID)) returnValue.setProvideBaseId( - Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_BASEID))); + Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_BASEID))); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_CERTIFICATE)) + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_CERTIFICATE)) returnValue.setProvideCertificate( - Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_CERTIFICATE))); + Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_CERTIFICATE))); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_MANDATE)) + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_MANDATE)) returnValue.setProvideMandate( - Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_MANDATE))); + Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_MANDATE))); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_RETURNERROR)) + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_RETURNERROR)) returnValue.setProvideAllErrors( - Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_RETURNERROR))); + Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_RETURNERROR))); return returnValue; } @@ -307,14 +273,14 @@ public String getKeyBoxIdentifier() { public List<String> getTemplateURL() { List<String> list = new ArrayList<String>(); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_FIRST_VALUE)) - list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_FIRST_VALUE)); + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_FIRST_VALUE)) + list.add(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_FIRST_VALUE)); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_SECOND_VALUE)) - list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_SECOND_VALUE)); + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_SECOND_VALUE)) + list.add(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_SECOND_VALUE)); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_THIRD_VALUE)) - list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_THIRD_VALUE)); + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_THIRD_VALUE)) + list.add(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_THIRD_VALUE)); return list; } @@ -324,7 +290,7 @@ public String getKeyBoxIdentifier() { */ @Override public String getAditionalAuthBlockText() { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_AUTHBLOCKTEXT); + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_AUTHBLOCKTEXT); } @@ -334,16 +300,16 @@ public String getKeyBoxIdentifier() { @Override public String getBKUURL(String bkutype) { if (bkutype.equals(THIRDBKU)) { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_THIRD); + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_THIRD); } else if (bkutype.equals(HANDYBKU)) { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_HANDY); + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_HANDY); } else if (bkutype.equals(LOCALBKU)) { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_LOCAL); + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_LOCAL); } else if (bkutype.equals(ONLINEBKU)) { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_THIRD); + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_THIRD); } @@ -361,14 +327,14 @@ public String getKeyBoxIdentifier() { public List<String> getBKUURL() { List<String> list = new ArrayList<String>(); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_THIRD)) - list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_THIRD)); + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_THIRD)) + list.add(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_THIRD)); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_HANDY)) - list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_HANDY)); + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_HANDY)) + list.add(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_HANDY)); - if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_LOCAL)) - list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_LOCAL)); + if (spConfiguration.containsConfigurationKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_LOCAL)) + list.add(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_LOCAL)); return list; } @@ -380,7 +346,7 @@ public String getKeyBoxIdentifier() { @Override public boolean useSSO() { try { - return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_SSO_ENABLED)); + return Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_SSO_ENABLED)); } catch (Exception e) { Logger.warn("Use SSO configuration parameter is not parseable.", e); @@ -395,7 +361,7 @@ public String getKeyBoxIdentifier() { @Override public boolean useSSOQuestion() { try { - return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_SSO_USERREQUEST)); + return Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_SSO_USERREQUEST)); } catch (Exception e) { Logger.warn("SSO user question configuration parameter is not parseable.", e); @@ -408,7 +374,7 @@ public String getKeyBoxIdentifier() { */ @Override public List<String> getMandateProfiles() { - String profileConfig = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_MANDATES_OVS_PROFILES); + String profileConfig = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_MANDATES_OVS_PROFILES); if (MiscUtil.isNotEmpty(profileConfig)) { List<String> list = new ArrayList<String>(); @@ -430,7 +396,7 @@ public List<String> getMandateProfiles() { @Override public boolean isShowMandateCheckBox() { try { - return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_MANDATES_OVS_USE)); + return Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_MANDATES_OVS_USE)); } catch (Exception e) { Logger.warn("Enable mandates configuration parameter is not parseable.", e); @@ -444,7 +410,7 @@ public boolean isShowMandateCheckBox() { @Override public boolean isOnlyMandateAllowed() { try { - return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_MANDATES_OVS_ONLY)); + return Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_MANDATES_OVS_ONLY)); } catch (Exception e) { Logger.warn("Use ONLY mandates configuration parameter is not parseable.", e); @@ -458,7 +424,7 @@ public boolean isOnlyMandateAllowed() { @Override public boolean isShowStorkLogin() { try { - return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ENABLED)); + return Boolean.valueOf(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ENABLED)); } catch (Exception e) { Logger.warn("Enable STORK login configuration parameter is not parseable.", e); @@ -472,7 +438,7 @@ public boolean isOnlyMandateAllowed() { */ @Override public String getQaaLevel() { - String eidasLoALevel = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_MINQAALEVEL); + String eidasLoALevel = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_MINQAALEVEL); if (MiscUtil.isEmpty(eidasLoALevel)) return MOAIDConstants.eIDAS_LOA_HIGH; else @@ -488,23 +454,23 @@ public Collection<StorkAttribute> getRequestedSTORKAttributes() { Map<String, Integer> attrMap = new HashMap<String, Integer>(); Map<String, StorkAttribute> resultMap = new HashMap<String, StorkAttribute>(); - Set<String> configKeys = oaConfiguration.keySet(); + Set<String> configKeys = spConfiguration.getFullConfiguration().keySet(); for (String el : configKeys) { if (el.startsWith(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST)) { String index = KeyValueUtils.getFirstChildAfterPrefix(el, MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST); if (!attrMap.containsKey(index)) { - String isRequested = oaConfiguration.get( + String isRequested = spConfiguration.getConfigurationValue( MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST + "." + index + "." + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST_REQUESTED); if (MiscUtil.isNotEmpty(isRequested) && Boolean.parseBoolean(isRequested)) { StorkAttribute attr = new StorkAttribute( - oaConfiguration.get( + spConfiguration.getConfigurationValue( MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST + "." + index + "." + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST_NAME), - Boolean.valueOf(oaConfiguration.get( + Boolean.valueOf(spConfiguration.getConfigurationValue( MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST + "." + index + "." + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST_MANDATORY))); @@ -540,13 +506,13 @@ public boolean isRequireConsentForStorkAttributes() { if (isSTORKPVPGateway()) return false; - if (MiscUtil.isEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_REQUIRECONSENT))) { + if (MiscUtil.isEmpty(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_REQUIRECONSENT))) { Logger.info("isRequireConsentForStorkAttributes() is empty, returning default value 'true'"); return true; } - return Boolean.parseBoolean(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_REQUIRECONSENT)); + return Boolean.parseBoolean(spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_REQUIRECONSENT)); }catch(Exception e) { Logger.warn("isRequireConsentForStorkAttributes() failed, returning default value 'true'", e); @@ -560,21 +526,21 @@ public boolean isRequireConsentForStorkAttributes() { @Override public Collection<StorkAttributeProviderPlugin> getStorkAPs() { Map<String, StorkAttributeProviderPlugin> pluginMap = new HashMap<String, StorkAttributeProviderPlugin>(); - Set<String> configKeys = oaConfiguration.keySet(); + Set<String> configKeys = spConfiguration.getFullConfiguration().keySet(); for (String el : configKeys) { if (el.startsWith(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST)) { String index = KeyValueUtils.getFirstChildAfterPrefix(el, MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST); if (!pluginMap.containsKey(index)) { StorkAttributeProviderPlugin attr = new StorkAttributeProviderPlugin( - oaConfiguration.get( + spConfiguration.getConfigurationValue( MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST + "." + index + "." + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST_NAME), - oaConfiguration.get( + spConfiguration.getConfigurationValue( MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST + "." + index + "." + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST_URL), - oaConfiguration.get( + spConfiguration.getConfigurationValue( MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST + "." + index + "." + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST_ATTRIBUTES)); @@ -592,7 +558,7 @@ public Collection<StorkAttributeProviderPlugin> getStorkAPs() { @Override public byte[] getBKUSelectionTemplate() { try { - String bkuSelectionTemplateBase64 = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_BKUSELECTION_DATA); + String bkuSelectionTemplateBase64 = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_BKUSELECTION_DATA); if (MiscUtil.isNotEmpty(bkuSelectionTemplateBase64)) { return Base64Utils.decode(bkuSelectionTemplateBase64, false); @@ -612,7 +578,7 @@ public byte[] getBKUSelectionTemplate() { @Override public byte[] getSendAssertionTemplate() { try { - String bkuSelectionTemplateBase64 = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_SENDASSERTION_DATA); + String bkuSelectionTemplateBase64 = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_SENDASSERTION_DATA); if (MiscUtil.isNotEmpty(bkuSelectionTemplateBase64)) { return Base64Utils.decode(bkuSelectionTemplateBase64, false); @@ -635,18 +601,18 @@ public Collection<CPEPS> getPepsList() { try { IStorkConfig availableSTORKConfig = AuthConfigurationProviderFactory.getInstance().getStorkConfig(); if (availableSTORKConfig != null) { - Set<String> configKeys = oaConfiguration.keySet(); + Set<String> configKeys = spConfiguration.getFullConfiguration().keySet(); for (String el : configKeys) { if (el.startsWith(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST)) { String index = KeyValueUtils.getFirstChildAfterPrefix(el, MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST); if (!cPEPSMap.containsKey(index)) { - if (Boolean.parseBoolean(oaConfiguration.get( + if (Boolean.parseBoolean(spConfiguration.getConfigurationValue( MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST + "." + index + "." + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST_ENABLED))) { CPEPS availableCPEPS = availableSTORKConfig.getCPEPSWithFullName( - oaConfiguration.get( + spConfiguration.getConfigurationValue( MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST + "." + index + "." + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST_COUNTRYCODE)); @@ -672,13 +638,13 @@ public Collection<CPEPS> getPepsList() { */ @Override public String getIDPAttributQueryServiceURL() { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_ATTRIBUTQUERY_URL); + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_ATTRIBUTQUERY_URL); } @Override public boolean isInboundSSOInterfederationAllowed() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_SSO_INBOUND); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_SSO_INBOUND); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -687,7 +653,7 @@ public boolean isInboundSSOInterfederationAllowed() { @Override public boolean isOutboundSSOInterfederationAllowed() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_SSO_OUTBOUND); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_SSO_OUTBOUND); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -696,7 +662,7 @@ public boolean isOutboundSSOInterfederationAllowed() { @Override public boolean isPassivRequestUsedForInterfederation() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_PASSIVEREQUEST); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_PASSIVEREQUEST); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -705,7 +671,7 @@ public boolean isPassivRequestUsedForInterfederation() { @Override public boolean isPerformLocalAuthenticationOnInterfederationError() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_LOCALAUTHONERROR); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_LOCALAUTHONERROR); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -714,7 +680,7 @@ public boolean isPerformLocalAuthenticationOnInterfederationError() { @Override public boolean isInterfederationSSOStorageAllowed() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_SSO_STORE); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_SSO_STORE); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -728,7 +694,7 @@ public boolean isIDPPublicService() throws ConfigurationException { public String getSTORKPVPForwardEntity() { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_FORWARD_IDPIDENTIFIER); + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_FORWARD_IDPIDENTIFIER); } @@ -737,7 +703,7 @@ public String getSTORKPVPForwardEntity() { */ @Override public boolean isTestCredentialEnabled() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_ENABLED); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_ENABLED); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -750,7 +716,7 @@ public boolean isTestCredentialEnabled() { */ @Override public List<String> getTestCredentialOIDs() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_OIDs); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_OIDs); if (MiscUtil.isNotEmpty(value)) { List<String> list = new ArrayList<String>(); String profilesArray[] = value.split(","); @@ -774,9 +740,9 @@ public PrivateKey getBPKDecBpkDecryptionKey() { try { EncryptedData encdata = new EncryptedData( Base64Utils.decode( - oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_FOREIGNBPK_DECRYPT_BLOB), false), + spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_FOREIGNBPK_DECRYPT_BLOB), false), Base64Utils.decode( - oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_FOREIGNBPK_DECRYPT_IV), false)); + spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_FOREIGNBPK_DECRYPT_IV), false)); byte[] serializedData = ConfigurationEncrytionUtil.getInstance().decrypt(encdata); BPKDecryptionParameters data = @@ -804,12 +770,13 @@ public PrivateKey getBPKDecBpkDecryptionKey() { */ @Override public String getPublicURLPrefix() { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_UNIQUEIDENTIFIER); + return spConfiguration.getUniqueIdentifier(); + } private boolean getBusinessService() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_BUSINESSSERVICE); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_BUSINESSSERVICE); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -821,7 +788,7 @@ private boolean getBusinessService() { */ @Override public boolean isInderfederationIDP() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES); return MOAIDConfigurationConstants.PREFIX_IIDP.equals(value); } @@ -832,7 +799,7 @@ public boolean isInderfederationIDP() { */ @Override public boolean isSTORKPVPGateway() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES); return MOAIDConfigurationConstants.PREFIX_GATEWAY.equals(value); } @@ -845,7 +812,7 @@ public boolean isSTORKPVPGateway() { */ @Override public String getFriendlyName() { - return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_FRIENDLYNAME); + return spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_FRIENDLYNAME); } @@ -866,7 +833,7 @@ public String getFriendlyName() { * @return true/false if bPK or wbPK should not be visible in AuthBlock */ public boolean isRemovePBKFromAuthBlock() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_AUTHBLOCK_REMOVEBPK); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_AUTHBLOCK_REMOVEBPK); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -879,9 +846,9 @@ public boolean isRemovePBKFromAuthBlock() { */ @Override public List<Integer> getReversionsLoggingEventCodes() { - String isEnabled = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_REVERSION_LOGS_ENABLED); + String isEnabled = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_REVERSION_LOGS_ENABLED); if (MiscUtil.isNotEmpty(isEnabled) && Boolean.parseBoolean(isEnabled)) { - String eventCodes = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_REVERSION_LOGS_EVENTCODES); + String eventCodes = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_REVERSION_LOGS_EVENTCODES); if (MiscUtil.isNotEmpty(eventCodes)) { String[] codes = eventCodes.split(","); List<Integer> result = new ArrayList<Integer>(); @@ -908,7 +875,7 @@ public List<Integer> getReversionsLoggingEventCodes() { */ @Override public boolean isUseIDLTestTrustStore() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_USETESTIDLTRUSTSTORE); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_USETESTIDLTRUSTSTORE); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -921,7 +888,7 @@ public boolean isUseIDLTestTrustStore() { */ @Override public boolean isUseAuthBlockTestTestStore() { - String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_USETESTAUTHBLOCKTRUSTSTORE); + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_USETESTAUTHBLOCKTRUSTSTORE); if (MiscUtil.isNotEmpty(value)) return Boolean.parseBoolean(value); else @@ -929,10 +896,110 @@ public boolean isUseAuthBlockTestTestStore() { } public String toString() { - if (oaConfiguration != null) - return Arrays.asList(oaConfiguration).toString(); + if (spConfiguration.getFullConfiguration() != null) + return Arrays.asList(spConfiguration.getFullConfiguration()).toString(); return "Object not initialized"; } + +@Override +public boolean containsConfigurationKey(String arg0) { + return spConfiguration.containsConfigurationKey(arg0); + +} + +@Override +public List<String> foreignbPKSectorsRequested() { + String value = spConfiguration.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_FOREIGN); + if (MiscUtil.isNotEmpty(value)) + return KeyValueUtils.getListOfCSVValues(KeyValueUtils.normalizeCSVValueString(value)); + + else + return null; + +} + + + +@Override +public Map<String, String> getFullConfiguration() { + return spConfiguration.getFullConfiguration(); +} + + +@Override +/** + * THIS METHODE IS NOT SUPPORTED IN THIS IMPLEMENTATION + */ +public List<String> getTargetsWithNoBaseIdInternalProcessingRestriction() { + return null; +} + + +@Override +/** + * THIS METHODE IS NOT SUPPORTED IN THIS IMPLEMENTATION + */ +public List<String> getTargetsWithNoBaseIdTransferRestriction() { + return null; +} + + +@Override +public String getUniqueIdentifier() { + return getPublicURLPrefix(); +} + + +@Override +public List<String> getRequiredLoA() { + String loa = getQaaLevel(); + if (loa != null) + return Arrays.asList(loa); + else + return null; +} + +@Override +public String getLoAMatchingMode() { + return EAAFConstants.EIDAS_LOA_MATCHING_MINIMUM; +} + +@Override +public String getConfigurationValue(String key) { + return spConfiguration.getConfigurationValue(key); +} + +@Override +public String getConfigurationValue(String key, String defaultValue) { + String value = getConfigurationValue(key); + if (value == null) + return defaultValue; + else + return value; +} + + +@Override +public Boolean isConfigurationValue(String key) { + String value = getConfigurationValue(key); + if (value == null) + return Boolean.parseBoolean(value); + + return null; + +} + + +@Override +public boolean isConfigurationValue(String key, boolean defaultValue) { + String value = getConfigurationValue(key); + if (value == null) + return Boolean.parseBoolean(value); + else + return defaultValue; + +} + } 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 d3e340a90..fff019ae7 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 @@ -1,12 +1,6 @@ package at.gv.egovernment.moa.id.config.auth; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; import java.net.MalformedURLException; -import java.net.URI; -import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; @@ -20,6 +14,11 @@ import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.idp.conf.SPConfigurationImpl; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.MOAIDConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; @@ -35,7 +34,6 @@ import at.gv.egovernment.moa.id.commons.db.dao.config.deprecated.MOASP; import at.gv.egovernment.moa.id.commons.db.dao.config.deprecated.OnlineApplication; import at.gv.egovernment.moa.id.commons.db.dao.config.deprecated.SecurityLayer; import at.gv.egovernment.moa.id.commons.db.dao.config.deprecated.VerifyIdentityLink; -import at.gv.egovernment.moa.id.commons.utils.KeyValueUtils; import at.gv.egovernment.moa.id.config.ConfigurationProviderImpl; import at.gv.egovernment.moa.id.config.ConfigurationUtils; import at.gv.egovernment.moa.id.config.ConnectionParameter; @@ -55,111 +53,77 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide private static final boolean TRUST_MANAGER_REVOCATION_CHECKING_DEFAULT = true; - private MOAIDConfiguration configuration; - private final Properties properties = new Properties(); - + private MOAIDConfiguration configuration; private boolean requireJDBCBackupImplementation = false; - public PropertyBasedAuthConfigurationProvider(String configFileName) throws ConfigurationException { - if (configFileName == null) { - configFileName = System.getProperty(ConfigurationProvider.CONFIG_PROPERTY_NAME); - - if (MiscUtil.isEmpty(configFileName)) - throw new ConfigurationException("config.01", null); - } - - Logger.info("Loading MOA-ID-AUTH configuration " + configFileName); - - try { - URI fileURI = new URI(configFileName); - //instance = new PropertyBasedAuthConfigurationProvider(fileURI); - initialize(fileURI); - - } catch (URISyntaxException e){ - Logger.error("MOA-ID-Auth configuration file does not starts with file:/ as prefix.", e); - throw new ConfigurationException("config24", new Object[]{MOAIDAuthConstants.FILE_URI_PREFIX, configFileName}); + public PropertyBasedAuthConfigurationProvider(String configFileName) throws ConfigurationException, EAAFConfigurationException { + super(configFileName); +// try { + Logger.info("Loading MOA-ID-AUTH configuration " + getConfigurationFilePath().toString()); + initialize(); - } +// } catch (URISyntaxException e){ +// Logger.error("MOA-ID-Auth configuration file does not starts with file:/ as prefix.", e); +// throw new ConfigurationException("config24", new Object[]{MOAIDAuthConstants.FILE_URI_PREFIX, configFileName}); +// +// } } -// /** -// * The constructor with path to a properties file as argument. -// * -// * @param fileName the path to the properties file -// * @throws ConfigurationException if an error occurs during loading the properties file. -// */ -// public PropertyBasedAuthConfigurationProvider(URI fileName) throws ConfigurationException { -// initialize(fileName); -// -// } + + //TODO: add EAAFCore configuration prefix if required + @Override + public String getApplicationSpecificKeyPrefix() { + return null; + + } - private void initialize(URI fileName) throws ConfigurationException { - File propertiesFile = new File(fileName); - rootConfigFileDir = propertiesFile.getParent(); - try { - rootConfigFileDir = new File(rootConfigFileDir).toURI().toURL().toString(); - - } catch (MalformedURLException t) { - throw new ConfigurationException("config.03", null, t); - - } + @Override + protected String getBackupConfigPath() { + return System.getProperty(ConfigurationProvider.CONFIG_PROPERTY_NAME); - FileInputStream in = null; - try { - in = new FileInputStream(propertiesFile); - properties.load(in); - super.initial(properties); - -// JPAPropertiesWithJavaConfig.setLocalProperties(configProp); -// System.getProperties().setProperty("location", "file:" + fileName); -// context = new ClassPathXmlApplicationContext( -// new String[] { "moaid.configuration.beans.xml", -// "configuration.beans.xml" -// }); -// AutowireCapableBeanFactory acbFactory = context.getAutowireCapableBeanFactory(); -// acbFactory.autowireBean(this); - - //Some databases do not allow the selection of a lob in SQL where expression - String dbDriver = properties.getProperty("configuration.hibernate.connection.driver_class"); - if (MiscUtil.isNotEmpty(dbDriver)) { - for (String el:MOAIDConstants.JDBC_DRIVER_NEEDS_WORKAROUND) { - if (dbDriver.startsWith(el)) { - requireJDBCBackupImplementation = true; - Logger.info("JDBC driver '" + dbDriver - + "' is blacklisted --> Switch to alternative DB access methode implementation."); - - } - } - } - - - } catch (FileNotFoundException e) { - throw new ConfigurationException("config.03", null, e); + } + + + /** + * Provides configuration information regarding the online application behind the given URL, relevant to the MOA-ID Auth component. + * + * @param oaURL URL requested for an online application + * @return an <code>OAAuthParameter</code>, or <code>null</code> if none is applicable + */ + @Override + @Transactional + public ISPConfiguration getServiceProviderConfiguration(String spIdentifier) throws EAAFConfigurationException { + Map<String, String> oa = getActiveOnlineApplication(spIdentifier); + if (oa == null) { + return null; + } + + return new OAAuthParameterDecorator(new SPConfigurationImpl(oa, this)); - } catch (IOException e) { - throw new ConfigurationException("config.03", null, e); - - } catch (org.opensaml.xml.ConfigurationException e) { - Logger.error("OpenSAML initilalization FAILED. ", e); - throw new ConfigurationException("config.23", null, e); - - } catch (Exception e) { - Logger.error("General error during start-up process.", e); - throw new ConfigurationException("init.02", null, e); - - - } finally { - if (in != null) - try { - in.close(); - - } catch (IOException e) { - Logger.warn("Close MOA-ID-Auth configuration file FAILED.", e); + } + + /** + * Provides configuration information regarding the online application behind the given URL, relevant to the MOA-ID Auth component. + * + * @param oaURL URL requested for an online application + * @return an <code>OAAuthParameter</code>, or <code>null</code> if none is applicable + */ + @SuppressWarnings("unchecked") + @Override + @Transactional + public <T> T getServiceProviderConfiguration(String spIdentifier, final Class<T> decorator) throws EAAFConfigurationException { + ISPConfiguration spConfig = getServiceProviderConfiguration(spIdentifier); + if (spConfig != null && decorator != null) { + if (decorator.isInstance(spConfig)) + return (T)spConfig; + else + Logger.error("SPConfig: " + spConfig.getClass().getName() + " is NOT instance of: " + decorator.getName()); - } } + return null; + } /** @@ -172,14 +136,6 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } /** - * Get the properties. - * @return the properties - */ - private Properties getProperties() { - return properties; - } - - /** * Method that avoids iterating over a {@link Collection} of type {@code T} which is actual {@code null}. * @param item the collection * @return the given {@link Collection} {@code item} if it is not {@code null}, or an empty {@link List} otherwise. @@ -225,23 +181,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } } - - public String getBasicMOAIDConfiguration(final String key) { - return properties.getProperty(key); - - } - - public String getBasicMOAIDConfiguration(final String key, final String defaultValue) { - return properties.getProperty(key, defaultValue); - - } - - public Map<String, String> getBasicMOAIDConfigurationWithPrefix(final String prefix) { - return KeyValueUtils.getSubSetWithPrefix(KeyValueUtils.concertPropertiesToMap(properties), prefix); - } - - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getPropertyWithKey(java.lang.String) */ @@ -400,22 +340,6 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } /** - * Provides configuration information regarding the online application behind the given URL, relevant to the MOA-ID Auth component. - * - * @param oaURL URL requested for an online application - * @return an <code>OAAuthParameter</code>, or <code>null</code> if none is applicable - */ - @Transactional - public OAAuthParameter getOnlineApplicationParameter(String oaURL) { - Map<String, String> oa = getActiveOnlineApplication(oaURL); - if (oa == null) { - return null; - } - - return new OAAuthParameter(oa, this); - } - - /** * Returns a string with a url-reference to the VerifyAuthBlock trust profile id within the moa-sp part of the authentication component. * * @return a string with a url-reference to the VerifyAuthBlock trust profile ID. @@ -505,7 +429,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide MOAIDConfigurationConstants.GENERAL_AUTH_MOASP_URL); if (moaspURL != null) { result = - new ConnectionParameterMOASP(moaspURL, this.getProperties(), this.getRootConfigFileDir()); + new ConnectionParameterMOASP(moaspURL, getFullConfigurationProperties(), getRootConfigFileDir()); } @@ -517,41 +441,42 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide return result; } - /** - * Returns the {@link ConnectionParameter} for the ForeignID. NOTE: may return {@code null}. - * - * @return the connection parameter. - * @throws ConfigurationException is thrown in case of missing {@link AuthComponentGeneral}. - */ - @Transactional - public ConnectionParameter getForeignIDConnectionParameter(IOAAuthParameters oaParameters) throws ConfigurationException { - String serviceURL = null; - try { - //load OA specific MIS service URL if OA configuration exists - if (oaParameters != null) - serviceURL = oaParameters.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_EXTERNAL_SZRGW_SERVICE_URL); - - //get first entry from general configuration if no OA specific URL exists - if (MiscUtil.isEmpty(serviceURL)) { - List<String> serviceURLs = KeyValueUtils.getListOfCSVValues( - configuration.getStringValue(MOAIDConfigurationConstants.GENERAL_AUTH_SERVICES_SZRGW_URL)); - if (serviceURLs.size() > 0) - serviceURL = serviceURLs.get(0); - - } - - if (MiscUtil.isNotEmpty(serviceURL)) - return new ConnectionParameterMandate(serviceURL, this.getProperties(), this.getRootConfigFileDir()); - - else - throw new ConfigurationException("service.09", new Object[]{"NO SZR-GW Service URL"}); - - } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { - Logger.warn("Initialize SZR-GW service connection parameters FAILED.", e); - throw new ConfigurationException("service.09", new Object[]{e.getMessage()}, e); - - } - } +// /** +// * Returns the {@link ConnectionParameter} for the ForeignID. NOTE: may return {@code null}. +// * +// * @return the connection parameter. +// * @throws ConfigurationException is thrown in case of missing {@link AuthComponentGeneral}. +// */ +// @Transactional +// @Deprecated +// public ConnectionParameter getForeignIDConnectionParameter(IOAAuthParameters oaParameters) throws ConfigurationException { +// String serviceURL = null; +// try { +// //load OA specific MIS service URL if OA configuration exists +// if (oaParameters != null) +// serviceURL = oaParameters.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_EXTERNAL_CENTRAL_EIDASNODE_SERVICE_URL); +// +// //get first entry from general configuration if no OA specific URL exists +// if (MiscUtil.isEmpty(serviceURL)) { +// List<String> serviceURLs = KeyValueUtils.getListOfCSVValues( +// configuration.getStringValue(MOAIDConfigurationConstants.GENERAL_AUTH_SERVICES_CENTRAL_EIDASNODE_URL)); +// if (serviceURLs.size() > 0) +// serviceURL = serviceURLs.get(0); +// +// } +// +// if (MiscUtil.isNotEmpty(serviceURL)) +// return new ConnectionParameterMandate(serviceURL, getFullConfigurationProperties(), getRootConfigFileDir()); +// +// else +// throw new ConfigurationException("service.09", new Object[]{"NO SZR-GW Service URL"}); +// +// } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { +// Logger.warn("Initialize SZR-GW service connection parameters FAILED.", e); +// throw new ConfigurationException("service.09", new Object[]{e.getMessage()}, e); +// +// } +// } /** * Returns the {@link ConnectionParameter} for the OnlineMandates. NOTE: may return {@code null}. @@ -577,7 +502,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } if (MiscUtil.isNotEmpty(serviceURL)) - return new ConnectionParameterMandate(serviceURL, this.getProperties(), this.getRootConfigFileDir()); + return new ConnectionParameterMandate(serviceURL, getFullConfigurationProperties(), getRootConfigFileDir()); else throw new ConfigurationException("service.06", new Object[]{"NO MIS Service URL"}); @@ -849,8 +774,9 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return the MOASessionEncryptionKey or {@code null} */ public String getMOASessionEncryptionKey() { - String prop = properties.getProperty("configuration.moasession.key"); + String prop = getFullConfigurationProperties().getProperty("configuration.moasession.key"); return MiscUtil.isNotEmpty(prop) ? prop : null; + } /** @@ -859,7 +785,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return the MOAConfigurationEncryptionKey or {@code null} */ public String getMOAConfigurationEncryptionKey() { - String prop = properties.getProperty("configuration.moaconfig.key"); + String prop = getFullConfigurationProperties().getProperty("configuration.moaconfig.key"); return MiscUtil.isNotEmpty(prop) ? prop : null; } @@ -867,7 +793,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return {@code true} if IdentityLinkResigning is set, {@code false} otherwise. */ public boolean isIdentityLinkResigning() { - String prop = properties.getProperty("configuration.resignidentitylink.active", "false"); + String prop = getFullConfigurationProperties().getProperty("configuration.resignidentitylink.active", "false"); return Boolean.valueOf(prop); } @@ -877,7 +803,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return the IdentityLinkResigningKey or {@code null} */ public String getIdentityLinkResigningKey() { - String prop = properties.getProperty("configuration.resignidentitylink.keygroup"); + String prop = getFullConfigurationProperties().getProperty("configuration.resignidentitylink.keygroup"); return MiscUtil.isNotEmpty(prop) ? prop : null; } @@ -885,7 +811,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return {@code true} if MonitoringActive is set, {@code false} otherwise. */ public boolean isMonitoringActive() { - String prop = properties.getProperty("configuration.monitoring.active", "false"); + String prop = getFullConfigurationProperties().getProperty("configuration.monitoring.active", "false"); return Boolean.valueOf(prop); } @@ -895,7 +821,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return the MonitoringTestIdentityLinkURL or {@code null} */ public String getMonitoringTestIdentityLinkURL() { - String prop = properties.getProperty("configuration.monitoring.test.identitylink.url"); + String prop = getFullConfigurationProperties().getProperty("configuration.monitoring.test.identitylink.url"); return MiscUtil.isNotEmpty(prop) ? prop : null; } @@ -905,7 +831,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return the MonitoringMessageSuccess or {@code null} */ public String getMonitoringMessageSuccess() { - String prop = properties.getProperty("configuration.monitoring.message.success"); + String prop = getFullConfigurationProperties().getProperty("configuration.monitoring.message.success"); return MiscUtil.isNotEmpty(prop) ? prop : null; } @@ -913,7 +839,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return {@code true} if AdvancedLoggingActive is set, {@code false} otherwise. */ public boolean isAdvancedLoggingActive() { - String prop = properties.getProperty("configuration.advancedlogging.active", "false"); + String prop = getFullConfigurationProperties().getProperty("configuration.advancedlogging.active", "false"); return Boolean.valueOf(prop); } @@ -965,7 +891,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return {@code true} if PVP2AssertionEncryptionActive is set, {@code false} otherwise. */ public boolean isPVP2AssertionEncryptionActive() { - String prop = this.getProperties().getProperty("protocols.pvp2.assertion.encryption.active", "true"); + String prop = getFullConfigurationProperties().getProperty("protocols.pvp2.assertion.encryption.active", "true"); return Boolean.valueOf(prop); } @@ -973,7 +899,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return {@code true} if CertifiacteQCActive is set, {@code false} otherwise. */ public boolean isCertifiacteQCActive() { - String prop = this.getProperties().getProperty("configuration.validation.certificate.QC.ignore", "false"); + String prop = getFullConfigurationProperties().getProperty("configuration.validation.certificate.QC.ignore", "false"); return !Boolean.valueOf(prop); } @@ -993,7 +919,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide Logger.warn("Error in MOA-ID Configuration. No STORK configuration found."); } else { - result = new STORKConfig(this.getProperties(), this.getRootConfigFileDir()); + result = new STORKConfig(getFullConfigurationProperties(), this.getRootConfigFileDir()); } } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { @@ -1055,10 +981,10 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide private Properties getGeneralProperiesConfig(final String propPrefix) { Properties configProp = new Properties(); - for (Object key : this.getProperties().keySet()) { + for (Object key : getFullConfigurationProperties().keySet()) { if (key.toString().startsWith(propPrefix)) { String propertyName = key.toString().substring(propPrefix.length()); - configProp.put(propertyName, this.getProperties().get(key.toString())); + configProp.put(propertyName, getFullConfigurationProperties().get(key.toString())); } } return configProp; @@ -1087,7 +1013,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide @Transactional public String getTrustedCACertificates() { try { - String path = rootConfigFileDir + configuration.getStringValue( + String path = getRootConfigFileDir() + configuration.getStringValue( MOAIDConfigurationConstants.GENERAL_AUTH_TRUSTSTORE_URL); if (MiscUtil.isNotEmpty(path)) return path; @@ -1098,7 +1024,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } - } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { + } catch (at.gv.egiz.components.configuration.api.ConfigurationException | ConfigurationException e) { Logger.warn("Error in MOA-ID Configuration. No TrustStoreDirectory defined.", e); return null; } @@ -1116,13 +1042,9 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide Logger.trace("Get active OnlineApplication with ID " + id + " from database."); Map<String, String> oaConfig = null; try { - - //TODO: //Some databases do not allow the selection of a lob in SQL where expression - String dbDriver = properties.getProperty("configuration.hibernate.connection.driver_class"); if (requireJDBCBackupImplementation) - oaConfig = configuration.getOnlineApplicationBackupVersion(id); - + oaConfig = configuration.getOnlineApplicationBackupVersion(id); else oaConfig = configuration.getOnlineApplication(id); @@ -1135,7 +1057,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide Logger.info("Online application with identifier " + id + " is found, but NOT active."); } else - Logger.warn("Online application with identifier " + id + " is not found."); + Logger.info("Online application with identifier " + id + " is not found."); } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { @@ -1149,13 +1071,13 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide //Load document service url from moa properties public String getDocumentServiceUrl() { - String prop = properties.getProperty("stork.documentservice.url", "false"); + String prop = getFullConfigurationProperties().getProperty("stork.documentservice.url", "false"); return prop; } public boolean isPVPSchemaValidationActive() { - String prop = properties.getProperty("protocols.pvp2.schemavalidation", "true"); + String prop = getFullConfigurationProperties().getProperty("protocols.pvp2.schemavalidation", "true"); return Boolean.valueOf(prop); } @@ -1165,7 +1087,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return true, if fake IdLs are available for stork */ public boolean isStorkFakeIdLActive() { - String prop = properties.getProperty("stork.fakeIdL.active", "false"); + String prop = getFullConfigurationProperties().getProperty("stork.fakeIdL.active", "false"); return Boolean.valueOf(prop); } @@ -1175,7 +1097,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return the countries */ public List<String> getStorkFakeIdLCountries() { - String prop = properties.getProperty("stork.fakeIdL.countries", ""); + String prop = getFullConfigurationProperties().getProperty("stork.fakeIdL.countries", ""); return Arrays.asList(prop.replaceAll(" ", "").split(",")); } @@ -1185,7 +1107,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return the resigning key */ public String getStorkFakeIdLResigningKey() { - String prop = properties.getProperty("stork.fakeIdL.keygroup"); + String prop = getFullConfigurationProperties().getProperty("stork.fakeIdL.keygroup"); if (MiscUtil.isNotEmpty(prop)) return prop; else @@ -1198,7 +1120,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide */ @Override public List<String> getStorkNoSignatureCountries() { - String prop = properties.getProperty("stork.fakeIdL.noSignatureCountries", ""); + String prop = getFullConfigurationProperties().getProperty("stork.fakeIdL.noSignatureCountries", ""); return Arrays.asList(prop.replaceAll(" ", "").split(",")); } @@ -1208,7 +1130,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide @Override @Deprecated public boolean isHTTPAuthAllowed() { - String prop = properties.getProperty("configuration.localhttpallowed.active", "false"); + String prop = getFullConfigurationProperties().getProperty("configuration.localhttpallowed.active", "false"); return Boolean.valueOf(prop); } @@ -1220,7 +1142,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide final String[] DEFAULTORDER = new String[] {RevocationSourceTypes.OCSP, RevocationSourceTypes.CRL}; List<String> result = new ArrayList<String>(); - String prop = properties.getProperty("configuration.ssl.validation.revocation.method.order"); + String prop = getFullConfigurationProperties().getProperty("configuration.ssl.validation.revocation.method.order"); if (MiscUtil.isNotEmpty(prop)) { String[] configOrder = prop.split(","); for (String el : configOrder) { @@ -1301,19 +1223,89 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } return false; + + } + + private void initialize() throws ConfigurationException { + try { + initial(getFullConfigurationProperties()); + String dbDriver = getFullConfigurationProperties().getProperty("configuration.hibernate.connection.driver_class"); + if (MiscUtil.isNotEmpty(dbDriver)) { + for (String el:MOAIDConstants.JDBC_DRIVER_NEEDS_WORKAROUND) { + if (dbDriver.startsWith(el)) { + requireJDBCBackupImplementation = true; + Logger.info("JDBC driver '" + dbDriver + + "' is blacklisted --> Switch to alternative DB access methode implementation."); + + } + } + } + + + } catch (org.opensaml.xml.ConfigurationException e) { + Logger.error("OpenSAML initilalization FAILED. ", e); + throw new ConfigurationException("config.23", null, e); + + } catch (Exception e) { + Logger.error("General error during start-up process.", e); + throw new ConfigurationException("init.02", null, e); + + } + } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.commons.api.AuthConfiguration#getBasicMOAIDConfigurationBoolean(java.lang.String, boolean) - */ + @Override - public boolean getBasicMOAIDConfigurationBoolean(String key, boolean defaultValue) { - String value = properties.getProperty(key); + public String validateIDPURL(URL requestedURL) throws EAAFException{ + List<String> configuredPublicURLPrefix = getPublicURLPrefix(); - if (MiscUtil.isNotEmpty(value)) - return Boolean.valueOf(value.trim()); - - return defaultValue; + if (!isVirtualIDPsEnabled()) { + Logger.trace("Virtual IDPs are disabled. Use default IDP PublicURLPrefix from configuration: " + configuredPublicURLPrefix.get(0)); + return configuredPublicURLPrefix.get(0); + + } else { + Logger.debug("Extract AuthenticationServiceURL: " + requestedURL); + URL resultURL = null; + + for (String el : configuredPublicURLPrefix) { + try { + URL configuredURL = new URL(el); + + //get Ports from URL + int configPort = configuredURL.getPort(); + if (configPort == -1) + configPort = configuredURL.getDefaultPort(); + + int authURLPort = requestedURL.getPort(); + if (authURLPort == -1) + authURLPort = requestedURL.getDefaultPort(); + + //check AuthURL against ConfigurationURL + if (configuredURL.getHost().equals(requestedURL.getHost()) && + configPort == authURLPort && + ( configuredURL.getPath().equals(requestedURL.getPath()) + || requestedURL.getPath().startsWith(configuredURL.getPath()) ) + && configuredURL.getProtocol().equals(requestedURL.getProtocol()) ) { + Logger.debug("Select configurated PublicURLPrefix: " + configuredURL + + " for authURL: " + requestedURL); + resultURL = configuredURL; + } + + } catch (MalformedURLException e) { + Logger.error("Configurated IDP PublicURLPrefix is not a valid URL." + el); + + } + } + + if (resultURL == null) { + Logger.warn("Extract AuthenticationServiceURL: " + requestedURL + " is NOT found in configuration."); + throw new ConfigurationException("config.25", new Object[]{requestedURL}); + + } else { + return resultURL.toExternalForm(); + + } + } } } 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 f3db82315..390b77dab 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 @@ -24,10 +24,12 @@ package at.gv.egovernment.moa.id.config.auth.data; import java.io.Serializable; import java.security.PrivateKey; +import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.commons.api.data.SAML1ConfigurationParameters; import at.gv.egovernment.moa.id.commons.api.data.StorkAttribute; @@ -59,7 +61,7 @@ public class DynamicOAAuthParameters implements IOAAuthParameters, Serializable{ * @see at.gv.egovernment.moa.id.commons.api.IOAAuthParameters#hasBaseIdInternalProcessingRestriction() */ @Override - public boolean hasBaseIdInternalProcessingRestriction() throws ConfigurationException { + public boolean hasBaseIdInternalProcessingRestriction() { return this.hasBaseIdProcessingRestriction; } @@ -67,7 +69,7 @@ public class DynamicOAAuthParameters implements IOAAuthParameters, Serializable{ * @see at.gv.egovernment.moa.id.commons.api.IOAAuthParameters#hasBaseIdTransferRestriction() */ @Override - public boolean hasBaseIdTransferRestriction() throws ConfigurationException { + public boolean hasBaseIdTransferRestriction() { return this.hasBaseIdTransfergRestriction; } @@ -75,7 +77,7 @@ public class DynamicOAAuthParameters implements IOAAuthParameters, Serializable{ * @see at.gv.egovernment.moa.id.commons.api.IOAAuthParameters#getAreaSpecificTargetIdentifier() */ @Override - public String getAreaSpecificTargetIdentifier() throws ConfigurationException { + public String getAreaSpecificTargetIdentifier() { return this.oaTargetAreaIdentifier; } @@ -531,5 +533,66 @@ public class DynamicOAAuthParameters implements IOAAuthParameters, Serializable{ return false; } + + @Override + public List<String> foreignbPKSectorsRequested() { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean containsConfigurationKey(String arg0) { + // TODO Auto-generated method stub + return false; + } + + @Override + public List<String> getTargetsWithNoBaseIdInternalProcessingRestriction() { + // TODO Auto-generated method stub + return null; + } + + @Override + public List<String> getTargetsWithNoBaseIdTransferRestriction() { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getUniqueIdentifier() { + return getPublicURLPrefix(); + } + + @Override + public List<String> getRequiredLoA() { + if (getQaaLevel() != null) + return Arrays.asList(getQaaLevel()); + else + return null; + } + + @Override + public String getConfigurationValue(String arg0, String arg1) { + // TODO Auto-generated method stub + return null; + } + + @Override + public Boolean isConfigurationValue(String arg0) { + // TODO Auto-generated method stub + return null; + } + + @Override + public boolean isConfigurationValue(String arg0, boolean arg1) { + // TODO Auto-generated method stub + return false; + } + + @Override + public String getLoAMatchingMode() { + return EAAFConstants.EIDAS_LOA_MATCHING_MINIMUM; + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/UserWhitelistStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/UserWhitelistStore.java new file mode 100644 index 000000000..9c296e2b8 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/UserWhitelistStore.java @@ -0,0 +1,154 @@ +package at.gv.egovernment.moa.id.config.auth.data; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.apache.commons.io.IOUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.core.impl.utils.KeyValueUtils; +import at.gv.egovernment.moa.id.auth.modules.internal.tasks.UserRestrictionTask; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.util.MiscUtil; +import at.gv.egovernment.moaspss.logging.Logger; + +@Service("UserWhiteList_Store") +public class UserWhitelistStore { + + @Autowired(required=true) AuthConfiguration authConfig; + + private List<String> whitelist = new ArrayList<String>(); + private String absWhiteListUrl = null; + + @PostConstruct + private void initialize() { + String whiteListUrl = authConfig.getBasicConfiguration(UserRestrictionTask.CONFIG_PROPS_CSV_USER_FILE); + String internalTarget = authConfig.getBasicConfiguration(UserRestrictionTask.CONFIG_PROPS_CSV_USER_SECTOR); + if (MiscUtil.isEmpty(whiteListUrl) || MiscUtil.isEmpty(internalTarget)) + Logger.debug("Do not initialize user whitelist. Reason: NO configuration path to CSV file or NO internal bPK target for whitelist"); + + else { + if (internalTarget.startsWith(MOAIDAuthConstants.PREFIX_CDID)) + internalTarget = internalTarget.substring(MOAIDAuthConstants.PREFIX_CDID.length()); + else if (internalTarget.startsWith(MOAIDAuthConstants.PREFIX_WPBK)) + internalTarget = internalTarget.substring(MOAIDAuthConstants.PREFIX_WPBK.length()); + else if (internalTarget.startsWith(MOAIDAuthConstants.PREFIX_EIDAS)) + internalTarget = internalTarget.substring(MOAIDAuthConstants.PREFIX_EIDAS.length()); + else { + Logger.warn("Sector: " + internalTarget + " is NOT supported for user whitelist."); + Logger.info("User whitelist-store MAY NOT contains all user from whitelist"); + } + + try { + absWhiteListUrl = new URL(FileUtils.makeAbsoluteURL(whiteListUrl, authConfig.getConfigurationRootDirectory())) + .toURI().toString().substring("file:".length()); + InputStream is = new FileInputStream(new File(absWhiteListUrl)); + String whiteListString = IOUtils.toString(new InputStreamReader(is)); + List<String> preWhitelist = KeyValueUtils.getListOfCSVValues(KeyValueUtils.normalizeCSVValueString(whiteListString)); + + + + //remove prefix if required + for (String bPK : preWhitelist) { + String[] bPKSplit = bPK.split(":"); + if (bPKSplit.length == 1) + whitelist.add(bPK); + + else if (bPKSplit.length ==2 ) { + if (internalTarget.equals(bPKSplit[0])) + whitelist.add(bPKSplit[1]); + else + Logger.info("Whitelist entry: " + bPK + " has an unsupported target. Entry will be removed ..."); + + } else + Logger.info("Whitelist entry: " + bPK + " has an unsupported format. Entry will be removed ..."); + + } + + Logger.info("User whitelist is initialized with " + whitelist.size() + " entries."); + + + } catch (FileNotFoundException e) { + Logger.warn("Do not initialize user whitelist. Reason: CSV file with bPKs NOT found", e); + + } catch (IOException e) { + Logger.warn("Do not initialize user whitelist. Reason: CSV file is NOT readable", e); + + } catch (URISyntaxException e) { + Logger.warn("Do not initialize user whitelist. Reason: CSV file looks wrong", e); + + } + + } + + } + + /** + * Get the number of entries of the static whitelist + * + * @return + */ + public int getNumberOfEntries() { + return whitelist.size(); + } + + /** + * Check if bPK is in whitelist + * + * @param bPK + * @return true if bPK is in whitelist, otherwise false + */ + public boolean isUserbPKInWhitelist(String bPK) { + if (whitelist != null) + return whitelist.contains(bPK); + else + return false; + + } + + public boolean isUserbPKInWhitelistDynamic(String bPK) { + return isUserbPKInWhitelistDynamic(bPK, false); + + } + + public boolean isUserbPKInWhitelistDynamic(String bPK, boolean onlyDynamic) { + try { + if (absWhiteListUrl != null) { + InputStream is = new FileInputStream(new File(absWhiteListUrl)); + String whiteListString = IOUtils.toString(new InputStreamReader(is)); + if (whiteListString != null && whiteListString.contains(bPK)) { + Logger.trace("Find user with dynamic whitelist check"); + return true; + + } else { + Logger.debug("Can NOT find user in dynamic loaded user whitelist. Switch to static version ... "); + if (!onlyDynamic) + return isUserbPKInWhitelist(bPK); + } + + } + } catch (Exception e) { + Logger.warn("Dynamic user whitelist check FAILED. Switch to static version ... ", e); + + } + if (!onlyDynamic) + return isUserbPKInWhitelist(bPK); + + + return false; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java deleted file mode 100644 index 7f56f519b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java +++ /dev/null @@ -1,819 +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.data; - -import java.io.Serializable; -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import org.apache.commons.collections4.map.HashedMap; -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.commons.api.data.IIdentityLink; -import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; -import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; -import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.egovernment.moa.util.DateTimeUtils; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ -public class AuthenticationData implements IAuthData, Serializable { - - private static final long serialVersionUID = -1042697056735596866L; - public static final String IDENTITY_LINK_DATE_FORMAT = "yyyy-MM-dd"; - - /** - * URL of the MOA-ID Auth component issueing this assertion - */ - private String issuer; - /** - * time instant of issue of this assertion - */ - private Date issueInstant; - /** - * user identification value (Stammzahl); <code>null</code>, - * if the authentication module is configured not to return this data - */ - private String identificationValue; - /** - * user identification type - */ - private String identificationType; - - /** - * user identityLink specialized to OAParamter - */ - private IIdentityLink identityLink; - - /** - * application specific user identifier (bPK/wbPK) - */ - private String bPK; - - /** - * application specific user identifier type - */ - private String bPKType; - - /** - * given name of the user - */ - private String givenName; - /** - * family name of the user - */ - private String familyName; - /** - * date of birth of the user - */ - private Date dateOfBirth; - /** - * says whether the certificate is a qualified certificate or not - */ - private boolean qualifiedCertificate; - /** - * says whether the certificate is a public authority or not - */ - private boolean publicAuthority; - /** - * public authority code (Behördenkennzeichen - BKZ) - */ - private String publicAuthorityCode; - - /** - * URL of the BKU - */ - private String bkuURL; - /** - * the corresponding <code>lt;saml:Assertion></code> - */ - - private boolean isBaseIDTransferRestrication = true; - - - /** - * STORK attributes from response - */ - private String ccc = null; - - private Map<String, Object> genericDataStorate = new HashedMap<String, Object>(); - - private byte[] signerCertificate = null; - - private String authBlock = null; - private List<String> encbPKList = null; - - //ISA 1.18 attributes - private List<AuthenticationRole> roles = null; - private String pvpAttribute_OU = null; - - private boolean useMandate = false; - private IMISMandate mandate = null; - private String mandateReferenceValue = null; - - private boolean foreigner =false; - private String QAALevel = null; - - private boolean ssoSession = false; - private Date ssoSessionValidTo = null; - -// private boolean interfederatedSSOSession = false; -// private String interfederatedIDP = null; - - private String sessionIndex = null; - private String nameID = null; - private String nameIDFormat = null; - - public AuthenticationData() { - issueInstant = new Date(); - } - - /** - * Returns the publicAuthority. - * @return boolean - */ - public boolean isPublicAuthority() { - return publicAuthority; - } - - /** - * Returns the publicAuthorityCode. - * @return String - */ - public String getPublicAuthorityCode() { - return publicAuthorityCode; - } - - /** - * Returns the qualifiedCertificate. - * @return boolean - */ - public boolean isQualifiedCertificate() { - return qualifiedCertificate; - } - - /** - * Returns the bPK. - * @return String - */ - public String getBPK() { - return bPK; - } - - /** - * Sets the publicAuthority. - * @param publicAuthority The publicAuthority to set - */ - public void setPublicAuthority(boolean publicAuthority) { - this.publicAuthority = publicAuthority; - } - - /** - * Sets the publicAuthorityCode. - * @param publicAuthorityIdentification The publicAuthorityCode to set - */ - public void setPublicAuthorityCode(String publicAuthorityIdentification) { - this.publicAuthorityCode = publicAuthorityIdentification; - } - - /** - * Sets the qualifiedCertificate. - * @param qualifiedCertificate The qualifiedCertificate to set - */ - public void setQualifiedCertificate(boolean qualifiedCertificate) { - this.qualifiedCertificate = qualifiedCertificate; - } - - /** - * Sets the bPK. - * @param bPK The bPK to set - */ - public void setBPK(String bPK) { - this.bPK = bPK; - } - - /** - * Returns the dateOfBirth. - * @return String - */ - public Date getDateOfBirth() { - return dateOfBirth; - } - - public String getFormatedDateOfBirth() { - DateFormat pvpDateFormat = new SimpleDateFormat(IDENTITY_LINK_DATE_FORMAT); - if (getDateOfBirth() != null) - return pvpDateFormat.format(getDateOfBirth()); - else - return "2999-12-31"; - } - - /** - * Returns the familyName. - * @return String - */ - public String getFamilyName() { - return familyName; - } - - /** - * Returns the givenName. - * @return String - */ - public String getGivenName() { - return givenName; - } - - /** - * Holds the baseID of a citizen - * - * @return baseID - */ - public String getIdentificationValue() { - return identificationValue; - } - - /** - * Holds the type of the baseID - * - * @return baseID-Type - */ - public String getIdentificationType() { - return identificationType; - } - - /** - * Returns the issueInstant. - * @return String - */ - public String getIssueInstantString() { - return DateTimeUtils.buildDateTimeUTC(issueInstant); - - } - - /** - * Returns the issueInstant. - * @return String - */ - public Date getIssueInstant() { - return issueInstant; - - } - - public void setIssueInstant(Date date) { - this.issueInstant = date; - } - - /** - * Returns the issuer. - * @return String - */ - public String getIssuer() { - return issuer; - } - - /** - * Returns the BKU URL. - * @return String - */ - public String getBkuURL() { - return bkuURL; - } - - /** - * Sets the dateOfBirth. - * @param dateOfBirth The dateOfBirth to set - */ - public void setDateOfBirth(Date dateOfBirth) { - this.dateOfBirth = dateOfBirth; - } - - public void setDateOfBirth(String dateOfBirth) { - try { - if (MiscUtil.isNotEmpty(dateOfBirth)) { - DateFormat identityLinkFormat = new SimpleDateFormat(IDENTITY_LINK_DATE_FORMAT); - this.dateOfBirth = identityLinkFormat.parse(dateOfBirth); - } - - } catch (ParseException e) { - Logger.warn("Parse dateOfBirht from IdentityLink FAILED", e); - - } - } - - /** - * Sets the familyName. - * @param familyName The familyName to set - */ - public void setFamilyName(String familyName) { - this.familyName = familyName; - } - - /** - * Sets the givenName. - * @param givenName The givenName to set - */ - public void setGivenName(String givenName) { - this.givenName = givenName; - } - - /** - * Sets the identificationValue. - * @param identificationValue The identificationValue to set - */ - public void setIdentificationValue(String identificationValue) { - this.identificationValue = identificationValue; - } - - /** - * Sets the identificationType. - * @param identificationType The identificationType to set - */ - public void setIdentificationType(String identificationType) { - this.identificationType = identificationType; - } - - /** - * Sets the issuer. - * @param issuer The issuer to set - */ - public void setIssuer(String issuer) { - this.issuer = issuer; - } - - /** - * Sets the bkuURL - * @param url The BKU URL to set - */ - public void setBkuURL(String url) { - this.bkuURL = url; - } - - public String getBPKType() { - return bPKType; - } - - public void setBPKType(String bPKType) { - this.bPKType = bPKType; - } - - /** - * @return the identityLink - */ - public IIdentityLink getIdentityLink() { - return identityLink; - } - - /** - * @param identityLink the identityLink to set - */ - public void setIdentityLink(IIdentityLink identityLink) { - this.identityLink = identityLink; - } - - /** - * @return the signerCertificate - */ - public byte[] getSignerCertificate() { - return signerCertificate; - } - - - /** - * @param signerCertificate the signerCertificate to set - */ - public void setSignerCertificate(byte[] signerCertificate) { - this.signerCertificate = signerCertificate; - } - - - /** - * @return the authBlock - */ - public String getAuthBlock() { - return authBlock; - } - - - /** - * @param authBlock the authBlock to set - */ - public void setAuthBlock(String authBlock) { - this.authBlock = authBlock; - } - - - /** - * @return the mandate - */ - public IMISMandate getMISMandate() { - return mandate; - } - - public Element getMandate() { - if (mandate == null) - return null; - - //parse Element from mandate XML - try { - byte[] byteMandate = mandate.getMandate(); - String stringMandate = new String(byteMandate); - return DOMUtils.parseDocument(stringMandate, false, null, null).getDocumentElement(); - - } - catch (Throwable e) { - Logger.warn("Mandate content could not be generated from MISMandate."); - return null; - } - } - - - /** - * @param mandate the mandate to set - */ - public void setMISMandate(IMISMandate mandate) { - this.mandate = mandate; - } - - - /** - * @return the useMandate - */ - public boolean isUseMandate() { - return useMandate; - } - - - /** - * @param useMandate the useMandate to set - */ - public void setUseMandate(boolean useMandate) { - this.useMandate = useMandate; - } - - - /** - * @return - */ - public String getQAALevel() { - if (this.QAALevel != null && - this.QAALevel.startsWith(PVPConstants.EIDAS_QAA_PREFIX)) { - String mappedQAA = PVPtoSTORKMapper.getInstance().mapeIDASQAAToSTORKQAA(this.QAALevel); - if (MiscUtil.isNotEmpty(mappedQAA)) - return mappedQAA; - - else { - Logger.error("eIDAS QAA-level:" + this.QAALevel - + " can not be mapped to STORK QAA-level! Use " - + PVPConstants.STORK_QAA_1_1 + " as default value."); - return PVPConstants.STORK_QAA_1_1; - - } - - - } else - return this.QAALevel; - } - - - public String getEIDASQAALevel() { - if (this.QAALevel != null && - this.QAALevel.startsWith(PVPConstants.STORK_QAA_PREFIX)) { - String mappedQAA = PVPtoSTORKMapper.getInstance().mapSTORKQAAToeIDASQAA(this.QAALevel); - if (MiscUtil.isNotEmpty(mappedQAA)) - return mappedQAA; - - else { - Logger.error("STORK QAA-level:" + this.QAALevel - + " can not be mapped to eIDAS QAA-level! Use " - + PVPConstants.EIDAS_QAA_LOW + " as default value."); - return PVPConstants.EIDAS_QAA_LOW; - - } - - - } else - return this.QAALevel; - - } - - - /** - * @return - */ - public boolean isForeigner() { - return this.foreigner; - } - - - /** - * @param foreigner the foreigner to set - */ - public void setForeigner(boolean foreigner) { - this.foreigner = foreigner; - } - - - /** - * Store QAA level in eIDAS format to authentication Data - * - * @param qAALevel the qAALevel to set - * @throws AssertionAttributeExtractorExeption - */ - public void setQAALevel(String qAALevel) { - QAALevel = qAALevel; - - } - - /** - * @return the ssoSession - */ - public boolean isSsoSession() { - return ssoSession; - } - - - /** - * @param ssoSession the ssoSession to set - */ - public void setSsoSession(boolean ssoSession) { - this.ssoSession = ssoSession; - } - - /** - * @return the mandateReferenceValue - */ - public String getMandateReferenceValue() { - return mandateReferenceValue; - } - - /** - * @param mandateReferenceValue the mandateReferenceValue to set - */ - public void setMandateReferenceValue(String mandateReferenceValue) { - this.mandateReferenceValue = mandateReferenceValue; - } - - /** - * CountryCode of the citizen which is identified and authenticated - * - * @return the CountryCode <pre>like. AT, SI, ...</pre> - */ - public String getCcc() { - return ccc; - } - - /** - * @param ccc the ccc to set - */ - public void setCcc(String ccc) { - this.ccc = ccc; - } - - /** - * @return the sessionIndex - */ - public String getSessionIndex() { - return sessionIndex; - } - - /** - * @param sessionIndex the sessionIndex to set - */ - public void setSessionIndex(String sessionIndex) { - this.sessionIndex = sessionIndex; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.IAuthData#getNameID() - */ - @Override - public String getNameID() { - return this.nameID; - } - - /** - * @param nameID the nameID to set - */ - public void setNameID(String nameID) { - this.nameID = nameID; - } - - /** - * @return the nameIDFormat - */ - public String getNameIDFormat() { - return nameIDFormat; - } - - /** - * @param nameIDFormat the nameIDFormat to set - */ - public void setNameIDFormat(String nameIDFormat) { - this.nameIDFormat = nameIDFormat; - } - -// /** -// * @return the interfederatedSSOSession -// */ -// public boolean isInterfederatedSSOSession() { -// return interfederatedSSOSession; -// } -// -// /** -// * @param interfederatedSSOSession the interfederatedSSOSession to set -// */ -// public void setInterfederatedSSOSession(boolean interfederatedSSOSession) { -// this.interfederatedSSOSession = interfederatedSSOSession; -// } -// -// /** -// * @return the interfederatedIDP -// */ -// public String getInterfederatedIDP() { -// return interfederatedIDP; -// } -// -// /** -// * @param interfederatedIDP the interfederatedIDP to set -// */ -// public void setInterfederatedIDP(String interfederatedIDP) { -// this.interfederatedIDP = interfederatedIDP; -// } - - /** - * @return the ssoSessionValidTo - */ - public Date getSsoSessionValidTo() { - return ssoSessionValidTo; - } - - /** - * @param ssoSessionValidTo the ssoSessionValidTo to set - */ - public void setSsoSessionValidTo(Date ssoSessionValidTo) { - this.ssoSessionValidTo = ssoSessionValidTo; - } - - /** - * @return the encbPKList - */ - public List<String> getEncbPKList() { - return encbPKList; - } - - /** - * @param encbPKList the encbPKList to set - */ - public void setEncbPKList(List<String> encbPKList) { - this.encbPKList = encbPKList; - } - - /** - * @return the roles - */ - public List<AuthenticationRole> getAuthenticationRoles() { -// if (this.roles == null) { -// this.roles = new ArrayList<AuthenticationRole>(); -// this.roles.add(new AuthenticationRole("xxpvprole", "xxpvprole")); -// this.roles.add(new AuthenticationRole("yypvprole", "yypvprole")); -// } - - return roles; - } - - //ISA 1.18 attributes - /** - * @param roles the roles to set - */ - public void addAuthenticationRole(AuthenticationRole role) { - if (this.roles == null) - this.roles = new ArrayList<AuthenticationRole>(); - - this.roles.add(role); - } - - /** - * @return the pvpAttribute_OU - */ - public String getPvpAttribute_OU() { - return pvpAttribute_OU; - } - - /** - * @param pvpAttribute_OU the pvpAttribute_OU to set - */ - public void setPvpAttribute_OU(String pvpAttribute_OU) { - this.pvpAttribute_OU = pvpAttribute_OU; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.IAuthData#isBusinessService() - */ - @Override - public boolean isBaseIDTransferRestrication() { - return isBaseIDTransferRestrication; - } - - /** - * @param isBaseIDTransmittionAllowed the isBaseIDTransmittionAllowed to set - */ - public void setBaseIDTransferRestrication(boolean isBaseIDTransferRestrication) { - this.isBaseIDTransferRestrication = isBaseIDTransferRestrication; - } - - /** - * Returns a generic data-object with is stored with a specific identifier - * - * @param key The specific identifier of the data object - * @param clazz The class type which is stored with this key - * @return The data object or null if no data is found with this key - */ - public <T> T getGenericData(String key, final Class<T> clazz) { - if (MiscUtil.isNotEmpty(key)) { - Object data = genericDataStorate.get(key); - - if (data == null) - return null; - - try { - @SuppressWarnings("unchecked") - T test = (T) data; - return test; - - } catch (Exception e) { - Logger.warn("Generic authentication-data object can not be casted to requsted type", e); - return null; - - } - - } - - Logger.warn("Can not load generic session-data with key='null'"); - return null; - - } - - /** - * Store a generic data-object to session with a specific identifier - * - * @param key Identifier for this data-object - * @param object Generic data-object which should be stored. This data-object had to be implement the 'java.io.Serializable' interface - * @throws SessionDataStorageException Error message if the data-object can not stored to generic session-data storage - */ - public void setGenericData(String key, Object object) throws SessionDataStorageException { - if (MiscUtil.isEmpty(key)) { - Logger.warn("Generic session-data can not be stored with a 'null' key"); - throw new SessionDataStorageException("Generic data can not be stored with a 'null' key", null); - - } - - if (object != null) { - if (!Serializable.class.isInstance(object)) { - Logger.warn("Generic data can only store objects which implements the 'Seralizable' interface"); - throw new SessionDataStorageException("Generic data can only store objects which implements the 'Seralizable' interface", null); - - } - } - - if (genericDataStorate.containsKey(key)) - Logger.debug("Overwrite generic data with key:" + key); - else - Logger.trace("Add generic data with key:" + key + " to session."); - - genericDataStorate.put(key, object); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ExceptionContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ExceptionContainer.java deleted file mode 100644 index 4820b6fdc..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ExceptionContainer.java +++ /dev/null @@ -1,86 +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.data; - -import java.io.Serializable; - -import at.gv.egovernment.moa.id.commons.api.IRequest; - -/** - * @author tlenz - * - */ -public class ExceptionContainer implements Serializable { - - private static final long serialVersionUID = 5355860753609684995L; - private Throwable exceptionThrown = null; - private String uniqueSessionID = null; - private String uniqueTransactionID = null; - private String uniqueServiceProviderId = null; - - /** - * - */ - public ExceptionContainer(IRequest pendingReq, Throwable exception) { - if (pendingReq != null) { - this.uniqueSessionID = pendingReq.getUniqueSessionIdentifier(); - this.uniqueTransactionID = pendingReq.getUniqueTransactionIdentifier(); - - if (pendingReq.getOnlineApplicationConfiguration() != null) - this.uniqueServiceProviderId = pendingReq.getOnlineApplicationConfiguration().getPublicURLPrefix(); - - } - - this.exceptionThrown = exception; - } - - /** - * @return the exceptionThrown - */ - public Throwable getExceptionThrown() { - return exceptionThrown; - } - /** - * @return the uniqueSessionID - */ - public String getUniqueSessionID() { - return uniqueSessionID; - } - /** - * @return the uniqueTransactionID - */ - public String getUniqueTransactionID() { - return uniqueTransactionID; - } - - /** - * @return the uniqueServiceProviderId - */ - public String getUniqueServiceProviderId() { - return uniqueServiceProviderId; - } - - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java deleted file mode 100644 index cb3def678..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java +++ /dev/null @@ -1,107 +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.data; - -import java.util.Date; -import java.util.List; - -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.commons.api.data.IIdentityLink; -import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; - -/** - * @author tlenz - * - */ -public interface IAuthData { - - Date getIssueInstant(); - String getIssuer(); - boolean isBaseIDTransferRestrication(); - - boolean isSsoSession(); - //boolean isInterfederatedSSOSession(); - boolean isUseMandate(); - - String getFamilyName(); - String getGivenName(); - Date getDateOfBirth(); - String getFormatedDateOfBirth(); - - String getBPK(); - String getBPKType(); - - Date getSsoSessionValidTo(); - - //String getInterfederatedIDP(); - - String getIdentificationValue(); - String getIdentificationType(); - - String getBkuURL(); - - List<String> getEncbPKList(); - - IIdentityLink getIdentityLink(); - byte[] getSignerCertificate(); - String getAuthBlock(); - - //ISA 1.18 attributes - String getPvpAttribute_OU(); - List<AuthenticationRole> getAuthenticationRoles(); - - boolean isPublicAuthority(); - String getPublicAuthorityCode(); - boolean isQualifiedCertificate(); - - IMISMandate getMISMandate(); - Element getMandate(); - String getMandateReferenceValue(); - - @Deprecated - /** - * Return STORK QAA level - * - * @return - */ - String getQAALevel(); - - /** - * Return authentication QAA level from eIDAS - * - * @return - */ - public String getEIDASQAALevel(); - - String getSessionIndex(); - String getNameID(); - String getNameIDFormat(); - - boolean isForeigner(); - String getCcc(); - - public <T> T getGenericData(String key, final Class<T> clazz); - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IMOAAuthData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IMOAAuthData.java new file mode 100644 index 000000000..ff4b96aab --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IMOAAuthData.java @@ -0,0 +1,38 @@ +package at.gv.egovernment.moa.id.data; + +import java.util.List; + +import org.w3c.dom.Element; + +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; + +public interface IMOAAuthData extends IAuthData{ + + @Deprecated + /** + * Return STORK QAA level + * + * @return + */ + String getQAALevel(); + + List<String> getEncbPKList(); + byte[] getSignerCertificate(); + String getAuthBlock(); + boolean isPublicAuthority(); + String getPublicAuthorityCode(); + boolean isQualifiedCertificate(); + String getBkuURL(); + String getInterfederatedIDP(); + boolean isInterfederatedSSOSession(); + boolean isUseMandate(); + IMISMandate getMISMandate(); + Element getMandate(); + String getMandateReferenceValue(); + + //ISA 1.18 attributes + String getPvpAttribute_OU(); + List<AuthenticationRole> getAuthenticationRoles(); + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ISLOInformationContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ISLOInformationContainer.java deleted file mode 100644 index 38f6948d3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ISLOInformationContainer.java +++ /dev/null @@ -1,70 +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.data; - -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; - -/** - * @author tlenz - * - */ -public interface ISLOInformationContainer { - - boolean hasFrontChannelOA(); - - Set<Entry<String, SLOInformationImpl>> getFrontChannelOASessionDescriptions(); - - void removeFrontChannelOA(String oaID); - - Iterator<String> getNextBackChannelOA(); - - SLOInformationImpl getBackChannelOASessionDescripten(String oaID); - - void removeBackChannelOA(String oaID); - - /** - * @return the sloRequest - */ - PVPTargetConfiguration getSloRequest(); - - /** - * @param sloRequest the sloRequest to set - */ - void setSloRequest(PVPTargetConfiguration sloRequest); - - /** - * @return the sloFailedOAs - */ - List<String> getSloFailedOAs(); - - void putFailedOA(String oaID); - - public String getTransactionID(); - - public String getSessionID(); -}
\ No newline at end of file diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java index 25d50f57a..d1e1e5c60 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java @@ -51,10 +51,10 @@ import java.io.Serializable; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; +import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.MiscUtil; public class MISMandate implements Serializable, IMISMandate{ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MOAAuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MOAAuthenticationData.java new file mode 100644 index 000000000..ca0ae0687 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MOAAuthenticationData.java @@ -0,0 +1,968 @@ +/** + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.data; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +import org.w3c.dom.Element; + +import at.gv.egiz.eaaf.core.api.data.ILoALevelMapper; +import at.gv.egiz.eaaf.core.impl.idp.AuthenticationData; +import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionAttributeExtractorExeption; +import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.util.LoALevelMapper; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + + + +/** + * @author tlenz + * + */ +public class MOAAuthenticationData extends AuthenticationData implements IMOAAuthData, Serializable { + + private static final long serialVersionUID = 1L; + private boolean qualifiedCertificate; + private boolean publicAuthority; + private String publicAuthorityCode; + private String bkuURL; + private byte[] signerCertificate = null; + private String authBlock = null; + private String QAALevel = null; + private List<String> encbPKList; + + //ISA 1.18 attributes + private List<AuthenticationRole> roles = null; + private String pvpAttribute_OU = null; + + private boolean useMandate = false; + private IMISMandate mandate = null; + private String mandateReferenceValue = null; + + private boolean interfederatedSSOSession; + private String interfederatedIDP; + + private LoALevelMapper loaMapper; + + public MOAAuthenticationData(ILoALevelMapper loaMapper) { + if (loaMapper instanceof LoALevelMapper) + this.loaMapper = (LoALevelMapper) loaMapper; + + } + + /** + * @return + */ + @Override + public String getQAALevel() { + if (this.QAALevel != null && + this.QAALevel.startsWith(PVPConstants.EIDAS_QAA_PREFIX)) { + if (loaMapper != null) { + String mappedQAA = loaMapper.mapeIDASQAAToSTORKQAA(this.QAALevel); + if (MiscUtil.isNotEmpty(mappedQAA)) + return mappedQAA; + else { + Logger.error("eIDAS QAA-level:" + this.QAALevel + + " can not be mapped to STORK QAA-level! Use " + + PVPConstants.STORK_QAA_1_1 + " as default value."); + } + + } else + Logger.error("NO LoALevelMapper found. Use " + + PVPConstants.STORK_QAA_1_1 + " as default value."); + + return PVPConstants.STORK_QAA_1_1; + + } else + return this.QAALevel; + + } + + @Override + public List<String> getEncbPKList() { + if (this.encbPKList == null) + this.encbPKList = new ArrayList<String>(); + + return this.encbPKList; + } + + + @Override + public byte[] getSignerCertificate() { + return signerCertificate; + } + + + /** + * @param signerCertificate the signerCertificate to set + */ + public void setSignerCertificate(byte[] signerCertificate) { + this.signerCertificate = signerCertificate; + } + + + @Override + public String getAuthBlock() { + return authBlock; + } + + + /** + * @param authBlock the authBlock to set + */ + public void setAuthBlock(String authBlock) { + this.authBlock = authBlock; + } + + + @Override + public IMISMandate getMISMandate() { + return mandate; + } + + @Override + public Element getMandate() { + if (mandate == null) + return null; + + //parse Element from mandate XML + try { + byte[] byteMandate = mandate.getMandate(); + String stringMandate = new String(byteMandate); + return DOMUtils.parseDocument(stringMandate, false, null, null).getDocumentElement(); + + } + catch (Throwable e) { + Logger.warn("Mandate content could not be generated from MISMandate."); + return null; + } + } + + + /** + * @param mandate the mandate to set + */ + public void setMISMandate(IMISMandate mandate) { + this.mandate = mandate; + } + + + @Override + public boolean isUseMandate() { + return useMandate; + } + + + public void setUseMandate(boolean useMandate) { + this.useMandate = useMandate; + } + + + @Override + public boolean isPublicAuthority() { + return publicAuthority; + } + + @Override + public String getPublicAuthorityCode() { + return publicAuthorityCode; + } + + @Override + public boolean isQualifiedCertificate() { + return qualifiedCertificate; + } + + + @Override + public String getBkuURL() { + return bkuURL; + + } + + /** + * Sets the bkuURL + * @param url The BKU URL to set + */ + public void setBkuURL(String url) { + this.bkuURL = url; + } + + @Override + public boolean isInterfederatedSSOSession() { + return this.interfederatedSSOSession; + } + + /** + * @param interfederatedSSOSession the interfederatedSSOSession to set + */ + public void setInterfederatedSSOSession(boolean interfederatedSSOSession) { + this.interfederatedSSOSession = interfederatedSSOSession; + } + + @Override + public String getInterfederatedIDP() { + return this.interfederatedIDP; + } + + /** + * @param interfederatedIDP the interfederatedIDP to set + */ + public void setInterfederatedIDP(String interfederatedIDP) { + this.interfederatedIDP = interfederatedIDP; + } + + + @Override + public String getMandateReferenceValue() { + return mandateReferenceValue; + } + + /** + * @param mandateReferenceValue the mandateReferenceValue to set + */ + public void setMandateReferenceValue(String mandateReferenceValue) { + this.mandateReferenceValue = mandateReferenceValue; + } + + + @Override + public List<AuthenticationRole> getAuthenticationRoles() { + return roles; + } + + //ISA 1.18 attributes + /** + * @param roles the roles to set + */ + public void addAuthenticationRole(AuthenticationRole role) { + if (this.roles == null) + this.roles = new ArrayList<AuthenticationRole>(); + + this.roles.add(role); + } + + @Override + public String getPvpAttribute_OU() { + return pvpAttribute_OU; + } + + /** + * @param pvpAttribute_OU the pvpAttribute_OU to set + */ + public void setPvpAttribute_OU(String pvpAttribute_OU) { + this.pvpAttribute_OU = pvpAttribute_OU; + } + + /** + * Store QAA level in eIDAS format to authentication Data + * + * @param qAALevel the qAALevel to set + * @throws AssertionAttributeExtractorExeption + */ + public void setQAALevel(String qAALevel) { + this.QAALevel = qAALevel; + + } + + /** + * @param encbPKList the encbPKList to set + */ + public void setEncbPKList(List<String> encbPKList) { + this.encbPKList = encbPKList; + } + + + /** + * Sets the publicAuthority. + * @param publicAuthority The publicAuthority to set + */ + public void setPublicAuthority(boolean publicAuthority) { + this.publicAuthority = publicAuthority; + } + + /** + * Sets the publicAuthorityCode. + * @param publicAuthorityIdentification The publicAuthorityCode to set + */ + public void setPublicAuthorityCode(String publicAuthorityIdentification) { + this.publicAuthorityCode = publicAuthorityIdentification; + } + + /** + * Sets the qualifiedCertificate. + * @param qualifiedCertificate The qualifiedCertificate to set + */ + public void setQualifiedCertificate(boolean qualifiedCertificate) { + this.qualifiedCertificate = qualifiedCertificate; + } + + +// private static final long serialVersionUID = -1042697056735596866L; +// public static final String IDENTITY_LINK_DATE_FORMAT = "yyyy-MM-dd"; +// +// /** +// * URL of the MOA-ID Auth component issueing this assertion +// */ +// private String issuer; +// /** +// * time instant of issue of this assertion +// */ +// private Date issueInstant; +// /** +// * user identification value (Stammzahl); <code>null</code>, +// * if the authentication module is configured not to return this data +// */ +// private String identificationValue; +// /** +// * user identification type +// */ +// private String identificationType; +// +// /** +// * user identityLink specialized to OAParamter +// */ +// private IIdentityLink identityLink; +// +// /** +// * application specific user identifier (bPK/wbPK) +// */ +// private String bPK; +// +// /** +// * application specific user identifier type +// */ +// private String bPKType; +// +// /** +// * given name of the user +// */ +// private String givenName; +// /** +// * family name of the user +// */ +// private String familyName; +// /** +// * date of birth of the user +// */ +// private Date dateOfBirth; +// /** +// * says whether the certificate is a qualified certificate or not +// */ +// +// /** +// * says whether the certificate is a public authority or not +// */ +// /** +// * public authority code (Behördenkennzeichen - BKZ) +// */ +// +// +// /** +// * URL of the BKU +// */ +// +// /** +// * the corresponding <code>lt;saml:Assertion></code> +// */ +// +// private boolean isBaseIDTransferRestrication = true; +// +// +// /** +// * STORK attributes from response +// */ +// private String ccc = null; +// +// private Map<String, Object> genericDataStorate = new HashedMap<String, Object>(); +// +// +// +// private String authBlock = null; +// private List<String> encbPKList = null; +// +// //ISA 1.18 attributes +// private List<AuthenticationRole> roles = null; +// private String pvpAttribute_OU = null; +// +// private boolean useMandate = false; +// private IMISMandate mandate = null; +// private String mandateReferenceValue = null; +// +// private boolean foreigner =false; +// private String QAALevel = null; +// +// private boolean ssoSession = false; +// private Date ssoSessionValidTo = null; +// +//// private boolean interfederatedSSOSession = false; +//// private String interfederatedIDP = null; +// +// private String sessionIndex = null; +// private String nameID = null; +// private String nameIDFormat = null; +// +// public AuthenticationData() { +// issueInstant = new Date(); +// } +// +// /** +// * Returns the publicAuthority. +// * @return boolean +// */ +// public boolean isPublicAuthority() { +// return publicAuthority; +// } +// +// /** +// * Returns the publicAuthorityCode. +// * @return String +// */ +// public String getPublicAuthorityCode() { +// return publicAuthorityCode; +// } +// +// /** +// * Returns the qualifiedCertificate. +// * @return boolean +// */ +// public boolean isQualifiedCertificate() { +// return qualifiedCertificate; +// } +// +// /** +// * Returns the bPK. +// * @return String +// */ +// public String getBPK() { +// return bPK; +// } +// +// /** +// * Sets the publicAuthority. +// * @param publicAuthority The publicAuthority to set +// */ +// public void setPublicAuthority(boolean publicAuthority) { +// this.publicAuthority = publicAuthority; +// } +// +// /** +// * Sets the publicAuthorityCode. +// * @param publicAuthorityIdentification The publicAuthorityCode to set +// */ +// public void setPublicAuthorityCode(String publicAuthorityIdentification) { +// this.publicAuthorityCode = publicAuthorityIdentification; +// } +// +// /** +// * Sets the qualifiedCertificate. +// * @param qualifiedCertificate The qualifiedCertificate to set +// */ +// public void setQualifiedCertificate(boolean qualifiedCertificate) { +// this.qualifiedCertificate = qualifiedCertificate; +// } +// +// /** +// * Sets the bPK. +// * @param bPK The bPK to set +// */ +// public void setBPK(String bPK) { +// this.bPK = bPK; +// } +// +// /** +// * Returns the dateOfBirth. +// * @return String +// */ +// public Date getDateOfBirth() { +// return dateOfBirth; +// } +// +// public String getFormatedDateOfBirth() { +// DateFormat pvpDateFormat = new SimpleDateFormat(IDENTITY_LINK_DATE_FORMAT); +// if (getDateOfBirth() != null) +// return pvpDateFormat.format(getDateOfBirth()); +// else +// return "2999-12-31"; +// } +// +// /** +// * Returns the familyName. +// * @return String +// */ +// public String getFamilyName() { +// return familyName; +// } +// +// /** +// * Returns the givenName. +// * @return String +// */ +// public String getGivenName() { +// return givenName; +// } +// +// /** +// * Holds the baseID of a citizen +// * +// * @return baseID +// */ +// public String getIdentificationValue() { +// return identificationValue; +// } +// +// /** +// * Holds the type of the baseID +// * +// * @return baseID-Type +// */ +// public String getIdentificationType() { +// return identificationType; +// } +// +// /** +// * Returns the issueInstant. +// * @return String +// */ +// public String getIssueInstantString() { +// return DateTimeUtils.buildDateTimeUTC(issueInstant); +// +// } +// +// /** +// * Returns the issueInstant. +// * @return String +// */ +// public Date getIssueInstant() { +// return issueInstant; +// +// } +// +// public void setIssueInstant(Date date) { +// this.issueInstant = date; +// } +// +// /** +// * Returns the issuer. +// * @return String +// */ +// public String getIssuer() { +// return issuer; +// } +// +// /** +// * Returns the BKU URL. +// * @return String +// */ +// public String getBkuURL() { +// return bkuURL; +// } +// +// /** +// * Sets the dateOfBirth. +// * @param dateOfBirth The dateOfBirth to set +// */ +// public void setDateOfBirth(Date dateOfBirth) { +// this.dateOfBirth = dateOfBirth; +// } +// +// public void setDateOfBirth(String dateOfBirth) { +// try { +// if (MiscUtil.isNotEmpty(dateOfBirth)) { +// DateFormat identityLinkFormat = new SimpleDateFormat(IDENTITY_LINK_DATE_FORMAT); +// this.dateOfBirth = identityLinkFormat.parse(dateOfBirth); +// } +// +// } catch (ParseException e) { +// Logger.warn("Parse dateOfBirht from IdentityLink FAILED", e); +// +// } +// } +// +// /** +// * Sets the familyName. +// * @param familyName The familyName to set +// */ +// public void setFamilyName(String familyName) { +// this.familyName = familyName; +// } +// +// /** +// * Sets the givenName. +// * @param givenName The givenName to set +// */ +// public void setGivenName(String givenName) { +// this.givenName = givenName; +// } +// +// /** +// * Sets the identificationValue. +// * @param identificationValue The identificationValue to set +// */ +// public void setIdentificationValue(String identificationValue) { +// this.identificationValue = identificationValue; +// } +// +// /** +// * Sets the identificationType. +// * @param identificationType The identificationType to set +// */ +// public void setIdentificationType(String identificationType) { +// this.identificationType = identificationType; +// } +// +// /** +// * Sets the issuer. +// * @param issuer The issuer to set +// */ +// public void setIssuer(String issuer) { +// this.issuer = issuer; +// } +// +// /** +// * Sets the bkuURL +// * @param url The BKU URL to set +// */ +// public void setBkuURL(String url) { +// this.bkuURL = url; +// } +// +// public String getBPKType() { +// return bPKType; +// } +// +// public void setBPKType(String bPKType) { +// this.bPKType = bPKType; +// } +// + +// +// + +// +// +// public String getEIDASQAALevel() { +// if (this.QAALevel != null && +// this.QAALevel.startsWith(PVPConstants.STORK_QAA_PREFIX)) { +// String mappedQAA = PVPtoSTORKMapper.getInstance().mapSTORKQAAToeIDASQAA(this.QAALevel); +// if (MiscUtil.isNotEmpty(mappedQAA)) +// return mappedQAA; +// +// else { +// Logger.error("STORK QAA-level:" + this.QAALevel +// + " can not be mapped to eIDAS QAA-level! Use " +// + PVPConstants.EIDAS_QAA_LOW + " as default value."); +// return PVPConstants.EIDAS_QAA_LOW; +// +// } +// +// +// } else +// return this.QAALevel; +// +// } +// +// +// /** +// * @return +// */ +// public boolean isForeigner() { +// return this.foreigner; +// } +// +// +// /** +// * @param foreigner the foreigner to set +// */ +// public void setForeigner(boolean foreigner) { +// this.foreigner = foreigner; +// } +// +// + +// +// /** +// * @return the ssoSession +// */ +// public boolean isSsoSession() { +// return ssoSession; +// } +// +// +// /** +// * @param ssoSession the ssoSession to set +// */ +// public void setSsoSession(boolean ssoSession) { +// this.ssoSession = ssoSession; +// } +// +// /** +// * @return the mandateReferenceValue +// */ +// public String getMandateReferenceValue() { +// return mandateReferenceValue; +// } +// +// /** +// * @param mandateReferenceValue the mandateReferenceValue to set +// */ +// public void setMandateReferenceValue(String mandateReferenceValue) { +// this.mandateReferenceValue = mandateReferenceValue; +// } +// +// /** +// * CountryCode of the citizen which is identified and authenticated +// * +// * @return the CountryCode <pre>like. AT, SI, ...</pre> +// */ +// public String getCcc() { +// return ccc; +// } +// +// /** +// * @param ccc the ccc to set +// */ +// public void setCcc(String ccc) { +// this.ccc = ccc; +// } +// +// /** +// * @return the sessionIndex +// */ +// public String getSessionIndex() { +// return sessionIndex; +// } +// +// /** +// * @param sessionIndex the sessionIndex to set +// */ +// public void setSessionIndex(String sessionIndex) { +// this.sessionIndex = sessionIndex; +// } +// +// /* (non-Javadoc) +// * @see at.gv.egovernment.moa.id.data.IAuthData#getNameID() +// */ +// @Override +// public String getNameID() { +// return this.nameID; +// } +// +// /** +// * @param nameID the nameID to set +// */ +// public void setNameID(String nameID) { +// this.nameID = nameID; +// } +// +// /** +// * @return the nameIDFormat +// */ +// public String getNameIDFormat() { +// return nameIDFormat; +// } +// +// /** +// * @param nameIDFormat the nameIDFormat to set +// */ +// public void setNameIDFormat(String nameIDFormat) { +// this.nameIDFormat = nameIDFormat; +// } +// +//// /** +//// * @return the interfederatedSSOSession +//// */ +//// public boolean isInterfederatedSSOSession() { +//// return interfederatedSSOSession; +//// } +//// +//// /** +//// * @param interfederatedSSOSession the interfederatedSSOSession to set +//// */ +//// public void setInterfederatedSSOSession(boolean interfederatedSSOSession) { +//// this.interfederatedSSOSession = interfederatedSSOSession; +//// } +//// +//// /** +//// * @return the interfederatedIDP +//// */ +//// public String getInterfederatedIDP() { +//// return interfederatedIDP; +//// } +//// +//// /** +//// * @param interfederatedIDP the interfederatedIDP to set +//// */ +//// public void setInterfederatedIDP(String interfederatedIDP) { +//// this.interfederatedIDP = interfederatedIDP; +//// } +// +// /** +// * @return the ssoSessionValidTo +// */ +// public Date getSsoSessionValidTo() { +// return ssoSessionValidTo; +// } +// +// /** +// * @param ssoSessionValidTo the ssoSessionValidTo to set +// */ +// public void setSsoSessionValidTo(Date ssoSessionValidTo) { +// this.ssoSessionValidTo = ssoSessionValidTo; +// } +// +// /** +// * @return the encbPKList +// */ +// public List<String> getEncbPKList() { +// return encbPKList; +// } +// +// /** +// * @param encbPKList the encbPKList to set +// */ +// public void setEncbPKList(List<String> encbPKList) { +// this.encbPKList = encbPKList; +// } +// +// /** +// * @return the roles +// */ +// public List<AuthenticationRole> getAuthenticationRoles() { +//// if (this.roles == null) { +//// this.roles = new ArrayList<AuthenticationRole>(); +//// this.roles.add(new AuthenticationRole("xxpvprole", "xxpvprole")); +//// this.roles.add(new AuthenticationRole("yypvprole", "yypvprole")); +//// } +// +// return roles; +// } +// +// //ISA 1.18 attributes +// /** +// * @param roles the roles to set +// */ +// public void addAuthenticationRole(AuthenticationRole role) { +// if (this.roles == null) +// this.roles = new ArrayList<AuthenticationRole>(); +// +// this.roles.add(role); +// } +// +// /** +// * @return the pvpAttribute_OU +// */ +// public String getPvpAttribute_OU() { +// return pvpAttribute_OU; +// } +// +// /** +// * @param pvpAttribute_OU the pvpAttribute_OU to set +// */ +// public void setPvpAttribute_OU(String pvpAttribute_OU) { +// this.pvpAttribute_OU = pvpAttribute_OU; +// } +// +// /* (non-Javadoc) +// * @see at.gv.egovernment.moa.id.data.IAuthData#isBusinessService() +// */ +// @Override +// public boolean isBaseIDTransferRestrication() { +// return isBaseIDTransferRestrication; +// } +// +// /** +// * @param isBaseIDTransmittionAllowed the isBaseIDTransmittionAllowed to set +// */ +// public void setBaseIDTransferRestrication(boolean isBaseIDTransferRestrication) { +// this.isBaseIDTransferRestrication = isBaseIDTransferRestrication; +// } +// +// /** +// * Returns a generic data-object with is stored with a specific identifier +// * +// * @param key The specific identifier of the data object +// * @param clazz The class type which is stored with this key +// * @return The data object or null if no data is found with this key +// */ +// public <T> T getGenericData(String key, final Class<T> clazz) { +// if (MiscUtil.isNotEmpty(key)) { +// Object data = genericDataStorate.get(key); +// +// if (data == null) +// return null; +// +// try { +// @SuppressWarnings("unchecked") +// T test = (T) data; +// return test; +// +// } catch (Exception e) { +// Logger.warn("Generic authentication-data object can not be casted to requsted type", e); +// return null; +// +// } +// +// } +// +// Logger.warn("Can not load generic session-data with key='null'"); +// return null; +// +// } +// +// /** +// * Store a generic data-object to session with a specific identifier +// * +// * @param key Identifier for this data-object +// * @param object Generic data-object which should be stored. This data-object had to be implement the 'java.io.Serializable' interface +// * @throws SessionDataStorageException Error message if the data-object can not stored to generic session-data storage +// */ +// public void setGenericData(String key, Object object) throws SessionDataStorageException { +// if (MiscUtil.isEmpty(key)) { +// Logger.warn("Generic session-data can not be stored with a 'null' key"); +// throw new SessionDataStorageException("Generic data can not be stored with a 'null' key", null); +// +// } +// +// if (object != null) { +// if (!Serializable.class.isInstance(object)) { +// Logger.warn("Generic data can only store objects which implements the 'Seralizable' interface"); +// throw new SessionDataStorageException("Generic data can only store objects which implements the 'Seralizable' interface", null); +// +// } +// } +// +// if (genericDataStorate.containsKey(key)) +// Logger.debug("Overwrite generic data with key:" + key); +// else +// Logger.trace("Add generic data with key:" + key + " to session."); +// +// genericDataStorate.put(key, object); +// } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Pair.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Pair.java deleted file mode 100644 index 0b46345d3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Pair.java +++ /dev/null @@ -1,45 +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.data; - -public class Pair<P1, P2> { - private final P1 first; - private final P2 second; - - private Pair(final P1 newFirst, final P2 newSecond) { - this.first = newFirst; - this.second = newSecond; - } - - public P1 getFirst() { - return this.first; - } - - public P2 getSecond() { - return this.second; - } - - public static <P1, P2> Pair<P1, P2> newInstance(final P1 newFirst, final P2 newSecond) { - return new Pair<P1, P2>(newFirst, newSecond); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationContainer.java index 20588ad0b..b1f123bbc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationContainer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationContainer.java @@ -30,7 +30,9 @@ import java.util.List; import java.util.Map.Entry; import java.util.Set; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; +import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; /** * @author tlenz @@ -40,9 +42,9 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon private static final long serialVersionUID = 7148730740582881862L; - private PVPTargetConfiguration sloRequest = null; - private LinkedHashMap<String, SLOInformationImpl> activeFrontChannalOAs; - private LinkedHashMap<String, SLOInformationImpl> activeBackChannelOAs; + private IRequest sloRequest = null; + private LinkedHashMap<String, SLOInformationInterface> activeFrontChannalOAs; + private LinkedHashMap<String, SLOInformationInterface> activeBackChannelOAs; private List<String> sloFailedOAs = null; private String transactionID = null; private String sessionID = null; @@ -51,8 +53,8 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon * */ public SLOInformationContainer() { - this.activeBackChannelOAs = new LinkedHashMap<String, SLOInformationImpl>(); - this.activeFrontChannalOAs = new LinkedHashMap<String, SLOInformationImpl>(); + this.activeBackChannelOAs = new LinkedHashMap<String, SLOInformationInterface>(); + this.activeFrontChannalOAs = new LinkedHashMap<String, SLOInformationInterface>(); this.sloFailedOAs = new ArrayList<String>(); } @@ -61,28 +63,28 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon /** * @return the activeFrontChannalOAs */ - public LinkedHashMap<String, SLOInformationImpl> getActiveFrontChannalOAs() { + public LinkedHashMap<String, SLOInformationInterface> getActiveFrontChannalOAs() { return activeFrontChannalOAs; } /** * @param activeFrontChannalOAs the activeFrontChannalOAs to set */ - public void setActiveFrontChannalOAs(LinkedHashMap<String, SLOInformationImpl> activeFrontChannalOAs) { + public void setActiveFrontChannalOAs(LinkedHashMap<String, SLOInformationInterface> activeFrontChannalOAs) { this.activeFrontChannalOAs = activeFrontChannalOAs; } /** * @return the activeBackChannelOAs */ - public LinkedHashMap<String, SLOInformationImpl> getActiveBackChannelOAs() { + public LinkedHashMap<String, SLOInformationInterface> getActiveBackChannelOAs() { return activeBackChannelOAs; } /** * @param activeBackChannelOAs the activeBackChannelOAs to set */ - public void setActiveBackChannelOAs(LinkedHashMap<String, SLOInformationImpl> activeBackChannelOAs) { + public void setActiveBackChannelOAs(LinkedHashMap<String, SLOInformationInterface> activeBackChannelOAs) { this.activeBackChannelOAs = activeBackChannelOAs; } @@ -98,7 +100,7 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#getFrontChannelOASessionDescriptions() */ @Override - public Set<Entry<String, SLOInformationImpl>> getFrontChannelOASessionDescriptions() { + public Set<Entry<String, SLOInformationInterface>> getFrontChannelOASessionDescriptions() { return activeFrontChannalOAs.entrySet(); } @@ -122,7 +124,7 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#getBackChannelOASessionDescripten(java.lang.String) */ @Override - public SLOInformationImpl getBackChannelOASessionDescripten(String oaID) { + public SLOInformationInterface getBackChannelOASessionDescripten(String oaID) { return activeBackChannelOAs.get(oaID); } @@ -134,19 +136,12 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon activeBackChannelOAs.remove(oaID); } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#getSloRequest() - */ - @Override - public PVPTargetConfiguration getSloRequest() { - return sloRequest; - } - + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#setSloRequest(at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration) */ @Override - public void setSloRequest(PVPTargetConfiguration sloRequest) { + public void setSloRequest(IRequest sloRequest) { this.sloRequest = sloRequest; } @@ -197,7 +192,11 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon public void setSessionID(String sessionID) { this.sessionID = sessionID; } - - + + + @Override + public IRequest getSloRequest() { + return this.sloRequest; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationImpl.java deleted file mode 100644 index 2d84bf472..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationImpl.java +++ /dev/null @@ -1,187 +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.data; - -import java.io.Serializable; - -import org.opensaml.saml2.metadata.SingleLogoutService; - -/** - * @author tlenz - * - */ -public class SLOInformationImpl implements SLOInformationInterface, Serializable { - - private static final long serialVersionUID = 295577931870512387L; - private String sessionIndex = null; - private String nameID = null; - private String protocolType = null; - private String nameIDFormat = null; - private String binding = null; - private String serviceURL = null; - private String authURL = null; - private String spEntityID = null; - - public SLOInformationImpl(String authURL, String spEntityID, String sessionID, String nameID, String nameIDFormat, String protocolType) { - new SLOInformationImpl(authURL, spEntityID, sessionID, nameID, nameIDFormat, protocolType, null); - } - - public SLOInformationImpl(String authURL, String spEntityID, String sessionID, String nameID, String nameIDFormat, String protocolType, SingleLogoutService sloService) { - this.sessionIndex = sessionID; - this.nameID = nameID; - this.nameIDFormat = nameIDFormat; - this.protocolType = protocolType; - this.spEntityID = spEntityID; - - if (authURL.endsWith("/")) - this.authURL = authURL.substring(0, authURL.length()-1); - else - this.authURL = authURL; - - if (sloService != null) { - this.binding = sloService.getBinding(); - this.serviceURL = sloService.getLocation(); - - } - } - - - /** - * - */ - public SLOInformationImpl() { - - } - - - - /** - * @return the spEntityID - */ - public String getSpEntityID() { - return spEntityID; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getSessionIndex() - */ - @Override - public String getSessionIndex() { - return sessionIndex; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getUserNameIdentifier() - */ - @Override - public String getUserNameIdentifier() { - return nameID; - - } - - - /** - * @param sessionIndex the sessionIndex to set - */ - public void setSessionIndex(String sessionIndex) { - this.sessionIndex = sessionIndex; - } - - - /** - * @param nameID the nameID to set - */ - public void setUserNameIdentifier(String nameID) { - this.nameID = nameID; - } - - - - /** - * @param protocolType the protocolType to set - */ - public void setProtocolType(String protocolType) { - this.protocolType = protocolType; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getProtocolType() - */ - @Override - public String getProtocolType() { - return protocolType; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getUserNameIDFormat() - */ - @Override - public String getUserNameIDFormat() { - return this.nameIDFormat; - } - - - /** - * @param nameIDFormat the nameIDFormat to set - */ - public void setNameIDFormat(String nameIDFormat) { - this.nameIDFormat = nameIDFormat; - } - - /** - * @return the binding - */ - public String getBinding() { - return binding; - } - - /** - * @return the serviceURL - */ - public String getServiceURL() { - return serviceURL; - } - - /** - * @return the authURL from requested IDP without ending / - */ - public String getAuthURL() { - return authURL; - } - - /** - * @param spEntityID the spEntityID to set - */ - public void setSpEntityID(String spEntityID) { - this.spEntityID = spEntityID; - } - - - - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationInterface.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationInterface.java deleted file mode 100644 index 31fdaacfd..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationInterface.java +++ /dev/null @@ -1,70 +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.data; - -/** - * @author tlenz - * - */ -public interface SLOInformationInterface{ - - - /** - * get AssertionID which was used for Service Provider Single LogOut request - * - * @return - * SessionID (SessionIndex in case of SAML2) - */ - public String getSessionIndex(); - - /** - * get user identifier which was used - * - * @return - * bPK / wbPK (nameID in case of SAML2) - */ - public String getUserNameIdentifier(); - - - /** - * get protocol type which was used for authentication - * - * @return - * return authentication protocol type - */ - public String getProtocolType(); - - /** - * @return - */ - public String getUserNameIDFormat(); - - /** - * Get the unique entityID of this Service-Provider - * - * @return unique identifier, but never null - */ - public String getSpEntityID(); - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java deleted file mode 100644 index 78e8be452..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java +++ /dev/null @@ -1,51 +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.data; - -public class Trible<P1, P2, P3> { - private final P1 first; - private final P2 second; - private final P3 third; - - private Trible(final P1 newFirst, final P2 newSecond, final P3 newThird) { - this.first = newFirst; - this.second = newSecond; - this.third = newThird; - } - - public P1 getFirst() { - return this.first; - } - - public P2 getSecond() { - return this.second; - } - - public P3 getThird() { - return this.third; - } - - public static <P1, P2, P3> Trible<P1, P2, P3> newInstance(final P1 newFirst, final P2 newSecond, final P3 newThird) { - return new Trible<P1, P2, P3>(newFirst, newSecond, newThird); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 7f183c5eb..77abe07af 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 @@ -22,491 +22,82 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; -import java.io.IOException; -import java.security.cert.X509Certificate; -import java.util.ArrayList; -import java.util.Collection; import java.util.Enumeration; -import java.util.Iterator; import java.util.List; -import java.util.Map.Entry; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; import org.opensaml.saml2.core.LogoutRequest; -import org.opensaml.saml2.core.LogoutResponse; -import org.opensaml.saml2.core.StatusCode; -import org.opensaml.saml2.metadata.SingleLogoutService; -import org.opensaml.ws.soap.common.SOAPException; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.process.ExecutionContext; +import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.idp.auth.AbstractAuthenticationManager; +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions; -import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.auth.frontend.builder.DefaultGUIFormBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; -import at.gv.egovernment.moa.id.auth.frontend.exception.GUIBuildException; -import at.gv.egovernment.moa.id.auth.modules.SingleSignOnConsentsModuleImpl; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.data.SLOInformationContainer; -import at.gv.egovernment.moa.id.data.SLOInformationImpl; -import at.gv.egovernment.moa.id.process.ExecutionContextImpl; -import at.gv.egovernment.moa.id.process.ProcessEngine; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.id.util.legacy.LegacyHelper; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Service("MOAID_AuthenticationManager") -public class AuthenticationManager extends MOAIDAuthConstants { +public class AuthenticationManager extends AbstractAuthenticationManager { - private static List<String> reqParameterWhiteListeForModules = new ArrayList<String>(); + public static final String eIDAS_GENERIC_REQ_DATA_LEVELOFASSURENCE = "eIDAS_LoA"; + public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; public static final String MOA_SESSION = "MoaAuthenticationSession"; public static final String MOA_AUTHENTICATED = "MoaAuthenticated"; - public static final int SLOTIMEOUT = 30 * 1000; //30 sec + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; + @Autowired private SingleLogOutBuilder sloBuilder;; - @Autowired private ProcessEngine processEngine; - @Autowired private SSOManager ssoManager; - @Autowired private IRequestStorage requestStoreage; - @Autowired private ITransactionStorage transactionStorage; - @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; - @Autowired private MOAReversionLogger revisionsLogger; - @Autowired protected AuthConfiguration authConfig; - @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, IAuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { - performSingleLogOut(httpReq, httpResp, session, pvpReq, null); - - } - - public void performSingleLogOut(HttpServletRequest httpReq, - HttpServletResponse httpResp, IAuthenticationSession session, String authURL) throws MOAIDException { - performSingleLogOut(httpReq, httpResp, session, null, authURL); - - } - - /** - * @param req - * @param resp - * @param moasessionid - */ - public void performOnlyIDPLogOut(AuthenticationSession authSession) { - - if (authSession == null) { - Logger.info("No internal MOA SSO-Session found. Nothing to destroy"); - return; - - } - - try { - - authSession.setAuthenticated(false); - //HTTPSessionUtils.setHTTPSessionString(session, MOA_SESSION, null); // remove moa session from HTTP Session - - //log Session_Destroy to reversionslog - AuthenticationSessionExtensions sessionExtensions = authenticatedSessionStore.getAuthenticationSessionExtensions(authSession.getSessionID()); - revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, sessionExtensions.getUniqueSessionId()); - - authenticatedSessionStore.destroyInternalSSOSession(authSession.getSessionID()); - - //session.invalidate(); - - } catch (MOADatabaseException e) { - Logger.info("NO MOA Authentication data for ID " + authSession.getSessionID()); - return; - } - - } - - - public void performOnlyIDPLogOut(HttpServletRequest request, - HttpServletResponse response, String internalMOASsoSessionID) { - Logger.info("Remove active user-session"); - - if(internalMOASsoSessionID == null) { - internalMOASsoSessionID = StringEscapeUtils.escapeHtml((String) request.getParameter(PARAM_SESSIONID)); - } - - if(internalMOASsoSessionID == null) { - Logger.info("NO MOA Session to logout"); - return; - } - - AuthenticationSession authSession; - try { - authSession = authenticatedSessionStore.getInternalSSOSession(internalMOASsoSessionID); - - if(authSession == null) { - Logger.info("NO MOA Authentication data for ID " + internalMOASsoSessionID); - return; - } - - performOnlyIDPLogOut(authSession); - - } catch (MOADatabaseException e) { - Logger.info("NO MOA Authentication data for ID " + internalMOASsoSessionID); - return; - } - - } - - - /** - * Authenticates the authentication request {pendingReq}, which is actually processed - * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * - * @return Return already authenticated MOASession if exists, otherwise return null - * @throws MOADatabaseException - * @throws MOAIDException - * @throws IOException - * @throws ServletException - * - */ - public AuthenticationSession doAuthentication(HttpServletRequest httpReq, - HttpServletResponse httpResp, RequestImpl pendingReq) throws MOADatabaseException, ServletException, IOException, MOAIDException { - - //load OA configuration from pending request - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - - //set logging context and log unique OA identifier to revision log - TransactionIDUtils.setServiceProviderId(pendingReq.getOnlineApplicationConfiguration().getPublicURLPrefix()); - revisionsLogger.logEvent(oaParam, - pendingReq, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, pendingReq.getOAURL()); - - //generic authentication request validation - if (pendingReq.isPassiv() - && pendingReq.forceAuth()) { - // conflict! - throw new NoPassivAuthenticationException(); - } - - //get SSO cookie from http request - String ssoId = ssoManager.getSSOSessionID(httpReq); - - //check if interfederation IDP is requested - ssoManager.checkInterfederationIsRequested(httpReq, httpResp, pendingReq); - - //check if SSO session cookie is already used - if (ssoId != null) { - String correspondingMOASession = ssoManager.existsOldSSOSession(ssoId); - - if (correspondingMOASession != null) { - Logger.warn("Request sends an old SSO Session ID("+ssoId+")! " + - "Invalidate the corresponding MOASession with ID="+ correspondingMOASession); - - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_INVALID); - - //destroy internal SSO-session object and SSO-session cooky - authenticatedSessionStore.destroyInternalSSOSession(correspondingMOASession); - ssoManager.deleteSSOSessionID(httpReq, httpResp); - } - } - - //check if SSO Session is valid - boolean isValidSSOSession = ssoManager.isValidSSOSession(ssoId, pendingReq); - - // check if Service-Provider allows SSO sessions - boolean useSSOOA = oaParam.useSSO() || oaParam.isInderfederationIDP(); - - //if a legacy request is used SSO should not be allowed in case of mandate authentication - boolean isUseMandateRequested = LegacyHelper.isUseMandateRequested(httpReq); - - //check if SSO is allowed for the actually executed request - //INFO: Actually, useMandate disables SSO functionality!!!!! - boolean isSSOAllowed = (useSSOOA && !isUseMandateRequested); - pendingReq.setNeedSingleSignOnFunctionality(isSSOAllowed); - - //get MOASession from SSO-Cookie if SSO is allowed - AuthenticationSession ssoMOASession = null; - if (isValidSSOSession && isSSOAllowed) { - ssoMOASession = ssoManager.getInternalMOASession(ssoId); - - if (ssoMOASession == null) - Logger.info("No MOASession FOUND with provided SSO-Cookie."); - - else { - Logger.debug("Found authenticated MOASession with provided SSO-Cookie."); - revisionsLogger.logEvent(oaParam, pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO); - - } - } - - //check if session is already authenticated - boolean isSessionAuthenticated = tryPerformAuthentication((RequestImpl) pendingReq, ssoMOASession); - - //force new authentication authentication process - if (pendingReq.forceAuth()) { - startAuthenticationProcess(httpReq, httpResp, pendingReq); - return null; - - //perform SSO-Consents evaluation if it it required - } else if (isSessionAuthenticated && oaParam.useSSOQuestion()) { - sendSingleSignOnConsentsEvaluation(httpReq, httpResp, pendingReq); - return null; - - } else if (pendingReq.isPassiv()) { - if (isSessionAuthenticated) { - // Passive authentication ok! - revisionsLogger.logEvent(oaParam, pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); - return ssoMOASession; - - } else { - throw new NoPassivAuthenticationException(); - - } - } else { - if (isSessionAuthenticated) { - // Is authenticated .. proceed - revisionsLogger.logEvent(oaParam, - pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); - return ssoMOASession; - - } else { - // Start authentication! - startAuthenticationProcess(httpReq, httpResp, pendingReq); - return null; - } - } - } - - /** - * Add a request parameter to whitelist. All parameters that are part of the white list are added into {@link ExecutionContext} - * - * @param httpReqParam http parameter name, but never null - */ - public void addParameterNameToWhiteList(String httpReqParam) { - if (MiscUtil.isNotEmpty(httpReqParam)) - reqParameterWhiteListeForModules.add(httpReqParam); - - } - - - /** - * Checks if a authenticated MOASession already exists and if {protocolRequest} is authenticated - * - * @param protocolRequest Authentication request which is actually in process - * @param moaSession MOASession with authentication information or null if no active MOASession exists - * - * @return true if session is already authenticated, otherwise false - * @throws MOAIDException - */ - private boolean tryPerformAuthentication(RequestImpl protocolRequest, AuthenticationSession ssoMOASession) { - - //if no MOASession exist -> authentication is required - if (ssoMOASession == null) { - return false; - - } else { - //if MOA SSO-Session is found but not authenticated --> authentication is required - if (!ssoMOASession.isAuthenticated()) { - return false; - } - - //if MOASession is already authenticated and protocol-request is authenticated - // --> no authentication is required any more - else if (ssoMOASession.isAuthenticated() && protocolRequest.isAuthenticated()) { - protocolRequest.setInternalSSOSessionIdentifier(ssoMOASession.getSessionID()); - return true; - - // if MOASession is authenticated and SSO is allowed --> authenticate pendingRequest - } else if (!protocolRequest.isAuthenticated() - && ssoMOASession.isAuthenticated() && protocolRequest.needSingleSignOnFunctionality()) { - Logger.debug("Found active MOASession and SSO is allowed --> pendingRequest is authenticted"); - protocolRequest.setAuthenticated(true); - protocolRequest.setInternalSSOSessionIdentifier(ssoMOASession.getSessionID()); - return true; - - } - - // force authentication as backup solution - else { - Logger.warn("Authentication-required check find an unsuspected state --> force authentication"); - return false; - - } - } - } - - private void startAuthenticationProcess(HttpServletRequest httpReq, - HttpServletResponse httpResp, RequestImpl pendingReq) - throws ServletException, IOException, MOAIDException { - - Logger.info("Starting authentication ..."); - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_START); - - //is legacy allowed - List<String> legacyallowed_prot = authConfig.getLegacyAllowedProtocols(); - boolean legacyallowed = legacyallowed_prot.contains(pendingReq.requestedModule()); - - //check legacy request parameter - boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(httpReq); - - //create authentication process execution context - ExecutionContext executionContext = new ExecutionContextImpl(); - - //set oaIdentifeir - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_UNIQUE_OA_IDENTFIER, - pendingReq.getOnlineApplicationConfiguration().getPublicURLPrefix()); - - //set interfederation authentication flag - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH, - MiscUtil.isNotEmpty( - pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); - - //set legacy mode or BKU-selection flags - boolean leagacyMode = (legacyallowed && legacyparamavail); - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_ISLEGACYREQUEST, leagacyMode); - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION, !leagacyMode - && MiscUtil.isEmpty(pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); - - //add X509 SSL client certificate if exist - if (httpReq.getAttribute("javax.servlet.request.X509Certificate") != null) { - Logger.debug("Find SSL-client-certificate on request --> Add it to context"); - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_SSL_CLIENT_CERTIFICATE, - ((X509Certificate[])httpReq.getAttribute("javax.servlet.request.X509Certificate"))); - - } - - //add additional http request parameter to context - if (!reqParameterWhiteListeForModules.isEmpty() || leagacyMode) { - Enumeration<String> reqParamNames = httpReq.getParameterNames(); - while(reqParamNames.hasMoreElements()) { - String paramName = reqParamNames.nextElement(); - if (MiscUtil.isNotEmpty(paramName) && - ( MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName) - || reqParameterWhiteListeForModules.contains(paramName) )) - executionContext.put(paramName, - StringEscapeUtils.escapeHtml(httpReq.getParameter(paramName))); - } - } - - //start process engine - startProcessEngine(pendingReq, executionContext); - - } - - private void sendSingleSignOnConsentsEvaluation(HttpServletRequest request, - HttpServletResponse response, RequestImpl pendingReq) - throws ServletException, IOException, MOAIDException { - - Logger.info("Start SSO user-consents evaluation ..."); - - //set authenticated flag to false, because user consents is required - pendingReq.setAuthenticated(false); - - //create execution context - ExecutionContext executionContext = new ExecutionContextImpl(); - executionContext.put(SingleSignOnConsentsModuleImpl.PARAM_SSO_CONSENTS_EVALUATION, true); - - //start process engine - startProcessEngine(pendingReq, executionContext); - - } - - private void startProcessEngine(RequestImpl pendingReq, ExecutionContext executionContext) throws MOAIDException { - try { - //put pending-request ID on execurtionContext - executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, pendingReq.getRequestID()); - - // create process instance - String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext); - - if (processDefinitionId == null) { - Logger.warn("No suitable process found for SessionID " + pendingReq.getRequestID() ); - throw new MOAIDException("process.02",new Object[] { - pendingReq.getRequestID()}); - } - - String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); - - // keep process instance id in protocol pending-request - pendingReq.setProcessInstanceId(processInstanceId); - - //store pending-request - requestStoreage.storePendingRequest(pendingReq); - - // start process - processEngine.start(pendingReq); - - } catch (ProcessExecutionException e) { - Throwable cause = e.getCause(); - if (cause != null && cause instanceof TaskExecutionException) { - Throwable taskCause = cause.getCause(); - if (taskCause != null && taskCause instanceof MOAIDException) { - MOAIDException moaTaskCause = (MOAIDException) taskCause; - Logger.warn(taskCause); - throw moaTaskCause; - - } - } - - throw new MOAIDException("process.01", new Object[] { pendingReq.getProcessInstanceId(), pendingReq.getRequestID() }, e); - } - } - - private void performSingleLogOut(HttpServletRequest httpReq, - HttpServletResponse httpResp, IAuthenticationSession session, PVPTargetConfiguration pvpReq, String authURL) throws MOAIDException { + @Override + public ISLOInformationContainer performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq, String internalSSOId) + throws EAAFException { String pvpSLOIssuer = null; - String inboundRelayState = null; String uniqueSessionIdentifier = "notSet"; String uniqueTransactionIdentifier = "notSet"; - + PVPSProfilePendingRequest pvpReq = null; Logger.debug("Start technical Single LogOut process ... "); - if (pvpReq != null) { - MOARequest samlReq = (MOARequest) pvpReq.getRequest(); - LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); - pvpSLOIssuer = logOutReq.getIssuer().getValue(); - inboundRelayState = samlReq.getRelayState(); - uniqueSessionIdentifier = pvpReq.getUniqueSessionIdentifier(); - uniqueTransactionIdentifier = pvpReq.getUniqueTransactionIdentifier(); + + if (pendingReq != null) { + uniqueSessionIdentifier = pendingReq.getUniqueSessionIdentifier(); + uniqueTransactionIdentifier = pendingReq.getUniqueTransactionIdentifier(); + + if (pendingReq instanceof PVPSProfileRequest) { + pvpReq = ((PVPSProfilePendingRequest)pendingReq); + PVPSProfileRequest samlReq = (PVPSProfileRequest) pvpReq.getRequest(); + LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); + pvpSLOIssuer = logOutReq.getIssuer().getValue(); + } + if (MiscUtil.isEmpty(internalSSOId)) + internalSSOId = pendingReq.getInternalSSOSessionIdentifier(); + } else { AuthenticationSessionExtensions sessionExt; try { - sessionExt = authenticatedSessionStore.getAuthenticationSessionExtensions(session.getSessionID()); + sessionExt = authenticatedSessionStore.getAuthenticationSessionExtensions(internalSSOId); if (sessionExt != null) uniqueSessionIdentifier = sessionExt.getUniqueSessionId(); @@ -520,8 +111,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { } //store active OAs to SLOContaine - List<OASessionStore> dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(session); - List<InterfederationSessionStore> dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(session); + List<OASessionStore> dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(internalSSOId); + List<InterfederationSessionStore> dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(internalSSOId); SLOInformationContainer sloContainer = new SLOInformationContainer(); sloContainer.setTransactionID(uniqueTransactionIdentifier); sloContainer.setSessionID(uniqueSessionIdentifier); @@ -534,13 +125,13 @@ public class AuthenticationManager extends MOAIDAuthConstants { + " BackChannel:" + sloContainer.getActiveBackChannelOAs().size() + " FrontChannel:" + sloContainer.getActiveFrontChannalOAs().size() + " NO_SLO_Support:" + sloContainer.getSloFailedOAs().size()); - + + //terminate MOASession try { - authenticatedSessionStore.destroyInternalSSOSession(session.getSessionID()); - ssoManager.deleteSSOSessionID(httpReq, httpResp); + authenticatedSessionStore.destroyInternalSSOSession(internalSSOId); + ssoManager.destroySSOSessionOnIDPOnly(httpReq, httpResp, pendingReq); revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, uniqueSessionIdentifier); - Logger.debug("Active SSO Session on IDP is remove."); } catch (MOADatabaseException e) { @@ -549,165 +140,48 @@ public class AuthenticationManager extends MOAIDAuthConstants { } - Logger.trace("Starting Service-Provider logout process ... "); - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_STARTED); - //start service provider back channel logout process - Iterator<String> nextOAInterator = sloContainer.getNextBackChannelOA(); - while (nextOAInterator.hasNext()) { - SLOInformationImpl sloDescr = sloContainer.getBackChannelOASessionDescripten(nextOAInterator.next()); - LogoutRequest sloReq = sloBuilder.buildSLORequestMessage(sloDescr); - - try { - Logger.trace("Send backchannel SLO Request to " + sloDescr.getSpEntityID()); - List<XMLObject> soapResp = MOASAMLSOAPClient.send(sloDescr.getServiceURL(), sloReq); - - LogoutResponse sloResp = null; - for (XMLObject el : soapResp) { - if (el instanceof LogoutResponse) - sloResp = (LogoutResponse) el; - } - - if (sloResp == null) { - Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() - + " FAILED. NO LogOut response received."); - sloContainer.putFailedOA(sloDescr.getSpEntityID()); - - } else { - samlVerificationEngine.verifySLOResponse(sloResp, - TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); - - } - - sloBuilder.checkStatusCode(sloContainer, sloResp); - - } catch (SOAPException e) { - Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() - + " FAILED.", e); - sloContainer.putFailedOA(sloDescr.getSpEntityID()); - - } catch (SecurityException | InvalidProtocolRequestException e) { - Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() - + " FAILED.", e); - sloContainer.putFailedOA(sloDescr.getSpEntityID()); - - } - } - - //start service provider front channel logout process - try { - if (sloContainer.hasFrontChannelOA()) { - String relayState = Random.nextRandom(); - - Collection<Entry<String, SLOInformationImpl>> sloDescr = sloContainer.getFrontChannelOASessionDescriptions(); - List<String> sloReqList = new ArrayList<String>(); - for (Entry<String, SLOInformationImpl> el : sloDescr) { - Logger.trace("Build frontChannel SLO Request for " + el.getValue().getSpEntityID()); - - LogoutRequest sloReq = sloBuilder.buildSLORequestMessage(el.getValue()); - try { - sloReqList.add(sloBuilder.getFrontChannelSLOMessageURL(el.getValue().getServiceURL(), el.getValue().getBinding(), - sloReq, httpReq, httpResp, relayState)); - - } catch (Exception e) { - Logger.warn("Failed to build SLO request for OA:" + el.getKey()); - sloContainer.putFailedOA(el.getKey()); - - } - } - - //put SLO process-information into transaction storage - transactionStorage.put(relayState, sloContainer, -1); - - if (MiscUtil.isEmpty(authURL)) - authURL = pvpReq.getAuthURL(); - - String timeOutURL = authURL - + "/idpSingleLogout" - + "?restart=" + relayState; - - DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( - authURL, - DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, - null); - - config.putCustomParameterWithOutEscaption("redirectURLs", sloReqList); - config.putCustomParameterWithOutEscaption("timeoutURL", timeOutURL); - config.putCustomParameter("timeout", String.valueOf(SLOTIMEOUT)); - - guiBuilder.build(httpResp, config, "Single-LogOut GUI"); - - - } else { - if (pvpReq != null) { - //send SLO response to SLO request issuer - SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, sloContainer.getSloFailedOAs()); - sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState, pvpReq); - - } else { - //print SLO information directly - DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( - authURL, - DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, - null); - - if (sloContainer.getSloFailedOAs() == null || - sloContainer.getSloFailedOAs().size() == 0) { - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); - config.putCustomParameter("successMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.00", null)); - - } else { - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); - config.putCustomParameterWithOutEscaption("errorMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - - } - guiBuilder.build(httpResp, config, "Single-LogOut GUI"); - - } - - } + return sloContainer; - } catch (GUIBuildException e) { - Logger.warn("Can not build GUI:'Single-LogOut'. Msg:" + e.getMessage()); - throw new MOAIDException("builder.09", new Object[]{e.getMessage()}, e); + } + + @Override + protected void populateExecutionContext(ExecutionContext executionContext, RequestImpl pendingReq, HttpServletRequest httpReq) + throws EAAFException { + //is legacy allowed + boolean legacyallowed = false; + if (authConfig instanceof AuthConfiguration) { + List<String> legacyallowed_prot = ((AuthConfiguration)authConfig).getLegacyAllowedProtocols(); + legacyallowed = legacyallowed_prot.contains(pendingReq.requestedModule()); - } catch (MOADatabaseException e) { - Logger.error("MOA AssertionDatabase ERROR", e); - if (pvpReq != null) { - SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState, pvpReq); + } else + Logger.info("Base configuration is NOT of type 'AuthConfiguration'. LegacyMode is disabled"); + - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); + //check legacy request parameter + boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(httpReq); - }else { - //print SLO information directly - DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( - authURL, - DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, - null); + + //set interfederation authentication flag + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH, + MiscUtil.isNotEmpty( + pendingReq.getRawData(SSOManager.DATAID_INTERFEDERATIOIDP_URL, String.class))); + + //set legacy mode or BKU-selection flags + boolean leagacyMode = (legacyallowed && legacyparamavail); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_ISLEGACYREQUEST, leagacyMode); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION, !leagacyMode + && MiscUtil.isEmpty(pendingReq.getRawData(SSOManager.DATAID_INTERFEDERATIOIDP_URL, String.class))); - revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); - config.putCustomParameterWithOutEscaption("errorMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - - try { - guiBuilder.build(httpResp, config, "Single-LogOut GUI"); - - } catch (GUIBuildException e1) { - Logger.warn("Can not build GUI:'Single-LogOut'. Msg:" + e.getMessage()); - throw new MOAIDException("builder.09", new Object[]{e.getMessage()}, e); - - } - - } - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } + //add additional http request parameter to context + if (leagacyMode) { + Enumeration<String> reqParamNames = httpReq.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (StringUtils.isNotEmpty(paramName) && MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName) ) + executionContext.put(paramName, StringEscapeUtils.escapeHtml(httpReq.getParameter(paramName))); + } + } + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java deleted file mode 100644 index ae2771427..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IAction.java +++ /dev/null @@ -1,39 +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.moduls; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -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.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; - -public interface IAction { - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) - throws MOAIDException; - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp); - - public String getDefaultActionName(); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java deleted file mode 100644 index b9b161bb6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IModulInfo.java +++ /dev/null @@ -1,42 +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.moduls; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.commons.api.IRequest; - - -public interface IModulInfo { - //public List<ServletInfo> getServlets(); - public String getName(); - public String getPath(); - - public boolean generateErrorMessage(Throwable e, - HttpServletRequest request, HttpServletResponse response, - IRequest protocolRequest) throws Throwable; - - public boolean validate(HttpServletRequest request, - HttpServletResponse response, IRequest pending); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java deleted file mode 100644 index 987d92e16..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java +++ /dev/null @@ -1,43 +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.moduls; - -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.ex.MOADatabaseException; - -/** - * @author tlenz - * - */ -public interface IRequestStorage { - - public IRequest getPendingRequest(String pendingReqID); - - public void storePendingRequest(IRequest pendingRequest) throws MOAIDException; - - public void removePendingRequest(String requestID); - - public String changePendingRequestID(IRequest pendingRequest) throws MOAIDException, MOADatabaseException; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java deleted file mode 100644 index f1db466e9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/NoPassivAuthenticationException.java +++ /dev/null @@ -1,38 +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.moduls; - -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; - -public class NoPassivAuthenticationException extends MOAIDException { - - public NoPassivAuthenticationException() { - super("auth.18", null); - } - - /** - * - */ - private static final long serialVersionUID = 596920452166197688L; - -} 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 deleted file mode 100644 index b87574d52..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ /dev/null @@ -1,454 +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.moduls; - -import java.io.Serializable; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -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.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionWrapper; -import at.gv.egovernment.moa.id.commons.MOAIDConstants; -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -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.data.AuthProzessDataConstants; -import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession; -import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; -import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public abstract class RequestImpl implements IRequest, Serializable{ - - public static final String DATAID_INTERFEDERATIOIDP_URL = "interIDPURL"; - public static final String DATAID_INTERFEDERATIOIDP_RESPONSE = "interIDPResponse"; - public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; - public static final String DATAID_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; - - private String module = null; - private String action = null; - - private String requestID; - private String processInstanceId; - private String ssoMoaSessionId; - - private String uniqueTransactionIdentifer; - private String uniqueSessionIdentifer; - - private String oaURL; - private String authURL = null; - - private IOAAuthParameters OAConfiguration = null; - - private boolean passiv = false; - private boolean force = false; - private boolean needSSO = false; - private boolean isAbortedByUser = false; - - //every request needs authentication by default - private boolean needAuthentication = true; - - //every request is not authenticated by default - private boolean isAuthenticated = false; - - private Map<String, Object> genericDataStorage = new HashMap<String, Object>(); - - private IAuthenticationSession moaSSOSessionContainer = null; - - - /** - * @throws ConfigurationException - * - */ - public final void initialize(HttpServletRequest req) throws ConfigurationException { - //set requestID - requestID = Random.nextLongRandom(); - - //set unique transaction identifier for logging - uniqueTransactionIdentifer = Random.nextLongRandom(); - TransactionIDUtils.setTransactionId(uniqueTransactionIdentifer); - - //initialize session object - genericDataStorage.put(AuthProzessDataConstants.VALUE_CREATED, new Date()); - genericDataStorage.put(AuthProzessDataConstants.VALUE_SESSIONID, Random.nextLongRandom()); - - //check if End-Point is valid - String authURLString = HTTPUtils.extractAuthURLFromRequest(req); - URL authURL; - try { - authURL = new URL(authURLString); - - } catch (MalformedURLException e) { - Logger.error("IDP AuthenticationServiceURL Prefix is not a valid URL." + authURLString, e); - throw new ConfigurationException("1299", null, e); - - } - - AuthConfiguration config = AuthConfigurationProviderFactory.getInstance(); - List<String> configuredPublicURLPrefix = config.getPublicURLPrefix(); - - if (!config.isVirtualIDPsEnabled()) { - Logger.trace("Virtual IDPs are disabled. Use default IDP PublicURLPrefix from configuration: " + configuredPublicURLPrefix.get(0)); - this.authURL = configuredPublicURLPrefix.get(0); - - } else { - Logger.debug("Extract AuthenticationServiceURL: " + authURLString); - URL resultURL = null; - - for (String el : configuredPublicURLPrefix) { - try { - URL configuredURL = new URL(el); - - //get Ports from URL - int configPort = configuredURL.getPort(); - if (configPort == -1) - configPort = configuredURL.getDefaultPort(); - - int authURLPort = authURL.getPort(); - if (authURLPort == -1) - authURLPort = authURL.getDefaultPort(); - - //check AuthURL against ConfigurationURL - if (configuredURL.getHost().equals(authURL.getHost()) && - configPort == authURLPort && - configuredURL.getPath().equals(authURL.getPath())) { - Logger.debug("Select configurated PublicURLPrefix: " + configuredURL - + " for authURL: " + authURLString); - resultURL = configuredURL; - } - - } catch (MalformedURLException e) { - Logger.error("Configurated IDP PublicURLPrefix is not a valid URL." + el); - - } - } - - if (resultURL == null) { - Logger.warn("Extract AuthenticationServiceURL: " + authURL + " is NOT found in configuration."); - throw new ConfigurationException("config.25", new Object[]{authURLString}); - - } else { - this.authURL = resultURL.toExternalForm(); - - } - } - - //set unique session identifier - String uniqueID = (String) req.getAttribute(MOAIDConstants.UNIQUESESSIONIDENTIFIER); - if (MiscUtil.isNotEmpty(uniqueID)) - uniqueSessionIdentifer = uniqueID; - - 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); - - } - - } - - /** - * This method map the protocol specific requested attributes to PVP 2.1 attributes. - * - * @return List of PVP 2.1 attribute names with maps all protocol specific attributes - */ - public abstract Collection<String> getRequestedAttributes(MetadataProvider metadataProvider); - - public void setOAURL(String value) { - oaURL = value; - } - - public String getOAURL() { - return oaURL; - } - - public boolean isPassiv() { - return passiv; - } - - public boolean forceAuth() { - return force; - } - - public void setPassiv(boolean passiv) { - this.passiv = passiv; - } - - public void setForce(boolean force) { - this.force = force; - } - - public String requestedAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - - /** - * @return the module - */ - public String requestedModule() { - return module; - } - - /** - * @param module the module to set - */ - public void setModule(String module) { - this.module = module; - } - - public void setRequestID(String id) { - this.requestID = id; - - } - - public String getRequestID() { - return requestID; - } - - public String getInternalSSOSessionIdentifier() { - return this.ssoMoaSessionId; - } - - /** - * Set the internal SSO session identifier, which associated with this pending request - * - * @param internalSSOSessionId - */ - public void setInternalSSOSessionIdentifier(String internalSSOSessionId) { - this.ssoMoaSessionId = internalSSOSessionId; - - } - - public IAuthenticationSession getMOASession() { - //if SSO session information are set, use this - if (moaSSOSessionContainer != null) - return moaSSOSessionContainer; - - else - return new AuthenticationSessionWrapper(genericDataStorage); - - } - - public void populateMOASessionWithSSOInformation(IAuthenticationSession ssoSession) { - if (ssoSession instanceof AuthenticationSession) { - moaSSOSessionContainer = ssoSession; - - } else - throw new IllegalStateException("Session information can only be populated with SSO information from database"); - - - } - - - public IOAAuthParameters getOnlineApplicationConfiguration() { - return this.OAConfiguration; - - } - - public void setOnlineApplicationConfiguration(IOAAuthParameters oaConfig) { - this.OAConfiguration = oaConfig; - - } - - public String getUniqueTransactionIdentifier() { - return this.uniqueTransactionIdentifer; - - } - - public String getUniqueSessionIdentifier() { - return this.uniqueSessionIdentifer; - - } - - public String getProcessInstanceId() { - return this.processInstanceId; - - } - - public void setUniqueTransactionIdentifier(String id) { - this.uniqueTransactionIdentifer = id; - - } - - public void setUniqueSessionIdentifier(String id) { - this.uniqueSessionIdentifer = id; - - } - - public void setProcessInstanceId(String id) { - this.processInstanceId = id; - - } - - /** - * @return the authURL - */ - public String getAuthURL() { - return authURL; - } - - public String getAuthURLWithOutSlash() { - if (authURL.endsWith("/")) - return authURL.substring(0, authURL.length()-1); - else - return authURL; - - } - - /** - * @return the needAuthentication - */ - public boolean isNeedAuthentication() { - return needAuthentication; - } - - /** - * @param needAuthentication the needAuthentication to set - */ - public void setNeedAuthentication(boolean needAuthentication) { - this.needAuthentication = needAuthentication; - } - - /** - * @return the isAuthenticated - */ - public boolean isAuthenticated() { - return isAuthenticated; - } - - /** - * @param isAuthenticated the isAuthenticated to set - */ - public void setAuthenticated(boolean isAuthenticated) { - this.isAuthenticated = isAuthenticated; - } - - public boolean needSingleSignOnFunctionality() { - return needSSO; - } - public void setNeedSingleSignOnFunctionality(boolean needSSO) { - this.needSSO = needSSO; - - } - - public boolean isAbortedByUser() { - return this.isAbortedByUser; - } - - public void setAbortedByUser(boolean isAborted) { - this.isAbortedByUser = isAborted; - - } - - public Object getGenericData(String key) { - if (MiscUtil.isNotEmpty(key)) { - return genericDataStorage.get(key); - - } - - Logger.warn("Can not load generic request-data with key='null'"); - return null; - } - - public <T> T getGenericData(String key, final Class<T> clazz) { - if (MiscUtil.isNotEmpty(key)) { - Object data = genericDataStorage.get(key); - - if (data == null) - return null; - - try { - @SuppressWarnings("unchecked") - T test = (T) data; - return test; - - } catch (Exception e) { - Logger.warn("Generic request-data object can not be casted to requested type", e); - return null; - - } - - } - - Logger.warn("Can not load generic request-data with key='null'"); - return null; - - } - - public void setGenericDataToSession(String key, Object object) throws SessionDataStorageException { - if (MiscUtil.isEmpty(key)) { - Logger.warn("Generic request-data can not be stored with a 'null' key"); - throw new SessionDataStorageException("Generic request-data can not be stored with a 'null' key", null); - - } - - if (object != null) { - if (!Serializable.class.isInstance(object)) { - Logger.warn("Generic request-data can only store objects which implements the 'Seralizable' interface"); - throw new SessionDataStorageException("Generic request-data can only store objects which implements the 'Seralizable' interface", null); - - } - } - - if (genericDataStorage.containsKey(key)) - Logger.debug("Overwrite generic request-data with key:" + key); - else - Logger.trace("Add generic request-data with key:" + key + " to session."); - - genericDataStorage.put(key, object); - - } - -} 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 deleted file mode 100644 index 90ccb3c27..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java +++ /dev/null @@ -1,135 +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.moduls; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -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.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAO; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.logging.Logger; - -@Service("RequestStorage") -public class RequestStorage implements IRequestStorage{ - - @Autowired ITransactionStorage transactionStorage; - @Autowired ProcessInstanceStoreDAO processInstanceStore; - - @Override - public IRequest getPendingRequest(String pendingReqID) { - - try { - IRequest pendingRequest = transactionStorage.get(pendingReqID, IRequest.class); - if (pendingRequest == null) { - Logger.info("No PendingRequst found with pendingRequestID " + pendingReqID); - return null; - - } - - //set transactionID and sessionID to Logger - TransactionIDUtils.setAllLoggingVariables(pendingRequest); - - return pendingRequest; - - } catch (MOADatabaseException | NullPointerException e) { - Logger.info("No PendingRequst found with pendingRequestID " + pendingReqID); - return null; - - } - } - - @Override - public void storePendingRequest(IRequest pendingRequest) throws MOAIDException { - try { - if (pendingRequest instanceof IRequest) { - transactionStorage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest, -1); - - } else { - throw new MOAIDException("auth.20", null); - - } - - } catch (MOADatabaseException e) { - Logger.warn("Pending Request with ID=" + ((IRequest)pendingRequest).getRequestID() + - " can not stored.", e); - throw new MOAIDException("auth.20", null); - } - - } - - @Override - public void removePendingRequest(String requestID) { - - if (requestID != null) { - - //remove process-management execution instance - try { - IRequest pendingReq = getPendingRequest(requestID); - - if (pendingReq != null && - pendingReq.getProcessInstanceId() != null) { - processInstanceStore.remove(pendingReq.getProcessInstanceId()); - - } - - } catch (MOADatabaseException e) { - Logger.warn("Removing process associated with pending-request:" + requestID + " FAILED.", e); - - } - - transactionStorage.remove(requestID); - - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.storage.IRequestStorage#changePendingRequestID(at.gv.egovernment.moa.id.moduls.IRequest) - */ - @Override - public String changePendingRequestID(IRequest pendingRequest) throws MOAIDException, MOADatabaseException { - - if (pendingRequest instanceof RequestImpl) { - String newRequestID = Random.nextRandom(); - String oldRequestID = pendingRequest.getRequestID(); - - Logger.debug("Change pendingRequestID from " + pendingRequest.getRequestID() - + " to " + newRequestID); - - ((RequestImpl)pendingRequest).setRequestID(newRequestID); - transactionStorage.changeKey(oldRequestID, newRequestID, pendingRequest); - //only delete oldRequestID, no change. - - return newRequestID; - - } else { - Logger.error("PendingRequest object is not of type 'RequestImpl.class'"); - throw new MOAIDException("internal.00", null); - } - - } -} 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 557d9af48..b5005d0c9 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 @@ -23,32 +23,49 @@ package at.gv.egovernment.moa.id.moduls; import java.util.Date; +import java.util.Map; +import java.util.Map.Entry; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.auth.ISSOManager; +import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; +import at.gv.egiz.eaaf.core.exceptions.EAAFSSOException; +import at.gv.egiz.eaaf.core.exceptions.EAAFStorageException; +import at.gv.egiz.eaaf.core.impl.idp.controller.protocols.RequestImpl; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions; +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.auth.exception.BuildException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.IRequest; +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.api.exceptions.SessionDataStorageException; import at.gv.egovernment.moa.id.commons.db.dao.session.AuthenticatedSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OldSSOSessionIDStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameterDecorator; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.id.util.legacy.LegacyHelper; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Service("MOAID_SSOManager") -public class SSOManager { +public class SSOManager implements ISSOManager { + private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; private static final String HTMLTEMPLATEFULL = "slo_template.html"; public static String CONTEXTPATH = "contextPath"; @@ -58,10 +75,228 @@ public class SSOManager { private static final int INTERFEDERATIONCOOKIEMAXAGE = 5 * 60;// sec + public static final String DATAID_INTERFEDERATIOIDP_URL = "interIDPURL"; + public static final String DATAID_INTERFEDERATIOIDP_RESPONSE = "interIDPResponse"; + public static final String DATAID_INTERFEDERATIOIDP_ENTITYID = "interIDPEntityID"; + + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; - @Autowired protected AuthConfiguration authConfig; + @Autowired private AuthConfiguration authConfig; + @Autowired private IRevisionLogger revisionsLogger; + + + + //@Autowired private MOASessionDBUtils moaSessionDBUtils; + @Override + public boolean checkAndValidateSSOSession(IRequest pendingReq, HttpServletRequest httpReq, HttpServletResponse httpResp) throws EAAFSSOException { + try { + //get SSO cookie from http request + String ssoId = getSSOSessionID(httpReq); + + //check if interfederation IDP is requested + checkInterfederationIsRequested(httpReq, httpResp, pendingReq); + + //check if SSO session cookie is already used + if (ssoId != null) { + String correspondingMOASession = existsOldSSOSession(ssoId); + + if (correspondingMOASession != null) { + Logger.warn("Request sends an old SSO Session ID("+ssoId+")! " + + "Invalidate the corresponding MOASession with ID="+ correspondingMOASession); + + revisionsLogger.logEvent(pendingReq, EVENT_SSO_SESSION_INVALID); + + //destroy internal SSO-session object and SSO-session cooky + authenticatedSessionStore.destroyInternalSSOSession(correspondingMOASession); + deleteSSOSessionID(httpReq, httpResp); + } + } + + //check if SSO Session is valid + boolean isSSOValid = isValidSSOSession(ssoId, pendingReq); + + return isSSOValid; + + + } catch (SessionDataStorageException | ConfigurationException | EAAFStorageException e) { + Logger.warn("Cann not process SSO session. Reason: " + e.getMessage(), e); + Logger.info("All SSO session will be ignored."); + + } + + return false; + + } + + + @Override + public void isSSOAllowedForSP(IRequest pendingReq, HttpServletRequest httpReq) { + // check if Service-Provider allows SSO sessions + IOAAuthParameters oaConfig = pendingReq.getServiceProviderConfiguration(OAAuthParameterDecorator.class); + boolean useSSOOA = oaConfig.useSSO() || oaConfig.isInderfederationIDP(); + + //if a legacy request is used SSO should not be allowed in case of mandate authentication + boolean isUseMandateRequested = false; + try { + isUseMandateRequested = LegacyHelper.isUseMandateRequested(httpReq); + + //check if SSO is allowed for the actually executed request + //INFO: Actually, useMandate disables SSO functionality!!!!! + pendingReq.setNeedSingleSignOnFunctionality((useSSOOA && !isUseMandateRequested)); + + //check if current service provider needs user consent for SSO + pendingReq.setNeedUserConsent(oaConfig.useSSOQuestion()); + + } catch (WrongParametersException e) { + Logger.warn("Find suspect http parameter for mandates! Reason: " + e.getMessage()); + + } + + } + + @Override + public void populatePendingRequestWithSSOInformation(IRequest pendingReq) throws EAAFSSOException { + //populate pending request with eID data from SSO session if no userConsent is required + try { + AuthenticationSession ssoMOASession = authenticatedSessionStore.getInternalSSOSession(pendingReq.getInternalSSOSessionIdentifier()); + + if (ssoMOASession == null) + Logger.info("No MOASession FOUND with provided SSO-Cookie."); + + else { + Logger.debug("Found authenticated MOASession with provided SSO-Cookie."); + revisionsLogger.logEvent(pendingReq, EVENT_SSO_SESSION_VALID); + + Logger.trace("Populatint pending request with SSO session information .... "); + Map<String, Object> fullSSOData = ssoMOASession.getKeyValueRepresentationFromAuthSession(); + if (Logger.isTraceEnabled()) { + Logger.trace("Full SSO DataSet: "); + for (Entry<String, Object> el : fullSSOData.entrySet()) { + Logger.trace(" Key: " + el.getKey() + " Value: " + el.getValue()); + + } + + } + pendingReq.setRawDataToTransaction(fullSSOData); + pendingReq.setAuthenticated(true); + + } + + } catch (EAAFStorageException e) { + Logger.warn("Can NOT populate pending request from SSO session.", e); + throw new EAAFSSOException("", new Object[] {}, e); + + } + + } + + + @Override + public boolean destroySSOSessionOnIDPOnly(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq) throws EAAFSSOException { + //get SSO token from request + String internalSSOSessionId = null; + try { + if (pendingReq != null && MiscUtil.isNotEmpty(pendingReq.getInternalSSOSessionIdentifier())) { + internalSSOSessionId = pendingReq.getInternalSSOSessionIdentifier(); + + } else { + String ssoid = getSSOSessionID(httpReq); + if (isValidSSOSession(ssoid, null)) { + internalSSOSessionId = authenticatedSessionStore.getInternalSSOSessionWithSSOID(ssoid); + + } + } + + //destroy SSO session if it was found + if (StringUtils.isNotEmpty(internalSSOSessionId)) { + //delete SSO session and MOA session + AuthenticationSession ssoMOASession = authenticatedSessionStore.getInternalSSOSession(internalSSOSessionId); + + if (ssoMOASession == null) { + Logger.info("No internal MOA SSO-Session found. Nothing to destroy"); + return false; + + } + + + ssoMOASession.setAuthenticated(false); + + //log Session_Destroy to reversionslog + AuthenticationSessionExtensions sessionExtensions = + authenticatedSessionStore.getAuthenticationSessionExtensions(ssoMOASession.getSSOSessionID()); + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, sessionExtensions.getUniqueSessionId()); + authenticatedSessionStore.destroyInternalSSOSession(ssoMOASession.getSSOSessionID()); + } + + } catch (ConfigurationException | SessionDataStorageException | EAAFStorageException e) { + Logger.info("NO MOA Authentication data for ID " + internalSSOSessionId); + return false; + + } + + + //Remove SSO token + deleteSSOSessionID(httpReq, httpResp); + + return true; + + } + + @Override + public String createNewSSOSessionCookie(HttpServletRequest httpReq, HttpServletResponse httpResp, IRequest pendingReq) + throws EAAFSSOException { + Logger.debug("Creating new SSO session-cookie for http response ... "); + + //Store SSO information into database + String newSSOSessionId = Random.nextHexRandom32(); + + //set SSO cookie to response + if (StringUtils.isNotEmpty(newSSOSessionId)) + setSSOSessionID(httpReq, httpResp, newSSOSessionId); + else + deleteSSOSessionID(httpReq, httpResp); + + return newSSOSessionId; + } + + +@Override +public void createNewSSOSession(IRequest pendingReq, String newSSOSessionId) throws EAAFSSOException { + AuthenticationSession internalDBSSOSession; + try { + internalDBSSOSession = authenticatedSessionStore.createInternalSSOSession(pendingReq); + pendingReq.setInternalSSOSessionIdentifier(internalDBSSOSession.getSSOSessionID()); + + } catch (MOADatabaseException | BuildException e) { + Logger.warn("Can NOT create SSO session.", e); + throw new EAAFSSOException("builder.10", null, e); + + } + +} + + +@Override +public void updateSSOSession(IRequest pendingReq, String newSSOSessionId, SLOInformationInterface sloInformation) throws EAAFSSOException { + try { + authenticatedSessionStore.addSSOInformation( + pendingReq.getInternalSSOSessionIdentifier(), + newSSOSessionId, + sloInformation, + pendingReq); + + } catch (AuthenticationException e) { + Logger.warn("Can NOT update SSO session.", e); + throw new EAAFSSOException("builder.10", null, e); + } + +} + + + //*********************************** old ************************************** + /** * Check if interfederation IDP is requested via HTTP GET parameter or if interfederation cookie exists. * Set the requested interfederation IDP as attribte of the {protocolRequest} @@ -70,14 +305,15 @@ public class SSOManager { * @param httpResp HttpServletResponse * @param protocolRequest Authentication request which is actually in process * @throws SessionDataStorageException + * @throws EAAFStorageException * **/ public void checkInterfederationIsRequested(HttpServletRequest httpReq, HttpServletResponse httpResp, - IRequest protocolRequest) throws SessionDataStorageException { + IRequest protocolRequest) throws SessionDataStorageException, EAAFStorageException { String interIDP = httpReq.getParameter(MOAIDAuthConstants.INTERFEDERATION_IDP); String interfederationIDP = - protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + protocolRequest.getRawData(DATAID_INTERFEDERATIOIDP_URL, String.class); if (MiscUtil.isNotEmpty(interfederationIDP)) { Logger.debug("Protocolspecific preprocessing already set interfederation IDP " + interfederationIDP); return; @@ -89,14 +325,14 @@ public class SSOManager { RequestImpl moaReq = (RequestImpl) protocolRequest; if (MiscUtil.isNotEmpty(interIDP)) { Logger.info("Receive SSO request for interfederation IDP " + interIDP); - moaReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, interIDP); + moaReq.setRawDataToTransaction(DATAID_INTERFEDERATIOIDP_URL, interIDP); } else { //check if IDP cookie is set String cookie = getValueFromCookie(httpReq, SSOINTERFEDERATION); if (MiscUtil.isNotEmpty(cookie)) { Logger.info("Receive SSO request for interfederated IDP from Cookie " + cookie); - moaReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, cookie); + moaReq.setRawDataToTransaction(DATAID_INTERFEDERATIOIDP_URL, cookie); deleteCookie(httpReq, httpResp, SSOINTERFEDERATION); } @@ -113,8 +349,7 @@ public class SSOManager { } - - public boolean isValidSSOSession(String ssoSessionID, IRequest protocolRequest) throws ConfigurationException, SessionDataStorageException { + public boolean isValidSSOSession(String ssoSessionID, IRequest protocolRequest) throws ConfigurationException, SessionDataStorageException, EAAFStorageException { // search SSO Session if (ssoSessionID == null) { @@ -144,7 +379,7 @@ public class SSOManager { //in case of federated SSO session, jump to federated IDP for authentication String interfederationIDP = - protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + protocolRequest.getRawData(DATAID_INTERFEDERATIOIDP_URL, String.class); if (MiscUtil.isEmpty(interfederationIDP)) { InterfederationSessionStore selectedIDP = authenticatedSessionStore.searchInterfederatedIDPFORSSOWithMOASession(storedSession.getSessionid()); @@ -152,8 +387,8 @@ public class SSOManager { if (selectedIDP != null) { //no local SSO session exist -> request interfederated IDP Logger.info("SSO Session refer to federated IDP: " + selectedIDP.getIdpurlprefix()); - protocolRequest.setGenericDataToSession( - RequestImpl.DATAID_INTERFEDERATIOIDP_URL, selectedIDP.getIdpurlprefix()); + protocolRequest.setRawDataToTransaction( + DATAID_INTERFEDERATIOIDP_URL, selectedIDP.getIdpurlprefix()); } else { Logger.warn("MOASession is marked as interfederated SSO session but no interfederated IDP is found. Switch to local authentication ..."); @@ -170,25 +405,32 @@ public class SSOManager { return false; } - + + //set internal SSO SessionID + if (protocolRequest != null) + protocolRequest.setInternalSSOSessionIdentifier(storedSession.getSessionid()); + return true; } } - public AuthenticationSession getInternalMOASession(String ssoSessionID) throws MOADatabaseException { - return authenticatedSessionStore.getInternalMOASessionWithSSOID(ssoSessionID); - - } +// public String getInternalSSOSession(String ssoSessionID) throws MOADatabaseException { +// return authenticatedSessionStore.getInternalSSOSessionWithSSOID(ssoSessionID); +// +// } //TODO: refactor for faster DB access public String getUniqueSessionIdentifier(String ssoSessionID) { try { if (MiscUtil.isNotEmpty(ssoSessionID)) { - AuthenticationSession moaSession = authenticatedSessionStore.getInternalMOASessionWithSSOID(ssoSessionID); - if (moaSession != null) { - AuthenticationSessionExtensions extSessionInformation = authenticatedSessionStore.getAuthenticationSessionExtensions(moaSession.getSessionID()); + String ssoSessionId = authenticatedSessionStore.getInternalSSOSessionWithSSOID(ssoSessionID); + if (MiscUtil.isNotEmpty(ssoSessionId)) { + AuthenticationSessionExtensions extSessionInformation = authenticatedSessionStore.getAuthenticationSessionExtensions(ssoSessionId); + if (extSessionInformation != null) return extSessionInformation.getUniqueSessionId(); + else + Logger.warn("Extended SSO-Session Information ARE NULL. Something looks wrong!"); } } @@ -199,55 +441,13 @@ public class SSOManager { return null; } - - public String existsOldSSOSession(String ssoId) { - - Logger.trace("Check that the SSOID has already been used"); - - OldSSOSessionIDStore oldSSOSession = authenticatedSessionStore.checkSSOTokenAlreadyUsed(ssoId); - - if (oldSSOSession == null) { - Logger.debug("SSO session-cookie was not used in parst"); - return null; - } - - AuthenticatedSessionStore correspondingMoaSession = oldSSOSession.getMoasession(); - - if (correspondingMoaSession == null) { - Logger.info("Get request with old SSO SessionID but no corresponding SSO Session is found."); - return null; - } - - return correspondingMoaSession.getSessionid(); - - } - - public String createSSOSessionInformations(String moaSessionID, String OAUrl) { - - String newSSOId = Random.nextRandom(); - - if (MiscUtil.isEmpty(moaSessionID) || MiscUtil.isEmpty(OAUrl)) { - Logger.warn("MoaSessionID or OAUrl are empty -> SSO is not enabled!"); - return null; - } - - return newSSOId; - - } - - public void setSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp, String ssoId) { - setCookie(httpReq, httpResp, SSOCOOKIE, ssoId, -1); - - } - + public String getSSOSessionID(HttpServletRequest httpReq) { return getValueFromCookie(httpReq, SSOCOOKIE); } - public void deleteSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp) { - deleteCookie(httpReq, httpResp, SSOCOOKIE); - } + /** * @param entityID @@ -284,7 +484,41 @@ public class SSOManager { return false; } - + + + private String existsOldSSOSession(String ssoId) { + + Logger.trace("Check that the SSOID has already been used"); + + OldSSOSessionIDStore oldSSOSession = authenticatedSessionStore.checkSSOTokenAlreadyUsed(ssoId); + + if (oldSSOSession == null) { + Logger.debug("SSO session-cookie was not used in parst"); + return null; + } + + AuthenticatedSessionStore correspondingMoaSession = oldSSOSession.getMoasession(); + + if (correspondingMoaSession == null) { + Logger.info("Get request with old SSO SessionID but no corresponding SSO Session is found."); + return null; + } + + return correspondingMoaSession.getSessionid(); + + } + + + private void setSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp, String ssoId) { + setCookie(httpReq, httpResp, SSOCOOKIE, ssoId, -1); + + } + + private void deleteSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp) { + deleteCookie(httpReq, httpResp, SSOCOOKIE); + + } + private String getValueFromCookie(HttpServletRequest httpReq, String cookieName) { Cookie[] cookies = httpReq.getCookies(); @@ -312,6 +546,7 @@ public class SSOManager { private void deleteCookie(HttpServletRequest httpReq, HttpServletResponse httpResp, String cookieName) { setCookie(httpReq, httpResp, cookieName, "", 0); + } - + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAIDHTTPPostEncoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAIDHTTPPostEncoder.java deleted file mode 100644 index b05e60e94..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAIDHTTPPostEncoder.java +++ /dev/null @@ -1,114 +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.opemsaml; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Writer; - -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.opensaml.common.binding.SAMLMessageContext; -import org.opensaml.saml2.binding.encoding.HTTPPostEncoder; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.ws.transport.http.HTTPOutTransport; -import org.opensaml.ws.transport.http.HTTPTransportUtils; - -import at.gv.egovernment.moa.id.auth.frontend.builder.GUIFormBuilderImpl; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -public class MOAIDHTTPPostEncoder extends HTTPPostEncoder { - - private VelocityEngine velocityEngine; - private IGUIBuilderConfiguration guiConfig; - private GUIFormBuilderImpl guiBuilder; - - /** - * @param engine - * @param templateId - */ - public MOAIDHTTPPostEncoder(IGUIBuilderConfiguration guiConfig, GUIFormBuilderImpl guiBuilder, VelocityEngine engine) { - super(engine, null); - this.velocityEngine = engine; - this.guiConfig = guiConfig; - this.guiBuilder = guiBuilder; - - } - - /** - * Base64 and POST encodes the outbound message and writes it to the outbound transport. - * - * @param messageContext current message context - * @param endpointURL endpoint URL to which to encode message - * - * @throws MessageEncodingException thrown if there is a problem encoding the message - */ - protected void postEncode(SAMLMessageContext messageContext, String endpointURL) throws MessageEncodingException { - Logger.debug("Invoking Velocity template to create POST body"); - InputStream is = null; - try { - //build Velocity Context from GUI input paramters - VelocityContext context = guiBuilder.generateVelocityContextFromConfiguration(guiConfig); - - //load template - is = guiBuilder.getTemplateInputStream(guiConfig); - - //populate velocity context with SAML2 parameters - populateVelocityContext(context, messageContext, endpointURL); - - //populate transport parameter - HTTPOutTransport outTransport = (HTTPOutTransport) messageContext.getOutboundMessageTransport(); - HTTPTransportUtils.addNoCacheHeaders(outTransport); - HTTPTransportUtils.setUTF8Encoding(outTransport); - HTTPTransportUtils.setContentType(outTransport, "text/html"); - - //evaluate template and write content to response - Writer out = new OutputStreamWriter(outTransport.getOutgoingStream(), "UTF-8"); - velocityEngine.evaluate(context, out, "SAML2_POST_BINDING", new BufferedReader(new InputStreamReader(is))); - out.flush(); - - } catch (Exception e) { - Logger.error("Error invoking Velocity template", e); - throw new MessageEncodingException("Error creating output document", e); - - } finally { - if (is != null) { - try { - is.close(); - - } catch (IOException e) { - Logger.error("Can NOT close GUI-Template InputStream.", e); - } - } - - } - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAKeyStoreX509CredentialAdapter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAKeyStoreX509CredentialAdapter.java deleted file mode 100644 index 81afcfbc1..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAKeyStoreX509CredentialAdapter.java +++ /dev/null @@ -1,52 +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.opemsaml; - -import java.security.KeyStore; - -import org.opensaml.xml.security.x509.X509Credential; - - -/** - * @author tlenz - * - */ -public class MOAKeyStoreX509CredentialAdapter extends - org.opensaml.xml.security.x509.KeyStoreX509CredentialAdapter { - - /** - * @param store - * @param alias - * @param password - */ - public MOAKeyStoreX509CredentialAdapter(KeyStore store, String alias, - char[] password) { - super(store, alias, password); - } - - public Class<? extends X509Credential> getCredentialType() { - return X509Credential.class; - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAStringRedirectDeflateEncoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAStringRedirectDeflateEncoder.java deleted file mode 100644 index acbb67b34..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAStringRedirectDeflateEncoder.java +++ /dev/null @@ -1,75 +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.opemsaml; - -import org.opensaml.common.binding.SAMLMessageContext; -import org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder; -import org.opensaml.ws.message.MessageContext; -import org.opensaml.ws.message.encoder.MessageEncodingException; - -import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -public class MOAStringRedirectDeflateEncoder extends HTTPRedirectDeflateEncoder { - - private String redirectURL = null; - - public void encode(MessageContext messageContext) - throws MessageEncodingException { - if (!(messageContext instanceof SAMLMessageContext)) { - Logger.error("Invalid message context type, this encoder only support SAMLMessageContext"); - throw new MessageEncodingException( - "Invalid message context type, this encoder only support SAMLMessageContext"); - } - - //load default PVP security configurations - MOADefaultBootstrap.initializeDefaultPVPConfiguration(); - - SAMLMessageContext samlMsgCtx = (SAMLMessageContext) messageContext; - - String endpointURL = getEndpointURL(samlMsgCtx).buildURL(); - - setResponseDestination(samlMsgCtx.getOutboundSAMLMessage(), endpointURL); - - removeSignature(samlMsgCtx); - - String encodedMessage = deflateAndBase64Encode(samlMsgCtx - .getOutboundSAMLMessage()); - - redirectURL = buildRedirectURL(samlMsgCtx, endpointURL, - encodedMessage); - } - - /** - * @return the redirectURL - */ - public String getRedirectURL() { - return redirectURL; - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java deleted file mode 100644 index 080990f71..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExecutionContextImpl.java +++ /dev/null @@ -1,79 +0,0 @@ -package at.gv.egovernment.moa.id.process; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import at.gv.egovernment.moa.id.process.api.ExecutionContext; - -/** - * ExecutionContext implementation, related to a certain process instance. - * - * @author tknall - * - */ -public class ExecutionContextImpl implements ExecutionContext { - - private static final long serialVersionUID = 1L; - - private Map<String, Serializable> ctxData = Collections.synchronizedMap(new HashMap<String, Serializable>()); - - private String processInstanceId; - - /** - * Creates a new instance. - */ - public ExecutionContextImpl() { - } - - /** - * Creates a new instance and associated it with a certain process instance. - */ - public ExecutionContextImpl(String processInstanceId) { - this.processInstanceId = processInstanceId; - } - - @Override - public void setProcessInstanceId(String processInstanceId) { - this.processInstanceId = processInstanceId; - } - - @Override - public String getProcessInstanceId() { - return processInstanceId; - } - - @Override - public Serializable get(String key) { - return ctxData.get(key); - } - - @Override - public Serializable remove(String key) { - return ctxData.remove(key); - } - - @Override - public void put(String key, Serializable object) { - ctxData.put(key, object); - } - - @Override - public Set<String> keySet() { - return Collections.unmodifiableSet(ctxData.keySet()); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ExecutionContextImpl ["); - builder.append("id=").append(processInstanceId); - builder.append(", variables="); - builder.append(ctxData.keySet()); - builder.append("]"); - return builder.toString(); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java deleted file mode 100644 index f0d1c861d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ExpressionEvaluationContextImpl.java +++ /dev/null @@ -1,44 +0,0 @@ -package at.gv.egovernment.moa.id.process; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; - -/** - * Context implementation used for expression evaluation only. - * - * @author tknall - * - */ -public class ExpressionEvaluationContextImpl implements ExpressionEvaluationContext { - - private static final long serialVersionUID = 1L; - - private Map<String, Serializable> ctxData; - - /** - * Creates a new instance and initializes it with data from a given process instance. - * - * @param processInstance - * The process instance. - */ - ExpressionEvaluationContextImpl(ProcessInstance processInstance) { - ExecutionContext executionContext = processInstance.getExecutionContext(); - Set<String> keys = executionContext.keySet(); - ctxData = Collections.synchronizedMap(new HashMap<String, Serializable>(keys.size())); - for (String key : keys) { - ctxData.put(key, executionContext.get(key)); - } - } - - @Override - public Map<String, Serializable> getCtx() { - return Collections.unmodifiableMap(ctxData); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java deleted file mode 100644 index 162ee624a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParser.java +++ /dev/null @@ -1,224 +0,0 @@ -package at.gv.egovernment.moa.id.process; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; - -import javax.xml.XMLConstants; -import javax.xml.namespace.QName; -import javax.xml.stream.XMLEventReader; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.events.Attribute; -import javax.xml.stream.events.StartElement; -import javax.xml.stream.events.XMLEvent; -import javax.xml.stream.util.EventReaderDelegate; -import javax.xml.transform.stax.StAXSource; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; -import javax.xml.validation.Validator; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.xml.sax.SAXException; - -import at.gv.egovernment.moa.id.process.model.EndEvent; -import at.gv.egovernment.moa.id.process.model.ProcessDefinition; -import at.gv.egovernment.moa.id.process.model.ProcessNode; -import at.gv.egovernment.moa.id.process.model.StartEvent; -import at.gv.egovernment.moa.id.process.model.TaskInfo; -import at.gv.egovernment.moa.id.process.model.Transition; - -/** - * Parses an XML representation of a process definition as defined by the respective XML schema. - * <p/ - * The parser is thread-safe. - * @author tknall - * - */ -public class ProcessDefinitionParser { - - private static final String NS = "http://reference.e-government.gv.at/namespace/moa/process/definition/v1"; - - private static Logger log = LoggerFactory.getLogger(ProcessDefinitionParser.class); - - private static class LazyProcessDefinitionSchemaHolder { - private static final Schema PD_SCHEMA_INSTANCE; - static { - try (InputStream in = ProcessDefinitionParser.class.getResourceAsStream("ProcessDefinition.xsd")) { - log.trace("Compiling process definition schema."); - SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - // schema is thread-safe - PD_SCHEMA_INSTANCE = factory.newSchema(new StreamSource(in)); - } catch (Exception e) { - throw new RuntimeException("Unable to compile process definition schema.", e); - } - } - } - - /** - * Parses an XML representation of a process definition. The representation is being validated in order to suffice - * the related XML schema. - * - * @param processDefinitionInputStream - * The process definition. - * @return A new process definition. - * @throws ProcessDefinitionParserException - * Thrown in case of error parsing the process definition. - */ - public ProcessDefinition parse(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException { - XMLEventReader reader = null; - final ProcessDefinition pd = new ProcessDefinition(); - log.debug("Parsing and validating process definition."); - try { - - // Standard implementation of XMLInputFactory seems not to be thread-safe - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - reader = inputFactory.createXMLEventReader(processDefinitionInputStream); - - final List<StartElement> transitionElements = new ArrayList<>(); - final List<StartEvent> startEvents = new ArrayList<>(); - - reader = new EventReaderDelegate(reader) { - - @Override - public XMLEvent nextEvent() throws XMLStreamException { - XMLEvent event = super.nextEvent(); - - switch (event.getEventType()) { - case XMLStreamConstants.START_ELEMENT: - StartElement element = event.asStartElement(); - QName qname = element.getName(); - - if (NS.equals(qname.getNamespaceURI())) { - log.trace("Found process description element '{}'.", qname.getLocalPart()); - Attribute id = element.getAttributeByName(new QName("id")); - - switch (qname.getLocalPart()) { - case "ProcessDefinition": - if (id != null) { - pd.setId(id.getValue()); - } - break; - case "StartEvent": - StartEvent startEvent = new StartEvent(); - if (id != null) { - startEvent.setId(id.getValue()); - } - startEvents.add(startEvent); - break; - case "EndEvent": - EndEvent endEvent = new EndEvent(); - if (id != null) { - endEvent.setId(id.getValue()); - pd.getEndEvents().put(id.getValue(), endEvent); - } - break; - case "Transition": - transitionElements.add(element); - break; - case "Task": - TaskInfo taskInfo = new TaskInfo(); - if (id != null) { - taskInfo.setId(id.getValue()); - pd.getTaskInfos().put(id.getValue(), taskInfo); - } - Attribute async = element.getAttributeByName(new QName("async")); - if (async != null) { - taskInfo.setAsync(Boolean.valueOf(async.getValue())); - } - Attribute implementingClass = element.getAttributeByName(new QName("class")); - if (implementingClass != null) { - taskInfo.setTaskImplementingClass(implementingClass.getValue()); - } - break; - } - - } - - break; - } - - return event; - } - - }; - - // validator is not thread-safe - Validator validator = LazyProcessDefinitionSchemaHolder.PD_SCHEMA_INSTANCE.newValidator(); - validator.validate(new StAXSource(reader)); - log.trace("Process definition successfully schema validated."); - - // perform some basic checks - log.trace("Building model and performing some plausibility checks."); - if (startEvents.size() != 1) { - throw new ProcessDefinitionParserException("A ProcessDefinition must contain exactly one single StartEvent."); - } - pd.setStartEvent(startEvents.get(0)); - - // link transitions - Iterator<StartElement> transitions = transitionElements.iterator(); - while (transitions.hasNext()) { - StartElement element = transitions.next(); - Transition transition = new Transition(); - Attribute id = element.getAttributeByName(new QName("id")); - if (id != null) { - transition.setId(id.getValue()); - } - Attribute conditionExpression = element.getAttributeByName(new QName("conditionExpression")); - if (conditionExpression != null) { - transition.setConditionExpression(conditionExpression.getValue()); - } - Attribute from = element.getAttributeByName(new QName("from")); - if (from != null) { - ProcessNode fromNode = pd.getProcessNode(from.getValue()); - if (fromNode == null) { - throw new ProcessDefinitionParserException("Transition's 'from'-attribute refers to a non-existing event or task '" + from.getValue() + '.'); - } - if (fromNode instanceof EndEvent) { - throw new ProcessDefinitionParserException("Transition cannot start from end event."); - } - transition.setFrom(fromNode); - fromNode.getOutgoingTransitions().add(transition); - } - Attribute to = element.getAttributeByName(new QName("to")); - if (to != null) { - ProcessNode toNode = pd.getProcessNode(to.getValue()); - if (toNode == null) { - throw new ProcessDefinitionParserException("Transition's 'to'-attribute refers to a non-existing event or task '" + to.getValue() + '.'); - } - transition.setTo(toNode); - toNode.getIncomingTransitions().add(transition); - } - if (transition.getConditionExpression() == null && Objects.equals(transition.getFrom(), transition.getTo())) { - throw new ProcessDefinitionParserException("Transition's 'from' equals its 'to'. Since no 'conditionExpression' has been set this will cause a loop."); - } - } - log.debug("Process definition '{}' successfully parsed.", pd.getId()); - return pd; - - } catch (ProcessDefinitionParserException e) { - throw e; - } catch (XMLStreamException|IOException e) { - throw new ProcessDefinitionParserException("Unable to read process definition from inputstream.", e); - } catch (SAXException e) { - throw new ProcessDefinitionParserException("Schema validation of process description failed.", e); - } catch (Exception e) { - throw new ProcessDefinitionParserException("Internal error creating process definition from inputstream.", e); - } finally { - if (reader != null) { - try { - reader.close(); - } catch (XMLStreamException e) { - // error freeing resources - } - } - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParserException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParserException.java deleted file mode 100644 index 0c214750d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessDefinitionParserException.java +++ /dev/null @@ -1,35 +0,0 @@ -package at.gv.egovernment.moa.id.process; - -/** - * Exception thrown in case of error parsing a process definition. - * - * @author tknall - * - */ -public class ProcessDefinitionParserException extends Exception { - - private static final long serialVersionUID = 1L; - - /** - * Creates a new parser exception providing a {@code message} describing the reason and the {@code cause}. - * - * @param message - * The message. - * @param cause - * The cause. - */ - public ProcessDefinitionParserException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Creates a new parser exception providing a {@code message} describing the reason. - * - * @param message - * The message. - */ - public ProcessDefinitionParserException(String message) { - super(message); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java deleted file mode 100644 index 44f622fa0..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngine.java +++ /dev/null @@ -1,110 +0,0 @@ -package at.gv.egovernment.moa.id.process; - - -import java.io.InputStream; - -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.process.model.ProcessDefinition; - -/** - * Process engine providing means for starting and resuming processes. - * - * @author tknall - */ -public interface ProcessEngine { - - /** - * Registers a new process definition. Note that existing definitions with the same identifier will be replaced. - * - * @param processDefinition - * The process definition to be registered. - */ - void registerProcessDefinition(ProcessDefinition processDefinition); - - /** - * Registers a new process definition given as {@link InputStream}. Note that existing definitions with the same identifier will be replaced. - * - * @param processDefinitionInputStream The input stream to the definition to be registered. - * @throws ProcessDefinitionParserException Thrown in case of an error parsing the process definition. - * @return The process definition's identifier. - */ - String registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException; - - /** - * Creates a process instance according to the referenced process definition, persists it into the database and returns it identifier. - * <p/> - * Note that the method returns the identifier of a process instance which will be needed in order to start a process or to continue - * process execution after asynchronous task execution (refer to {@link #start(String)} and - * {@link #signal(String)} for further information). - * - * @param processDefinitionId - * The identifier of the respective process definition. - * @param executionContext The execution context (may be {@code null}). - * @return The id of the newly created process instance (never {@code null}). - * @throws ProcessExecutionException - * Thrown in case of error, e.g. when a {@code processDefinitionId} is referenced that does not exist. - */ - String createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException; - - /** - * Creates a process instance according to the referenced process definition, persists it into the database and returns it identifier. - * <p/> - * Note that the method returns the identifier of a process instance which will be needed in order to start a process or to continue - * process execution after asynchronous task execution (refer to {@link #start(String)} and - * {@link #signal(String)} for further information). - * - * @param processDefinitionId - * The identifier of the respective process definition. - * @return The id of the newly created process instance (never {@code null}). - * @throws ProcessExecutionException - * Thrown in case of error, e.g. when a {@code processDefinitionId} is referenced that does not exist. - */ - String createProcessInstance(String processDefinitionId) throws ProcessExecutionException; - - - /** - * Delete a process instance - * - * @param processInstanceId - * The identifier of the respective process. - * @throws ProcessExecutionException - * Thrown in case of error, e.g. when a {@code processInstanceId} is referenced that does not exist. - */ - void deleteProcessInstance(String processInstanceId) throws ProcessExecutionException; - - /** - * Returns the process instance with a given {@code processInstanceId}. - * - * @param processInstanceId - * The process instance id. - * @return The process instance (never {@code null}). - * @throws IllegalArgumentException - * In case the process instance does not/no longer exist. - * @throws RuntimeException - * In case the process instance could not be retrieved from persistence. - */ - ProcessInstance getProcessInstance(String processInstanceId); - - /** - * Starts the process using the given {@code pendingReq}. - * - * @param pendingReq - * The protocol request for which a process should be started. - * @throws ProcessExecutionException - * Thrown in case of error. - */ - void start(IRequest pendingReq) throws ProcessExecutionException; - - - /** - * Resumes process execution after an asynchronous task has been executed. - * - * @param pendingReq - * The process instance id. - * @throws ProcessExecutionException - * Thrown in case of error. - */ - void signal(IRequest pendingReq) throws ProcessExecutionException; - -}
\ No newline at end of file diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java deleted file mode 100644 index 76e6605c1..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessEngineImpl.java +++ /dev/null @@ -1,420 +0,0 @@ -package at.gv.egovernment.moa.id.process; - -import java.io.InputStream; -import java.io.Serializable; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.Predicate; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - -import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; -import at.gv.egovernment.moa.id.process.api.ExpressionEvaluator; -import at.gv.egovernment.moa.id.process.api.Task; -import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStore; -import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAO; -import at.gv.egovernment.moa.id.process.model.EndEvent; -import at.gv.egovernment.moa.id.process.model.ProcessDefinition; -import at.gv.egovernment.moa.id.process.model.ProcessNode; -import at.gv.egovernment.moa.id.process.model.StartEvent; -import at.gv.egovernment.moa.id.process.model.TaskInfo; -import at.gv.egovernment.moa.id.process.model.Transition; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * Process engine implementation allowing starting and continuing processes as well as providing means for cleanup actions. - */ -public class ProcessEngineImpl implements ProcessEngine { - - private Logger log = LoggerFactory.getLogger(getClass()); - - @Autowired ProcessInstanceStoreDAO piStoreDao; - @Autowired ApplicationContext context; - - private ProcessDefinitionParser pdp = new ProcessDefinitionParser(); - - private Map<String, ProcessDefinition> processDefinitions = new ConcurrentHashMap<String, ProcessDefinition>(); - - private final static String MDC_CTX_PI_NAME = "processInstanceId"; - private final static String MDC_CTX_TASK_NAME = "taskId"; - - private ExpressionEvaluator transitionConditionExpressionEvaluator; - - @Override - public void registerProcessDefinition(ProcessDefinition processDefinition) { - log.info("Registering process definition '{}'.", processDefinition.getId()); - processDefinitions.put(processDefinition.getId(), processDefinition); - } - - @Override - public String registerProcessDefinition(InputStream processDefinitionInputStream) throws ProcessDefinitionParserException{ - ProcessDefinition pd = pdp.parse(processDefinitionInputStream); - registerProcessDefinition(pd); - return pd.getId(); - } - - /** - * Sets the process definitions. - * - * @param processDefinitions - * The process definitions. - * @throws IllegalArgumentException - * In case the process definitions contain definitions with the same identifier. - */ - public void setProcessDefinitions(Iterable<ProcessDefinition> processDefinitions) { - this.processDefinitions.clear(); - for (ProcessDefinition pd : processDefinitions) { - if (this.processDefinitions.containsKey(pd.getId())) { - throw new IllegalArgumentException("Duplicate process definition identifier '" + pd.getId() + "'."); - } - registerProcessDefinition(pd); - } - } - - /** - * Sets an expression evaluator that should be used to process transition condition expressions. - * @param transitionConditionExpressionEvaluator The expression evaluator. - */ - public void setTransitionConditionExpressionEvaluator( - ExpressionEvaluator transitionConditionExpressionEvaluator) { - this.transitionConditionExpressionEvaluator = transitionConditionExpressionEvaluator; - } - - - @Override - public String createProcessInstance(String processDefinitionId, ExecutionContext executionContext) throws ProcessExecutionException { - // look for respective process definition - ProcessDefinition pd = processDefinitions.get(processDefinitionId); - if (pd == null) { - throw new ProcessExecutionException("Unable to find process definition for process '" + processDefinitionId + "'."); - } - // create and keep process instance - ProcessInstance pi = new ProcessInstance(pd, executionContext); - log.info("Creating process instance from process definition '{}': {}", processDefinitionId, pi.getId()); - - try { - saveOrUpdateProcessInstance(pi); - } catch (MOADatabaseException e) { - throw new ProcessExecutionException("Unable to persist process instance.", e); - } - - return pi.getId(); - } - - @Override - public String createProcessInstance(String processDefinitionId) throws ProcessExecutionException { - return createProcessInstance(processDefinitionId, null); - } - - @Override - public void start(IRequest pendingReq) throws ProcessExecutionException { - try { - if (MiscUtil.isEmpty(pendingReq.getProcessInstanceId())) { - log.error("Pending-request with id:" + pendingReq.getRequestID() - + " includes NO 'ProcessInstanceId'"); - throw new ProcessExecutionException("Pending-request with id:" + pendingReq.getRequestID() - + " includes NO 'ProcessInstanceId'"); - } - - ProcessInstance pi = loadProcessInstance(pendingReq.getProcessInstanceId()); - - if (pi == null ) { - throw new ProcessExecutionException("Process instance '" + pendingReq.getProcessInstanceId() + "' does not exist."); - - } - - MDC.put(MDC_CTX_PI_NAME, pi.getId()); - - if (!ProcessInstanceState.NOT_STARTED.equals(pi.getState())) { - throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has already been started (current state is " + pi.getState() + ")."); - } - log.info("Starting process instance '{}'.", pi.getId()); - // execute process - pi.setState(ProcessInstanceState.STARTED); - execute(pi, pendingReq); - - //store ProcessInstance if it is not already ended - if (!ProcessInstanceState.ENDED.equals(pi.getState())) - saveOrUpdateProcessInstance(pi); - - } catch (MOADatabaseException e) { - throw new ProcessExecutionException("Unable to load/save process instance.", e); - - } finally { - MDC.remove(MDC_CTX_PI_NAME); - } - } - - @Override - public void signal(IRequest pendingReq) throws ProcessExecutionException { - - try { - if (MiscUtil.isEmpty(pendingReq.getProcessInstanceId())) { - log.error("Pending-request with id:" + pendingReq.getRequestID() - + " includes NO 'ProcessInstanceId'"); - throw new ProcessExecutionException("Pending-request with id:" + pendingReq.getRequestID() - + " includes NO 'ProcessInstanceId'"); - } - - ProcessInstance pi = loadProcessInstance(pendingReq.getProcessInstanceId()); - - if (pi == null ) { - throw new ProcessExecutionException("Process instance '" + pendingReq.getProcessInstanceId() + "' does not exist."); - - } - - MDC.put(MDC_CTX_PI_NAME, pi.getId()); - - if (!ProcessInstanceState.SUSPENDED.equals(pi.getState())) { - throw new ProcessExecutionException("Process instance '" + pi.getId() + "' has not been suspended (current state is " + pi.getState() + ")."); - } - - log.info("Waking up process instance '{}'.", pi.getId()); - pi.setState(ProcessInstanceState.STARTED); - - //put pending-request ID on execution-context because it could be changed - pi.getExecutionContext().put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, pendingReq.getRequestID()); - - execute(pi, pendingReq); - - //store ProcessInstance if it is not already ended - if (!ProcessInstanceState.ENDED.equals(pi.getState())) - saveOrUpdateProcessInstance(pi); - - } catch (MOADatabaseException e) { - throw new ProcessExecutionException("Unable to load/save process instance.", e); - - } finally { - MDC.remove(MDC_CTX_PI_NAME); - } - } - - - /** - * Instantiates a task implementation given by a {@link TaskInfo}. - * @param ti The task info. - * @return A Task implementation or {@code null} if the task info does not reference any task implementing classes. - * @throws ProcessExecutionException Thrown in case of error (when the referenced class does not implement {@link Task} for instance). - */ - private Task createTaskInstance(TaskInfo ti) throws ProcessExecutionException { - String clazz = StringUtils.trimToNull(ti.getTaskImplementingClass()); - Task task = null; - - if (clazz != null) { - log.debug("Instantiating task implementing class '{}'.", clazz); - Object instanceClass = null; - try { - instanceClass = context.getBean(clazz); - - } catch (Exception e) { - throw new ProcessExecutionException("Unable to get class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); - - } - if (instanceClass == null || !(instanceClass instanceof Task)) { - throw new ProcessExecutionException("Class '" + clazz + "' associated with task '" + ti.getId() + "' is not assignable to " + Task.class.getName() + "."); - - } - try { - task = (Task) instanceClass; - - } catch (Exception e) { - throw new ProcessExecutionException("Unable to instantiate class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); - } - } - - return task; - } - - /** - * Starts/executes a given process instance. - * @param pi The process instance. - * @param pendingReq - * @throws ProcessExecutionException Thrown in case of error. - */ - private void execute(final ProcessInstance pi, IRequest pendingReq) throws ProcessExecutionException { - if (ProcessInstanceState.ENDED.equals(pi.getState())) { - throw new ProcessExecutionException("Process for instance '" + pi.getId() + "' has already been ended."); - } - ProcessDefinition pd = pi.getProcessDefinition(); - ProcessNode processNode = pd.getProcessNode(pi.getNextId()); - log.debug("Processing node '{}'.", processNode.getId()); - - // distinguish process node types StartEvent, TaskInfo and EndEvent - - if (processNode instanceof TaskInfo) { - // TaskInfo types need to be executed - TaskInfo ti = (TaskInfo) processNode; - MDC.put(MDC_CTX_TASK_NAME, ti.getId()); - try { - log.info("Processing task '{}'.", ti.getId()); - Task task = createTaskInstance(ti); - if (task != null) { - try { - log.info("Executing task implementation for task '{}'.", ti.getId()); - log.debug("Execution context before task execution: {}", pi.getExecutionContext().keySet()); - pendingReq = task.execute(pendingReq, pi.getExecutionContext()); - log.info("Returned from execution of task '{}'.", ti.getId()); - log.debug("Execution context after task execution: {}", pi.getExecutionContext().keySet()); - } catch (Throwable t) { - throw new ProcessExecutionException("Error executing task '" + ti.getId() + "'.", t); - } - } else { - log.debug("No task implementing class set."); - } - } finally { - MDC.remove(MDC_CTX_TASK_NAME); - } - - } else if (processNode instanceof EndEvent) { - log.info("Finishing process instance '{}'.", pi.getId()); - - try { - piStoreDao.remove(pi.getId()); - - } catch (MOADatabaseException e) { - throw new ProcessExecutionException("Unable to remove process instance.", e); - - } - pi.setState(ProcessInstanceState.ENDED); - log.debug("Final process context: {}", pi.getExecutionContext().keySet()); - return; - } - - final ExpressionEvaluationContext expressionContext = new ExpressionEvaluationContextImpl(pi); - - // traverse pointer - Transition t = CollectionUtils.find(processNode.getOutgoingTransitions(), new Predicate<Transition>() { - @Override - public boolean evaluate(Transition transition) { - if (transitionConditionExpressionEvaluator != null && transition.getConditionExpression() != null) { - log.trace("Evaluating transition expression '{}'.", transition.getConditionExpression()); - return transitionConditionExpressionEvaluator.evaluate(expressionContext, transition.getConditionExpression()); - } - return true; - } - }); - if (t == null) { - throw new ProcessExecutionException("No valid transition starting from process node '" + processNode.getId()+ "'."); - } - log.trace("Found suitable transition: {}", t); - // update pointer - log.trace("Shifting process token from '{}' to '{}'.", pi.getNextId(), t.getTo().getId()); - pi.setNextId(t.getTo().getId()); - - // inspect current task - if (t.getTo() instanceof TaskInfo && (((TaskInfo) t.getTo()).isAsync())) { - // immediately return in case of asynchonous task - log.info("Suspending process instance '{}' for asynchronous task '{}'.", pi.getId(), t.getTo().getId()); - pi.setState(ProcessInstanceState.SUSPENDED); - return; - } - - // continue execution in case of StartEvent or Task - if (processNode instanceof StartEvent || processNode instanceof TaskInfo) { - execute(pi, pendingReq); - } - } - - @Override - public ProcessInstance getProcessInstance(String processInstanceId) { - - ProcessInstance processInstance; - try { - processInstance = loadProcessInstance(processInstanceId); - - } catch (MOADatabaseException e) { - throw new RuntimeException("The process instance '" + processInstanceId + "' could not be retrieved.", e); - } - - if (processInstance == null) { - throw new IllegalArgumentException("The process instance '" + processInstanceId + "' does not/no longer exist."); - } - - return processInstance; - } - - /** - * Persists a {@link ProcessInstance} to the database. - * @param processInstance The object to persist. - * @throws MOADatabaseException Thrown if an error occurs while accessing the database. - */ - private void saveOrUpdateProcessInstance(ProcessInstance processInstance) throws MOADatabaseException { - ProcessInstanceStore store = new ProcessInstanceStore(); - - ExecutionContext ctx = processInstance.getExecutionContext(); - - Map<String, Serializable> ctxData = new HashMap<String, Serializable>(); - for (String key : ctx.keySet()) { - ctxData.put(key, ctx.get(key)); - } - store.setExecutionContextData(ctxData); - - store.setNextTaskId(processInstance.getNextId()); - store.setProcessDefinitionId(processInstance.getProcessDefinition().getId()); - - store.setProcessInstanceId(processInstance.getId()); - store.setProcessState(processInstance.getState()); - - piStoreDao.saveOrUpdate(store); - } - - /** - * Load a {@link ProcessInstance} with a certain id from the database. - * @param processInstanceId The process instance id - * @return The process instance corresponding to the id or {@code null} if no such object is found. - * @throws MOADatabaseException Thrown if an error occurs while accessing the database. - */ - private ProcessInstance loadProcessInstance(String processInstanceId) throws MOADatabaseException { - - ProcessInstanceStore piStore = piStoreDao.load(processInstanceId); - - if (piStore == null) { - return null; - } - - ExecutionContext executionContext = new ExecutionContextImpl(piStore.getProcessInstanceId()); - - Map<String, Serializable> executionContextData = piStore.getExecutionContextData(); - for (String key : executionContextData.keySet()) { - executionContext.put(key, executionContextData.get(key)); - } - - ProcessInstance pi = new ProcessInstance(processDefinitions.get(piStore.getProcessDefinitionId()), executionContext); - pi.setNextId(piStore.getNextTaskId()); - pi.setState(piStore.getProcessState()); - - return pi; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.process.ProcessEngine#deleteProcessInstance(java.lang.String) - */ - @Override - public void deleteProcessInstance(String processInstanceId) throws ProcessExecutionException { - if (MiscUtil.isEmpty(processInstanceId)) { - throw new ProcessExecutionException("Unable to remove process instance: ProcessInstanceId is empty"); - - } - - try { - piStoreDao.remove(processInstanceId); - - } catch (MOADatabaseException e) { - throw new ProcessExecutionException("Unable to remove process instance.", e); - - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessExecutionException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessExecutionException.java deleted file mode 100644 index 821bbe6dc..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessExecutionException.java +++ /dev/null @@ -1,36 +0,0 @@ -package at.gv.egovernment.moa.id.process; - -/** - * Indicates a problem when executing a process. - * - * @author tknall - * - */ -public class ProcessExecutionException extends Exception { - - private static final long serialVersionUID = 1L; - - /** - * Creates a new process execution exception providing a {@code message} describing the reason and the respective - * {@code cause}. - * - * @param message - * The message. - * @param cause - * The cause. - */ - public ProcessExecutionException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Creates a new process execution exception providing a {@code message} describing the reason. - * - * @param message - * The message. - */ - public ProcessExecutionException(String message) { - super(message); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java deleted file mode 100644 index a6cf3b57f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstance.java +++ /dev/null @@ -1,164 +0,0 @@ -package at.gv.egovernment.moa.id.process; - -import java.io.Serializable; -import java.util.Date; - -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.time.DurationFormatUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.process.model.ProcessDefinition; -import at.gv.egovernment.moa.id.process.support.SecureRandomHolder; - -/** - * Represents a process being executed. The process instance provides information about the process and its state. - * - * @author tknall - * - */ -public class ProcessInstance implements Serializable { - - private static final long serialVersionUID = 1L; - private static final int RND_ID_LENGTH = 22; - - private ProcessDefinition processDefinition; - private String nextId; - private Date lru; - private ExecutionContext executionContext; - private ProcessInstanceState state = ProcessInstanceState.NOT_STARTED; - - private Logger log = LoggerFactory.getLogger(getClass()); - - /** - * Creates a new process instance, based on a given process definition and a - * given execution context. If the given execution context is {@code null} a new execution context will be created.<p/> - * The process instance id of the execution context will be newly generated if it is {@code null} in the execution context. - * - * @param processDefinition - * The process definition. - * @param executionContext - * The execution context (may be {@code null}). If {@code null} a new execution context will be created internally. - */ - ProcessInstance(ProcessDefinition processDefinition, ExecutionContext executionContext) { - this.processDefinition = processDefinition; - nextId = processDefinition.getStartEvent().getId(); - if (executionContext == null) { - executionContext = new ExecutionContextImpl(); - } - if (executionContext.getProcessInstanceId() == null) { - String pdIdLocalPart = RandomStringUtils.random(RND_ID_LENGTH, 0, 0, true, true, null, - SecureRandomHolder.getInstance()); - executionContext.setProcessInstanceId(this.processDefinition.getId() + "-" + pdIdLocalPart); - } else { - log.debug("Using process instance id from execution context."); - } - log.debug("Creating process instance with id '{}'.", executionContext.getProcessInstanceId()); - this.executionContext = executionContext; - touch(); - } - - /** - * Returns the underlying process definition. - * - * @return The underlying process definition. - */ - ProcessDefinition getProcessDefinition() { - touch(); - return processDefinition; - } - - /** - * Returns the id of the process node to be executed next. - * - * @return The process node pointer indicating the process node to be executed next. - */ - public String getNextId() { - touch(); - return nextId; - } - - /** - * Sets the internal pointer to the process node to be executed next. - * - * @param nextId - * The process node id to be executed next. - */ - void setNextId(String nextId) { - touch(); - this.nextId = nextId; - } - - /** - * Returns the current state of the process instance. - * - * @return The current state. - */ - public ProcessInstanceState getState() { - touch(); - return state; - } - - /** - * Sets the current state of the process instance. - * - * @param state - * The current state. - */ - void setState(ProcessInstanceState state) { - touch(); - this.state = state; - } - - public String getId() { - touch(); - return executionContext.getProcessInstanceId(); - } - - /** - * Updates the last recently used date of the process instance. - */ - private void touch() { - lru = new Date(); - } - - /** - * Returns the date the process instance has been accessed last. - * - * @return The last recently used date. - */ - Date getLru() { - return lru; - } - - /** - * Returns the associated execution context. - * @return The execution context (never {@code null}). - */ - public ExecutionContext getExecutionContext() { - touch(); - return executionContext; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("ProcessInstance ["); - builder.append("id=").append(executionContext.getProcessInstanceId()); - builder.append(", idle since=").append( - DurationFormatUtils.formatDurationWords(new Date().getTime() - this.lru.getTime(), true, true)); - if (processDefinition != null) { - builder.append(", processDefinition.id="); - builder.append(processDefinition.getId()); - } - if (nextId != null) { - builder.append(", nextId="); - builder.append(nextId); - } - builder.append(", executionContext=").append(executionContext); - builder.append("]"); - return builder.toString(); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstanceState.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstanceState.java deleted file mode 100644 index 2765283a0..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/ProcessInstanceState.java +++ /dev/null @@ -1,30 +0,0 @@ -package at.gv.egovernment.moa.id.process; - -/** - * Represents a certain process instance state. - * @author tknall - * - */ -public enum ProcessInstanceState { - - /** - * Indicates that the process with this process instance has not yet been started. - */ - NOT_STARTED, - - /** - * Indicates that the process is currently running. - */ - STARTED, - - /** - * Indicates that the process has been suspended until being waken up by someonce calling {@code signal}. - */ - SUSPENDED, - - /** - * Indicates that the process has been completed. - */ - ENDED - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExecutionContext.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExecutionContext.java deleted file mode 100644 index 4a9dfc336..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExecutionContext.java +++ /dev/null @@ -1,63 +0,0 @@ -package at.gv.egovernment.moa.id.process.api; - -import java.io.Serializable; -import java.util.Set; - -/** - * Encapsulates data needed for or provided by task execution. - * - * @author tknall - * - */ -public interface ExecutionContext extends Serializable { - - /** - * Returns the identifier of underlying process instance. - * - * @return The identifier of the process instance. - */ - String getProcessInstanceId(); - - /** - * Sets the identifier of underlying process instance. - * - * @param processInstanceId - * The identifier of the process instance. - */ - void setProcessInstanceId(String processInstanceId); - - /** - * Stores a serializable object using {@code key}. - * - * @param key - * The key under that the {@code object} should be stored. - * @param object The object to be stored. - */ - void put(String key, Serializable object); - - /** - * Returns an serializable object stored within this process context using {@code key}. - * - * @param key - * The key that has been used to store the serializable object (may be {@code null}). - * @return The object or {@code null} in case the key does not relate to a stored object or the stored object itself - * was {@code null}. - */ - Serializable get(String key); - - /** - * Removes the object stored using {@code key}. - * @param key - * The key that has been used to store the serializable object (may be {@code null}). - * @return The object that has been removed or {@code null} there was no object stored using {@code key}. - */ - Serializable remove(String key); - - /** - * Returns an unmodifiable set containing the stored keys. - * - * @return The keyset (never {@code null}). - */ - Set<String> keySet(); - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java deleted file mode 100644 index 94854dcad..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluationContext.java +++ /dev/null @@ -1,23 +0,0 @@ -package at.gv.egovernment.moa.id.process.api; - -import java.io.Serializable; -import java.util.Map; - -import at.gv.egovernment.moa.id.process.model.Transition; - -/** - * Context used for evaluation of condition expressions set for {@linkplain Transition Transitions}. - * - * @author tknall - * - */ -public interface ExpressionEvaluationContext extends Serializable { - - /** - * Returns the context data map used for expression evaluation. - * - * @return An unmodifiable map (never {@code null}). - */ - Map<String, Serializable> getCtx(); - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluator.java deleted file mode 100644 index fe0743201..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/ExpressionEvaluator.java +++ /dev/null @@ -1,25 +0,0 @@ -package at.gv.egovernment.moa.id.process.api; - -/** - * Evaluates a given {@code expression} returning a boolean value. - * - * @author tknall - */ -public interface ExpressionEvaluator { - - /** - * Evaluates a given {@code expression} returning a boolean value. - * - * @param expressionContext - * The context which can be used for evaluation of the expression. - * @param expression - * The expression resulting in a boolean (must not be {@code null}). - * @return A boolean value. - * @throws IllegalArgumentException - * In case of an invalid {@code expression}. - * @throws NullPointerException - * In case of a {@code null} expression. - */ - boolean evaluate(ExpressionEvaluationContext expressionContext, String expression); - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java deleted file mode 100644 index cff85ad60..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/api/Task.java +++ /dev/null @@ -1,26 +0,0 @@ -package at.gv.egovernment.moa.id.process.api; - -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.commons.api.IRequest; - - -/** - * Represents a single task to be performed upon process execution. - * - * @author tknall - * - */ -public interface Task { - - /** - * Executes this task. - * @param pendingReq - * Provides the current processed protocol request - * @param executionContext - * Provides execution related information. - * @return The pending-request object, because Process-management works recursive - * @throws Exception An exception upon task execution. - */ - IRequest execute(IRequest pendingReq, ExecutionContext executionContext) throws TaskExecutionException; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java deleted file mode 100644 index 3620f2950..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStore.java +++ /dev/null @@ -1,91 +0,0 @@ -package at.gv.egovernment.moa.id.process.dao; - -import java.io.Serializable; -import java.util.Map; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.EnumType; -import javax.persistence.Enumerated; -import javax.persistence.Id; -import javax.persistence.Lob; -import javax.persistence.Table; - -import org.hibernate.internal.util.SerializationHelper; - -import at.gv.egovernment.moa.id.process.ProcessInstanceState; - -@Entity -@Table(name = "processinstance") -public class ProcessInstanceStore implements Serializable{ - - private static final long serialVersionUID = -6147519767313903808L; - - /** - * A process instance identifier qualifies as natural primary key by satisfying these requirements - * ("unique, constant, required"): - * <ul> - * <li>unique value</li> - * <li>never changes (immutable)</li> - * <li>never {@code null}</li> - * </ul> - */ - @Id - private String processInstanceId; - - @Column(name = "processDefinitionId", nullable = false) - private String processDefinitionId; - - @Column(name = "nextTaskId", nullable = false) - private String nextTaskId; - - @Column(name = "processState", nullable = false) - @Enumerated(value = EnumType.STRING) - private ProcessInstanceState processState; - - @Column(name = "executionContextData", nullable = false) - @Lob - private byte[] executionContextData; - - public String getProcessInstanceId() { - return processInstanceId; - } - - public String getProcessDefinitionId() { - return processDefinitionId; - } - - public String getNextTaskId() { - return nextTaskId; - } - - public ProcessInstanceState getProcessState() { - return processState; - } - - @SuppressWarnings("unchecked") - public Map<String, Serializable> getExecutionContextData() { - return (Map<String, Serializable>) SerializationHelper.deserialize(executionContextData); - } - - public void setProcessInstanceId(String processInstanceId) { - this.processInstanceId = processInstanceId; - } - - public void setProcessDefinitionId(String processDefinitionId) { - this.processDefinitionId = processDefinitionId; - } - - public void setNextTaskId(String nextTaskId) { - this.nextTaskId = nextTaskId; - } - - public void setProcessState(ProcessInstanceState processState) { - this.processState = processState; - } - - public void setExecutionContextData(Map<String, Serializable> executionContextData) { - this.executionContextData = SerializationHelper.serialize((Serializable) executionContextData); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java deleted file mode 100644 index 57ce70c08..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAO.java +++ /dev/null @@ -1,43 +0,0 @@ -package at.gv.egovernment.moa.id.process.dao; - -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.process.ProcessInstance; - -public interface ProcessInstanceStoreDAO { - - /** - * Stores a {@link ProcessInstance} defined by {@code pIStore} in the - * database. - * - * @param pIStore - * the {@link ProcessInstanceStore} to persist. - * @throws MOADatabaseException - * is thrown if a problem occurs while accessing the database. - */ - void saveOrUpdate(ProcessInstanceStore pIStore) throws MOADatabaseException; - - /** - * Returns a {@link ProcessInstanceStore}, defined by - * {@code processInstanceID} from the database, or {@code null} if the - * object could not be found. - * - * @param processInstanceId - * the id of the {@code ProcessInstanceStore} to retrieve. - * @return a ProcessInstanceStore, or {@code null}. - * @throws MOADatabaseException - * is thrown if a problem occurs while accessing the database. - */ - ProcessInstanceStore load(String processInstanceId) throws MOADatabaseException; - - /** - * Deletes the {@link ProcessInstance} corresponding with the - * {@code processInstanceId}. - * - * @param processInstanceId - * the id of the {@code ProcessInstance} to be deleted. - * @throws MOADatabaseException - * is thrown if a problem occurs while accessing the database. - */ - void remove(String processInstanceId) throws MOADatabaseException; - -} 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 deleted file mode 100644 index 428931b5e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ /dev/null @@ -1,93 +0,0 @@ -package at.gv.egovernment.moa.id.process.dao; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; - -/** - * Database backed implementation of the {@link ProcessInstanceStoreDAO} - * interface. - */ -@Service("ProcessInstanceStoreage") -public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { - - private Logger log = LoggerFactory.getLogger(getClass()); - - @Autowired ITransactionStorage transactionStorage; - - @Override - public void saveOrUpdate(ProcessInstanceStore pIStore) throws MOADatabaseException { - try { - transactionStorage.put(pIStore.getProcessInstanceId(), pIStore, -1); - -// MOASessionDBUtils.saveOrUpdate(pIStore); - log.debug("Store process instance with='{}' in the database.", pIStore.getProcessInstanceId()); - } catch (MOADatabaseException e) { - log.warn("ProcessInstanceStore could not be persisted to the database."); - throw e; - } - } - - @Override - public ProcessInstanceStore load(String processInstanceId) throws MOADatabaseException { - - log.debug("Retrieve the ProcessInstanceStore for id='{}' from the database.", processInstanceId); - - -// Session session = MOASessionDBUtils.getCurrentSession(); -// - ProcessInstanceStore result = null; -// Transaction tx = null; -// synchronized (session) { - try { - - result = transactionStorage.get(processInstanceId, ProcessInstanceStore.class); - -// tx = session.beginTransaction(); -// // select all where processInstanceId equals processInstanceId -// Criteria criteria = session.createCriteria(ProcessInstanceStore.class); -// criteria.add(Restrictions.eq("processInstanceId", processInstanceId)); -// result = (ProcessInstanceStore) criteria.uniqueResult(); -// tx.commit(); -// - } catch (Exception e) { - log.error("There are multiple persisted processes with the same process instance id '{}'", - processInstanceId); -// if (tx != null) { -// tx.rollback(); -// } - throw e; - } finally { - //MOASessionDBUtils.closeSession(); - } -// } - if (result != null) { - log.debug("Found process instance store for instance '{}'.", processInstanceId); - } else { - log.debug("Unable to find process instance store for instance '{}'.", processInstanceId); - } - return result; - } - - @Override - public void remove(String processInstanceId) throws MOADatabaseException { - - log.debug("Delete the ProcessInstanceStore for id='{}' from the database.", processInstanceId); - //ProcessInstanceStore toBeDeleted = load(processInstanceId); - - if (transactionStorage.containsKey(processInstanceId)) { - transactionStorage.remove(processInstanceId); -// if (!MOASessionDBUtils.delete(toBeDeleted)) { -// log.warn("Could not delete the ProcessInstanceStore with process instance id '{}'", processInstanceId); -// throw new MOADatabaseException("Could not delete the ProcessInstanceStore with process instance id '" -// + processInstanceId + "'."); -// } - } else - log.trace("ProcessInstanceStore for id='{}' was not found and could therefore not be deleted.", processInstanceId); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/EndEvent.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/EndEvent.java deleted file mode 100644 index 49fb082ea..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/EndEvent.java +++ /dev/null @@ -1,42 +0,0 @@ -package at.gv.egovernment.moa.id.process.model; - -import java.io.Serializable; - -import org.apache.commons.collections4.CollectionUtils; - -/** - * Represents an end event. Process execution terminates when an end event is reached. - * - * @author tknall - */ -public class EndEvent extends ProcessNode implements Serializable { - - private static final long serialVersionUID = 1L; - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("EndEvent ["); - if (getId() != null) { - builder.append("id="); - builder.append(getId()); - } - if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("incomingTransitions="); - builder.append(getIncomingTransitions()); - } - if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("outgoingTransitions="); - builder.append(getOutgoingTransitions()); - } - builder.append("]"); - return builder.toString(); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java deleted file mode 100644 index 518409ecf..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessDefinition.java +++ /dev/null @@ -1,158 +0,0 @@ -package at.gv.egovernment.moa.id.process.model; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Objects; - -import at.gv.egovernment.moa.id.process.ProcessDefinitionParser; - -/** - * Represents a single process definition containing - * <ul> - * <li>a {@link StartEvent},</li> - * <li>one or more {@linkplain TaskInfo Tasks},</li> - * <li>one or more {@linkplain EndEvent EndEvents} and</li> - * <li>some {@linkplain Transition Transitions} linking StartEvents, Tasks and EndEvents. - * </ul> - * - * @author tknall - * - */ -public class ProcessDefinition { - - private String id; - private StartEvent startEvent; - private Map<String, TaskInfo> taskInfos = new LinkedHashMap<>(); - private Map<String, EndEvent> endEvents = new LinkedHashMap<>(); - - /** - * Returns the unique identifier of the process definition. - * - * @return The unique identifier (never {@code null} if process definition comes from - * {@link ProcessDefinitionParser}). - */ - public String getId() { - return id; - } - - /** - * Sets the unique identifier of the process definition. - * - * @param id - * The unique identifier. - */ - public void setId(String id) { - this.id = id; - } - - /** - * Returns the start event of the process definition. - * - * @return The start event (never {@code null} if process definition comes from {@link ProcessDefinitionParser}). - */ - public StartEvent getStartEvent() { - return startEvent; - } - - /** - * Sets the start event of the process definition. - * - * @param startEvent - * The start event. - */ - public void setStartEvent(StartEvent startEvent) { - this.startEvent = startEvent; - } - - /** - * Returns a map containing the tasks of the process definition. - * - * @return The tasks (map is never {@code null} if process definition comes from {@link ProcessDefinitionParser}). - */ - public Map<String, TaskInfo> getTaskInfos() { - return taskInfos; - } - - /** - * Sets the map containing the tasks. - * - * @param taskInfos - * The map containing the tasks. - */ - public void setTaskInfos(Map<String, TaskInfo> taskInfos) { - this.taskInfos = taskInfos; - } - - /** - * Returns a map containing the end events of the process description. - * - * @return The map containing the end events (map is never {@code null} if process definition comes from - * {@link ProcessDefinitionParser}). - */ - public Map<String, EndEvent> getEndEvents() { - return endEvents; - } - - /** - * Sets a map containing the end events of the process description. - * - * @param endEvents - * The map containing the end events. - */ - public void setEndEvents(Map<String, EndEvent> endEvents) { - this.endEvents = endEvents; - } - - /** - * Returns the process node associated with the given {@code id}. - * - * @param id - * The identifier of the process node. - * @return The process node (may be {code null} when no process node with the given {@code id} exists). - */ - public ProcessNode getProcessNode(String id) { - Objects.requireNonNull(id, "Identifier must not be null."); - if (startEvent != null && id.equals(startEvent.getId())) { - return startEvent; - } - TaskInfo task = taskInfos.get(id); - if (task != null) { - return task; - } - return endEvents.get(id); - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - if (id != null) { - builder.append("id="); - builder.append(id); - } - if (startEvent != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("startEvent="); - builder.append(startEvent); - } - if (taskInfos != null && !taskInfos.isEmpty()) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("tasksInfos="); - builder.append(taskInfos.values()); - } - if (endEvents != null && !endEvents.isEmpty()) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("endEvents="); - builder.append(endEvents.values()); - } - builder.insert(0, "ProcessDefinition ["); - builder.append("]"); - return builder.toString(); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java deleted file mode 100644 index 42f2e3cc2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/ProcessNode.java +++ /dev/null @@ -1,69 +0,0 @@ -package at.gv.egovernment.moa.id.process.model; - -import java.util.ArrayList; -import java.util.List; - -import at.gv.egovernment.moa.id.process.ProcessDefinitionParser; - -/** - * Represents a {@link StartEvent}, an {@link EndEvent} or a {@linkplain TaskInfo Task}. - * @author tknall - * - */ -public abstract class ProcessNode { - - private String id; - private List<Transition> outgoingTransitions = new ArrayList<>(); - private List<Transition> incomingTransitions = new ArrayList<>(); - - /** - * Returns the unique identifier of the process node. - * - * @return The unique identifier (never {@code null} if process node comes from a process definition from - * {@link ProcessDefinitionParser}). - */ - public String getId() { - return id; - } - - /** - * Sets the unique identifier of the process node. - * @param id The unique identifier. - */ - public void setId(String id) { - this.id = id; - } - - /** - * Returns a list of transitions pointing from this process node to another one. - * @return A list of transitions (never {@code null} if process node comes from a process definition from {@link ProcessDefinitionParser}). - */ - public List<Transition> getOutgoingTransitions() { - return outgoingTransitions; - } - - /** - * Sets the list of transitions pointing from this process node to another one. - * @param outgoingTransitions The list of transitions originating from this process node. - */ - public void setOutgoingTransitions(List<Transition> outgoingTransitions) { - this.outgoingTransitions = outgoingTransitions; - } - - /** - * Returns a list of transitions pointing from another process node to this one. - * @return A list of transitions (never {@code null} if process node comes from a process definition from {@link ProcessDefinitionParser}). - */ - public List<Transition> getIncomingTransitions() { - return incomingTransitions; - } - - /** - * Sets the list of transitions pointing from another process node to this one. - * @param incomingTransitions A list of transitions pointing to this process node. - */ - public void setIncomingTransitions(List<Transition> incomingTransitions) { - this.incomingTransitions = incomingTransitions; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/StartEvent.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/StartEvent.java deleted file mode 100644 index 60175e09c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/StartEvent.java +++ /dev/null @@ -1,45 +0,0 @@ -package at.gv.egovernment.moa.id.process.model; - -import java.io.Serializable; - -import org.apache.commons.collections4.CollectionUtils; - -/** - * Represents a start event. Each process description contains a single start event. Process execution starts with a - * start event. - * - * @author tknall - * - */ -public class StartEvent extends ProcessNode implements Serializable { - - private static final long serialVersionUID = 1L; - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - builder.append("StartEvent ["); - if (getId() != null) { - builder.append("id="); - builder.append(getId()); - } - if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("incomingTransitions="); - builder.append(getIncomingTransitions()); - } - if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("outgoingTransitions="); - - builder.append(getOutgoingTransitions()); - } - builder.append("]"); - return builder.toString(); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java deleted file mode 100644 index 78a9d6a0a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/TaskInfo.java +++ /dev/null @@ -1,94 +0,0 @@ -package at.gv.egovernment.moa.id.process.model; - -import java.io.Serializable; - -import org.apache.commons.collections4.CollectionUtils; - -import at.gv.egovernment.moa.id.process.api.Task; - -/** - * Represents information about a single task to be performed upon process execution. - * @author tknall - * - */ -public class TaskInfo extends ProcessNode implements Serializable { - - private static final long serialVersionUID = 1L; - private static final boolean DEFAULT_ASYNC = false; - - private String taskImplementingClass; - private boolean async = DEFAULT_ASYNC; - - /** - * Determines if the task is marked asynchronous ({@code true}) or synchronous ({@code false}). - * @return A flag indicating if the task should be executed asynchronously or synchronously. (Default: {@code false}) - */ - public boolean isAsync() { - return async; - } - - /** - * Marks a task to executed asynchronously ({@code true}) or synchronously ({@code false}). - * @param async The flag. - */ - public void setAsync(boolean async) { - this.async = async; - } - - /** - * Returns the class that implements the actual task (must implement {@link Task}). - * @return The task implementing class. - */ - public String getTaskImplementingClass() { - return taskImplementingClass; - } - - /** - * Sets the class that implements the actual task (must implement {@link Task}). - * @param taskImplementingClass The task implementing class. - */ - public void setTaskImplementingClass(String taskImplementingClass) { - this.taskImplementingClass = taskImplementingClass; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - if (getId() != null) { - builder.append("id="); - builder.append(getId()); - } - if (async != DEFAULT_ASYNC) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("async="); - builder.append(async); - } - if (taskImplementingClass != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("taskImplementingClass="); - builder.append(taskImplementingClass); - } - if (CollectionUtils.isNotEmpty(getIncomingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("incomingTransitions="); - builder.append(getIncomingTransitions()); - } - if (CollectionUtils.isNotEmpty(getOutgoingTransitions())) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("outgoingTransitions="); - builder.append(getOutgoingTransitions()); - } - builder.insert(0, "TaskInfo ["); - builder.append("]"); - return builder.toString(); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java deleted file mode 100644 index bc3005534..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/model/Transition.java +++ /dev/null @@ -1,136 +0,0 @@ -package at.gv.egovernment.moa.id.process.model; - -import java.io.Serializable; - -import at.gv.egovernment.moa.id.process.ProcessDefinitionParser; - -/** - * Represents a single transition from a {@link StartEvent} or {@linkplain TaskInfo Task} to another - * {@linkplain TaskInfo Task} or {@link EndEvent}. - * - * @author tknall - * - */ -public class Transition implements Serializable { - - private static final long serialVersionUID = 1L; - - private String id; - private String conditionExpression; - private ProcessNode from; - private ProcessNode to; - - /** - * Returns the process node (effectively a {@link StartEvent} or {@linkplain TaskInfo Task}) the transition is - * pointing from. - * - * @return The transition's source process node (never {@code null} if transition comes from a process definition - * from {@link ProcessDefinitionParser}). - */ - public ProcessNode getFrom() { - return from; - } - - /** - * Sets the process node the transition is pointing from. - * - * @param from - * The transition's source process node. - */ - public void setFrom(ProcessNode from) { - this.from = from; - } - - /** - * Returns the process node (effectively a {@linkplain TaskInfo Task} or {@link EndEvent}) the transition is - * pointing to. - * - * @return The transition's destination process node (never {@code null} if transition comes from a process - * definition from {@link ProcessDefinitionParser}). - */ - public ProcessNode getTo() { - return to; - } - - /** - * Sets the process node the transition is pointing to. - * - * @param to - * The transition's destination process node. - */ - public void setTo(ProcessNode to) { - this.to = to; - } - - /** - * Returns the unique identifier of the transition. - * - * @return The unique identifier (may be {@code null}). - */ - public String getId() { - return id; - } - - /** - * Sets the unique identifier of the transition. - * - * @param id - * The unique identifier. - */ - public void setId(String id) { - this.id = id; - } - - /** - * Returns the condition expression for this transition. - * - * @return The condition expression (may be {@code null}). - */ - public String getConditionExpression() { - return conditionExpression; - } - - /** - * Sets the condition expression for this transition. - * - * @param conditionExpression - * The condition expression. - */ - public void setConditionExpression(String conditionExpression) { - this.conditionExpression = conditionExpression; - } - - @Override - public String toString() { - StringBuilder builder = new StringBuilder(); - if (id != null) { - builder.append("id="); - builder.append(id); - } - if (from != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("from.id="); - builder.append(from.getId()); - } - if (to != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("to.id="); - builder.append(to.getId()); - } - if (conditionExpression != null) { - if (builder.length() > 0) { - builder.append(", "); - } - builder.append("conditionExpression="); - builder.append(conditionExpression); - } - builder.insert(0, "Transition ["); - builder.append("]"); - return builder.toString(); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java deleted file mode 100644 index 5b30c7172..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/spring/SpringExpressionEvaluator.java +++ /dev/null @@ -1,61 +0,0 @@ -package at.gv.egovernment.moa.id.process.spring; - -import java.util.Objects; - -import javax.annotation.PostConstruct; - -import org.apache.commons.lang3.BooleanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.expression.BeanFactoryResolver; -import org.springframework.expression.Expression; -import org.springframework.expression.ExpressionParser; -import org.springframework.expression.spel.standard.SpelExpressionParser; -import org.springframework.expression.spel.support.StandardEvaluationContext; - -import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; -import at.gv.egovernment.moa.id.process.api.ExpressionEvaluator; -import at.gv.egovernment.moa.id.process.model.Transition; - -/** - * Expression evaluator for processing {@link Transition} conditions allowing to reference Spring beans from the - * application context. - * - * @author tknall - * - */ -public class SpringExpressionEvaluator implements ExpressionEvaluator { - - private Logger log = LoggerFactory.getLogger(getClass()); - private ExpressionParser parser = new SpelExpressionParser(); - private StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); - - @Autowired(required = false) - private ApplicationContext ctx; - - @PostConstruct - private void init() { - if (ctx != null) { - evaluationContext.setBeanResolver(new BeanFactoryResolver(ctx)); - } - } - - @Override - public boolean evaluate(ExpressionEvaluationContext expressionContext, String expression) { - Objects.requireNonNull(expression, "Expression must not be null."); - log.trace("Evaluating '{}'.", expression); - - Expression expr = parser.parseExpression(expression); - Boolean result = expr.getValue(evaluationContext, expressionContext, Boolean.class); - if (result == null) { - log.warn("Evaluation of '{}' results in null-value.", expression); - } else { - log.debug("Expression '{}' -> {}", expression, result); - } - - return BooleanUtils.isTrue(result); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java deleted file mode 100644 index 738b58834..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/AbstractAuthSourceServlet.java +++ /dev/null @@ -1,116 +0,0 @@ -package at.gv.egovernment.moa.id.process.springweb; - -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.beans.factory.NoUniqueBeanDefinitionException; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.context.support.WebApplicationContextUtils; - -import at.gv.egovernment.moa.id.process.ProcessEngine; -import at.gv.egovernment.moa.id.process.ProcessInstance; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; - -/** - * Abstract HttpServlet that provides means for retrieving the process engine (Spring Web required) as well as - * retrieving the underlying process instance and execution context evaluating a certain request parameter. - * - * @author tknall - * - */ -public abstract class AbstractAuthSourceServlet extends HttpServlet { - - private static final long serialVersionUID = 1L; - - private ProcessEngine processEngine; - - /** - * Returns the name of the request parameter representing the respective instance id. - * <p/>Default is {@code processInstanceId}. - * @return The request parameter name. - */ - public String getProcessInstanceIdParameterName() { - return "processInstanceId"; - } - - /** - * Returns the underlying process engine instance. - * - * @return The process engine (never {@code null}). - * @throws NoSuchBeanDefinitionException - * if no {@link ProcessEngine} bean was found. - * @throws NoUniqueBeanDefinitionException - * if more than one {@link ProcessEngine} bean was found. - * @throws BeansException - * if a problem getting the {@link ProcessEngine} bean occurred. - * @throws IllegalStateException - * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a - * Spring web environment. - */ - public synchronized ProcessEngine getProcessEngine() { - if (processEngine == null) { - WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); - if (ctx == null) { - throw new IllegalStateException( - "Unable to find Spring WebApplicationContext. Servlet needs to be executed within a Spring web environment."); - } - processEngine = ctx.getBean(ProcessEngine.class); - } - return processEngine; - } - - /** - * Retrieves the process instance referenced by the request parameter {@link #getProcessInstanceIdParameterName()}. - * - * @param request - * The HttpServletRequest. - * @return The process instance (never {@code null}). - * @throws NoSuchBeanDefinitionException - * if no {@link ProcessEngine} bean was found. - * @throws NoUniqueBeanDefinitionException - * if more than one {@link ProcessEngine} bean was found. - * @throws BeansException - * if a problem getting the {@link ProcessEngine} bean occurred. - * @throws IllegalStateException - * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a - * Spring web environment. - * @throws IllegalArgumentException - * in case the process instance id referenced by the request parameter - * {@link #getProcessInstanceIdParameterName()} does not exist. - */ - public ProcessInstance getProcessInstance(HttpServletRequest request) { - String processInstanceId = StringUtils.trimToNull(request.getParameter(getProcessInstanceIdParameterName())); - if (processInstanceId == null) { - throw new IllegalArgumentException("Missing request parameter '" + getProcessInstanceIdParameterName() + "'."); - } - return getProcessEngine().getProcessInstance(processInstanceId); - } - - /** - * Retrieves the execution context for the respective process instance referenced by the request parameter - * {@link #getProcessInstanceIdParameterName()}. - * - * @param request - * The HttpServletRequest. - * @return The execution context (never {@code null}). - * @throws NoSuchBeanDefinitionException - * if no {@link ProcessEngine} bean was found. - * @throws NoUniqueBeanDefinitionException - * if more than one {@link ProcessEngine} bean was found. - * @throws BeansException - * if a problem getting the {@link ProcessEngine} bean occurred. - * @throws IllegalStateException - * if the Spring WebApplicationContext was not found, which means that the servlet is used outside a - * Spring web environment. - * @throws IllegalArgumentException - * in case the process instance id referenced by the request parameter - * {@link #getProcessInstanceIdParameterName()} does not exist. - */ - public ExecutionContext getExecutionContext(HttpServletRequest request) { - return getProcessInstance(request).getExecutionContext(); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java deleted file mode 100644 index dd0d87dd7..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/MoaIdTask.java +++ /dev/null @@ -1,99 +0,0 @@ -package at.gv.egovernment.moa.id.process.springweb; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.web.context.request.RequestAttributes; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; -import org.springframework.web.filter.RequestContextFilter; - -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.process.api.Task; - -/** - * Abstract task implementation providing {@link HttpServletRequest} and {@link HttpServletResponse}. - * <p/> - * Note that this abstract task requires the Spring (web) framework including a {@link RequestContextFilter} to be set - * within {@code web.xml}. - * - * <pre> - * ... - * <filter> - * <filter-name>requestContextFilter</filter-name> - * <filter-class>org.springframework.web.filter.RequestContextFilter</filter-class> - * </filter> - * <filter-mapping> - * <filter-name>requestContextFilter</filter-name> - * <url-pattern>/*</url-pattern> - * </filter-mapping> - * ... - * </pre> - * - * @author tknall - * @author tlenz - * - */ -public abstract class MoaIdTask implements Task { - - /** - * Executes the task providing the underlying {@link ExecutionContext} {@code executionContext} as well as the - * respective {@link HttpServletRequest} and {@link HttpServletResponse}. - * - * @param executionContext - * The execution context (never {@code null}). - * @param request - * The HttpServletRequest (never {@code null}). - * @param response - * The HttpServletResponse (never {@code null}). - * @throws IllegalStateException - * Thrown in case the task is nur being run within the required environment. Refer to javadoc for - * further information. - * @throws Exception - * Thrown in case of error executing the task. - */ - public abstract void execute(ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws TaskExecutionException; - - /** - * Executes the task providing the underlying {@link ExecutionContext} {@code executionContext} - * and the {@link IRequest} {@code pendingReq }as well as the - * respective {@link HttpServletRequest} and {@link HttpServletResponse}. - * - * This method sets the pending-request object of the task implementation and starts the - * {@code execute} method of the task - * - * @param pendingReq The pending-request object (never {@code null}). - * @param executionContext The execution context (never {@code null}). - * @param request The HttpServletRequest (never {@code null}). - * @param response The HttpServletResponse (never {@code null}). - * @return The pending-request object, because Process-management works recursive - * - * @throws IllegalStateException - * Thrown in case the task is being run within the required environment. Refer to javadoc for - * further information. - * @throws Exception - * Thrown in case of error executing the task. - */ - protected abstract IRequest internalExecute(IRequest pendingReq, ExecutionContext executionContext, HttpServletRequest request, - HttpServletResponse response) throws TaskExecutionException; - - @Override - public IRequest execute(IRequest pendingReq, ExecutionContext executionContext) throws TaskExecutionException { - RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); - if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) { - HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); - HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse(); - if (request == null || response == null) { - throw new IllegalStateException( - "Spring's RequestContextHolder did not provide HttpServletResponse. Did you forget to set the required org.springframework.web.filter.RequestContextFilter in your web.xml."); - } - return internalExecute(pendingReq, executionContext, request, response); - } else { - throw new IllegalStateException("Task needs to be executed within a Spring web environment."); - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java deleted file mode 100644 index af6822ba6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/springweb/SpringWebExpressionEvaluator.java +++ /dev/null @@ -1,143 +0,0 @@ -package at.gv.egovernment.moa.id.process.springweb; - -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Objects; - -import javax.annotation.PostConstruct; -import javax.servlet.http.HttpServletRequest; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.BooleanUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.expression.BeanFactoryResolver; -import org.springframework.expression.Expression; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import org.springframework.expression.ExpressionParser; -import org.springframework.expression.spel.standard.SpelExpressionParser; -import org.springframework.expression.spel.support.StandardEvaluationContext; - -import at.gv.egovernment.moa.id.process.api.ExpressionEvaluationContext; -import at.gv.egovernment.moa.id.process.api.ExpressionEvaluator; -import at.gv.egovernment.moa.id.process.model.Transition; - -/** - * Expression evaluator for processing {@link Transition} conditions allowing to - * <ul> - * <li>reference Spring beans from the application context using {@code @myBeanName...},</li> - * <li>{@link ExecutionContext} properties using {@code ctx['property']},</li> - * <li>Multi valued {@link HttpServletRequest} parameters using {@code requestParameters['foo']} (keep in mind that this - * expression returns an array of String values) and</li> - * <li>Single valued {@link HttpServletRequest} parameters using {@code requestParameter['foo']}</li> - * </ul> - * - * @author tknall - * - */ -public class SpringWebExpressionEvaluator implements ExpressionEvaluator { - - private Logger log = LoggerFactory.getLogger(getClass()); - private ExpressionParser parser = new SpelExpressionParser(); - private StandardEvaluationContext evaluationContext = new StandardEvaluationContext(); - - @Autowired(required = false) - private ApplicationContext ctx; - - @Autowired(required = false) - private HttpServletRequest request; - - @PostConstruct - private void init() { - if (ctx != null) { - evaluationContext.setBeanResolver(new BeanFactoryResolver(ctx)); - } - } - - /** - * Evaluation context that provides access to {@link HttpServletRequest} parameters using - * {@code requestParameter['foo']} for single value parameters or {@code requestParameters['foo']} for multi value - * parameters. Basic calls to {@code ctx} will be delegated. - * - * @author tknall - * - */ - private class SpringWebExpressionEvaluationContext implements ExpressionEvaluationContext { - - private static final long serialVersionUID = 1L; - - /** - * Creates a new expression evaluation context, providing access to HttpServletRequest parameter(s). - * - * @param delegate - * The original {@link ExpressionEvaluationContext} to be delegated to for {@code ctx['foo']} - * expressions. - */ - public SpringWebExpressionEvaluationContext(ExpressionEvaluationContext delegate) { - this.delegate = delegate; - } - - private ExpressionEvaluationContext delegate; - - @Override - public Map<String, Serializable> getCtx() { - return delegate.getCtx(); - } - - @SuppressWarnings("unused") - public Map<String, String> getRequestParameter() { - if (request != null) { - Map<String, String> singleValueMap = new HashMap<String, String>(); - Iterator<Entry<String, String[]>> it = request.getParameterMap().entrySet().iterator(); - while (it.hasNext()) { - Entry<String, String[]> entry = it.next(); - if (ArrayUtils.isNotEmpty(entry.getValue())) { - singleValueMap.put(entry.getKey(), entry.getValue()[0]); - } - } - return singleValueMap; - } else { - return Collections.<String, String> emptyMap(); - } - } - - @SuppressWarnings("unused") - public Map<String, String[]> getRequestParameters() { - if (request != null) { - return request.getParameterMap(); - } else { - return Collections.<String, String[]> emptyMap(); - } - } - - } - - @Override - public boolean evaluate(ExpressionEvaluationContext expressionContext, String expression) { - Objects.requireNonNull(expression, "Expression must not be null."); - log.trace("Evaluating '{}'.", expression); - - Expression expr = parser.parseExpression(expression); - Boolean result = null; - try { - result = expr.getValue(evaluationContext, new SpringWebExpressionEvaluationContext(expressionContext), - Boolean.class); - if (result == null) { - log.warn("Evaluation of '{}' results in null-value.", expression); - } else { - log.debug("Expression '{}' -> {}", expression, result); - } - } catch (Exception e) { - log.warn("Expression '{}' could not be processed.", expression, e); - } - - return BooleanUtils.isTrue(result); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/support/SecureRandomHolder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/support/SecureRandomHolder.java deleted file mode 100644 index 72677739a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/support/SecureRandomHolder.java +++ /dev/null @@ -1,35 +0,0 @@ -package at.gv.egovernment.moa.id.process.support; - -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; - -/** - * Holder for a secure random instance following the initialization on demand holder design pattern. The secure random - * instance is a singleton that is initialized on first usage. - * - * @author tknall - * - */ -public class SecureRandomHolder { - - private SecureRandomHolder() { - } - - private static final SecureRandom SRND_INSTANCE; - static { - try { - SRND_INSTANCE = SecureRandom.getInstance("SHA1PRNG"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("Unable to instantiate SHA1PRNG.", e); - } - } - - /** - * Returns a secure random generator instance. - * @return The secure random instance. - */ - public static SecureRandom getInstance() { - return SecureRandomHolder.SRND_INSTANCE; - } - -}
\ No newline at end of file diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractAuthProtocolModulController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractAuthProtocolModulController.java deleted file mode 100644 index 9b30368e3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractAuthProtocolModulController.java +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - -import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.servlet.AbstractController; -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.data.IAuthenticationSession; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.AuthenticationManager; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IModulInfo; -import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ - -public abstract class AbstractAuthProtocolModulController extends AbstractController implements IModulInfo { - - public static final String FINALIZEPROTOCOL_ENDPOINT = "finalizeAuthProtocol"; - - @Autowired protected ApplicationContext applicationContext; - @Autowired private SSOManager ssomanager; - @Autowired protected AuthenticationManager authmanager; - @Autowired protected IAuthenticationSessionStoreage authenticatedSessionStorage; - @Autowired private AuthenticationDataBuilder authDataBuilder; - - /** - * Initialize an authentication process for this protocol request - * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @throws IOException - */ - protected void performAuthentication(HttpServletRequest req, HttpServletResponse resp, - RequestImpl pendingReq) throws IOException { - try { - if (pendingReq.isNeedAuthentication()) { - //request needs authentication --> start authentication process ... - - //load Parameters from OnlineApplicationConfiguration - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - - if (oaParam == null) { - throw new AuthenticationException("auth.00", new Object[] { pendingReq.getOAURL() }); - } - - - AuthenticationSession ssoMoaSession = authmanager.doAuthentication(req, resp, pendingReq); - if (ssoMoaSession != null) { - //authenticated MOASession already exists --> protocol-specific postProcessing can start directly - finalizeAuthenticationProcess(req, resp, pendingReq, ssoMoaSession); - - //transaction is finished, log transaction finished event - revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); - - } - - } else { - executeProtocolSpecificAction(req, resp, pendingReq, null); - - } - - } catch (Exception e) { - buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); - - removeUserSession(pendingReq, req, resp); - - } - } - - - protected String createNewSSOSessionCookie(HttpServletRequest req, HttpServletResponse resp, - IRequest pendingReq, IAuthenticationSession moaSession) { - Logger.debug("Add SSO information to MOASession."); - - //Store SSO information into database - String newSSOSessionId = ssomanager.createSSOSessionInformations(moaSession.getSessionID(), - pendingReq.getOAURL()); - - //set SSO cookie to response - if (MiscUtil.isNotEmpty(newSSOSessionId)) { - ssomanager.setSSOSessionID(req, resp, newSSOSessionId); - - } else { - ssomanager.deleteSSOSessionID(req, resp); - - } - - return newSSOSessionId; - } - - /** - * Finalize the requested protocol operation - * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @param moaSession MOASession object, which is used to generate the protocol specific authentication information - * @throws Exception - */ - protected void finalizeAuthenticationProcess(HttpServletRequest req, HttpServletResponse resp, - IRequest pendingReq, IAuthenticationSession moaSession) throws Exception { - - String newSSOSessionId = null; - - //if Single Sign-On functionality is enabled for this request - if (pendingReq.needSingleSignOnFunctionality()) { - newSSOSessionId = createNewSSOSessionCookie(req, resp, pendingReq, moaSession); - - } - - //build authenticationdata from session information and OA configuration - IAuthData authData = authDataBuilder.buildAuthenticationData(pendingReq, moaSession); - - //execute the protocol-specific action - SLOInformationInterface sloInformation = executeProtocolSpecificAction(req, resp, pendingReq, authData); - - //check if SSO - boolean isSSOCookieSetted = MiscUtil.isNotEmpty(newSSOSessionId); - - //Store OA specific SSO session information if an SSO cookie is set - if (isSSOCookieSetted) { - try { - AuthenticationSession internalDBSSOSession = null; - - //create new SSO session, if actually no SSO session exists - if (MiscUtil.isEmpty(pendingReq.getInternalSSOSessionIdentifier())) { - internalDBSSOSession = authenticatedSessionStorage.createInternalSSOSession(pendingReq); - authenticatedSessionStorage.addSSOInformation(internalDBSSOSession.getSessionID(), - newSSOSessionId, sloInformation, pendingReq); - - //MOA SSO-session already exists only update is required - } else if (MiscUtil.isNotEmpty(pendingReq.getInternalSSOSessionIdentifier()) && - moaSession instanceof AuthenticationSession) { - authenticatedSessionStorage.addSSOInformation(moaSession.getSessionID(), - newSSOSessionId, sloInformation, pendingReq); - - } else { - Logger.fatal("MOA-Session data object has a suspect or unsupported type:" + moaSession.getClass().getName() - + " pendingReq_internalSsoId:" + pendingReq.getInternalSSOSessionIdentifier()); - throw new AuthenticationException("1299", null); - - } - - } catch (AuthenticationException e) { - Logger.warn("SSO Session information can not be stored -> SSO is not enabled!"); - authmanager.performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); - - } - - } else { - //remove MOASession from database - authmanager.performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); - - } - - //Advanced statistic logging - statisticLogger.logSuccessOperation(pendingReq, authData, isSSOCookieSetted); - - } - - /** - * Executes the requested protocol action - * - * @param httpReq HttpServletRequest - * @param httpResp HttpServletResponse - * @param protocolRequest Authentication request which is actually in process - * @param authData Service-provider specific authentication data - * - * @return Return Single LogOut information or null if protocol supports no SSO - * - * @throws Exception - */ - private SLOInformationInterface executeProtocolSpecificAction(HttpServletRequest httpReq, HttpServletResponse httpResp, - IRequest pendingReq, IAuthData authData) throws Exception { - try { - // request needs no authentication --> start request processing - Class<?> clazz = Class.forName(pendingReq.requestedAction()); - if (clazz == null || - !IAction.class.isAssignableFrom(clazz)) { - Logger.fatal("Requested protocol-action processing Class is NULL or does not implement the IAction interface."); - throw new Exception("Requested protocol-action processing Class is NULL or does not implement the IAction interface."); - - } - - IAction protocolAction = (IAction) applicationContext.getBean(clazz); - return protocolAction.processRequest(pendingReq, httpReq, httpResp, authData); - - } catch (ClassNotFoundException e) { - Logger.fatal("Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); - throw new Exception("Requested Auth. protocol processing Class is NULL or does not implement the IAction interface."); - } - - } - - protected void removeUserSession(IRequest pendingReq, HttpServletRequest req, - HttpServletResponse resp) { - authmanager.performOnlyIDPLogOut(req, resp, pendingReq.getInternalSSOSessionIdentifier()); - - } - - protected void buildProtocolSpecificErrorResponse(Throwable throwable, HttpServletRequest req, - HttpServletResponse resp, IRequest protocolRequest) throws IOException { - try { - - Class<?> clazz = Class.forName(protocolRequest.requestedModule()); - - if (clazz == null || - !IModulInfo.class.isAssignableFrom(clazz)) { - Logger.fatal("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - throw new Exception("Requested protocol module Class is NULL or does not implement the IModulInfo interface."); - - } - - IModulInfo handlingModule = (IModulInfo) applicationContext.getBean(clazz); - - if (handlingModule.generateErrorMessage( - throwable, req, resp, protocolRequest)) { - - //log Error to technical log - logExceptionToTechnicalLog(throwable); - - //log Error Message - statisticLogger.logErrorOperation(throwable, protocolRequest); - - //write revision log entries - revisionsLogger.logEvent(protocolRequest, MOAIDEventConstants.TRANSACTION_ERROR, protocolRequest.getUniqueTransactionIdentifier()); - - return; - - } else { - handleErrorNoRedirect(throwable, req, resp, true); - - } - - } catch (Throwable e) { - handleErrorNoRedirect(throwable, req, resp, true); - - } - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IModulInfo#getName() - */ - @Override - public abstract String getName(); - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IModulInfo#getPath() - */ - @Override - public abstract String getPath(); - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IModulInfo#generateErrorMessage(java.lang.Throwable, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.moduls.IRequest) - */ - @Override - public abstract boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, - IRequest protocolRequest) throws Throwable; - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IModulInfo#validate(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.moduls.IRequest) - */ - @Override - public abstract boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending); - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/ProtocolFinalizationController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/ProtocolFinalizationController.java deleted file mode 100644 index 41a4c9835..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/ProtocolFinalizationController.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols; - -import java.io.IOException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.data.ExceptionContainer; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -@Controller -public class ProtocolFinalizationController extends AbstractAuthProtocolModulController { - - @RequestMapping(value = "/finalizeAuthProtocol", method = {RequestMethod.GET}) - public void finalizeAuthProtocol(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException, IOException { - - //read pendingRequest from http request - Object idObject = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_TARGET_PENDINGREQUESTID)); - IRequest pendingReq = null; - String pendingRequestID = null; - if (idObject != null && (idObject instanceof String)) { - pendingRequestID = (String) idObject; - pendingReq = requestStorage.getPendingRequest(pendingRequestID); - - } - - //receive an authentication error - String errorid = StringEscapeUtils.escapeHtml(req.getParameter(ERROR_CODE_PARAM)); - if (errorid != null) { - try { - //load stored exception from database - ExceptionContainer container = transactionStorage.get(errorid, ExceptionContainer.class); - if (container != null) { - //remove exception if it was found - transactionStorage.remove(errorid); - - Throwable throwable = container.getExceptionThrown(); - - if (pendingReq != null) { - //build protocol-specific error message if possible - buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); - - //remove active user-session - removeUserSession(pendingReq, req, resp); - - return; - - } else { - handleErrorNoRedirect(throwable, req, resp, true); - - } - } else { - handleErrorNoRedirect(new MOAIDException("auth.26", null), req, resp, false); - - } - - } catch (Throwable e) { - Logger.error(e); - handleErrorNoRedirect(e, req, resp, false); - - } - - // receive a pending request - } else { - if (pendingReq == null) { - Logger.error("No PendingRequest with ID " + pendingRequestID + " found.!"); - handleErrorNoRedirect(new MOAIDException("auth.28", new Object[]{pendingRequestID}), req, resp, false); - return; - - } - try { - Logger.debug("Finalize PendingRequest with ID " + pendingRequestID); - - //get MOA session data object from pending request - IAuthenticationSession pendingMoaSession = pendingReq.getMOASession(); - - //check if pending-request has 'abortedByUser' flag set - if (pendingReq.isAbortedByUser()) { - //send authentication aborted error to Service Provider - buildProtocolSpecificErrorResponse( - new AuthenticationException("auth.21", new Object[] {}), - req, resp, pendingReq); - - //do not remove the full active SSO-Session - // in case of only one Service-Provider authentication request is aborted - if ( !(pendingMoaSession.isAuthenticated() - && pendingReq.needSingleSignOnFunctionality()) ) { - removeUserSession(pendingReq, req, resp); - - } - - //check if MOASession and pending-request are authenticated - } else if (pendingMoaSession.isAuthenticated() && pendingReq.isAuthenticated()) { - finalizeAuthenticationProcess(req, resp, pendingReq, pendingMoaSession); - - } else { - //suspect state: pending-request is not aborted but also are not authenticated - Logger.error("MOASession oder Pending-Request are not authenticated --> Abort authentication process!"); - handleErrorNoRedirect(new MOAIDException("auth.20", null), req, resp, true); - - } - - } catch (Exception e) { - Logger.error("Finalize authentication protocol FAILED." , e); - buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); - - removeUserSession(pendingReq, req, resp); - - } - } - - //remove pending-request - if (pendingReq != null) { - requestStorage.removePendingRequest(pendingReq.getRequestID()); - revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); - - } - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController#getName() - */ - @Override - public String getName() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController#getPath() - */ - @Override - public String getPath() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController#generateErrorMessage(java.lang.Throwable, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.moduls.IRequest) - */ - @Override - public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, - IRequest protocolRequest) throws Throwable { - // TODO Auto-generated method stub - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController#validate(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.moduls.IRequest) - */ - @Override - public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) { - // TODO Auto-generated method stub - return false; - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BPKAttributeBuilder.java deleted file mode 100644 index c13c5e288..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BPKAttributeBuilder.java +++ /dev/null @@ -1,69 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.MiscUtil; - -public class BPKAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return BPK_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - String bpk = authData.getBPK(); - String type = authData.getBPKType(); - - if (MiscUtil.isEmpty(bpk)) - throw new UnavailableAttributeException(BPK_NAME); - - if (type.startsWith(Constants.URN_PREFIX_WBPK)) - type = type.substring((Constants.URN_PREFIX_WBPK + "+").length()); - - else if (type.startsWith(Constants.URN_PREFIX_CDID)) - type = type.substring((Constants.URN_PREFIX_CDID + "+").length()); - - else if (type.startsWith(Constants.URN_PREFIX_EIDAS)) - type = type.substring((Constants.URN_PREFIX_EIDAS + "+").length()); - - if (bpk.length() > BPK_MAX_LENGTH) { - bpk = bpk.substring(0, BPK_MAX_LENGTH); - } - - Logger.trace("Authenticate user with bPK/wbPK " + bpk + " and Type=" + type); - - return g.buildStringAttribute(BPK_FRIENDLY_NAME, BPK_NAME, type + ":" + bpk); - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(BPK_FRIENDLY_NAME, BPK_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java deleted file mode 100644 index f1d88f877..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class BirthdateAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return BIRTHDATE_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - if (authData.getDateOfBirth() != null) { - DateFormat pvpDateFormat = new SimpleDateFormat(BIRTHDATE_FORMAT_PATTERN); - String dateString = pvpDateFormat.format(authData.getDateOfBirth()); - - return g.buildStringAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME, dateString); - - } else { - //build empty attribute if no Birthday date is found (STORK2) - return g.buildEmptyAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME); - - } - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(BIRTHDATE_FRIENDLY_NAME, BIRTHDATE_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDAuthBlock.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDAuthBlock.java index 6f7c0dc97..139bb15cc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDAuthBlock.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDAuthBlock.java @@ -26,28 +26,37 @@ import java.io.IOException; import org.springframework.util.Base64Utils; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class EIDAuthBlock implements IPVPAttributeBuilder { public String getName() { return EID_AUTH_BLOCK_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { try { - String authblock = authData.getAuthBlock(); - if (MiscUtil.isNotEmpty(authblock)) { - return g.buildStringAttribute(EID_AUTH_BLOCK_FRIENDLY_NAME, EID_AUTH_BLOCK_NAME, - Base64Utils.encodeToString(authblock.getBytes("UTF-8"))); - } + if (authData instanceof IMOAAuthData) { + String authblock = ((IMOAAuthData)authData).getAuthBlock(); + if (MiscUtil.isNotEmpty(authblock)) { + return g.buildStringAttribute(EID_AUTH_BLOCK_FRIENDLY_NAME, EID_AUTH_BLOCK_NAME, + Base64Utils.encodeToString(authblock.getBytes("UTF-8"))); + } + + } else + Logger.info(EID_AUTH_BLOCK_FRIENDLY_NAME + " is only available in MOA-ID context"); } catch (IOException e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCcsURL.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCcsURL.java index 623acd18e..1e630cf16 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCcsURL.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCcsURL.java @@ -22,27 +22,36 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; +import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class EIDCcsURL implements IPVPAttributeBuilder { public String getName() { return EID_CCS_URL_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + String bkuurl = ((IMOAAuthData)authData).getBkuURL(); + if (MiscUtil.isNotEmpty(bkuurl)) + return g.buildStringAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME, bkuurl); + + + } else + Logger.info(EID_CCS_URL_FRIENDLY_NAME + " is only available in MOA-ID context"); - String bkuurl = authData.getBkuURL(); - if (MiscUtil.isNotEmpty(bkuurl)) - return g.buildStringAttribute(EID_CCS_URL_FRIENDLY_NAME, EID_CCS_URL_NAME, bkuurl); - else - throw new UnavailableAttributeException(EID_CCS_URL_NAME); + throw new UnavailableAttributeException(EID_CCS_URL_NAME); } public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java index b254bc305..95e6d5bca 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDCitizenQAALevelAttributeBuilder.java @@ -22,28 +22,43 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.logging.Logger; + @Deprecated +@PVPMETADATA public class EIDCitizenQAALevelAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return EID_CITIZEN_QAA_LEVEL_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + String qaaLevel = null; + if (((IMOAAuthData)authData).getQAALevel().startsWith(PVPConstants.STORK_QAA_PREFIX)) + qaaLevel = ((IMOAAuthData)authData).getQAALevel().substring(PVPConstants.STORK_QAA_PREFIX.length()); + else + qaaLevel = ((IMOAAuthData)authData).getQAALevel(); + + return g.buildIntegerAttribute(EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME, + EID_CITIZEN_QAA_LEVEL_NAME, Integer.valueOf(qaaLevel)); + + } else + Logger.info(EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME + " is only available in MOA-ID context"); - String qaaLevel = null; - if (authData.getQAALevel().startsWith(STORK_QAA_PREFIX)) - qaaLevel = authData.getQAALevel().substring(STORK_QAA_PREFIX.length()); - else - qaaLevel = authData.getQAALevel(); + throw new UnavailableAttributeException(EID_CITIZEN_QAA_LEVEL_NAME); - return g.buildIntegerAttribute(EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME, - EID_CITIZEN_QAA_LEVEL_NAME, Integer.valueOf(qaaLevel)); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIdentityLinkBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIdentityLinkBuilder.java deleted file mode 100644 index a01605986..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIdentityLinkBuilder.java +++ /dev/null @@ -1,67 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import java.io.IOException; - -import org.springframework.util.Base64Utils; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -import at.gv.egovernment.moa.logging.Logger; - -public class EIDIdentityLinkBuilder implements IPVPAttributeBuilder { - - public String getName() { - return EID_IDENTITY_LINK_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - try { - String ilAssertion = null; - - if (authData.getIdentityLink() == null) - throw new UnavailableAttributeException(EID_IDENTITY_LINK_NAME); - - ilAssertion = authData.getIdentityLink().getSerializedSamlAssertion(); - - return g.buildStringAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, - EID_IDENTITY_LINK_NAME, Base64Utils.encodeToString(ilAssertion.getBytes("UTF-8"))); - - } catch (IOException e) { - Logger.warn("IdentityLink serialization error.", e); - return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, - EID_IDENTITY_LINK_NAME); - } - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(EID_IDENTITY_LINK_FRIENDLY_NAME, - EID_IDENTITY_LINK_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIssuingNationAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIssuingNationAttributeBuilder.java deleted file mode 100644 index fc80ad7fe..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDIssuingNationAttributeBuilder.java +++ /dev/null @@ -1,52 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.util.MiscUtil; - -public class EIDIssuingNationAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return EID_ISSUING_NATION_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - String countryCode = authData.getCcc(); - if (MiscUtil.isNotEmpty(countryCode)) - return g.buildStringAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, - EID_ISSUING_NATION_NAME, countryCode); - - else - return null; - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, - EID_ISSUING_NATION_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSTORKTOKEN.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSTORKTOKEN.java index 71fc7966c..97bf2f78e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSTORKTOKEN.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSTORKTOKEN.java @@ -26,23 +26,27 @@ import java.io.IOException; import org.springframework.util.Base64Utils; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Deprecated +@PVPMETADATA public class EIDSTORKTOKEN implements IPVPAttributeBuilder { public String getName() { return EID_STORK_TOKEN_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { if (!authData.isForeigner()) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSectorForIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSectorForIDAttributeBuilder.java deleted file mode 100644 index c3300d60f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSectorForIDAttributeBuilder.java +++ /dev/null @@ -1,54 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -import at.gv.egovernment.moa.util.MiscUtil; - -public class EIDSectorForIDAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return EID_SECTOR_FOR_IDENTIFIER_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - String bpktype = authData.getBPKType(); - - if (MiscUtil.isEmpty(authData.getBPKType())) - throw new UnavailableAttributeException(EID_SECTOR_FOR_IDENTIFIER_NAME); - - return g.buildStringAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, - EID_SECTOR_FOR_IDENTIFIER_NAME, bpktype); - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, - EID_SECTOR_FOR_IDENTIFIER_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSignerCertificate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSignerCertificate.java index 4b4296536..dfb234ee7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSignerCertificate.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSignerCertificate.java @@ -25,27 +25,35 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.springframework.util.Base64Utils; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.logging.Logger; +@PVPMETADATA public class EIDSignerCertificate implements IPVPAttributeBuilder { public String getName() { return EID_SIGNER_CERTIFICATE_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { try { - byte[] signerCertificate = authData.getSignerCertificate(); - if (signerCertificate != null) { - return g.buildStringAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, EID_SIGNER_CERTIFICATE_NAME, + if (authData instanceof IMOAAuthData) { + byte[] signerCertificate = ((IMOAAuthData)authData).getSignerCertificate(); + if (signerCertificate != null) { + return g.buildStringAttribute(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME, EID_SIGNER_CERTIFICATE_NAME, Base64Utils.encodeToString(signerCertificate)); - } + } + } else + Logger.info(EID_SIGNER_CERTIFICATE_FRIENDLY_NAME + " is only available in MOA-ID context"); }catch (Exception e) { Logger.info("Signer certificate BASE64 encoding error"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java deleted file mode 100644 index b4846db12..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributePolicyException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -import at.gv.egovernment.moa.util.MiscUtil; - -public class EIDSourcePIN implements IPVPAttributeBuilder { - - public String getName() { - return EID_SOURCE_PIN_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - if (authData.isBaseIDTransferRestrication()) - throw new AttributePolicyException(EID_SOURCE_PIN_NAME); - - else { - if (MiscUtil.isEmpty(authData.getIdentificationValue())) - throw new UnavailableAttributeException(EID_SOURCE_PIN_NAME); - - return g.buildStringAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME, authData.getIdentificationValue()); - } - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(EID_SOURCE_PIN_FRIENDLY_NAME, EID_SOURCE_PIN_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePINType.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePINType.java deleted file mode 100644 index ccaecb3b6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePINType.java +++ /dev/null @@ -1,51 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; - -public class EIDSourcePINType implements IPVPAttributeBuilder { - - public String getName() { - return EID_SOURCE_PIN_TYPE_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - if (authData.isBaseIDTransferRestrication()) - throw new UnavailableAttributeException(EID_SOURCE_PIN_TYPE_NAME); - - else { - return g.buildStringAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME, authData.getIdentificationType()); - } - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(EID_SOURCE_PIN_TYPE_FRIENDLY_NAME, EID_SOURCE_PIN_TYPE_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDeIDASQAALevelAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDeIDASQAALevelAttributeBuilder.java deleted file mode 100644 index ca3dfa765..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDeIDASQAALevelAttributeBuilder.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class EIDeIDASQAALevelAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return EID_CITIZEN_EIDAS_QAA_LEVEL_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME, - EID_CITIZEN_EIDAS_QAA_LEVEL_NAME, authData.getEIDASQAALevel()); - } - - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME, - EID_CITIZEN_EIDAS_QAA_LEVEL_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EncryptedBPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EncryptedBPKAttributeBuilder.java index 9dfbe00b2..44043ec40 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EncryptedBPKAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EncryptedBPKAttributeBuilder.java @@ -22,33 +22,40 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Constants; +@PVPMETADATA public class EncryptedBPKAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return ENC_BPK_LIST_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { - if (authData.getEncbPKList() != null && - authData.getEncbPKList().size() > 0) { - String value = authData.getEncbPKList().get(0); - for (int i=1; i<authData.getEncbPKList().size(); i++) - value += ";"+authData.getEncbPKList().get(i); + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).getEncbPKList() != null && + ((IMOAAuthData)authData).getEncbPKList().size() > 0) { + String value = ((IMOAAuthData)authData).getEncbPKList().get(0); + for (int i=1; i<((IMOAAuthData)authData).getEncbPKList().size(); i++) + value += ";"+((IMOAAuthData)authData).getEncbPKList().get(i); - return g.buildStringAttribute(ENC_BPK_LIST_FRIENDLY_NAME, ENC_BPK_LIST_NAME, - value); + return g.buildStringAttribute(ENC_BPK_LIST_FRIENDLY_NAME, ENC_BPK_LIST_NAME, + value); - } + } + + } else + Logger.info(ENC_BPK_LIST_FRIENDLY_NAME + " is only available in MOA-ID context"); throw new UnavailableAttributeException(ENC_BPK_LIST_NAME); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/GivenNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/GivenNameAttributeBuilder.java deleted file mode 100644 index af87a319a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/GivenNameAttributeBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class GivenNameAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return GIVEN_NAME_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - return g.buildStringAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME, authData.getGivenName()); - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(GIVEN_NAME_FRIENDLY_NAME, GIVEN_NAME_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/HolderOfKey.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/HolderOfKey.java index 1d3faff2d..c65199dd6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/HolderOfKey.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/HolderOfKey.java @@ -24,11 +24,13 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; -import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.api.data.EAAFConstants; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; @@ -38,12 +40,12 @@ public class HolderOfKey implements IPVPAttributeBuilder { return PVP_HOLDEROFKEY_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { try { byte[] certEncoded = authData.getGenericData( - MOAIDAuthConstants.MOASESSION_DATA_HOLDEROFKEY_CERTIFICATE, + EAAFConstants.PROCESS_ENGINE_SSL_CLIENT_CERTIFICATE, byte[].class); if (certEncoded != null) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeBuilder.java deleted file mode 100644 index 5b44f02aa..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeBuilder.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public interface IAttributeBuilder { - public String getName(); - - public <ATT> ATT build(final IOAAuthParameters oaParam, final IAuthData authData, - final IAttributeGenerator<ATT> g) throws AttributeException; - - public <ATT> ATT buildEmpty(final IAttributeGenerator<ATT> g); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeGenerator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeGenerator.java deleted file mode 100644 index ecd67db64..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IAttributeGenerator.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -public interface IAttributeGenerator<ATT> { - /** - * - * @param friendlyName FriendlyName - * @param name Name - * @param value value - * @return - */ - public abstract ATT buildStringAttribute(final String friendlyName, final String name, final String value); - - public abstract ATT buildIntegerAttribute(final String friendlyName, final String name, final int value); - - public abstract ATT buildLongAttribute(final String friendlyName, final String name, final long value); - - public abstract ATT buildEmptyAttribute(final String friendlyName, final String name); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IPVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IPVPAttributeBuilder.java deleted file mode 100644 index dbb799256..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/IPVPAttributeBuilder.java +++ /dev/null @@ -1,29 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; - -interface IPVPAttributeBuilder extends PVPConstants, IAttributeBuilder { - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java index ffb69c2dc..a40c0fefb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java @@ -28,40 +28,50 @@ import javax.xml.transform.TransformerException; import org.springframework.util.Base64Utils; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; +@PVPMETADATA public class MandateFullMandateAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_FULL_MANDATE_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if (authData.isUseMandate()) { - //only provide full mandate if it is included. - //In case of federation only a short mandate could be include - if (authData.getMandate() != null) { - String fullMandate; - try { - fullMandate = DOMUtils.serializeNode(authData - .getMandate()); - return g.buildStringAttribute(MANDATE_FULL_MANDATE_FRIENDLY_NAME, - MANDATE_FULL_MANDATE_NAME, Base64Utils.encodeToString(fullMandate.getBytes())); - } catch (TransformerException e) { - Logger.error("Failed to generate Full Mandate", e); - } catch (IOException e) { - Logger.error("Failed to generate Full Mandate", e); + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).isUseMandate()) { + //only provide full mandate if it is included. + //In case of federation only a short mandate could be include + if (((IMOAAuthData)authData).getMandate() != null) { + String fullMandate; + try { + fullMandate = DOMUtils.serializeNode(((IMOAAuthData)authData) + .getMandate()); + return g.buildStringAttribute(MANDATE_FULL_MANDATE_FRIENDLY_NAME, + MANDATE_FULL_MANDATE_NAME, Base64Utils.encodeToString(fullMandate.getBytes())); + } catch (TransformerException e) { + Logger.error("Failed to generate Full Mandate", e); + } catch (IOException e) { + Logger.error("Failed to generate Full Mandate", e); + } } + throw new NoMandateDataAttributeException(); + } - throw new NoMandateDataAttributeException(); - } + } else + Logger.info(MANDATE_FULL_MANDATE_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java index f85fd7cae..67d9a356d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonFullNameAttributeBuilder.java @@ -26,50 +26,60 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateLegalPersonFullNameAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_LEG_PER_FULL_NAME_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if (authData.isUseMandate()) { - - //get PVP attribute directly, if exists - String fullName = authData.getGenericData(MANDATE_LEG_PER_FULL_NAME_NAME, String.class); - - if (MiscUtil.isEmpty(fullName)) { - Element mandate = authData.getMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); - - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).isUseMandate()) { + + //get PVP attribute directly, if exists + String fullName = authData.getGenericData(MANDATE_LEG_PER_FULL_NAME_NAME, String.class); + + if (MiscUtil.isEmpty(fullName)) { + Element mandate = ((IMOAAuthData)authData).getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); + + } + CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); + if (corporation == null) { + Logger.info("No corporation mandate"); + throw new NoMandateDataAttributeException(); + + } + fullName = corporation.getFullName(); } - CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); - if (corporation == null) { - Logger.info("No corporation mandate"); - throw new NoMandateDataAttributeException(); - - } - fullName = corporation.getFullName(); + return g.buildStringAttribute(MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, MANDATE_LEG_PER_FULL_NAME_NAME, + fullName); + } - return g.buildStringAttribute(MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, MANDATE_LEG_PER_FULL_NAME_NAME, - fullName); - } + } else + Logger.info(MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java index 7e0815ab2..fc85e3413 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinAttributeBuilder.java @@ -26,27 +26,35 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateLegalPersonSourcePinAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_LEG_PER_SOURCE_PIN_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if(authData.isUseMandate()) { - return g.buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, - MANDATE_LEG_PER_SOURCE_PIN_NAME, getLegalPersonIdentifierFromMandate(authData)); + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if(((IMOAAuthData)authData).isUseMandate()) { + return g.buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, + MANDATE_LEG_PER_SOURCE_PIN_NAME, getLegalPersonIdentifierFromMandate(((IMOAAuthData)authData))); - } + } + } else + Logger.info(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME + " is only available in MOA-ID context"); return null; @@ -57,7 +65,7 @@ public class MandateLegalPersonSourcePinAttributeBuilder implements IPVPAttribu } - protected String getLegalPersonIdentifierFromMandate(IAuthData authData) throws NoMandateDataAttributeException { + protected String getLegalPersonIdentifierFromMandate(IMOAAuthData authData) throws NoMandateDataAttributeException { //get PVP attribute directly, if exists String sourcePin = authData.getGenericData(MANDATE_LEG_PER_SOURCE_PIN_NAME, String.class); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java index 8b22acc01..e89d34e3d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateLegalPersonSourcePinTypeAttributeBuilder.java @@ -26,55 +26,65 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateLegalPersonSourcePinTypeAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if (authData.isUseMandate()) { - //get PVP attribute directly, if exists - String sourcePinType = authData.getGenericData(MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, String.class); + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).isUseMandate()) { + //get PVP attribute directly, if exists + String sourcePinType = authData.getGenericData(MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, String.class); + + if (MiscUtil.isEmpty(sourcePinType)) { + Element mandate = ((IMOAAuthData)authData).getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); - if (MiscUtil.isEmpty(sourcePinType)) { - Element mandate = authData.getMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); - - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - - } - CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); - if (corporation == null) { - Logger.info("No corporate mandate"); - throw new NoMandateDataAttributeException(); - - } - if (corporation.getIdentification().size() == 0) { - Logger.info("Failed to generate IdentificationType"); - throw new NoMandateDataAttributeException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); + + } + CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); + if (corporation == null) { + Logger.info("No corporate mandate"); + throw new NoMandateDataAttributeException(); + + } + if (corporation.getIdentification().size() == 0) { + Logger.info("Failed to generate IdentificationType"); + throw new NoMandateDataAttributeException(); + + } + sourcePinType = corporation.getIdentification().get(0).getType(); } - sourcePinType = corporation.getIdentification().get(0).getType(); + return g.buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, + sourcePinType); } - return g.buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, - sourcePinType); - } + } else + Logger.info(MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java index ad469921c..f67f79dcf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBPKAttributeBuilder.java @@ -27,30 +27,37 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; -import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.EAAFBuilderException; +import at.gv.egiz.eaaf.core.exceptions.UnavailableAttributeException; +import at.gv.egiz.eaaf.core.impl.data.Pair; +import at.gv.egiz.eaaf.core.impl.idp.auth.builder.BPKBuilder; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; import at.gv.egovernment.moa.id.auth.exception.BuildException; 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.data.IAuthData; -import at.gv.egovernment.moa.id.data.Pair; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateNaturalPersonBPKAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_NAT_PER_BPK_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - try { - Pair<String, String> calcResult = internalBPKGenerator(oaParam, authData); + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + try { + Pair<String, String> calcResult = internalBPKGenerator((IOAAuthParameters)oaParam, authData); if (calcResult != null) { String bpk = calcResult.getFirst(); String type = calcResult.getSecond(); @@ -87,7 +94,7 @@ public class MandateNaturalPersonBPKAttributeBuilder implements IPVPAttributeBui } } - catch (BuildException | ConfigurationException e) { + catch (BuildException | ConfigurationException | EAAFBuilderException e) { Logger.error("Failed to generate IdentificationType"); throw new NoMandateDataAttributeException(); @@ -101,49 +108,52 @@ public class MandateNaturalPersonBPKAttributeBuilder implements IPVPAttributeBui return g.buildEmptyAttribute(MANDATE_NAT_PER_BPK_FRIENDLY_NAME, MANDATE_NAT_PER_BPK_NAME); } - protected Pair<String, String> internalBPKGenerator(IOAAuthParameters oaParam, IAuthData authData) throws NoMandateDataAttributeException, BuildException, ConfigurationException { + protected Pair<String, String> internalBPKGenerator(ISPConfiguration oaParam, IAuthData authData) throws NoMandateDataAttributeException, BuildException, ConfigurationException, EAAFBuilderException { //get PVP attribute directly, if exists Pair<String, String> calcResult = null; - - if (authData.isUseMandate()) { - String bpk = authData.getGenericData(MANDATE_NAT_PER_BPK_NAME, String.class); - - if (MiscUtil.isEmpty(bpk)) { - //read bPK from mandate if it is not directly included - Element mandate = authData.getMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); - if (physicalPerson == null) { - Logger.debug("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } - IdentificationType id = null; - id = physicalPerson.getIdentification().get(0); - if (id == null) { - Logger.info("Failed to generate IdentificationType"); - throw new NoMandateDataAttributeException(); - } - - - if (id.getType().equals(Constants.URN_PREFIX_BASEID)) - calcResult = new BPKBuilder().generateAreaSpecificPersonIdentifier(id.getValue().getValue(), - oaParam.getAreaSpecificTargetIdentifier()); - else - calcResult = Pair.newInstance(id.getValue().getValue(), id.getType()); - + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).isUseMandate()) { + String bpk = authData.getGenericData(MANDATE_NAT_PER_BPK_NAME, String.class); - } else { - Logger.info("Find '" + MANDATE_NAT_PER_BPK_NAME + "' in AuthData. Use it what is is."); - calcResult = Pair.newInstance(bpk, null); + if (MiscUtil.isEmpty(bpk)) { + //read bPK from mandate if it is not directly included + Element mandate = ((IMOAAuthData)authData).getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); + if (physicalPerson == null) { + Logger.debug("No physicalPerson mandate"); + throw new NoMandateDataAttributeException(); + } + IdentificationType id = null; + id = physicalPerson.getIdentification().get(0); + if (id == null) { + Logger.info("Failed to generate IdentificationType"); + throw new NoMandateDataAttributeException(); + } + + + if (id.getType().equals(Constants.URN_PREFIX_BASEID)) + calcResult = new BPKBuilder().generateAreaSpecificPersonIdentifier(id.getValue().getValue(), + oaParam.getAreaSpecificTargetIdentifier()); + else + calcResult = Pair.newInstance(id.getValue().getValue(), id.getType()); + + } else { + Logger.info("Find '" + MANDATE_NAT_PER_BPK_NAME + "' in AuthData. Use it what is is."); + calcResult = Pair.newInstance(bpk, null); + + } } - } + + } else + Logger.info(MANDATE_NAT_PER_BPK_FRIENDLY_NAME + " is only available in MOA-ID context"); return calcResult; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java index ebba376f8..3ee184fb1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonBirthDateAttributeBuilder.java @@ -31,23 +31,28 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.InvalidDateFormatAttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.InvalidDateFormatAttributeException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateNaturalPersonBirthDateAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_NAT_PER_BIRTHDATE_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { String attrValue = internalAttributGeneration(oaParam, authData); if (attrValue != null) @@ -62,42 +67,45 @@ public class MandateNaturalPersonBirthDateAttributeBuilder implements IPVPAttrib } - protected String internalAttributGeneration(IOAAuthParameters oaParam, IAuthData authData) throws InvalidDateFormatAttributeException, NoMandateDataAttributeException { - if (authData.isUseMandate()) { + protected String internalAttributGeneration(ISPConfiguration oaParam, IAuthData authData) throws InvalidDateFormatAttributeException, NoMandateDataAttributeException { + if (((IMOAAuthData)authData).isUseMandate()) { //get PVP attribute directly, if exists String birthDayString = authData.getGenericData(MANDATE_NAT_PER_BIRTHDATE_NAME, String.class); if (MiscUtil.isEmpty(birthDayString)) { - //read bPK from mandate if it is not directly included - Element mandate = authData.getMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); - if (physicalPerson == null) { - Logger.info("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } + if (authData instanceof IMOAAuthData) { + //read bPK from mandate if it is not directly included + Element mandate = ((IMOAAuthData)authData).getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); + if (physicalPerson == null) { + Logger.info("No physicalPerson mandate"); + throw new NoMandateDataAttributeException(); + } - String dateOfBirth = physicalPerson.getDateOfBirth(); - try { - DateFormat mandateFormat = new SimpleDateFormat(MandateBuilder.MANDATE_DATE_OF_BIRTH_FORMAT); - mandateFormat.setLenient(false); - Date date = mandateFormat.parse(dateOfBirth); - DateFormat pvpDateFormat = new SimpleDateFormat(MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN); - birthDayString = pvpDateFormat.format(date); + String dateOfBirth = physicalPerson.getDateOfBirth(); + try { + DateFormat mandateFormat = new SimpleDateFormat(MandateBuilder.MANDATE_DATE_OF_BIRTH_FORMAT); + mandateFormat.setLenient(false); + Date date = mandateFormat.parse(dateOfBirth); + DateFormat pvpDateFormat = new SimpleDateFormat(MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN); + birthDayString = pvpDateFormat.format(date); - } - catch (ParseException e) { - Logger.warn("MIS mandate birthday has an incorrect formt. (Value:" + dateOfBirth, e); - throw new InvalidDateFormatAttributeException(); + } + catch (ParseException e) { + Logger.warn("MIS mandate birthday has an incorrect formt. (Value:" + dateOfBirth, e); + throw new InvalidDateFormatAttributeException(); - } + } + } else + Logger.info(MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME + " is only available in MOA-ID context"); } else { try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java index 07e5c9d09..6dd669663 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonFamilyNameAttributeBuilder.java @@ -29,56 +29,66 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameType.FamilyName; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateNaturalPersonFamilyNameAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_NAT_PER_FAMILY_NAME_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if(authData.isUseMandate()) { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if(((IMOAAuthData)authData).isUseMandate()) { - //get PVP attribute directly, if exists - String familyName = authData.getGenericData(MANDATE_NAT_PER_FAMILY_NAME_NAME, String.class); - - if (MiscUtil.isEmpty(familyName)) { - //read mandator familyName from mandate if it is not directly included - Element mandate = authData.getMandate(); - if(mandate == null) { - throw new NoMandateDataAttributeException(); - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); - if(physicalPerson == null) { - Logger.debug("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } - - StringBuilder sb = new StringBuilder(); - Iterator<FamilyName> fNamesit = physicalPerson.getName().getFamilyName().iterator(); + //get PVP attribute directly, if exists + String familyName = authData.getGenericData(MANDATE_NAT_PER_FAMILY_NAME_NAME, String.class); - while(fNamesit.hasNext()) - sb.append(" " + fNamesit.next().getValue()); - - familyName = sb.toString(); + if (MiscUtil.isEmpty(familyName)) { + //read mandator familyName from mandate if it is not directly included + Element mandate = ((IMOAAuthData)authData).getMandate(); + if(mandate == null) { + throw new NoMandateDataAttributeException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAttributeException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); + if(physicalPerson == null) { + Logger.debug("No physicalPerson mandate"); + throw new NoMandateDataAttributeException(); + } + + StringBuilder sb = new StringBuilder(); + Iterator<FamilyName> fNamesit = physicalPerson.getName().getFamilyName().iterator(); + + while(fNamesit.hasNext()) + sb.append(" " + fNamesit.next().getValue()); + + familyName = sb.toString(); + + } + return g.buildStringAttribute(MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, + MANDATE_NAT_PER_FAMILY_NAME_NAME, familyName); } - return g.buildStringAttribute(MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, - MANDATE_NAT_PER_FAMILY_NAME_NAME, familyName); - } + } else + Logger.info(MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java index 51a3d2e74..3d661459a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java @@ -28,53 +28,62 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateNaturalPersonGivenNameAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_NAT_PER_GIVEN_NAME_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if (authData.isUseMandate()) { - //get PVP attribute directly, if exists - String givenName = authData.getGenericData(MANDATE_NAT_PER_GIVEN_NAME_NAME, String.class); - - if (MiscUtil.isEmpty(givenName)) { - Element mandate = authData.getMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); - if (physicalPerson == null) { - Logger.debug("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).isUseMandate()) { + //get PVP attribute directly, if exists + String givenName = authData.getGenericData(MANDATE_NAT_PER_GIVEN_NAME_NAME, String.class); - StringBuilder sb = new StringBuilder(); - Iterator<String> gNamesit = physicalPerson.getName().getGivenName().iterator(); - - while (gNamesit.hasNext()) - sb.append(" " + gNamesit.next()); - - givenName = sb.toString(); + if (MiscUtil.isEmpty(givenName)) { + Element mandate = ((IMOAAuthData)authData).getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator().getPhysicalPerson(); + if (physicalPerson == null) { + Logger.debug("No physicalPerson mandate"); + throw new NoMandateDataAttributeException(); + } + + StringBuilder sb = new StringBuilder(); + Iterator<String> gNamesit = physicalPerson.getName().getGivenName().iterator(); + + while (gNamesit.hasNext()) + sb.append(" " + gNamesit.next()); + + givenName = sb.toString(); + + } + return g.buildStringAttribute(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, MANDATE_NAT_PER_GIVEN_NAME_NAME, givenName); } - return g.buildStringAttribute(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, MANDATE_NAT_PER_GIVEN_NAME_NAME, givenName); - } + } else + Logger.info(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME + " is only available in MOA-ID context"); return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java index 8be85415e..32b45a595 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinAttributeBuilder.java @@ -27,52 +27,62 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributePolicyException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.exceptions.AttributePolicyException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; +@PVPMETADATA public class MandateNaturalPersonSourcePinAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_NAT_PER_SOURCE_PIN_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if(authData.isUseMandate()) { - Element mandate = authData.getMandate(); - if(mandate == null) { - throw new NoMandateDataAttributeException(); - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - PhysicalPersonType physicalPerson = mandateObject.getMandator() - .getPhysicalPerson(); - if (physicalPerson == null) { - Logger.debug("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } - IdentificationType id = null; - id = physicalPerson.getIdentification().get(0); - - if(authData.isBaseIDTransferRestrication()) { - throw new AttributePolicyException(this.getName()); - } - - if(id == null) { - Logger.info("Failed to generate IdentificationType"); - throw new NoMandateDataAttributeException(); + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if(((IMOAAuthData)authData).isUseMandate()) { + Element mandate = ((IMOAAuthData)authData).getMandate(); + if(mandate == null) { + throw new NoMandateDataAttributeException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAttributeException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator() + .getPhysicalPerson(); + if (physicalPerson == null) { + Logger.debug("No physicalPerson mandate"); + throw new NoMandateDataAttributeException(); + } + IdentificationType id = null; + id = physicalPerson.getIdentification().get(0); + + if(authData.isBaseIDTransferRestrication()) { + throw new AttributePolicyException(this.getName()); + } + + if(id == null) { + Logger.info("Failed to generate IdentificationType"); + throw new NoMandateDataAttributeException(); + } + + return g.buildStringAttribute(MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME, + MANDATE_NAT_PER_SOURCE_PIN_NAME, id.getValue().getValue()); } - return g.buildStringAttribute(MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME, - MANDATE_NAT_PER_SOURCE_PIN_NAME, id.getValue().getValue()); - } + } else + Logger.info(MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java index d89ae0225..90a0d61c9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonSourcePinTypeAttributeBuilder.java @@ -27,46 +27,56 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; +@PVPMETADATA public class MandateNaturalPersonSourcePinTypeAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if(authData.isUseMandate()) { - Element mandate = authData.getMandate(); - if(mandate == null) { - throw new NoMandateDataAttributeException(); - } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - PhysicalPersonType physicalPerson = mandateObject.getMandator() - .getPhysicalPerson(); - if (physicalPerson == null) { - Logger.debug("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } - IdentificationType id = null; - id = physicalPerson.getIdentification().get(0); - if(id == null) { - Logger.info("Failed to generate IdentificationType"); - throw new NoMandateDataAttributeException(); - } - - return g.buildStringAttribute(MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, - MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME, id.getType()); - } + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if(((IMOAAuthData)authData).isUseMandate()) { + Element mandate = ((IMOAAuthData)authData).getMandate(); + if(mandate == null) { + throw new NoMandateDataAttributeException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if(mandateObject == null) { + throw new NoMandateDataAttributeException(); + } + PhysicalPersonType physicalPerson = mandateObject.getMandator() + .getPhysicalPerson(); + if (physicalPerson == null) { + Logger.debug("No physicalPerson mandate"); + throw new NoMandateDataAttributeException(); + } + IdentificationType id = null; + id = physicalPerson.getIdentification().get(0); + if(id == null) { + Logger.info("Failed to generate IdentificationType"); + throw new NoMandateDataAttributeException(); + } + + return g.buildStringAttribute(MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, + MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME, id.getType()); + } + + } else + Logger.info(MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepDescAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepDescAttributeBuilder.java index b7d21f903..9c42f14e4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepDescAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepDescAttributeBuilder.java @@ -25,58 +25,69 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateProfRepDescAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_PROF_REP_DESC_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if(authData.isUseMandate()) { - String profRepName = authData.getGenericData(MANDATE_PROF_REP_DESC_NAME, String.class); - - if (MiscUtil.isEmpty(profRepName)) { - IMISMandate misMandate = authData.getMISMandate(); - - if(misMandate == null) { - throw new NoMandateDataAttributeException(); - } - - profRepName = misMandate.getTextualDescriptionOfOID(); + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if(((IMOAAuthData)authData).isUseMandate()) { + String profRepName = authData.getGenericData(MANDATE_PROF_REP_DESC_NAME, String.class); - //only read textual prof. rep. OID describtion from mandate annotation - // if also OID exists - if (MiscUtil.isEmpty(profRepName) - && MiscUtil.isNotEmpty(misMandate.getProfRep())) { - Element mandate = authData.getMandate(); - if (mandate == null) { + if (MiscUtil.isEmpty(profRepName)) { + IMISMandate misMandate = ((IMOAAuthData)authData).getMISMandate(); + + if(misMandate == null) { throw new NoMandateDataAttributeException(); } - Mandate mandateObject = MandateBuilder.buildMandate(authData.getMandate()); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - - profRepName = mandateObject.getAnnotation(); + profRepName = misMandate.getTextualDescriptionOfOID(); + + //only read textual prof. rep. OID describtion from mandate annotation + // if also OID exists + if (MiscUtil.isEmpty(profRepName) + && MiscUtil.isNotEmpty(misMandate.getProfRep())) { + Element mandate = ((IMOAAuthData)authData).getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(((IMOAAuthData)authData).getMandate()); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); + } + + profRepName = mandateObject.getAnnotation(); + + } } + + if(MiscUtil.isNotEmpty(profRepName)) + return g.buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, + MANDATE_PROF_REP_DESC_NAME, profRepName); + } - if(MiscUtil.isNotEmpty(profRepName)) - return g.buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, - MANDATE_PROF_REP_DESC_NAME, profRepName); - - } + } else + Logger.info(MANDATE_PROF_REP_DESC_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepOIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepOIDAttributeBuilder.java index 04de3288a..c7f9ace31 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepOIDAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepOIDAttributeBuilder.java @@ -22,40 +22,51 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; import at.gv.egovernment.moa.id.commons.api.data.IMISMandate; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; +import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateProfRepOIDAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_PROF_REP_OID_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if (authData.isUseMandate()) { - String profRepOID = authData.getGenericData(MANDATE_PROF_REP_OID_NAME, String.class); - - if (MiscUtil.isEmpty(profRepOID)) { - IMISMandate mandate = authData.getMISMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).isUseMandate()) { + String profRepOID = authData.getGenericData(MANDATE_PROF_REP_OID_NAME, String.class); + + if (MiscUtil.isEmpty(profRepOID)) { + IMISMandate mandate = ((IMOAAuthData)authData).getMISMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + } + + profRepOID = mandate.getProfRep(); + } - - profRepOID = mandate.getProfRep(); + + if(MiscUtil.isEmpty(profRepOID)) + return null; + else + return g.buildStringAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, MANDATE_PROF_REP_OID_NAME, profRepOID); } - - if(MiscUtil.isEmpty(profRepOID)) - return null; - else - return g.buildStringAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, MANDATE_PROF_REP_OID_NAME, profRepOID); - } + } else + Logger.info(MANDATE_PROF_REP_OID_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateReferenceValueAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateReferenceValueAttributeBuilder.java index 5ad562ffa..3ceebcd4c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateReferenceValueAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateReferenceValueAttributeBuilder.java @@ -22,24 +22,34 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; +import at.gv.egovernment.moa.logging.Logger; +@PVPMETADATA public class MandateReferenceValueAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_REFERENCE_VALUE_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if (authData.isUseMandate()) { + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).isUseMandate()) { + + return g.buildStringAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, MANDATE_REFERENCE_VALUE_NAME, + ((IMOAAuthData)authData).getMandateReferenceValue()); + } + + } else + Logger.info(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME + " is only available in MOA-ID context"); - return g.buildStringAttribute(MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, MANDATE_REFERENCE_VALUE_NAME, - authData.getMandateReferenceValue()); - } return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeAttributeBuilder.java index a531e31fc..0f9995ab1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeAttributeBuilder.java @@ -25,42 +25,53 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateTypeAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_TYPE_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if (authData.isUseMandate()) { - //get PVP attribute directly, if exists - String mandateType = authData.getGenericData(MANDATE_TYPE_NAME, String.class); - - if (MiscUtil.isEmpty(mandateType)) { - Element mandate = authData.getMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).isUseMandate()) { + //get PVP attribute directly, if exists + String mandateType = authData.getGenericData(MANDATE_TYPE_NAME, String.class); + + if (MiscUtil.isEmpty(mandateType)) { + Element mandate = ((IMOAAuthData)authData).getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + + } + Mandate mandateObject = MandateBuilder.buildMandate(mandate); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); + + } + mandateType = mandateObject.getAnnotation(); } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - mandateType = mandateObject.getAnnotation(); - + return g.buildStringAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME, mandateType); } - - return g.buildStringAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME, mandateType); - } + + } else + Logger.info(MANDATE_TYPE_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeOIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeOIDAttributeBuilder.java index b967ad42c..76992af39 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeOIDAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeOIDAttributeBuilder.java @@ -22,32 +22,42 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import at.gv.egiz.eaaf.core.api.idp.IAttributeGenerator; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IPVPAttributeBuilder; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; +import at.gv.egiz.eaaf.core.impl.idp.builder.attributes.PVPMETADATA; +import at.gv.egovernment.moa.id.data.IMOAAuthData; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@PVPMETADATA public class MandateTypeOIDAttributeBuilder implements IPVPAttributeBuilder { public String getName() { return MANDATE_TYPE_OID_NAME; } - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - if (authData.isUseMandate()) { - //get PVP attribute directly, if exists - String mandateType = authData.getGenericData(MANDATE_TYPE_OID_NAME, String.class); - - if (MiscUtil.isEmpty(mandateType)) { - Logger.info("MIS Mandate does not include 'Mandate-Type OID'."); - return null; + public <ATT> ATT build(ISPConfiguration oaParam, IAuthData authData, + IAttributeGenerator<ATT> g) throws AttributeBuilderException { + if (authData instanceof IMOAAuthData) { + if (((IMOAAuthData)authData).isUseMandate()) { + //get PVP attribute directly, if exists + String mandateType = authData.getGenericData(MANDATE_TYPE_OID_NAME, String.class); + if (MiscUtil.isEmpty(mandateType)) { + Logger.info("MIS Mandate does not include 'Mandate-Type OID'."); + return null; + + } + + return g.buildStringAttribute(MANDATE_TYPE_OID_FRIENDLY_NAME, MANDATE_TYPE_OID_NAME, mandateType); } - - return g.buildStringAttribute(MANDATE_TYPE_OID_FRIENDLY_NAME, MANDATE_TYPE_OID_NAME, mandateType); - } + + } else + Logger.info(MANDATE_TYPE_OID_FRIENDLY_NAME + " is only available in MOA-ID context"); + return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PVPVersionAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PVPVersionAttributeBuilder.java deleted file mode 100644 index 285a6977f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PVPVersionAttributeBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class PVPVersionAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return PVP_VERSION_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - return g.buildStringAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME, PVP_VERSION_2_1); - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(PVP_VERSION_FRIENDLY_NAME, PVP_VERSION_NAME); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PrincipalNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PrincipalNameAttributeBuilder.java deleted file mode 100644 index b2465b5c1..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/PrincipalNameAttributeBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class PrincipalNameAttributeBuilder implements IPVPAttributeBuilder { - - public String getName() { - return PRINCIPAL_NAME_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - return g.buildStringAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME, authData.getFamilyName()); - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(PRINCIPAL_NAME_FRIENDLY_NAME, PRINCIPAL_NAME_NAME); - } - -} 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 72691a034..e98e1cb78 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 @@ -37,36 +37,53 @@ import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeQuery; import org.opensaml.saml2.core.Response; import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.soap.common.SOAPException; +import org.opensaml.xml.XMLObject; import org.opensaml.xml.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.IAction; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.IAuthenticationDataBuilder; +import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.exceptions.EAAFAuthenticationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.data.Trible; +import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.exception.AttributQueryException; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.builder.AuthResponseBuilder; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.builder.PVP2AssertionBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.SoapBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PVPAttributeBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionAttributeExtractorExeption; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionValidationExeption; +import at.gv.egiz.eaaf.modules.pvp2.sp.impl.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.auth.builder.DynamicOAAuthParameterBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; 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.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.data.Trible; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.SoapBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameterDecorator; +import at.gv.egovernment.moa.id.data.IMOAAuthData; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -76,12 +93,17 @@ import at.gv.egovernment.moa.logging.Logger; public class AttributQueryAction implements IAction { @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; - @Autowired private AuthenticationDataBuilder authDataBuilder; + @Autowired private IAuthenticationDataBuilder authDataBuilder; @Autowired private IDPCredentialProvider pvpCredentials; @Autowired private AuthConfiguration authConfig; @Autowired(required=true) private MOAMetadataProvider metadataProvider; @Autowired(required=true) ApplicationContext springContext; + @Autowired private AttributQueryBuilder attributQueryBuilder; + @Autowired private SAMLVerificationEngineSP samlVerificationEngine; + @Autowired(required=true) IPVP2BasicConfiguration pvpBasicConfiguration; + @Autowired(required=true) PVP2AssertionBuilder assertionBuilder; + private final static List<String> DEFAULTSTORKATTRIBUTES = Arrays.asList( new String[]{PVPConstants.EID_STORK_TOKEN_NAME}); @@ -97,11 +119,11 @@ public class AttributQueryAction implements IAction { @Override public SLOInformationInterface processRequest(IRequest pendingReq, HttpServletRequest httpReq, HttpServletResponse httpResp, - IAuthData authData) throws MOAIDException { + IAuthData authData) throws EAAFException { - if (pendingReq instanceof PVPTargetConfiguration && - ((PVPTargetConfiguration) pendingReq).getRequest() instanceof MOARequest && - ((MOARequest)((PVPTargetConfiguration) pendingReq).getRequest()).getSamlRequest() instanceof AttributeQuery) { + if (pendingReq instanceof PVPSProfilePendingRequest && + ((PVPSProfilePendingRequest) pendingReq).getRequest() instanceof PVPSProfileRequest && + ((PVPSProfileRequest)((PVPSProfilePendingRequest) pendingReq).getRequest()).getSamlRequest() instanceof AttributeQuery) { //set time reference DateTime date = new DateTime(); @@ -116,10 +138,10 @@ public class AttributQueryAction implements IAction { } InterfederationSessionStore nextIDPInformation = - authenticationSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(moaSession.getSessionID()); + authenticationSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(moaSession.getSSOSessionID()); AttributeQuery attrQuery = - (AttributeQuery)((MOARequest)((PVPTargetConfiguration) pendingReq).getRequest()).getSamlRequest(); + (AttributeQuery)((PVPSProfileRequest)((PVPSProfilePendingRequest) pendingReq).getRequest()).getSamlRequest(); //build PVP 2.1 response-attribute information for this AttributQueryRequest Trible<List<Attribute>, Date, String> responseInfo = @@ -131,10 +153,9 @@ public class AttributQueryAction implements IAction { //build PVP 2.1 assertion - String issuerEntityID = PVPConfiguration.getInstance().getIDPSSOMetadataService( - pendingReq.getAuthURL()); + String issuerEntityID = pvpBasicConfiguration.getIDPEntityId(pendingReq.getAuthURL()); - Assertion assertion = PVP2AssertionBuilder.buildAssertion(issuerEntityID, + Assertion assertion = assertionBuilder.buildAssertion(issuerEntityID, attrQuery, responseInfo.getFirst(), date, new DateTime(responseInfo.getSecond().getTime()), responseInfo.getThird(), authData.getSessionIndex()); @@ -184,39 +205,42 @@ public class AttributQueryAction implements IAction { */ @Override public String getDefaultActionName() { - return PVP2XProtocol.ATTRIBUTEQUERY; + return at.gv.egiz.eaaf.modules.pvp2.PVPConstants.ATTRIBUTEQUERY; } private Trible<List<Attribute>, Date, String> buildResponseInformationForAttributQuery(IRequest pendingReq, - AuthenticationSession session, List<Attribute> reqAttributes, InterfederationSessionStore nextIDPInformation) throws MOAIDException { + AuthenticationSession session, List<Attribute> reqAttributes, InterfederationSessionStore nextIDPInformation) throws MOAIDException, AssertionAttributeExtractorExeption, AttributQueryException, AssertionValidationExeption { try { //mark AttributeQuery as used if it exists - if ( pendingReq instanceof PVPTargetConfiguration && - ((PVPTargetConfiguration) pendingReq).getRequest() instanceof MOARequest && - ((PVPTargetConfiguration) pendingReq).getRequest().getInboundMessage() instanceof AttributeQuery) { + if ( pendingReq instanceof PVPSProfileRequest && + ((PVPSProfilePendingRequest) pendingReq).getRequest() instanceof PVPSProfileRequest && + ((PVPSProfilePendingRequest) pendingReq).getRequest().getInboundMessage() instanceof AttributeQuery) { - authenticationSessionStorage.markOAWithAttributeQueryUsedFlag(session, pendingReq.getOAURL(), pendingReq.requestedModule()); + authenticationSessionStorage.markOAWithAttributeQueryUsedFlag(session, pendingReq.getSPEntityId(), pendingReq.requestedModule()); } //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) and configuration IOAAuthParameters spConfig = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes); - //search federated IDP information for this MOASession + //search federated IDP information for this MOASession if (nextIDPInformation != null) { Logger.info("Find active federated IDP information." + ". --> Request next IDP:" + nextIDPInformation.getIdpurlprefix() + " for authentication information."); //load configuration of next IDP - IOAAuthParameters idpLoaded = authConfig.getOnlineApplicationParameter(nextIDPInformation.getIdpurlprefix()); - if (idpLoaded == null || !(idpLoaded instanceof OAAuthParameter)) { + IOAAuthParameters idpLoaded = + authConfig.getServiceProviderConfiguration( + nextIDPInformation.getIdpurlprefix(), + OAAuthParameterDecorator.class); + if (idpLoaded == null || !(idpLoaded instanceof IOAAuthParameters)) { Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() + "is not loadable."); throw new MOAIDException("auth.32", new Object[]{nextIDPInformation.getIdpurlprefix()}); } - OAAuthParameter idp = (OAAuthParameter) idpLoaded; + IOAAuthParameters idp = idpLoaded; //check if next IDP config allows inbound messages if (!idp.isInboundSSOInterfederationAllowed()) { @@ -227,7 +251,7 @@ public class AttributQueryAction implements IAction { } //check next IDP service area policy. BusinessService IDPs can only request wbPKs - if (!spConfig.hasBaseIdTransferRestriction() && !idp.isIDPPublicService()) { + if (!spConfig.hasBaseIdTransferRestriction() && idp.hasBaseIdTransferRestriction()) { Logger.error("Interfederated IDP " + idp.getPublicURLPrefix() + " is a BusinessService-IDP but requests PublicService attributes."); throw new MOAIDException("auth.34", new Object[]{nextIDPInformation.getIdpurlprefix()}); @@ -235,8 +259,12 @@ public class AttributQueryAction implements IAction { } //validation complete --> start AttributeQuery Request - AssertionAttributeExtractor extractor = authDataBuilder.getAuthDataFromAttributeQuery(reqAttributes, - nextIDPInformation.getUserNameID(), idp); + /*TODO: + * 'pendingReq.getAuthURL() + "/sp/federated/metadata"' is implemented in federated_authentication module + * but used in moa-id-lib. This should be refactored!!! + */ + AssertionAttributeExtractor extractor = getAuthDataFromAttributeQuery(reqAttributes, + nextIDPInformation.getUserNameID(), idp, pendingReq.getAuthURL() + "/sp/federated/metadata"); //mark attribute request as used if (nextIDPInformation.isStoreSSOInformation()) { @@ -258,7 +286,7 @@ public class AttributQueryAction implements IAction { } else { Logger.debug("Build authData for AttributQuery from local MOASession."); - IAuthData authData = authDataBuilder.buildAuthenticationData(pendingReq, session, spConfig); + IAuthData authData = authDataBuilder.buildAuthenticationData(pendingReq); //add default attributes in case of mandates or STORK is in use List<String> attrList = addDefaultAttributes(reqAttributes, authData); @@ -266,12 +294,19 @@ public class AttributQueryAction implements IAction { //build Set of response attributes List<Attribute> respAttr = PVPAttributeBuilder.buildSetOfResponseAttributes(authData, attrList); - return Trible.newInstance(respAttr, authData.getSsoSessionValidTo(), authData.getQAALevel()); + return Trible.newInstance(respAttr, authData.getSsoSessionValidTo(), authData.getEIDASQAALevel()); } } catch (MOAIDException e) { throw e; + + } catch (EAAFAuthenticationException e) { + throw new MOAIDException(e.getErrorId(), e.getParams(), e); + + } catch (EAAFConfigurationException e) { + throw new MOAIDException(e.getErrorId(), e.getParams(), e); + } } @@ -303,7 +338,8 @@ public class AttributQueryAction implements IAction { } //add default mandate attributes if it is a authentication with mandates - if (authData.isUseMandate() && !reqAttributeNames.containsAll(DEFAULTMANDATEATTRIBUTES)) { + if (authData instanceof IMOAAuthData) + if (((IMOAAuthData)authData).isUseMandate() && !reqAttributeNames.containsAll(DEFAULTMANDATEATTRIBUTES)) { for (String el : DEFAULTMANDATEATTRIBUTES) { if (!reqAttributeNames.contains(el)) reqAttributeNames.add(el); @@ -313,4 +349,78 @@ public class AttributQueryAction implements IAction { return reqAttributeNames; } + /** + * Get PVP authentication attributes by using a SAML2 AttributeQuery + * + * @param reqQueryAttr List of PVP attributes which are requested + * @param userNameID SAML2 UserNameID of the user for which attributes are requested + * @param idpConfig Configuration of the IDP, which is requested + * @return + * @return PVP attribute DAO, which contains all received information + * @throws MOAIDException + * @throws AttributQueryException + * @throws AssertionValidationExeption + */ + public AssertionAttributeExtractor getAuthDataFromAttributeQuery(List<Attribute> reqQueryAttr, + String userNameID, IOAAuthParameters idpConfig, String spEntityID) throws MOAIDException, AttributQueryException, AssertionValidationExeption{ + String idpEnityID = idpConfig.getPublicURLPrefix(); + + try { + Logger.debug("Starting AttributeQuery process ..."); + //collect attributes by using BackChannel communication + String endpoint = idpConfig.getIDPAttributQueryServiceURL(); + if (MiscUtil.isEmpty(endpoint)) { + Logger.error("No AttributeQueryURL for interfederationIDP " + idpEnityID); + throw new ConfigurationException("config.26", new Object[]{idpEnityID}); + + } + + //build attributQuery request + AttributeQuery query = attributQueryBuilder.buildAttributQueryRequest(spEntityID, userNameID, endpoint, reqQueryAttr); + + //build SOAP request + List<XMLObject> xmlObjects = MOASAMLSOAPClient.send(endpoint, query); + + if (xmlObjects.size() == 0) { + Logger.error("Receive emptry AttributeQuery response-body."); + throw new AttributQueryException("auth.27", + new Object[]{idpEnityID, "Receive emptry AttributeQuery response-body."}); + + } + + Response intfResp; + if (xmlObjects.get(0) instanceof Response) { + intfResp = (Response) xmlObjects.get(0); + + //validate PVP 2.1 response + try { + samlVerificationEngine.verifyIDPResponse(intfResp, + TrustEngineFactory.getSignatureKnownKeysTrustEngine( + metadataProvider)); + + //create assertion attribute extractor from AttributeQuery response + return new AssertionAttributeExtractor(intfResp); + + } catch (Exception e) { + Logger.warn("PVP 2.1 assertion validation FAILED.", e); + throw new AssertionValidationExeption("auth.27", + new Object[]{idpEnityID, e.getMessage()}, e); + } + + } else { + Logger.error("Receive AttributeQuery response-body include no PVP 2.1 response"); + throw new AttributQueryException("auth.27", + new Object[]{idpEnityID, "Receive AttributeQuery response-body include no PVP 2.1 response"}); + + } + + } catch (SOAPException e) { + throw new BuildException("builder.06", null, e); + + } catch (SecurityException e) { + throw new BuildException("builder.06", null, e); + + } + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java deleted file mode 100644 index 9d60ae4b2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ /dev/null @@ -1,151 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.joda.time.DateTime; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.Assertion; -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.Response; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.xml.security.SecurityException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -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.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationImpl; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.BindingNotSupportedException; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.logging.Logger; - -@Service("PVPAuthenticationRequestAction") -public class AuthenticationAction implements IAction { - @Autowired IDPCredentialProvider pvpCredentials; - @Autowired AuthConfiguration authConfig; - @Autowired(required=true) private MOAMetadataProvider metadataProvider; - @Autowired(required=true) ApplicationContext springContext; - - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, - HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { - - PVPTargetConfiguration pvpRequest = (PVPTargetConfiguration) req; - - //get basic information - MOARequest moaRequest = (MOARequest) pvpRequest.getRequest(); - AuthnRequest authnRequest = (AuthnRequest) moaRequest.getSamlRequest(); - EntityDescriptor peerEntity = moaRequest.getEntityMetadata(metadataProvider); - - AssertionConsumerService consumerService = - SAML2Utils.createSAMLObject(AssertionConsumerService.class); - consumerService.setBinding(pvpRequest.getBinding()); - consumerService.setLocation(pvpRequest.getConsumerURL()); - - DateTime date = new DateTime(); - - SLOInformationImpl sloInformation = new SLOInformationImpl(); - - //change to entity value from entity name to IDP EntityID (URL) -// String issuerEntityID = pvpRequest.getAuthURL(); -// if (issuerEntityID.endsWith("/")) -// issuerEntityID = issuerEntityID.substring(0, issuerEntityID.length()-1); - - String issuerEntityID = PVPConfiguration.getInstance().getIDPSSOMetadataService( - pvpRequest.getAuthURL()); - - //build Assertion - Assertion assertion = PVP2AssertionBuilder.buildAssertion(issuerEntityID, pvpRequest, authnRequest, authData, - peerEntity, date, consumerService, sloInformation); - - Response authResponse = AuthResponseBuilder.buildResponse( - metadataProvider, issuerEntityID, authnRequest, - date, assertion, authConfig.isPVP2AssertionEncryptionActive()); - - IEncoder binding = null; - - if (consumerService.getBinding().equals( - SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = springContext.getBean("PVPRedirectBinding", RedirectBinding.class); - - } else if (consumerService.getBinding().equals( - SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = springContext.getBean("PVPPOSTBinding", PostBinding.class); - - } - - if (binding == null) { - throw new BindingNotSupportedException(consumerService.getBinding()); - } - - try { - binding.encodeRespone(httpReq, httpResp, authResponse, - consumerService.getLocation(), moaRequest.getRelayState(), - pvpCredentials.getIDPAssertionSigningCredential(), req); - - //set protocol type - sloInformation.setProtocolType(req.requestedModule()); - sloInformation.setSpEntityID(req.getOnlineApplicationConfiguration().getPublicURLPrefix()); - return sloInformation; - - } catch (MessageEncodingException e) { - Logger.error("Message Encoding exception", e); - throw new MOAIDException("pvp2.01", null, e); - - } catch (SecurityException e) { - Logger.error("Security exception", e); - throw new MOAIDException("pvp2.01", null, e); - - } - - } - - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, - HttpServletResponse httpResp) { - return true; - } - - public String getDefaultActionName() { - return "PVPAuthenticationRequestAction"; - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java deleted file mode 100644 index 851f47a68..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java +++ /dev/null @@ -1,93 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import com.google.common.net.MediaType; - -import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -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.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPMetadataBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.IDPPVPMetadataConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; -import at.gv.egovernment.moa.logging.Logger; - -@Service("pvpMetadataService") -public class MetadataAction implements IAction { - - - - @Autowired private MOAReversionLogger revisionsLogger; - @Autowired private IDPCredentialProvider credentialProvider; - @Autowired private PVPMetadataBuilder metadatabuilder; - - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, - HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { - try { - revisionsLogger.logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_PVP_METADATA); - - //build metadata - IPVPMetadataBuilderConfiguration metadataConfig = - new IDPPVPMetadataConfiguration(req.getAuthURLWithOutSlash(), credentialProvider); - - String metadataXML = metadatabuilder.buildPVPMetadata(metadataConfig); - Logger.debug("METADATA: " + metadataXML); - - byte[] content = metadataXML.getBytes("UTF-8"); - httpResp.setStatus(HttpServletResponse.SC_OK); - httpResp.setContentLength(content.length); - httpResp.setContentType(MediaType.XML_UTF_8.toString()); - httpResp.getOutputStream().write(content); - return null; - - } catch (Exception e) { - Logger.error("Failed to generate metadata", e); - throw new MOAIDException("pvp2.13", null); - } - } - - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, - HttpServletResponse httpResp) { - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() - */ - @Override - public String getDefaultActionName() { - return "IDP - PVP Metadata action"; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java index 4369a469a..5c71852f2 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 @@ -22,6 +22,8 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x; +import java.net.MalformedURLException; +import java.net.URL; import java.util.Arrays; import java.util.List; @@ -29,92 +31,54 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; -import org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.AttributeQuery; -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.Issuer; import org.opensaml.saml2.core.LogoutRequest; import org.opensaml.saml2.core.LogoutResponse; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.Response; -import org.opensaml.saml2.core.Status; -import org.opensaml.saml2.core.StatusCode; -import org.opensaml.saml2.core.StatusMessage; -import org.opensaml.saml2.core.impl.AuthnRequestImpl; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.AttributeConsumingService; import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.ws.security.SecurityPolicyException; import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.x509.X509Credential; -import org.opensaml.xml.signature.SignableXMLObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; +import at.gv.egiz.eaaf.core.exceptions.ProtocolNotActiveException; +import at.gv.egiz.eaaf.core.impl.gui.velocity.VelocityLogAdapter; +import at.gv.egiz.eaaf.core.impl.utils.HTTPUtils; +import at.gv.egiz.eaaf.modules.pvp2.exception.AttributQueryException; +import at.gv.egiz.eaaf.modules.pvp2.exception.NoMetadataInformationException; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.AbstractPVP2XProtocol; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.SoapBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.InboundMessage; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileResponse; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.EAAFURICompare; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionValidationExeption; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -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.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.frontend.velocity.VelocityLogAdapter; -import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; 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.data.IAuthenticationSession; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; -import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.MOAURICompare; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.SoapBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidAssertionConsumerServiceException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.MandateAttributesNotHandleAbleException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NameIDFormatNotSupportedException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMetadataInformationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SLOException; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.CheckMandateAttributes; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.id.protocols.pvp2x.validation.AuthnRequestValidator; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.util.ErrorResponseUtils; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; - + @Controller -public class PVP2XProtocol extends AbstractAuthProtocolModulController { +public class PVP2XProtocol extends AbstractPVP2XProtocol { - @Autowired IDPCredentialProvider pvpCredentials; - @Autowired SAMLVerificationEngineSP samlVerificationEngine; - @Autowired(required=true) private MOAMetadataProvider metadataProvider; + @Autowired(required=true) AuthConfiguration moaAuthConfig; + @Autowired protected IAuthenticationSessionStoreage authenticatedSessionStorage; public static final String NAME = PVP2XProtocol.class.getName(); - public static final String PATH = "id_pvp2x"; + public static final String PATH = "id_pvp2-sprofile"; - public static final String REDIRECT = "Redirect"; - public static final String POST = "Post"; - public static final String SOAP = "Soap"; - public static final String METADATA = "Metadata"; - public static final String ATTRIBUTEQUERY = "AttributeQuery"; - public static final String SINGLELOGOUT = "SingleLogOut"; public static final List<String> DEFAULTREQUESTEDATTRFORINTERFEDERATION = Arrays.asList( new String[] { @@ -130,202 +94,68 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { return NAME; } - public String getPath() { + public String getAuthProtocolIdentifier() { return PATH; } public PVP2XProtocol() { super(); - } + } //PVP2.x metadata end-point - @RequestMapping(value = "/pvp2/metadata", method = {RequestMethod.POST, RequestMethod.GET}) - public void PVPMetadataRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException { - if (!authConfig.getAllowedProtocols().isPVP21Active()) { + @RequestMapping(value = PVPConfiguration.PVP2_METADATA, method = {RequestMethod.POST, RequestMethod.GET}) + public void PVPMetadataRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { + if (!moaAuthConfig.getAllowedProtocols().isPVP21Active()) { Logger.info("PVP2.1 is deaktivated!"); throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }); } - //create pendingRequest object - PVPTargetConfiguration pendingReq = applicationContext.getBean(PVPTargetConfiguration.class); - pendingReq.initialize(req); - pendingReq.setModule(NAME); - revisionsLogger.logEvent( - pendingReq.getUniqueSessionIdentifier(), - pendingReq.getUniqueTransactionIdentifier(), - MOAIDEventConstants.TRANSACTION_IP, - req.getRemoteAddr()); - - MetadataAction metadataAction = applicationContext.getBean(MetadataAction.class); - metadataAction.processRequest(pendingReq, - req, resp, null); + super.pvpMetadataRequest(req, resp); } //PVP2.x IDP POST-Binding end-point - @RequestMapping(value = "/pvp2/post", method = {RequestMethod.POST}) - public void PVPIDPPostRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException { - if (!authConfig.getAllowedProtocols().isPVP21Active()) { + @RequestMapping(value = PVPConfiguration.PVP2_IDP_POST, method = {RequestMethod.POST}) + public void PVPIDPPostRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { + if (!moaAuthConfig.getAllowedProtocols().isPVP21Active()) { Logger.info("PVP2.1 is deaktivated!"); throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }); } - PVPTargetConfiguration pendingReq = null; - - try { - //create pendingRequest object - pendingReq = applicationContext.getBean(PVPTargetConfiguration.class); - pendingReq.initialize(req); - pendingReq.setModule(NAME); - - revisionsLogger.logEvent(MOAIDEventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); - revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_CREATED, pendingReq.getUniqueTransactionIdentifier()); - revisionsLogger.logEvent( - pendingReq.getUniqueSessionIdentifier(), - pendingReq.getUniqueTransactionIdentifier(), - MOAIDEventConstants.TRANSACTION_IP, - req.getRemoteAddr()); - - //get POST-Binding decoder implementation - InboundMessage msg = (InboundMessage) new PostBinding().decode( - req, resp, metadataProvider, false, - new MOAURICompare(PVPConfiguration.getInstance().getIDPSSOPostService(pendingReq.getAuthURL()))); - pendingReq.setRequest(msg); - - //preProcess Message - preProcess(req, resp, pendingReq); + super.PVPIDPPostRequest(req, resp); - } catch (SecurityPolicyException e) { - String samlRequest = req.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SecurityException e) { - String samlRequest = req.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } catch (MOAIDException e) { - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw e; - - } catch (Throwable e) { - String samlRequest = req.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new MOAIDException("pvp2.24", new Object[] {e.getMessage()}); - } } //PVP2.x IDP Redirect-Binding end-point - @RequestMapping(value = "/pvp2/redirect", method = {RequestMethod.GET}) - public void PVPIDPRedirecttRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException { + @RequestMapping(value = PVPConfiguration.PVP2_IDP_REDIRECT, method = {RequestMethod.GET}) + public void PVPIDPRedirecttRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { if (!AuthConfigurationProviderFactory.getInstance().getAllowedProtocols().isPVP21Active()) { Logger.info("PVP2.1 is deaktivated!"); throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }); } - PVPTargetConfiguration pendingReq = null; - try { - //create pendingRequest object - pendingReq = applicationContext.getBean(PVPTargetConfiguration.class); - pendingReq.initialize(req); - pendingReq.setModule(NAME); - - revisionsLogger.logEvent(MOAIDEventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); - revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_CREATED, pendingReq.getUniqueTransactionIdentifier()); - revisionsLogger.logEvent( - pendingReq.getUniqueSessionIdentifier(), - pendingReq.getUniqueTransactionIdentifier(), - MOAIDEventConstants.TRANSACTION_IP, - req.getRemoteAddr()); - - //get POST-Binding decoder implementation - InboundMessage msg = (InboundMessage) new RedirectBinding().decode( - req, resp, metadataProvider, false, - new MOAURICompare(PVPConfiguration.getInstance().getIDPSSORedirectService(pendingReq.getAuthURL()))); - pendingReq.setRequest(msg); - - //preProcess Message - preProcess(req, resp, pendingReq); - - } catch (SecurityPolicyException e) { - String samlRequest = req.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SecurityException e) { - String samlRequest = req.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } catch (MOAIDException e) { - String samlRequest = req.getParameter("SAMLRequest"); - Logger.info("Receive INVALID protocol request: " + samlRequest); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw e; - - } catch (Throwable e) { - String samlRequest = req.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - - //write revision log entries - if (pendingReq != null) - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR, pendingReq.getUniqueTransactionIdentifier()); - - throw new MOAIDException("pvp2.24", new Object[] {e.getMessage()}); - } + + super.PVPIDPRedirecttRequest(req, resp); + } //PVP2.x IDP SOAP-Binding end-point @RequestMapping(value = "/pvp2/soap", method = {RequestMethod.POST}) - public void PVPIDPSOAPRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException { - if (!authConfig.getAllowedProtocols().isPVP21Active()) { - Logger.info("PVP2.1 is deaktivated!"); - throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }); - - } + public void PVPIDPSOAPRequest(HttpServletRequest req, HttpServletResponse resp) throws EAAFException { +// if (!authConfig.getAllowedProtocols().isPVP21Active()) { +// Logger.info("PVP2.1 is deaktivated!"); +// throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }, "PVP2.1 is deaktivated!"); +// +// } - PVPTargetConfiguration pendingReq = null; + PVPSProfilePendingRequest pendingReq = null; try { //create pendingRequest object - pendingReq = applicationContext.getBean(PVPTargetConfiguration.class); - pendingReq.initialize(req); + pendingReq = applicationContext.getBean(PVPSProfilePendingRequest.class); + pendingReq.initialize(req, authConfig); pendingReq.setModule(NAME); revisionsLogger.logEvent(MOAIDEventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); @@ -339,7 +169,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { //get POST-Binding decoder implementation InboundMessage msg = (InboundMessage) new SoapBinding().decode( req, resp, metadataProvider, false, - new MOAURICompare(PVPConfiguration.getInstance().getIDPSSOPostService(pendingReq.getAuthURL()))); + new EAAFURICompare(pvpBasicConfiguration.getIDPSSOPostService(pendingReq.getAuthURL()))); pendingReq.setRequest(msg); //preProcess Message @@ -385,157 +215,27 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { } - - private void preProcess(HttpServletRequest request, - HttpServletResponse response, PVPTargetConfiguration pendingReq) throws Throwable { - - InboundMessage msg = pendingReq.getRequest(); - - if (MiscUtil.isEmpty(msg.getEntityID())) { - throw new InvalidProtocolRequestException("pvp2.20", new Object[] {}); - - } - - if(!msg.isVerified()) { - samlVerificationEngine.verify(msg, - TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); - msg.setVerified(true); - - } - - if (msg instanceof MOARequest && - ((MOARequest)msg).getSamlRequest() instanceof AuthnRequest) - preProcessAuthRequest(request, response, pendingReq); - - else if (msg instanceof MOARequest && - ((MOARequest)msg).getSamlRequest() instanceof AttributeQuery) - preProcessAttributQueryRequest(request, response, pendingReq); + protected boolean childPreProcess(HttpServletRequest request, + HttpServletResponse response, PVPSProfilePendingRequest pendingReq) throws Throwable { + InboundMessage msg = pendingReq.getRequest(); + if (msg instanceof PVPSProfileRequest && + ((PVPSProfileRequest)msg).getSamlRequest() instanceof AttributeQuery) + preProcessAttributQueryRequest(request, response, pendingReq); - else if (msg instanceof MOARequest && - ((MOARequest)msg).getSamlRequest() instanceof LogoutRequest) - preProcessLogOut(request, response, pendingReq); + else if (msg instanceof PVPSProfileRequest && + ((PVPSProfileRequest)msg).getSamlRequest() instanceof LogoutRequest) + preProcessLogOut(request, response, pendingReq); - else if (msg instanceof MOAResponse && - ((MOAResponse)msg).getResponse() instanceof LogoutResponse) - preProcessLogOut(request, response, pendingReq); - - else { - Logger.error("Receive unsupported PVP21 message"); - throw new MOAIDException("Unsupported PVP21 message", new Object[] {}); - } + else if (msg instanceof PVPSProfileResponse && + ((PVPSProfileResponse)msg).getResponse() instanceof LogoutResponse) + preProcessLogOut(request, response, pendingReq); - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROTOCOL_TYPE, PATH); - - //switch to session authentication - performAuthentication(request, response, pendingReq); - } - - public boolean generateErrorMessage(Throwable e, - HttpServletRequest request, HttpServletResponse response, - IRequest protocolRequest) throws Throwable { - - if(protocolRequest == null) { - throw e; - } - - if(!(protocolRequest instanceof PVPTargetConfiguration) ) { - throw e; - } - PVPTargetConfiguration pvpRequest = (PVPTargetConfiguration)protocolRequest; - - Response samlResponse = - SAML2Utils.createSAMLObject(Response.class); - Status status = SAML2Utils.createSAMLObject(Status.class); - StatusCode statusCode = SAML2Utils.createSAMLObject(StatusCode.class); - StatusMessage statusMessage = SAML2Utils.createSAMLObject(StatusMessage.class); - - ErrorResponseUtils errorUtils = ErrorResponseUtils.getInstance(); - String moaError = null; - - if(e instanceof NoPassivAuthenticationException) { - statusCode.setValue(StatusCode.NO_PASSIVE_URI); - statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); - - } else if (e instanceof NameIDFormatNotSupportedException) { - statusCode.setValue(StatusCode.INVALID_NAMEID_POLICY_URI); - statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); - - } else if (e instanceof SLOException) { - //SLOExecpetions only occurs if session information is lost + else return false; - } else if(e instanceof PVP2Exception) { - PVP2Exception ex = (PVP2Exception) e; - statusCode.setValue(ex.getStatusCodeValue()); - String statusMessageValue = ex.getStatusMessageValue(); - if(statusMessageValue != null) { - statusMessage.setMessage(StringEscapeUtils.escapeXml(statusMessageValue)); - } - moaError = errorUtils.mapInternalErrorToExternalError(ex.getMessageId()); - - } else { - statusCode.setValue(StatusCode.RESPONDER_URI); - statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); - moaError = errorUtils.getResponseErrorCode(e); - } - - - if (MiscUtil.isNotEmpty(moaError)) { - StatusCode moaStatusCode = SAML2Utils.createSAMLObject(StatusCode.class); - moaStatusCode.setValue(moaError); - statusCode.setStatusCode(moaStatusCode); - } - - status.setStatusCode(statusCode); - if(statusMessage.getMessage() != null) { - status.setStatusMessage(statusMessage); - } - samlResponse.setStatus(status); - String remoteSessionID = SAML2Utils.getSecureIdentifier(); - samlResponse.setID(remoteSessionID); - - samlResponse.setIssueInstant(new DateTime()); - Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); - nissuer.setValue(PVPConfiguration.getInstance().getIDPSSOMetadataService( - pvpRequest.getAuthURL())); - nissuer.setFormat(NameID.ENTITY); - samlResponse.setIssuer(nissuer); - - IEncoder encoder = null; - - if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - encoder = applicationContext.getBean("PVPRedirectBinding", RedirectBinding.class); - - } else if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { - encoder = applicationContext.getBean("PVPPOSTBinding", PostBinding.class); - } else if (pvpRequest.getBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) { - encoder = applicationContext.getBean("PVPSOAPBinding", SoapBinding.class); - } - - if(encoder == null) { - // default to redirect binding - encoder = new RedirectBinding(); - } - - String relayState = null; - if (pvpRequest.getRequest() != null) - relayState = pvpRequest.getRequest().getRelayState(); - - X509Credential signCred = pvpCredentials.getIDPAssertionSigningCredential(); - - encoder.encodeRespone(request, response, samlResponse, pvpRequest.getConsumerURL(), - relayState, signCred, protocolRequest); return true; } - - public boolean validate(HttpServletRequest request, - HttpServletResponse response, IRequest pending) { - - return true; - } - /** * PreProcess Single LogOut request @@ -543,18 +243,19 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { * @param response * @param msg * @return + * @throws EAAFException * @throws MOAIDException */ private void preProcessLogOut(HttpServletRequest request, - HttpServletResponse response, PVPTargetConfiguration pendingReq) throws MOAIDException { + HttpServletResponse response, PVPSProfilePendingRequest pendingReq) throws EAAFException { InboundMessage inMsg = pendingReq.getRequest(); - MOARequest msg; - if (inMsg instanceof MOARequest && - ((MOARequest)inMsg).getSamlRequest() instanceof LogoutRequest) { + PVPSProfileRequest msg; + if (inMsg instanceof PVPSProfileRequest && + ((PVPSProfileRequest)inMsg).getSamlRequest() instanceof LogoutRequest) { //preProcess single logout request from service provider - msg = (MOARequest) inMsg; + msg = (PVPSProfileRequest) inMsg; EntityDescriptor metadata = msg.getEntityMetadata(metadataProvider); if(metadata == null) { @@ -563,11 +264,11 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { String oaURL = metadata.getEntityID(); oaURL = StringEscapeUtils.escapeHtml(oaURL); - IOAAuthParameters oa = authConfig.getOnlineApplicationParameter(oaURL); + ISPConfiguration oa = authConfig.getServiceProviderConfiguration(oaURL); Logger.info("Dispatch PVP2 SingleLogOut: OAURL=" + oaURL + " Binding=" + msg.getRequestBinding()); - pendingReq.setOAURL(oaURL); + pendingReq.setSPEntityId(oaURL); pendingReq.setOnlineApplicationConfiguration(oa); pendingReq.setBinding(msg.getRequestBinding()); @@ -575,25 +276,33 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { - } else if (inMsg instanceof MOAResponse && - ((MOAResponse)inMsg).getResponse() instanceof LogoutResponse) { + } else if (inMsg instanceof PVPSProfileResponse && + ((PVPSProfileResponse)inMsg).getResponse() instanceof LogoutResponse) { //preProcess single logour response from service provider - LogoutResponse resp = (LogoutResponse) (((MOAResponse)inMsg).getResponse()); + LogoutResponse resp = (LogoutResponse) (((PVPSProfileResponse)inMsg).getResponse()); Logger.debug("PreProcess SLO Response from " + resp.getIssuer()); - List<String> allowedPublicURLPrefix = - AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); - boolean isAllowedDestination = false; +// List<String> allowedPublicURLPrefix = authConfig.getIDPPublicURLPrefixes(); +// AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); - for (String prefix : allowedPublicURLPrefix) { - if (resp.getDestination().startsWith( - prefix)) { - isAllowedDestination = true; - break; - } + boolean isAllowedDestination = false; + try { + isAllowedDestination = MiscUtil.isNotEmpty(authConfig.validateIDPURL(new URL(resp.getDestination()))); + + } catch (MalformedURLException e) { + Logger.info(resp.getDestination() + " is NOT valid. Reason: " + e.getMessage()); + } + +// for (String prefix : allowedPublicURLPrefix) { +// if (resp.getDestination().startsWith( +// prefix)) { +// isAllowedDestination = true; +// break; +// } +// } if (!isAllowedDestination) { Logger.warn("PVP 2.1 single logout response destination does not match to IDP URL"); @@ -606,11 +315,11 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { } else - throw new MOAIDException("Unsupported request", new Object[] {}); + throw new EAAFException("Unsupported request"); pendingReq.setRequest(inMsg); - pendingReq.setAction(SINGLELOGOUT); + pendingReq.setAction(PVPConstants.SINGLELOGOUT); //Single LogOut Request needs no authentication pendingReq.setNeedAuthentication(false); @@ -627,26 +336,21 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { * @throws Throwable */ private void preProcessAttributQueryRequest(HttpServletRequest request, - HttpServletResponse response, PVPTargetConfiguration pendingReq) throws Throwable { - MOARequest moaRequest = ((MOARequest)pendingReq.getRequest()); + HttpServletResponse response, PVPSProfilePendingRequest pendingReq) throws Throwable { + PVPSProfileRequest moaRequest = ((PVPSProfileRequest)pendingReq.getRequest()); AttributeQuery attrQuery = (AttributeQuery) moaRequest.getSamlRequest(); moaRequest.setEntityID(attrQuery.getIssuer().getValue()); //validate destination String destinaten = attrQuery.getDestination(); - if (!PVPConfiguration.getInstance().getIDPAttributeQueryService(HTTPUtils.extractAuthURLFromRequest(request)).equals(destinaten)) { + if (!pvpBasicConfiguration.getIDPSSOSOAPService(HTTPUtils.extractAuthURLFromRequest(request)).equals(destinaten)) { Logger.warn("AttributeQuery destination does not match IDP AttributeQueryService URL"); throw new AttributQueryException("AttributeQuery destination does not match IDP AttributeQueryService URL", null); } - //check if Issuer is an interfederation IDP - // check parameter - if (!ParamValidatorUtils.isValidOA(moaRequest.getEntityID())) - throw new WrongParametersException("StartAuthentication", - PARAM_OA, "auth.12"); - - IOAAuthParameters oa = authConfig.getOnlineApplicationParameter(moaRequest.getEntityID()); + //check if Issuer is an interfederation IDP + IOAAuthParameters oa = authConfig.getServiceProviderConfiguration(moaRequest.getEntityID(), IOAAuthParameters.class); if (!oa.isInderfederationIDP()) { Logger.warn("AttributeQuery requests are only allowed for interfederation IDPs."); throw new AttributQueryException("AttributeQuery requests are only allowed for interfederation IDPs.", null); @@ -670,7 +374,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { //set preProcessed information into pending-request pendingReq.setRequest(moaRequest); - pendingReq.setOAURL(moaRequest.getEntityID()); + pendingReq.setSPEntityId(moaRequest.getEntityID()); pendingReq.setOnlineApplicationConfiguration(oa); pendingReq.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); @@ -681,147 +385,12 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { pendingReq.setAction(AttributQueryAction.class.getName()); //add moasession - pendingReq.setInternalSSOSessionIdentifier(session.getSessionID()); + pendingReq.setInternalSSOSessionIdentifier(session.getSSOSessionID()); //write revisionslog entry revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_ATTRIBUTQUERY); } - - /** - * PreProcess Authn request - * @param request - * @param response - * @param pendingReq - * @throws Throwable - */ - private void preProcessAuthRequest(HttpServletRequest request, - HttpServletResponse response, PVPTargetConfiguration pendingReq) throws Throwable { - - MOARequest moaRequest = ((MOARequest)pendingReq.getRequest()); - SignableXMLObject samlReq = moaRequest.getSamlRequest(); - - if(!(samlReq instanceof AuthnRequest)) { - throw new MOAIDException("Unsupported request", new Object[] {}); - } - - EntityDescriptor metadata = moaRequest.getEntityMetadata(metadataProvider); - if(metadata == null) { - throw new NoMetadataInformationException(); - } - SPSSODescriptor spSSODescriptor = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); - - AuthnRequest authnRequest = (AuthnRequest)samlReq; - - if (authnRequest.getIssueInstant() == null) { - Logger.warn("Unsupported request: No IssueInstant Attribute found."); - throw new AuthnRequestValidatorException("Unsupported request: No IssueInstant Attribute found.", new Object[] {}); - - } - - if (authnRequest.getIssueInstant().minusMinutes(MOAIDAuthConstants.TIME_JITTER).isAfterNow()) { - Logger.warn("Unsupported request: No IssueInstant DateTime is not valid anymore."); - throw new AuthnRequestValidatorException("Unsupported request: No IssueInstant DateTime is not valid anymore.", new Object[] {}); - - } - - //parse AssertionConsumerService - AssertionConsumerService consumerService = null; - if (MiscUtil.isNotEmpty(authnRequest.getAssertionConsumerServiceURL()) && - MiscUtil.isNotEmpty(authnRequest.getProtocolBinding())) { - //use AssertionConsumerServiceURL from request - - //check requested AssertionConsumingService URL against metadata - List<AssertionConsumerService> metadataAssertionServiceList = spSSODescriptor.getAssertionConsumerServices(); - for (AssertionConsumerService service : metadataAssertionServiceList) { - if (authnRequest.getProtocolBinding().equals(service.getBinding()) - && authnRequest.getAssertionConsumerServiceURL().equals(service.getLocation())) { - consumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - consumerService.setBinding(authnRequest.getProtocolBinding()); - consumerService.setLocation(authnRequest.getAssertionConsumerServiceURL()); - Logger.debug("Requested AssertionConsumerServiceURL is valid."); - } - } - - if (consumerService == null) { - throw new InvalidAssertionConsumerServiceException(authnRequest.getAssertionConsumerServiceURL()); - - } - - } else { - //use AssertionConsumerServiceIndex and select consumerService from metadata - Integer aIdx = authnRequest.getAssertionConsumerServiceIndex(); - int assertionidx = 0; - - if(aIdx != null) { - assertionidx = aIdx.intValue(); - - } else { - assertionidx = SAML2Utils.getDefaultAssertionConsumerServiceIndex(spSSODescriptor); - - } - consumerService = spSSODescriptor.getAssertionConsumerServices().get(assertionidx); - - if (consumerService == null) { - throw new InvalidAssertionConsumerServiceException(aIdx); - - } - } - - - //select AttributeConsumingService from request - AttributeConsumingService attributeConsumer = null; - Integer aIdx = authnRequest.getAttributeConsumingServiceIndex(); - int attributeIdx = 0; - - if(aIdx != null) { - attributeIdx = aIdx.intValue(); - } - - if (spSSODescriptor.getAttributeConsumingServices() != null && - spSSODescriptor.getAttributeConsumingServices().size() > 0) { - attributeConsumer = spSSODescriptor.getAttributeConsumingServices().get(attributeIdx); - } - - //validate AuthnRequest - AuthnRequestImpl authReq = (AuthnRequestImpl) samlReq; - AuthnRequestValidator.validate(authReq); - - String useMandate = request.getParameter(PARAM_USEMANDATE); - if(useMandate != null) { - if(useMandate.equals("true") && attributeConsumer != null) { - if(!CheckMandateAttributes.canHandleMandate(attributeConsumer)) { - throw new MandateAttributesNotHandleAbleException(); - } - } - } - - String oaURL = moaRequest.getEntityMetadata(metadataProvider).getEntityID(); - oaURL = StringEscapeUtils.escapeHtml(oaURL); - IOAAuthParameters oa = authConfig.getOnlineApplicationParameter(oaURL); - - Logger.info("Dispatch PVP2 AuthnRequest: OAURL=" + oaURL + " Binding=" + consumerService.getBinding()); - - pendingReq.setOAURL(oaURL); - pendingReq.setOnlineApplicationConfiguration(oa); - pendingReq.setBinding(consumerService.getBinding()); - pendingReq.setRequest(moaRequest); - pendingReq.setConsumerURL(consumerService.getLocation()); - - //parse AuthRequest - pendingReq.setPassiv(authReq.isPassive()); - pendingReq.setForce(authReq.isForceAuthn()); - - //AuthnRequest needs authentication - pendingReq.setNeedAuthentication(true); - - //set protocol action, which should be executed after authentication - pendingReq.setAction(AuthenticationAction.class.getName()); - - //write revisionslog entry - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHREQUEST); - - } } 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 62105abda..67cbafe90 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 @@ -28,9 +28,9 @@ import org.opensaml.xml.io.MarshallingException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.StoredAssertion; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; @Service("PVPAssertionStorage") public class PVPAssertionStorage implements SAMLArtifactMap { @@ -47,11 +47,11 @@ public class PVPAssertionStorage implements SAMLArtifactMap { relyingPartyId, issuerId, samlMessage); - - try { + + try { transactionStorage.put(artifact, assertion, -1); - } catch (MOADatabaseException e) { + } catch (EAAFException e) { // TODO Insert Error Handling, if Assertion could not be stored throw new MarshallingException("Assertion are not stored in Database.",e); } @@ -61,7 +61,7 @@ public class PVPAssertionStorage implements SAMLArtifactMap { try { return transactionStorage.get(artifact, SAMLArtifactMapEntry.class); - } catch (MOADatabaseException e) { + } catch (EAAFException e) { // TODO Insert Error Handling, if Assertion could not be read e.printStackTrace(); return null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java index 95e3c5bc2..cdd0b659e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java @@ -22,24 +22,9 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.opensaml.xml.encryption.EncryptionConstants; -import org.opensaml.xml.signature.SignatureConstants; - -import at.gv.egovernment.moa.id.data.Trible; - -public interface PVPConstants { +public interface PVPConstants extends at.gv.egiz.eaaf.modules.pvp2.PVPConstants { public static final String SSLSOCKETFACTORYNAME = "MOAMetaDataProvider"; - - public static final String DEFAULT_SIGNING_METHODE = SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256; - public static final String DEFAULT_DIGESTMETHODE = SignatureConstants.ALGO_ID_DIGEST_SHA256; - public static final String DEFAULT_SYM_ENCRYPTION_METHODE = EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256; - public static final String DEFAULT_ASYM_ENCRYPTION_METHODE = EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP; - public static final String STORK_QAA_PREFIX = "http://www.stork.gov.eu/1.0/citizenQAALevel/"; public static final String STORK_QAA_1_1 = "http://www.stork.gov.eu/1.0/citizenQAALevel/1"; @@ -51,327 +36,5 @@ public interface PVPConstants { public static final String EIDAS_QAA_LOW = EIDAS_QAA_PREFIX + "low"; public static final String EIDAS_QAA_SUBSTANTIAL = EIDAS_QAA_PREFIX + "substantial"; public static final String EIDAS_QAA_HIGH = EIDAS_QAA_PREFIX + "high"; - - public static final String STORK_ATTRIBUTE_PREFIX = "http://www.stork.gov.eu/"; - - public static final String URN_OID_PREFIX = "urn:oid:"; - - public static final String PVP_VERSION_OID = "1.2.40.0.10.2.1.1.261.10"; - public static final String PVP_VERSION_NAME = URN_OID_PREFIX + PVP_VERSION_OID; - public static final String PVP_VERSION_FRIENDLY_NAME = "PVP-VERSION"; - public static final String PVP_VERSION_2_1 = "2.1"; - - - public static final String SECCLASS_OID = "1.2.40.0.10.2.1.1.261.110"; - public static final String SECCLASS_FRIENDLY_NAME = "SECCLASS"; - public static final String SECCLASS_NAME = URN_OID_PREFIX + SECCLASS_OID; - public static final int SECCLASS_MAX_LENGTH = 128; - - public static final String PRINCIPAL_NAME_OID = "1.2.40.0.10.2.1.1.261.20"; - public static final String PRINCIPAL_NAME_NAME = URN_OID_PREFIX + PRINCIPAL_NAME_OID; - public static final String PRINCIPAL_NAME_FRIENDLY_NAME = "PRINCIPAL-NAME"; - public static final int PRINCIPAL_NAME_MAX_LENGTH = 128; - - public static final String GIVEN_NAME_OID = "2.5.4.42"; - public static final String GIVEN_NAME_NAME = URN_OID_PREFIX + GIVEN_NAME_OID; - public static final String GIVEN_NAME_FRIENDLY_NAME = "GIVEN-NAME"; - public static final int GIVEN_NAME_MAX_LENGTH = 128; - - public static final String BIRTHDATE_OID = "1.2.40.0.10.2.1.1.55"; - public static final String BIRTHDATE_NAME = URN_OID_PREFIX + BIRTHDATE_OID; - public static final String BIRTHDATE_FRIENDLY_NAME = "BIRTHDATE"; - public static final String BIRTHDATE_FORMAT_PATTERN = "yyyy-MM-dd"; - - public static final String USERID_OID = "0.9.2342.19200300.100.1.1"; - public static final String USERID_NAME = URN_OID_PREFIX + USERID_OID; - public static final String USERID_FRIENDLY_NAME = "USERID"; - public static final int USERID_MAX_LENGTH = 128; - - public static final String GID_OID = "1.2.40.0.10.2.1.1.1"; - public static final String GID_NAME = URN_OID_PREFIX + GID_OID; - public static final String GID_FRIENDLY_NAME = "GID"; - public static final int GID_MAX_LENGTH = 128; - - public static final String BPK_OID = "1.2.40.0.10.2.1.1.149"; - public static final String BPK_NAME = URN_OID_PREFIX + BPK_OID; - public static final String BPK_FRIENDLY_NAME = "BPK"; - public static final int BPK_MAX_LENGTH = 1024; - - public static final String ENC_BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.22"; - public static final String ENC_BPK_LIST_NAME = URN_OID_PREFIX+ENC_BPK_LIST_OID; - public static final String ENC_BPK_LIST_FRIENDLY_NAME = "ENC-BPK-LIST"; - public static final int ENC_BPK_LIST_MAX_LENGTH = 32767; - - public static final String MAIL_OID = "0.9.2342.19200300.100.1.3"; - public static final String MAIL_NAME = URN_OID_PREFIX + MAIL_OID; - public static final String MAIL_FRIENDLY_NAME = "MAIL"; - public static final int MAIL_MAX_LENGTH = 128; - - public static final String TEL_OID = "2.5.4.20"; - public static final String TEL_NAME = URN_OID_PREFIX + TEL_OID; - public static final String TEL_FRIENDLY_NAME = "TEL"; - public static final int TEL_MAX_LENGTH = 32; - - public static final String PARTICIPANT_ID_OID = "1.2.40.0.10.2.1.1.71"; - public static final String PARTICIPANT_ID_NAME = URN_OID_PREFIX + PARTICIPANT_ID_OID; - public static final String PARTICIPANT_ID_FRIENDLY_NAME = "PARTICIPANT-ID"; - public static final int PARTICIPANT_MAX_LENGTH = 39; - - public static final String PARTICIPANT_OKZ_OID = "1.2.40.0.10.2.1.1.261.24"; - public static final String PARTICIPANT_OKZ_NAME = URN_OID_PREFIX + PARTICIPANT_OKZ_OID; - public static final String PARTICIPANT_OKZ_FRIENDLY_NAME = "PARTICIPANT-OKZ"; - public static final int PARTICIPANT_OKZ_MAX_LENGTH = 32; - - public static final String OU_OKZ_OID = "1.2.40.0.10.2.1.1.153"; - public static final String OU_OKZ_NAME = URN_OID_PREFIX + OU_OKZ_OID; - public static final int OU_OKZ_MAX_LENGTH = 32; - - public static final String OU_GV_OU_ID_OID = "1.2.40.0.10.2.1.1.3"; - public static final String OU_GV_OU_ID_NAME = URN_OID_PREFIX + OU_GV_OU_ID_OID; - public static final String OU_GV_OU_ID_FRIENDLY_NAME = "OU-GV-OU-ID"; - public static final int OU_GV_OU_ID_MAX_LENGTH = 39; - - public static final String OU_OID = "2.5.4.11"; - public static final String OU_NAME = URN_OID_PREFIX + OU_OID; - public static final String OU_FRIENDLY_NAME = "OU"; - public static final int OU_MAX_LENGTH = 64; - - public static final String FUNCTION_OID = "1.2.40.0.10.2.1.1.33"; - public static final String FUNCTION_NAME = URN_OID_PREFIX + FUNCTION_OID; - public static final String FUNCTION_FRIENDLY_NAME = "FUNCTION"; - public static final int FUNCTION_MAX_LENGTH = 32; - - public static final String ROLES_OID = "1.2.40.0.10.2.1.1.261.30"; - public static final String ROLES_NAME = URN_OID_PREFIX + ROLES_OID; - public static final String ROLES_FRIENDLY_NAME = "ROLES"; - public static final int ROLES_MAX_LENGTH = 32767; - - @Deprecated public static final String EID_CITIZEN_QAA_LEVEL_OID = "1.2.40.0.10.2.1.1.261.94"; - @Deprecated public static final String EID_CITIZEN_QAA_LEVEL_NAME = URN_OID_PREFIX + EID_CITIZEN_QAA_LEVEL_OID; - @Deprecated public static final String EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME = "EID-CITIZEN-QAA-LEVEL"; - - public static final String EID_CITIZEN_EIDAS_QAA_LEVEL_OID = "1.2.40.0.10.2.1.1.261.108"; - public static final String EID_CITIZEN_EIDAS_QAA_LEVEL_NAME = URN_OID_PREFIX + EID_CITIZEN_EIDAS_QAA_LEVEL_OID; - public static final String EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME = "EID-CITIZEN-QAA-EIDAS-LEVEL"; - - public static final String EID_ISSUING_NATION_OID = "1.2.40.0.10.2.1.1.261.32"; - public static final String EID_ISSUING_NATION_NAME = URN_OID_PREFIX + EID_ISSUING_NATION_OID; - public static final String EID_ISSUING_NATION_FRIENDLY_NAME = "EID-ISSUING-NATION"; - public static final int EID_ISSUING_NATION_MAX_LENGTH = 2; - - public static final String EID_SECTOR_FOR_IDENTIFIER_OID = "1.2.40.0.10.2.1.1.261.34"; - public static final String EID_SECTOR_FOR_IDENTIFIER_NAME = URN_OID_PREFIX + EID_SECTOR_FOR_IDENTIFIER_OID; - public static final String EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME = "EID-SECTOR-FOR-IDENTIFIER"; - public static final int EID_SECTOR_FOR_IDENTIFIER_MAX_LENGTH = 255; - - public static final String EID_SOURCE_PIN_OID = "1.2.40.0.10.2.1.1.261.36"; - public static final String EID_SOURCE_PIN_NAME = URN_OID_PREFIX + EID_SOURCE_PIN_OID; - public static final String EID_SOURCE_PIN_FRIENDLY_NAME = "EID-SOURCE-PIN"; - public static final int EID_SOURCE_PIN_MAX_LENGTH = 128; - - public static final String EID_SOURCE_PIN_TYPE_OID = "1.2.40.0.10.2.1.1.261.104"; - public static final String EID_SOURCE_PIN_TYPE_NAME = URN_OID_PREFIX + EID_SOURCE_PIN_TYPE_OID; - public static final String EID_SOURCE_PIN_TYPE_FRIENDLY_NAME = "EID-SOURCE-PIN-TYPE"; - public static final int EID_SOURCE_PIN_TYPE_MAX_LENGTH = 128; - - public static final String EID_IDENTITY_LINK_OID = "1.2.40.0.10.2.1.1.261.38"; - public static final String EID_IDENTITY_LINK_NAME = URN_OID_PREFIX + EID_IDENTITY_LINK_OID; - public static final String EID_IDENTITY_LINK_FRIENDLY_NAME = "EID-IDENTITY-LINK"; - public static final int EID_IDENTITY_LINK_MAX_LENGTH = 32767; - - public static final String EID_AUTH_BLOCK_OID = "1.2.40.0.10.2.1.1.261.62"; - public static final String EID_AUTH_BLOCK_NAME = URN_OID_PREFIX + EID_AUTH_BLOCK_OID; - public static final String EID_AUTH_BLOCK_FRIENDLY_NAME = "EID-AUTH-BLOCK"; - public static final int EID_AUTH_BLOCK_MAX_LENGTH = 32767; - - public static final String EID_CCS_URL_OID = "1.2.40.0.10.2.1.1.261.64"; - public static final String EID_CCS_URL_NAME = URN_OID_PREFIX + EID_CCS_URL_OID; - public static final String EID_CCS_URL_FRIENDLY_NAME = "EID-CCS-URL"; - public static final int EID_CCS_URL_MAX_LENGTH = 1024; - - public static final String EID_SIGNER_CERTIFICATE_OID = "1.2.40.0.10.2.1.1.261.66"; - public static final String EID_SIGNER_CERTIFICATE_NAME = URN_OID_PREFIX + EID_SIGNER_CERTIFICATE_OID; - public static final String EID_SIGNER_CERTIFICATE_FRIENDLY_NAME = "EID-SIGNER-CERTIFICATE"; - public static final int EID_SIGNER_CERTIFICATE_MAX_LENGTH = 32767; - - public static final String EID_STORK_TOKEN_OID = "1.2.40.0.10.2.1.1.261.96"; - public static final String EID_STORK_TOKEN_NAME = URN_OID_PREFIX + EID_STORK_TOKEN_OID; - public static final String EID_STORK_TOKEN_FRIENDLY_NAME = "EID-STORK-TOKEN"; - public static final int EID_STORK_TOKEN_MAX_LENGTH = 32767; - - public static final String MANDATE_TYPE_OID = "1.2.40.0.10.2.1.1.261.68"; - public static final String MANDATE_TYPE_NAME = URN_OID_PREFIX + MANDATE_TYPE_OID; - public static final String MANDATE_TYPE_FRIENDLY_NAME = "MANDATE-TYPE"; - public static final int MANDATE_TYPE_MAX_LENGTH = 256; - - public static final String MANDATE_TYPE_OID_OID = "1.2.40.0.10.2.1.1.261.106"; - public static final String MANDATE_TYPE_OID_NAME = URN_OID_PREFIX + MANDATE_TYPE_OID_OID; - public static final String MANDATE_TYPE_OID_FRIENDLY_NAME = "MANDATE-TYPE-OID"; - public static final int MANDATE_TYPE_OID_MAX_LENGTH = 256; - - public static final String MANDATE_NAT_PER_SOURCE_PIN_OID = "1.2.40.0.10.2.1.1.261.70"; - public static final String MANDATE_NAT_PER_SOURCE_PIN_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_SOURCE_PIN_OID; - public static final String MANDATE_NAT_PER_SOURCE_PIN_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-SOURCE-PIN"; - public static final int MANDATE_NAT_PER_SOURCE_PIN_MAX_LENGTH = 128; - - public static final String MANDATE_LEG_PER_SOURCE_PIN_OID = "1.2.40.0.10.2.1.1.261.100"; - public static final String MANDATE_LEG_PER_SOURCE_PIN_NAME = URN_OID_PREFIX + MANDATE_LEG_PER_SOURCE_PIN_OID; - public static final String MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME = "MANDATOR-LEGAL-PERSON-SOURCE-PIN"; - public static final int MANDATE_LEG_PER_SOURCE_PIN_MAX_LENGTH = 128; - - public static final String MANDATE_NAT_PER_SOURCE_PIN_TYPE_OID = "1.2.40.0.10.2.1.1.261.102"; - public static final String MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_SOURCE_PIN_TYPE_OID; - public static final String MANDATE_NAT_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-SOURCE-PIN-TYPE"; - public static final int MANDATE_NAT_PER_SOURCE_PIN_TYPE_MAX_LENGTH = 128; - - public static final String MANDATE_LEG_PER_SOURCE_PIN_TYPE_OID = "1.2.40.0.10.2.1.1.261.76"; - public static final String MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME = URN_OID_PREFIX + MANDATE_LEG_PER_SOURCE_PIN_TYPE_OID; - public static final String MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME = "MANDATOR-LEGAL-PERSON-SOURCE-PIN-TYPE"; - public static final int MANDATE_LEG_PER_SOURCE_PIN_TYPE_MAX_LENGTH = 128; - - public static final String MANDATE_NAT_PER_BPK_OID = "1.2.40.0.10.2.1.1.261.98"; - public static final String MANDATE_NAT_PER_BPK_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_BPK_OID; - public static final String MANDATE_NAT_PER_BPK_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-BPK"; - public static final int MANDATE_NAT_PER_BPK_MAX_LENGTH = 1024; - - public static final String MANDATE_NAT_PER_ENC_BPK_LIST_OID = "1.2.40.0.10.2.1.1.261.72"; - public static final String MANDATE_NAT_PER_ENC_BPK_LIST_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_ENC_BPK_LIST_OID; - public static final String MANDATE_NAT_PER_ENC_BPK_LIST_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-ENC-BPK-LIST"; - public static final int MANDATE_NAT_PER_ENC_BPK_LIST_MAX_LENGTH = 32767; - - public static final String MANDATE_NAT_PER_GIVEN_NAME_OID = "1.2.40.0.10.2.1.1.261.78"; - public static final String MANDATE_NAT_PER_GIVEN_NAME_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_GIVEN_NAME_OID; - public static final String MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-GIVEN-NAME"; - public static final int MANDATE_NAT_PER_GIVEN_NAME_MAX_LENGTH = 128; - - public static final String MANDATE_NAT_PER_FAMILY_NAME_OID = "1.2.40.0.10.2.1.1.261.80"; - public static final String MANDATE_NAT_PER_FAMILY_NAME_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_FAMILY_NAME_OID; - public static final String MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-FAMILY-NAME"; - public static final int MANDATE_NAT_PER_FAMILY_NAME_MAX_LENGTH = 128; - - public static final String MANDATE_NAT_PER_BIRTHDATE_OID = "1.2.40.0.10.2.1.1.261.82"; - public static final String MANDATE_NAT_PER_BIRTHDATE_NAME = URN_OID_PREFIX + MANDATE_NAT_PER_BIRTHDATE_OID; - public static final String MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME = "MANDATOR-NATURAL-PERSON-BIRTHDATE"; - public static final String MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN = BIRTHDATE_FORMAT_PATTERN; - - public static final String MANDATE_LEG_PER_FULL_NAME_OID = "1.2.40.0.10.2.1.1.261.84"; - public static final String MANDATE_LEG_PER_FULL_NAME_NAME = URN_OID_PREFIX + MANDATE_LEG_PER_FULL_NAME_OID; - public static final String MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME = "MANDATOR-LEGAL-PERSON-FULL-NAME"; - public static final int MANDATE_LEG_PER_FULL_NAME_MAX_LENGTH = 256; - - public static final String MANDATE_PROF_REP_OID_OID = "1.2.40.0.10.2.1.1.261.86"; - public static final String MANDATE_PROF_REP_OID_NAME = URN_OID_PREFIX + MANDATE_PROF_REP_OID_OID; - public static final String MANDATE_PROF_REP_OID_FRIENDLY_NAME = "MANDATE-PROF-REP-OID"; - public static final int MANDATE_PROF_REP_OID_MAX_LENGTH = 256; - - public static final String MANDATE_PROF_REP_DESC_OID = "1.2.40.0.10.2.1.1.261.88"; - public static final String MANDATE_PROF_REP_DESC_NAME = URN_OID_PREFIX + MANDATE_PROF_REP_DESC_OID; - public static final String MANDATE_PROF_REP_DESC_FRIENDLY_NAME = "MANDATE-PROF-REP-DESCRIPTION"; - public static final int MANDATE_PROF_REP_DESC_MAX_LENGTH = 1024; - - public static final String MANDATE_REFERENCE_VALUE_OID = "1.2.40.0.10.2.1.1.261.90"; - public static final String MANDATE_REFERENCE_VALUE_NAME = URN_OID_PREFIX + MANDATE_REFERENCE_VALUE_OID; - public static final String MANDATE_REFERENCE_VALUE_FRIENDLY_NAME = "MANDATE-REFERENCE-VALUE"; - public static final int MANDATE_REFERENCE_VALUE_MAX_LENGTH = 100; - - public static final String MANDATE_FULL_MANDATE_OID = "1.2.40.0.10.2.1.1.261.92"; - public static final String MANDATE_FULL_MANDATE_NAME = URN_OID_PREFIX + MANDATE_FULL_MANDATE_OID; - public static final String MANDATE_FULL_MANDATE_FRIENDLY_NAME = "MANDATE-FULL-MANDATE"; - public static final int MANDATE_FULL_MANDATE_MAX_LENGTH = 32767; - - public static final String INVOICE_RECPT_ID_OID = "1.2.40.0.10.2.1.1.261.40"; - public static final String INVOICE_RECPT_ID_NAME = URN_OID_PREFIX + INVOICE_RECPT_ID_OID; - public static final String INVOICE_RECPT_ID_FRIENDLY_NAME = "INVOICE-RECPT-ID"; - public static final int INVOICE_RECPT_ID_MAX_LENGTH = 64; - - public static final String COST_CENTER_ID_OID = "1.2.40.0.10.2.1.1.261.50"; - public static final String COST_CENTER_ID_NAME = URN_OID_PREFIX + COST_CENTER_ID_OID; - public static final String COST_CENTER_ID_FRIENDLY_NAME = "COST-CENTER-ID"; - public static final int COST_CENTER_ID_MAX_LENGTH = 32767; - - public static final String CHARGE_CODE_OID = "1.2.40.0.10.2.1.1.261.60"; - public static final String CHARGE_CODE_NAME = URN_OID_PREFIX + CHARGE_CODE_OID; - public static final String CHARGE_CODE_FRIENDLY_NAME = "CHARGE-CODE"; - public static final int CHARGE_CODE_MAX_LENGTH = 32767; - - public static final String PVP_HOLDEROFKEY_OID = "1.2.40.0.10.2.1.1.261.xx.xx"; - public static final String PVP_HOLDEROFKEY_NAME = URN_OID_PREFIX + PVP_HOLDEROFKEY_OID; - public static final String PVP_HOLDEROFKEY_FRIENDLY_NAME = "HOLDER-OF-KEY-CERTIFICATE"; - - - - public static final String ENTITY_CATEGORY_ATTRIBITE = "http://macedir.org/entity-category"; - public static final String EGOVTOKEN = "http://www.ref.gv.at/ns/names/agiz/pvp/egovtoken"; - public static final String CITIZENTOKEN = "http://www.ref.gv.at/ns/names/agiz/pvp/citizentoken"; - - /** - * - * Get required PVP attributes for egovtoken - * First : PVP attribute name (OID) - * Second: FriendlyName - * Third: Required - * - */ - public static final List<Trible<String, String, Boolean>> EGOVTOKEN_PVP_ATTRIBUTES = - Collections.unmodifiableList(new ArrayList<Trible<String, String, Boolean>>() { - private static final long serialVersionUID = 1L; - { - //currently supported attributes - add(Trible.newInstance(PVP_VERSION_NAME, PVP_VERSION_FRIENDLY_NAME, true)); - add(Trible.newInstance(PRINCIPAL_NAME_NAME, PRINCIPAL_NAME_FRIENDLY_NAME, true)); - - //currently not supported attributes - add(Trible.newInstance(USERID_NAME, USERID_FRIENDLY_NAME, false)); - add(Trible.newInstance(GID_NAME, GID_FRIENDLY_NAME, false)); - add(Trible.newInstance(PARTICIPANT_ID_NAME, PARTICIPANT_ID_FRIENDLY_NAME, false)); - add(Trible.newInstance(OU_GV_OU_ID_NAME, OU_GV_OU_ID_FRIENDLY_NAME, false)); - add(Trible.newInstance(OU_NAME, OU_FRIENDLY_NAME, false)); - add(Trible.newInstance(SECCLASS_NAME, SECCLASS_FRIENDLY_NAME, false)); - - - } - }); - - /** - * - * Get required PVP attributes for citizenToken - * First : PVP attribute name (OID) - * Second: FriendlyName - * Third: Required - * - */ - public static final List<Trible<String, String, Boolean>> CITIZENTOKEN_PVP_ATTRIBUTES = - Collections.unmodifiableList(new ArrayList<Trible<String, String, Boolean>>() { - private static final long serialVersionUID = 1L; - { - //required attributes - eIDAS minimal-data set - add(Trible.newInstance(PVP_VERSION_NAME, PVP_VERSION_FRIENDLY_NAME, true)); - add(Trible.newInstance(PRINCIPAL_NAME_NAME, PRINCIPAL_NAME_FRIENDLY_NAME, true)); - add(Trible.newInstance(GIVEN_NAME_NAME, GIVEN_NAME_FRIENDLY_NAME, true)); - add(Trible.newInstance(BIRTHDATE_NAME, BIRTHDATE_FRIENDLY_NAME, true)); - add(Trible.newInstance(BPK_NAME, BPK_FRIENDLY_NAME, true)); - - - //not required attributes - add(Trible.newInstance(EID_CITIZEN_EIDAS_QAA_LEVEL_NAME, EID_CITIZEN_EIDAS_QAA_LEVEL_FRIENDLY_NAME, false)); - add(Trible.newInstance(EID_ISSUING_NATION_NAME, EID_ISSUING_NATION_FRIENDLY_NAME, false)); - add(Trible.newInstance(EID_SECTOR_FOR_IDENTIFIER_NAME, EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_TYPE_NAME, MANDATE_TYPE_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_TYPE_OID_NAME, MANDATE_TYPE_OID_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_LEG_PER_SOURCE_PIN_NAME, MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_NAT_PER_BPK_NAME, MANDATE_NAT_PER_BPK_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_NAT_PER_GIVEN_NAME_NAME, MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_NAT_PER_FAMILY_NAME_NAME, MANDATE_NAT_PER_FAMILY_NAME_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_NAT_PER_BIRTHDATE_NAME, MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_LEG_PER_FULL_NAME_NAME, MANDATE_LEG_PER_FULL_NAME_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_PROF_REP_OID_NAME, MANDATE_PROF_REP_OID_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_PROF_REP_DESC_NAME, MANDATE_PROF_REP_DESC_FRIENDLY_NAME, false)); - add(Trible.newInstance(MANDATE_REFERENCE_VALUE_NAME, MANDATE_REFERENCE_VALUE_FRIENDLY_NAME, false)); - - - - } - }); - + } 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 deleted file mode 100644 index caf66942e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ /dev/null @@ -1,144 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x; - -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.opensaml.common.xml.SAMLConstants; -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; - -import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMetadataInformationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.logging.Logger; - -@Component("PVPTargetConfiguration") -@Scope(value = BeanDefinition.SCOPE_PROTOTYPE) -public class PVPTargetConfiguration extends RequestImpl { - - public static final String DATAID_INTERFEDERATION_MINIMAL_FRONTCHANNEL_RESP = "useMinimalFrontChannelResponse"; - public static final String DATAID_INTERFEDERATION_NAMEID = "federatedNameID"; - public static final String DATAID_INTERFEDERATION_QAALEVEL = "federatedQAALevel"; - - public static final String DATAID_INTERFEDERATION_REQUESTID = "authnReqID"; - - private static final long serialVersionUID = 4889919265919638188L; - - InboundMessage request; - String binding; - String consumerURL; - - public InboundMessage getRequest() { - return request; - } - - public void setRequest(InboundMessage request) { - this.request = request; - } - - public String getBinding() { - return binding; - } - - public void setBinding(String binding) { - this.binding = binding; - } - - public String getConsumerURL() { - return consumerURL; - } - - public void setConsumerURL(String consumerURL) { - this.consumerURL = consumerURL; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes() - */ - @Override - 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(metadataProvider).getSPSSODescriptor(SAMLConstants.SAML20P_NS); - if (spSSODescriptor.getAttributeConsumingServices() != null && - spSSODescriptor.getAttributeConsumingServices().size() > 0) { - - Integer aIdx = null; - if (getRequest() instanceof MOARequest && - ((MOARequest)getRequest()).getSamlRequest() instanceof AuthnRequestImpl) { - AuthnRequestImpl authnRequest = (AuthnRequestImpl)((MOARequest)getRequest()).getSamlRequest(); - aIdx = authnRequest.getAttributeConsumingServiceIndex(); - - } else { - Logger.error("MOARequest is NOT of type AuthnRequest"); - } - - int idx = 0; - - AttributeConsumingService attributeConsumingService = null; - - if (aIdx != null) { - idx = aIdx.intValue(); - attributeConsumingService = spSSODescriptor - .getAttributeConsumingServices().get(idx); - - } else { - List<AttributeConsumingService> attrConsumingServiceList = spSSODescriptor.getAttributeConsumingServices(); - for (AttributeConsumingService el : attrConsumingServiceList) { - if (el.isDefault()) - attributeConsumingService = el; - } - } - - for ( RequestedAttribute attr : attributeConsumingService.getRequestAttributes()) - reqAttr.put(attr.getName(), ""); - } - - //return attributQueryBuilder.buildSAML2AttributeList(this.getOnlineApplicationConfiguration(), reqAttr.keySet().iterator()); - return reqAttr.keySet(); - - } catch (NoMetadataInformationException e) { - Logger.warn("NO metadata found for Entity " + getRequest().getEntityID()); - return null; - - } - - } - -} 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 f709da213..68158cd61 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 @@ -35,30 +35,31 @@ import org.opensaml.saml2.metadata.SingleLogoutService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.IAction; +import at.gv.egiz.eaaf.core.api.idp.IAuthData; +import at.gv.egiz.eaaf.core.api.idp.auth.IAuthenticationManager; +import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; +import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.SLOException; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileResponse; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; 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.data.IAuthenticationSession; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; 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; -import at.gv.egovernment.moa.id.data.ISLOInformationContainer; import at.gv.egovernment.moa.id.data.SLOInformationContainer; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.AuthenticationManager; -import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.SSOManager; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SLOException; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; -import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLEncoder; @@ -71,11 +72,11 @@ import at.gv.egovernment.moa.util.URLEncoder; public class SingleLogOutAction implements IAction { @Autowired private SSOManager ssomanager; - @Autowired private AuthenticationManager authManager; + @Autowired private IAuthenticationManager authManager; @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; @Autowired private ITransactionStorage transactionStorage; @Autowired private SingleLogOutBuilder sloBuilder; - @Autowired private MOAReversionLogger revisionsLogger; + @Autowired private IRevisionLogger revisionsLogger; /* (non-Javadoc) @@ -84,22 +85,22 @@ public class SingleLogOutAction implements IAction { @Override public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, - IAuthData authData) throws MOAIDException { + IAuthData authData) throws EAAFException { - PVPTargetConfiguration pvpReq = (PVPTargetConfiguration) req; + PVPSProfilePendingRequest pvpReq = (PVPSProfilePendingRequest) req; - if (pvpReq.getRequest() instanceof MOARequest && - ((MOARequest)pvpReq.getRequest()).getSamlRequest() instanceof LogoutRequest) { + if (pvpReq.getRequest() instanceof PVPSProfileRequest && + ((PVPSProfileRequest)pvpReq.getRequest()).getSamlRequest() instanceof LogoutRequest) { Logger.debug("Process Single LogOut request"); - MOARequest samlReq = (MOARequest) pvpReq.getRequest(); + PVPSProfileRequest samlReq = (PVPSProfileRequest) pvpReq.getRequest(); LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); - IAuthenticationSession session = - authenticationSessionStorage.searchMOASessionWithNameIDandOAID( + String ssoSessionId = + authenticationSessionStorage.searchSSOSessionWithNameIDandOAID( logOutReq.getIssuer().getValue(), logOutReq.getNameID().getValue()); - if (session == null) { + if (MiscUtil.isEmpty(ssoSessionId)) { Logger.warn("Can not find active SSO session with nameID " + logOutReq.getNameID().getValue() + " and OA " + logOutReq.getIssuer().getValue()); @@ -116,10 +117,10 @@ public class SingleLogOutAction implements IAction { } else { try { - session = ssomanager.getInternalMOASession(ssoID); + ssoSessionId = authenticationSessionStorage.getInternalSSOSessionWithSSOID(ssoID); - if (session == null) - throw new MOADatabaseException(); + if (MiscUtil.isEmpty(ssoSessionId)) + throw new MOADatabaseException(""); } catch (MOADatabaseException e) { Logger.info("Can not find active Session. Single LogOut not possible!"); @@ -134,12 +135,17 @@ public class SingleLogOutAction implements IAction { } } - authManager.performSingleLogOut(httpReq, httpResp, session, pvpReq); - - } else if (pvpReq.getRequest() instanceof MOAResponse && - ((MOAResponse)pvpReq.getRequest()).getResponse() instanceof LogoutResponse) { + pvpReq.setInternalSSOSessionIdentifier(ssoSessionId); + ISLOInformationContainer sloInformationContainer + = authManager.performSingleLogOut(httpReq, httpResp, pvpReq, ssoSessionId); + + Logger.debug("Starting technical SLO process ... "); + sloBuilder.toTechnicalLogout(sloInformationContainer, httpReq, httpResp, null); + + } else if (pvpReq.getRequest() instanceof PVPSProfileResponse && + ((PVPSProfileResponse)pvpReq.getRequest()).getResponse() instanceof LogoutResponse) { Logger.debug("Process Single LogOut response"); - LogoutResponse logOutResp = (LogoutResponse) ((MOAResponse)pvpReq.getRequest()).getResponse(); + LogoutResponse logOutResp = (LogoutResponse) ((PVPSProfileResponse)pvpReq.getRequest()).getResponse(); //Transaction tx = null; @@ -159,26 +165,8 @@ public class SingleLogOutAction implements IAction { //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) { - // 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); + Logger.debug("Current Thread: " +Thread.currentThread().getId() + " requests TransactionStore"); + Object o = transactionStorage.getRaw(relayState); if(o==null){ Logger.trace("No entries found."); throw new MOADatabaseException("No sessioninformation found with this ID"); @@ -198,43 +186,44 @@ public class SingleLogOutAction implements IAction { byte[] serializedSLOContainer = SerializationUtils.serialize((Serializable) sloContainer); element.setAssertion(serializedSLOContainer); element.setType(sloContainer.getClass().getName()); - - // session.saveOrUpdate(element); - // tx.commit(); - Logger.debug("Current Thread putAssertionStore: "+Thread.currentThread().getId()); - transactionStorage.putAssertionStore(element); + Logger.debug("Current Thread: " + Thread.currentThread().getId() + " puts SLOInformation into TransactionStore"); + transactionStorage.putRaw(element.getArtifact(), element); //sloContainer could be stored to database storageSuccess = true; - } catch(MOADatabaseException e) { - //tx.rollback(); - + } catch(EAAFException e) { counter++; Logger.debug("SLOContainter could not stored to database. Wait some time and restart storage process ... "); - java.util.Random rand = new java.util.Random(); - + if (counter > 1000) { + Logger.warn("Stopping SLO process with an error, because it runs in a loop.", e); + throw new EAAFException("internal.01", null, e); + + } + + try { + java.util.Random rand = new java.util.Random(); Thread.sleep(rand.nextInt(20)*10); } catch (InterruptedException e1) { Logger.warn("Thread could not stopped. ReStart storage process immediately", e1); + } } } else { - Logger.debug("Current Thread removeElement by Artifact: "+Thread.currentThread().getId()); + Logger.debug("Current Thread: " + Thread.currentThread().getId() + " remove SLOInformation from TransactionStore"); transactionStorage.remove(element.getArtifact()); - // session.delete(element); - // tx.commit(); storageSuccess = true; String redirectURL = null; - if (sloContainer.getSloRequest() != null) { - //send SLO response to SLO request issuer - 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()); + IRequest sloReq = sloContainer.getSloRequest(); + if (sloReq != null && sloReq instanceof PVPSProfilePendingRequest) { + //send SLO response to SLO request issuer + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor((PVPSProfilePendingRequest)sloReq); + LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, (PVPSProfilePendingRequest)sloReq, sloContainer.getSloFailedOAs()); + redirectURL = sloBuilder.getFrontChannelSLOMessageURL(sloService, message, httpReq, httpResp, ((PVPSProfilePendingRequest)sloReq).getRequest().getRelayState()); } else { //print SLO information directly @@ -276,7 +265,7 @@ public class SingleLogOutAction implements IAction { } } } - } catch (MOADatabaseException e) { + } catch (EAAFException e) { Logger.error("MOA AssertionDatabase ERROR", e); throw new SLOException("pvp2.19", null); @@ -285,16 +274,7 @@ public class SingleLogOutAction implements IAction { 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); @@ -318,7 +298,7 @@ public class SingleLogOutAction implements IAction { */ @Override public String getDefaultActionName() { - return PVP2XProtocol.SINGLELOGOUT; + return PVPConstants.SINGLELOGOUT; } protected static String addURLParameter(String url, String paramname, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java deleted file mode 100644 index 71c5a46a4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.binding; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.opensaml.common.binding.decoding.URIComparator; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.ws.message.decoder.MessageDecodingException; -import org.opensaml.xml.security.SecurityException; - -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; - -public interface IDecoder { - public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) - throws MessageDecodingException, SecurityException, PVP2Exception; - - public boolean handleDecode(String action, HttpServletRequest req); - - public String getSAML2BindingName(); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java deleted file mode 100644 index ccbef6e6c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java +++ /dev/null @@ -1,71 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.binding; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.credential.Credential; - -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; - -public interface IEncoder { - - /** - * - * @param req The http request - * @param resp The http response - * @param request The SAML2 request object - * @param targetLocation URL, where the request should be transmit - * @param relayState token for session handling - * @param credentials Credential to sign the request object - * @param pendingReq Internal MOA-ID request object that contains session-state informations but never null - * @throws MessageEncodingException - * @throws SecurityException - * @throws PVP2Exception - */ - public void encodeRequest(HttpServletRequest req, - HttpServletResponse resp, RequestAbstractType request, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException, PVP2Exception; - - /** - * Encoder SAML Response - * @param req The http request - * @param resp The http response - * @param response The SAML2 repsonse object - * @param targetLocation URL, where the request should be transmit - * @param relayState token for session handling - * @param credentials Credential to sign the response object - * @param pendingReq Internal MOA-ID request object that contains session-state informations but never null - * @throws MessageEncodingException - * @throws SecurityException - */ - public void encodeRespone(HttpServletRequest req, - HttpServletResponse resp, StatusResponseType response, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException, PVP2Exception; -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOAURICompare.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOAURICompare.java deleted file mode 100644 index 7bb64a106..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOAURICompare.java +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.binding; - -import org.opensaml.common.binding.decoding.URIComparator; - -import at.gv.egovernment.moa.logging.Logger; - -public class MOAURICompare implements URIComparator { - - /** - * @param idpssoPostService - */ - - private String serviceURL = ""; - - public MOAURICompare(String serviceURL) { - this.serviceURL = serviceURL; - } - - public boolean compare(String uri1, String uri2) { - if (this.serviceURL.equals(uri1)) - return true; - - else { - Logger.warn("PVP request destination-endpoint: " + uri1 - + " does not match to IDP endpoint:" + serviceURL); - return false; - - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java deleted file mode 100644 index c7688c14b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ /dev/null @@ -1,240 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.binding; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.opensaml.common.SAMLObject; -import org.opensaml.common.binding.BasicSAMLMessageContext; -import org.opensaml.common.binding.decoding.URIComparator; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.binding.decoding.HTTPPostDecoder; -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.metadata.IDPSSODescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.saml2.metadata.impl.SingleSignOnServiceBuilder; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.ws.message.decoder.MessageDecodingException; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.ws.security.SecurityPolicyResolver; -import org.opensaml.ws.security.provider.BasicSecurityPolicy; -import org.opensaml.ws.security.provider.StaticSecurityPolicyResolver; -import org.opensaml.ws.transport.http.HttpServletRequestAdapter; -import org.opensaml.ws.transport.http.HttpServletResponseAdapter; -import org.opensaml.xml.parse.BasicParserPool; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.credential.Credential; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.auth.frontend.builder.GUIFormBuilderImpl; -import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.frontend.builder.SPSpecificGUIBuilderConfigurationWithFileSystemLoad; -import at.gv.egovernment.moa.id.auth.frontend.velocity.VelocityProvider; -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; -import at.gv.egovernment.moa.id.opemsaml.MOAIDHTTPPostEncoder; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; -import at.gv.egovernment.moa.id.protocols.pvp2x.validation.MOAPVPSignedRequestPolicyRule; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -@Service("PVPPOSTBinding") -public class PostBinding implements IDecoder, IEncoder { - - @Autowired(required=true) AuthConfiguration authConfig; - @Autowired(required=true) GUIFormBuilderImpl guiBuilder; - - public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException { - - try { -// X509Credential credentials = credentialProvider -// .getIDPAssertionSigningCredential(); - - //load default PVP security configurations - MOADefaultBootstrap.initializeDefaultPVPConfiguration(); - - //initialize POST binding encoder with template decoration - IGUIBuilderConfiguration guiConfig = - new SPSpecificGUIBuilderConfigurationWithFileSystemLoad( - pendingReq, - "pvp_postbinding_template.html", - MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_SAML2POSTBINDING_URL, - null, - authConfig.getRootConfigFileDir()); - MOAIDHTTPPostEncoder encoder = new MOAIDHTTPPostEncoder(guiConfig, guiBuilder, - VelocityProvider.getClassPathVelocityEngine()); - - //set OpenSAML2 process parameter into binding context dao - HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); - SingleSignOnService service = new SingleSignOnServiceBuilder().buildObject(); - service.setBinding("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"); - service.setLocation(targetLocation);; - - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setPeerEntityEndpoint(service); - context.setOutboundSAMLMessage(request); - context.setOutboundMessageTransport(responseAdapter); - context.setRelayState(relayState); - - encoder.encode(context); - -// } catch (CredentialsNotAvailableException e) { -// e.printStackTrace(); -// throw new SecurityException(e); - } catch (Exception e) { - e.printStackTrace(); - throw new SecurityException(e); - } - } - - public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException { - - try { - //load default PVP security configurations - MOADefaultBootstrap.initializeDefaultPVPConfiguration(); - - Logger.debug("create SAML POSTBinding response"); - - //initialize POST binding encoder with template decoration - IGUIBuilderConfiguration guiConfig = - new SPSpecificGUIBuilderConfigurationWithFileSystemLoad( - pendingReq, - "pvp_postbinding_template.html", - MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_SAML2POSTBINDING_URL, - null, - authConfig.getRootConfigFileDir()); - MOAIDHTTPPostEncoder encoder = new MOAIDHTTPPostEncoder(guiConfig, guiBuilder, - VelocityProvider.getClassPathVelocityEngine()); - - //set OpenSAML2 process parameter into binding context dao - HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); - SingleSignOnService service = new SingleSignOnServiceBuilder() - .buildObject(); - service.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - service.setLocation(targetLocation); - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setPeerEntityEndpoint(service); - // context.setOutboundMessage(authReq); - context.setOutboundSAMLMessage(response); - context.setOutboundMessageTransport(responseAdapter); - context.setRelayState(relayState); - - encoder.encode(context); -// } catch (CredentialsNotAvailableException e) { -// e.printStackTrace(); -// throw new SecurityException(e); - } catch (Exception e) { - e.printStackTrace(); - throw new SecurityException(e); - } - } - - public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, - SecurityException { - - HTTPPostDecoder decode = new HTTPPostDecoder(new BasicParserPool()); - BasicSAMLMessageContext<SAMLObject, ?, ?> messageContext = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); - messageContext - .setInboundMessageTransport(new HttpServletRequestAdapter(req)); - //set metadata descriptor type - if (isSPEndPoint) { - messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(comparator); - - } else { - messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(comparator); - } - - messageContext.setMetadataProvider(metadataProvider); - - //set security policy context - BasicSecurityPolicy policy = new BasicSecurityPolicy(); - policy.getPolicyRules().add( - new MOAPVPSignedRequestPolicyRule(metadataProvider, - TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider), - messageContext.getPeerEntityRole())); - SecurityPolicyResolver secResolver = new StaticSecurityPolicyResolver(policy); - messageContext.setSecurityPolicyResolver(secResolver); - - decode.decode(messageContext); - - InboundMessage msg = null; - if (messageContext.getInboundMessage() instanceof RequestAbstractType) { - RequestAbstractType inboundMessage = (RequestAbstractType) messageContext - .getInboundMessage(); - msg = new MOARequest(inboundMessage, getSAML2BindingName()); - msg.setEntityID(inboundMessage.getIssuer().getValue()); - - } else if (messageContext.getInboundMessage() instanceof StatusResponseType){ - StatusResponseType inboundMessage = (StatusResponseType) messageContext.getInboundMessage(); - msg = new MOAResponse(inboundMessage); - msg.setEntityID(inboundMessage.getIssuer().getValue()); - - } else - //create empty container if request type is unknown - msg = new InboundMessage(); - - if (messageContext.getPeerEntityMetadata() != null) - msg.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); - - else { - if (MiscUtil.isEmpty(msg.getEntityID())) - Logger.info("No Metadata found for OA with EntityID " + messageContext.getInboundMessageIssuer()); - } - - - msg.setVerified(true); - msg.setRelayState(messageContext.getRelayState()); - - return msg; - } - - public boolean handleDecode(String action, HttpServletRequest req) { - return (req.getMethod().equals("POST") && action.equals(PVP2XProtocol.POST)); - } - - public String getSAML2BindingName() { - return SAMLConstants.SAML2_POST_BINDING_URI; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java deleted file mode 100644 index 95c4f1726..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ /dev/null @@ -1,244 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.binding; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.opensaml.common.SAMLObject; -import org.opensaml.common.binding.BasicSAMLMessageContext; -import org.opensaml.common.binding.decoding.URIComparator; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.binding.decoding.HTTPRedirectDeflateDecoder; -import org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder; -import org.opensaml.saml2.binding.security.SAML2HTTPRedirectDeflateSignatureRule; -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.metadata.IDPSSODescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.saml2.metadata.impl.SingleSignOnServiceBuilder; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.ws.message.decoder.MessageDecodingException; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.ws.security.SecurityPolicyResolver; -import org.opensaml.ws.security.provider.BasicSecurityPolicy; -import org.opensaml.ws.security.provider.StaticSecurityPolicyResolver; -import org.opensaml.ws.transport.http.HttpServletRequestAdapter; -import org.opensaml.ws.transport.http.HttpServletResponseAdapter; -import org.opensaml.xml.parse.BasicParserPool; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.credential.Credential; -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IMOARefreshableMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.validation.MOASAML2AuthRequestSignedRole; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -@Service("PVPRedirectBinding") -public class RedirectBinding implements IDecoder, IEncoder { - - public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException { - -// try { -// X509Credential credentials = credentialProvider -// .getIDPAssertionSigningCredential(); - - //load default PVP security configurations - MOADefaultBootstrap.initializeDefaultPVPConfiguration(); - - Logger.debug("create SAML RedirectBinding response"); - - HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); - HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); - SingleSignOnService service = new SingleSignOnServiceBuilder() - .buildObject(); - service.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - service.setLocation(targetLocation); - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setPeerEntityEndpoint(service); - context.setOutboundSAMLMessage(request); - context.setOutboundMessageTransport(responseAdapter); - context.setRelayState(relayState); - - encoder.encode(context); -// } catch (CredentialsNotAvailableException e) { -// e.printStackTrace(); -// throw new SecurityException(e); -// } - } - - public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState, - Credential credentials, IRequest pendingReq) throws MessageEncodingException, SecurityException { -// try { -// X509Credential credentials = credentialProvider -// .getIDPAssertionSigningCredential(); - - //load default PVP security configurations - MOADefaultBootstrap.initializeDefaultPVPConfiguration(); - - Logger.debug("create SAML RedirectBinding response"); - - HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); - HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); - SingleSignOnService service = new SingleSignOnServiceBuilder() - .buildObject(); - service.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - service.setLocation(targetLocation); - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setPeerEntityEndpoint(service); - context.setOutboundSAMLMessage(response); - context.setOutboundMessageTransport(responseAdapter); - context.setRelayState(relayState); - - encoder.encode(context); -// } catch (CredentialsNotAvailableException e) { -// e.printStackTrace(); -// throw new SecurityException(e); -// } - } - - public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, - SecurityException { - - HTTPRedirectDeflateDecoder decode = new HTTPRedirectDeflateDecoder( - new BasicParserPool()); - - BasicSAMLMessageContext<SAMLObject, ?, ?> messageContext = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); - messageContext - .setInboundMessageTransport(new HttpServletRequestAdapter(req)); - - //set metadata descriptor type - if (isSPEndPoint) { - messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(comparator); - - } else { - messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.setURIComparator(comparator); - } - - messageContext.setMetadataProvider(metadataProvider); - - SAML2HTTPRedirectDeflateSignatureRule signatureRule = new SAML2HTTPRedirectDeflateSignatureRule( - TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); - MOASAML2AuthRequestSignedRole signedRole = new MOASAML2AuthRequestSignedRole(); - BasicSecurityPolicy policy = new BasicSecurityPolicy(); - policy.getPolicyRules().add(signedRole); - policy.getPolicyRules().add(signatureRule); - SecurityPolicyResolver resolver = new StaticSecurityPolicyResolver( - policy); - messageContext.setSecurityPolicyResolver(resolver); - - //set metadata descriptor type - if (isSPEndPoint) - messageContext.setPeerEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - else - messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); - - try { - decode.decode(messageContext); - - //check signature - signatureRule.evaluate(messageContext); - - } catch (SecurityException e) { - if (MiscUtil.isEmpty(messageContext.getInboundMessageIssuer())) { - throw e; - - } - - if (metadataProvider instanceof IMOARefreshableMetadataProvider) { - Logger.debug("PVP2X message validation FAILED. Reload metadata for entityID: " + messageContext.getInboundMessageIssuer()); - if (!((IMOARefreshableMetadataProvider) metadataProvider).refreshMetadataProvider(messageContext.getInboundMessageIssuer())) - throw e; - - else { - Logger.trace("PVP2X metadata reload finished. Check validate message again."); - decode.decode(messageContext); - - //check signature - signatureRule.evaluate(messageContext); - - } - Logger.trace("Second PVP2X message validation finished"); - - } else { - throw e; - - } - } - - InboundMessage msg = null; - if (messageContext.getInboundMessage() instanceof RequestAbstractType) { - RequestAbstractType inboundMessage = (RequestAbstractType) messageContext - .getInboundMessage(); - msg = new MOARequest(inboundMessage, getSAML2BindingName()); - - - } else if (messageContext.getInboundMessage() instanceof StatusResponseType){ - StatusResponseType inboundMessage = (StatusResponseType) messageContext.getInboundMessage(); - msg = new MOAResponse(inboundMessage); - - } else - //create empty container if request type is unknown - msg = new InboundMessage(); - - if (messageContext.getPeerEntityMetadata() != null) - msg.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); - - else - Logger.info("No Metadata found for OA with EntityID " + messageContext.getInboundMessageIssuer()); - - msg.setVerified(true); - msg.setRelayState(messageContext.getRelayState()); - - return msg; - } - - public boolean handleDecode(String action, HttpServletRequest req) { - return ((action.equals(PVP2XProtocol.REDIRECT) || action.equals(PVP2XProtocol.SINGLELOGOUT)) - && req.getMethod().equals("GET")); - } - - public String getSAML2BindingName() { - return SAMLConstants.SAML2_REDIRECT_BINDING_URI; - } -} 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 deleted file mode 100644 index 552b64ac6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ /dev/null @@ -1,176 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.binding; - -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.opensaml.common.SAMLObject; -import org.opensaml.common.binding.BasicSAMLMessageContext; -import org.opensaml.common.binding.decoding.URIComparator; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.binding.encoding.HTTPSOAP11Encoder; -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.ws.message.decoder.MessageDecodingException; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.ws.soap.soap11.Envelope; -import org.opensaml.ws.soap.soap11.decoder.http.HTTPSOAP11Decoder; -import org.opensaml.ws.transport.http.HttpServletRequestAdapter; -import org.opensaml.ws.transport.http.HttpServletResponseAdapter; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.parse.BasicParserPool; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.credential.Credential; -import org.opensaml.xml.signature.SignableXMLObject; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -@Service("PVPSOAPBinding") -public class SoapBinding implements IDecoder, IEncoder { - - @Autowired(required=true) private MOAMetadataProvider metadataProvider; - @Autowired private IDPCredentialProvider credentialProvider; - - public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint, URIComparator comparator) throws MessageDecodingException, - SecurityException, PVP2Exception { - HTTPSOAP11Decoder soapDecoder = new HTTPSOAP11Decoder(new BasicParserPool()); - BasicSAMLMessageContext<SAMLObject, ?, ?> messageContext = - new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); - messageContext - .setInboundMessageTransport(new HttpServletRequestAdapter( - req)); - messageContext.setMetadataProvider(metadataProvider); - - //TODO: update in a futher version: - // requires a special SignedSOAPRequestPolicyRole because - // messageContext.getInboundMessage() is not directly signed - - //set security context -// BasicSecurityPolicy policy = new BasicSecurityPolicy(); -// policy.getPolicyRules().add( -// new MOAPVPSignedRequestPolicyRule( -// TrustEngineFactory.getSignatureKnownKeysTrustEngine(), -// SPSSODescriptor.DEFAULT_ELEMENT_NAME)); -// SecurityPolicyResolver resolver = new StaticSecurityPolicyResolver( -// policy); -// messageContext.setSecurityPolicyResolver(resolver); - - //decode message - soapDecoder.decode(messageContext); - - Envelope inboundMessage = (Envelope) messageContext - .getInboundMessage(); - - if (inboundMessage.getBody() != null) { - List<XMLObject> xmlElemList = inboundMessage.getBody().getUnknownXMLObjects(); - - if (!xmlElemList.isEmpty()) { - SignableXMLObject attrReq = (SignableXMLObject) xmlElemList.get(0); - MOARequest request = new MOARequest(attrReq, getSAML2BindingName()); - - if (messageContext.getPeerEntityMetadata() != null) - request.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); - - else if (attrReq instanceof RequestAbstractType) { - RequestAbstractType attributeRequest = (RequestAbstractType) attrReq; - try { - if (MiscUtil.isNotEmpty(attributeRequest.getIssuer().getValue()) && - metadataProvider.getRole( - attributeRequest.getIssuer().getValue(), - SPSSODescriptor.DEFAULT_ELEMENT_NAME) != null) - request.setEntityID(attributeRequest.getIssuer().getValue()); - - } catch (Exception e) { - Logger.warn("No Metadata found with EntityID " + attributeRequest.getIssuer().getValue()); - } - } - - request.setVerified(false); - return request; - - } - } - - Logger.error("Receive empty PVP 2.1 attributequery request."); - throw new AttributQueryException("Receive empty PVP 2.1 attributequery request.", null); - } - - public boolean handleDecode(String action, HttpServletRequest req) { - return (req.getMethod().equals("POST") && - (action.equals(PVP2XProtocol.SOAP) || action.equals(PVP2XProtocol.ATTRIBUTEQUERY))); - } - - public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException, PVP2Exception { - - } - - public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState, Credential credentials, IRequest pendingReq) - throws MessageEncodingException, SecurityException, PVP2Exception { -// try { -// Credential credentials = credentialProvider -// .getIDPAssertionSigningCredential(); - - //load default PVP security configurations - MOADefaultBootstrap.initializeDefaultPVPConfiguration(); - - HTTPSOAP11Encoder encoder = new HTTPSOAP11Encoder(); - HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setOutboundSAMLMessage(response); - context.setOutboundMessageTransport(responseAdapter); - - encoder.encode(context); -// } catch (CredentialsNotAvailableException e) { -// e.printStackTrace(); -// throw new SecurityException(e); -// } - } - - public String getSAML2BindingName() { - return SAMLConstants.SAML2_SOAP11_BINDING_URI; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AttributQueryBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AttributQueryBuilder.java index 4aa4f7419..b5f77ce1a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AttributQueryBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AttributQueryBuilder.java @@ -49,15 +49,15 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Document; +import at.gv.egiz.eaaf.modules.pvp2.exception.AttributQueryException; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PVPAttributeBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.SamlAttributeGenerator; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; 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.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.SamlAttributeGenerator; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; /** @@ -101,11 +101,11 @@ public class AttributQueryBuilder { } - public AttributeQuery buildAttributQueryRequest(String nameID, + public AttributeQuery buildAttributQueryRequest(String spEntityID, String nameID, String endpoint, List<Attribute> requestedAttributes) throws AttributQueryException { - try { + try { AttributeQuery query = new AttributeQueryBuilder().buildObject(); @@ -125,7 +125,7 @@ public class AttributQueryBuilder { query.setIssueInstant(now); Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); - nissuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath().get(0)); + nissuer.setValue(spEntityID); nissuer.setFormat(NameID.ENTITY); query.setIssuer(nissuer); @@ -156,10 +156,6 @@ public class AttributQueryBuilder { return query; - } catch (ConfigurationException e) { - Logger.error("Build AttributQuery Request FAILED.", e); - throw new AttributQueryException("Build AttributQuery Request FAILED.", null, e); - } catch (CredentialsNotAvailableException e) { Logger.error("Build AttributQuery Request FAILED.", e); throw new AttributQueryException("Build AttributQuery Request FAILED.", null, e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java deleted file mode 100644 index 78ddab488..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder; - -import java.util.ArrayList; -import java.util.List; - -import org.joda.time.DateTime; -import org.opensaml.Configuration; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.Assertion; -import org.opensaml.saml2.core.EncryptedAssertion; -import org.opensaml.saml2.core.Issuer; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.Response; -import org.opensaml.saml2.encryption.Encrypter; -import org.opensaml.saml2.encryption.Encrypter.KeyPlacement; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.security.MetadataCredentialResolver; -import org.opensaml.security.MetadataCriteria; -import org.opensaml.xml.encryption.EncryptionException; -import org.opensaml.xml.encryption.EncryptionParameters; -import org.opensaml.xml.encryption.KeyEncryptionParameters; -import org.opensaml.xml.security.CriteriaSet; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.criteria.EntityIDCriteria; -import org.opensaml.xml.security.criteria.UsageCriteria; -import org.opensaml.xml.security.keyinfo.KeyInfoGeneratorFactory; -import org.opensaml.xml.security.x509.X509Credential; - -import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidAssertionEncryptionException; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -public class AuthResponseBuilder { - - public static Response buildResponse(MetadataProvider metadataProvider, String issuerEntityID, RequestAbstractType req, DateTime date, Assertion assertion, boolean enableEncryption) throws InvalidAssertionEncryptionException, ConfigurationException { - Response authResponse = SAML2Utils.createSAMLObject(Response.class); - - Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); - - nissuer.setValue(issuerEntityID); - nissuer.setFormat(NameID.ENTITY); - authResponse.setIssuer(nissuer); - authResponse.setInResponseTo(req.getID()); - - //set responseID - String remoteSessionID = SAML2Utils.getSecureIdentifier(); - authResponse.setID(remoteSessionID); - - - //SAML2 response required IssueInstant - authResponse.setIssueInstant(date); - - authResponse.setStatus(SAML2Utils.getSuccessStatus()); - - //check, if metadata includes an encryption key - MetadataCredentialResolver mdCredResolver = - new MetadataCredentialResolver(metadataProvider); - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(req.getIssuer().getValue()) ); - criteriaSet.add( new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.ENCRYPTION) ); - - X509Credential encryptionCredentials = null; - try { - encryptionCredentials = (X509Credential) mdCredResolver.resolveSingle(criteriaSet); - - } catch (SecurityException e2) { - Logger.warn("Can not extract the Assertion Encryption-Key from metadata", e2); - throw new InvalidAssertionEncryptionException(); - - } - - if (encryptionCredentials != null && enableEncryption) { - //encrypt SAML2 assertion - - try { - - EncryptionParameters dataEncParams = new EncryptionParameters(); - dataEncParams.setAlgorithm(PVPConstants.DEFAULT_SYM_ENCRYPTION_METHODE); - - List<KeyEncryptionParameters> keyEncParamList = new ArrayList<KeyEncryptionParameters>(); - KeyEncryptionParameters keyEncParam = new KeyEncryptionParameters(); - - keyEncParam.setEncryptionCredential(encryptionCredentials); - keyEncParam.setAlgorithm(PVPConstants.DEFAULT_ASYM_ENCRYPTION_METHODE); - KeyInfoGeneratorFactory kigf = Configuration.getGlobalSecurityConfiguration() - .getKeyInfoGeneratorManager().getDefaultManager() - .getFactory(encryptionCredentials); - keyEncParam.setKeyInfoGenerator(kigf.newInstance()); - keyEncParamList.add(keyEncParam); - - Encrypter samlEncrypter = new Encrypter(dataEncParams, keyEncParamList); - //samlEncrypter.setKeyPlacement(KeyPlacement.INLINE); - samlEncrypter.setKeyPlacement(KeyPlacement.PEER); - - EncryptedAssertion encryptAssertion = null; - - encryptAssertion = samlEncrypter.encrypt(assertion); - - authResponse.getEncryptedAssertions().add(encryptAssertion); - - } catch (EncryptionException e1) { - Logger.warn("Can not encrypt the PVP2 assertion", e1); - throw new InvalidAssertionEncryptionException(); - - } - - } else { - authResponse.getAssertions().add(assertion); - - } - - return authResponse; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/CitizenTokenBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/CitizenTokenBuilder.java deleted file mode 100644 index d2a63c72f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/CitizenTokenBuilder.java +++ /dev/null @@ -1,171 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder; - -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeValue; -import org.opensaml.xml.Configuration; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.schema.XSInteger; -import org.opensaml.xml.schema.XSString; -import org.opensaml.xml.schema.impl.XSIntegerBuilder; -import org.opensaml.xml.schema.impl.XSStringBuilder; - -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; - -public class CitizenTokenBuilder { - - public static XMLObject buildAttributeStringValue(String value) { - XSStringBuilder stringBuilder = (XSStringBuilder) Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME); - XSString stringValue = stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); - stringValue.setValue(value); - return stringValue; - } - - public static XMLObject buildAttributeIntegerValue(int value) { - XSIntegerBuilder integerBuilder = (XSIntegerBuilder) Configuration.getBuilderFactory().getBuilder(XSInteger.TYPE_NAME); - XSInteger integerValue = integerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME); - integerValue.setValue(value); - return integerValue; - } - - public static Attribute buildStringAttribute(String friendlyName, - String name, String value) { - Attribute attribute = - SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.getAttributeValues().add(buildAttributeStringValue(value)); - return attribute; - } - - public static Attribute buildIntegerAttribute(String friendlyName, - String name, int value) { - Attribute attribute = - SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.getAttributeValues().add(buildAttributeIntegerValue(value)); - return attribute; - } - - public static Attribute buildPVPVersion(String value) { - return buildStringAttribute("PVP-VERSION", - "urn:oid:1.2.40.0.10.2.1.1.261.10", value); - } - - public static Attribute buildSecClass(int value) { - return buildIntegerAttribute("SECCLASS", - "", value); - } - - public static Attribute buildPrincipalName(String value) { - return buildStringAttribute("PRINCIPAL-NAME", - "urn:oid:1.2.40.0.10.2.1.1.261.20", value); - } - - public static Attribute buildGivenName(String value) { - return buildStringAttribute("GIVEN-NAME", - "urn:oid:2.5.4.42", value); - } - - public static Attribute buildBirthday(String value) { - return buildStringAttribute("BIRTHDATE", - "urn:oid:1.2.40.0.10.2.1.1.55", value); - } - - public static Attribute buildBPK(String value) { - return buildStringAttribute("BPK", - "urn:oid:1.2.40.0.10.2.1.1.149", value); - } - - public static Attribute buildEID_CITIZEN_QAALEVEL(int value) { - return buildIntegerAttribute("EID-CITIZEN-QAA-LEVEL", - "urn:oid:1.2.40.0.10.2.1.1.261.94", value); - } - - public static Attribute buildEID_ISSUING_NATION(String value) { - return buildStringAttribute("EID-ISSUING-NATION", - "urn:oid:1.2.40.0.10.2.1.1.261.32", value); - } - - public static Attribute buildEID_SECTOR_FOR_IDENTIFIER(String value) { - return buildStringAttribute("EID-SECTOR-FOR-IDENTIFIER", - "urn:oid:1.2.40.0.10.2.1.1.261.34", value); - } - - -// public static AttributeStatement buildCitizenToken(MOARequest obj, -// AuthenticationSession authSession) { -// AttributeStatement statement = -// SAML2Utils.createSAMLObject(AttributeStatement.class); -// -// //TL: AuthData generation is moved out from VerifyAuthBlockServlet -// try { -// -// //TODO: LOAD oaParam from request and not from MOASession in case of SSO -// OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() -// .getOnlineApplicationParameter(authSession.getPublicOAURLPrefix()); -// -// AuthenticationData authData = AuthenticationServer.buildAuthenticationData(authSession, -// oaParam, -// authSession.getTarget()); -// -// Attribute pvpVersion = buildPVPVersion("2.1"); -// Attribute secClass = buildSecClass(3); -// Attribute principalName = buildPrincipalName(authData.getFamilyName()); -// Attribute givenName = buildGivenName(authData.getGivenName()); -// Attribute birthdate = buildBirthday(authData.getDateOfBirth()); -// -// //TL: getIdentificationValue holds the baseID --> change to pBK -// Attribute bpk = buildBPK(authData.getBPK()); -// -// Attribute eid_citizen_qaa = buildEID_CITIZEN_QAALEVEL(3); -// Attribute eid_issuing_nation = buildEID_ISSUING_NATION("AT"); -// Attribute eid_sector_for_id = buildEID_SECTOR_FOR_IDENTIFIER(authData.getIdentificationType()); -// -// statement.getAttributes().add(pvpVersion); -// statement.getAttributes().add(secClass); -// statement.getAttributes().add(principalName); -// statement.getAttributes().add(givenName); -// statement.getAttributes().add(birthdate); -// statement.getAttributes().add(bpk); -// statement.getAttributes().add(eid_citizen_qaa); -// statement.getAttributes().add(eid_issuing_nation); -// statement.getAttributes().add(eid_sector_for_id); -// -// return statement; -// -// } catch (ConfigurationException e) { -// -// // TODO: check Exception Handling -// return null; -// } catch (BuildException e) { -// -// // TODO: check Exception Handling -// return null; -// } -// -// -// } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java deleted file mode 100644 index b82e6c1f0..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java +++ /dev/null @@ -1,207 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.ServiceLoader; - -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.metadata.RequestedAttribute; - -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.SamlAttributeGenerator; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.InvalidDateFormatAttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.InvalidDateFormatException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.logging.Logger; - -public class PVPAttributeBuilder { - - private static IAttributeGenerator<Attribute> generator = new SamlAttributeGenerator(); - - private static HashMap<String, IAttributeBuilder> builders; - - private static ServiceLoader<IAttributeBuilder> attributBuilderLoader = - ServiceLoader.load(IAttributeBuilder.class); - - private static void addBuilder(IAttributeBuilder builder) { - builders.put(builder.getName(), builder); - } - - static { - builders = new HashMap<String, IAttributeBuilder>(); - - Logger.info("Loading protocol attribut-builder modules:"); - if (attributBuilderLoader != null ) { - Iterator<IAttributeBuilder> moduleLoaderInterator = attributBuilderLoader.iterator(); - while (moduleLoaderInterator.hasNext()) { - try { - IAttributeBuilder modul = moduleLoaderInterator.next(); - Logger.info("Loading attribut-builder Modul Information: " + modul.getName()); - addBuilder(modul); - - } catch(Throwable e) { - Logger.error("Check configuration! " + "Some attribute-builder modul" + - " is not a valid IAttributeBuilder", e); - } - } - } - - Logger.info("Loading attribute-builder modules done"); - - } - - - /** - * Get a specific attribute builder - * - * @param name Attribute-builder friendly name - * - * @return Attribute-builder with this name or null if builder does not exists - */ - public static IAttributeBuilder getAttributeBuilder(String name) { - return builders.get(name); - - } - - public static Attribute buildAttribute(String name, IOAAuthParameters oaParam, - IAuthData authData) throws PVP2Exception, AttributeException { - if (builders.containsKey(name)) { - try { - return builders.get(name).build(oaParam, authData, generator); - } - catch (AttributeException e) { - if (e instanceof UnavailableAttributeException) { - throw e; - } else if (e instanceof InvalidDateFormatAttributeException) { - throw new InvalidDateFormatException(); - } else if (e instanceof NoMandateDataAttributeException) { - throw new NoMandateDataAvailableException(); - } else { - throw new UnprovideableAttributeException(name); - } - } - } - return null; - } - - public static Attribute buildEmptyAttribute(String name) { - if (builders.containsKey(name)) { - return builders.get(name).buildEmpty(generator); - } - return null; - } - - public static Attribute buildAttribute(String name, String value) { - if (builders.containsKey(name)) { - return builders.get(name).buildEmpty(generator); - } - return null; - } - - - - public static List<Attribute> buildSupportedEmptyAttributes() { - List<Attribute> attributes = new ArrayList<Attribute>(); - Iterator<IAttributeBuilder> builderIt = builders.values().iterator(); - while (builderIt.hasNext()) { - IAttributeBuilder builder = builderIt.next(); - Attribute emptyAttribute = builder.buildEmpty(generator); - if (emptyAttribute != null) { - attributes.add(emptyAttribute); - } - } - return attributes; - } - - public static RequestedAttribute buildReqAttribute(String name, String friendlyName, boolean required) { - RequestedAttribute attribute = SAML2Utils.createSAMLObject(RequestedAttribute.class); - attribute.setIsRequired(required); - attribute.setName(name); - attribute.setFriendlyName(friendlyName); - attribute.setNameFormat(Attribute.URI_REFERENCE); - return attribute; - } - - /** - * Build a set of PVP Response-Attributes - * <br><br> - * <b>INFO:</b> If a specific attribute can not be build, a info is logged, but no execpetion is thrown. - * Therefore, the return List must not include all requested attributes. - * - * @param authData AuthenticationData <code>IAuthData</code> which is used to build the attribute values, but never <code>null</code> - * @param reqAttributenName List of PVP attribute names which are requested, but never <code>null</code> - * @return List of PVP attributes, but never <code>null</code> - */ - public static List<Attribute> buildSetOfResponseAttributes(IAuthData authData, - Collection<String> reqAttributenName) { - List<Attribute> attrList = new ArrayList<Attribute>(); - if (reqAttributenName != null) { - Iterator<String> it = reqAttributenName.iterator(); - while (it.hasNext()) { - String reqAttributName = it.next(); - try { - Attribute attr = PVPAttributeBuilder.buildAttribute( - reqAttributName, null, authData); - if (attr == null) { - Logger.info( - "Attribute generation failed! for " - + reqAttributName); - - } else { - attrList.add(attr); - - } - - } catch (PVP2Exception e) { - Logger.info( - "Attribute generation failed! for " - + reqAttributName); - - } catch (Exception e) { - Logger.warn( - "General Attribute generation failed! for " - + reqAttributName, e); - - } - } - } - - return attrList; - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java deleted file mode 100644 index f29418853..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder; - -import java.security.NoSuchAlgorithmException; - -import javax.servlet.http.HttpServletResponse; - -import org.joda.time.DateTime; -import org.opensaml.common.impl.SecureRandomIdentifierGenerator; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.AuthnContextClassRef; -import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.Issuer; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.NameIDPolicy; -import org.opensaml.saml2.core.NameIDType; -import org.opensaml.saml2.core.RequestedAuthnContext; -import org.opensaml.saml2.core.Subject; -import org.opensaml.saml2.core.SubjectConfirmation; -import org.opensaml.saml2.core.SubjectConfirmationData; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.xml.security.SecurityException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.commons.api.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestBuildException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ -@Service("PVPAuthnRequestBuilder") -public class PVPAuthnRequestBuilder { - - @Autowired(required=true) ApplicationContext springContext; - - /** - * Build a PVP2.x specific authentication request - * - * @param pendingReq Currently processed pendingRequest - * @param config AuthnRequest builder configuration, never null - * @param idpEntity SAML2 EntityDescriptor of the IDP, which receive this AuthnRequest, never null - * @param httpResp - * @throws NoSuchAlgorithmException - * @throws SecurityException - * @throws PVP2Exception - * @throws MessageEncodingException - */ - public void buildAuthnRequest(IRequest pendingReq, IPVPAuthnRequestBuilderConfiguruation config, - HttpServletResponse httpResp) throws NoSuchAlgorithmException, MessageEncodingException, PVP2Exception, SecurityException { - //get IDP Entity element from config - EntityDescriptor idpEntity = config.getIDPEntityDescriptor(); - - AuthnRequest authReq = SAML2Utils - .createSAMLObject(AuthnRequest.class); - - //select SingleSignOn Service endpoint from IDP metadata - SingleSignOnService endpoint = null; - for (SingleSignOnService sss : - idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS).getSingleSignOnServices()) { - - // use POST binding as default if it exists - if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { - endpoint = sss; - - } else if ( sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) - && endpoint == null ) - endpoint = sss; - - } - - if (endpoint == null) { - Logger.warn("Building AuthnRequest FAILED: > Requested IDP " + idpEntity.getEntityID() - + " does not support POST or Redirect Binding."); - throw new AuthnRequestBuildException("sp.pvp2.00", new Object[]{config.getSPNameForLogging(), idpEntity.getEntityID()}); - - } else - authReq.setDestination(endpoint.getLocation()); - - - //set basic AuthnRequest information - String reqID = config.getRequestID(); - if (MiscUtil.isNotEmpty(reqID)) - authReq.setID(reqID); - - else { - SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); - authReq.setID(gen.generateIdentifier()); - - } - - authReq.setIssueInstant(new DateTime()); - - //set isPassive flag - if (config.isPassivRequest() == null) - authReq.setIsPassive(false); - else - authReq.setIsPassive(config.isPassivRequest()); - - //set EntityID of the service provider - Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - issuer.setFormat(NameIDType.ENTITY); - issuer.setValue(config.getSPEntityID()); - authReq.setIssuer(issuer); - - //set AssertionConsumerService ID - if (config.getAssertionConsumerServiceId() != null) - authReq.setAssertionConsumerServiceIndex(config.getAssertionConsumerServiceId()); - - //set NameIDPolicy - if (config.getNameIDPolicyFormat() != null) { - NameIDPolicy policy = SAML2Utils.createSAMLObject(NameIDPolicy.class); - policy.setAllowCreate(config.getNameIDPolicyAllowCreation()); - policy.setFormat(config.getNameIDPolicyFormat()); - authReq.setNameIDPolicy(policy); - } - - //set requested QAA level - if (config.getAuthnContextClassRef() != null) { - RequestedAuthnContext reqAuthContext = SAML2Utils.createSAMLObject(RequestedAuthnContext.class); - AuthnContextClassRef authnClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - - authnClassRef.setAuthnContextClassRef(config.getAuthnContextClassRef()); - - if (config.getAuthnContextComparison() == null) - reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); - else - reqAuthContext.setComparison(config.getAuthnContextComparison()); - - reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); - authReq.setRequestedAuthnContext(reqAuthContext); - } - - //set request Subject element - if (MiscUtil.isNotEmpty(config.getSubjectNameID())) { - Subject reqSubject = SAML2Utils.createSAMLObject(Subject.class); - NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); - - subjectNameID.setValue(config.getSubjectNameID()); - if (MiscUtil.isNotEmpty(config.getSubjectNameIDQualifier())) - subjectNameID.setNameQualifier(config.getSubjectNameIDQualifier()); - - if (MiscUtil.isNotEmpty(config.getSubjectNameIDFormat())) - subjectNameID.setFormat(config.getSubjectNameIDFormat()); - else - subjectNameID.setFormat(NameID.TRANSIENT); - - reqSubject.setNameID(subjectNameID); - - if (config.getSubjectConformationDate() != null) { - SubjectConfirmation subjectConformation = SAML2Utils.createSAMLObject(SubjectConfirmation.class); - SubjectConfirmationData subjectConformDate = SAML2Utils.createSAMLObject(SubjectConfirmationData.class); - subjectConformation.setSubjectConfirmationData(subjectConformDate); - reqSubject.getSubjectConfirmations().add(subjectConformation ); - - if (config.getSubjectConformationMethode() != null) - subjectConformation.setMethod(config.getSubjectConformationMethode()); - - subjectConformDate.setDOM(config.getSubjectConformationDate()); - - } - - authReq.setSubject(reqSubject ); - - } - - //TODO: implement requested attributes - //maybe: config.getRequestedAttributes(); - - //select message encoder - IEncoder binding = null; - if (endpoint.getBinding().equals( - SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = springContext.getBean("PVPRedirectBinding", RedirectBinding.class); - - } else if (endpoint.getBinding().equals( - SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = springContext.getBean("PVPPOSTBinding", PostBinding.class); - - } - - //encode message - binding.encodeRequest(null, httpResp, authReq, - endpoint.getLocation(), pendingReq.getRequestID(), config.getAuthnRequestSigningCredential(), pendingReq); - } - -} 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 deleted file mode 100644 index e2ac50e5e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java +++ /dev/null @@ -1,442 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder; - -import java.io.IOException; -import java.io.StringWriter; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.joda.time.DateTime; -import org.opensaml.Configuration; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.AttributeConsumingService; -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.EntitiesDescriptor; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.IDPSSODescriptor; -import org.opensaml.saml2.metadata.KeyDescriptor; -import org.opensaml.saml2.metadata.LocalizedString; -import org.opensaml.saml2.metadata.NameIDFormat; -import org.opensaml.saml2.metadata.Organization; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.saml2.metadata.RoleDescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.ServiceName; -import org.opensaml.saml2.metadata.SingleLogoutService; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.xml.io.Marshaller; -import org.opensaml.xml.io.MarshallingException; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.SecurityHelper; -import org.opensaml.xml.security.credential.Credential; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; -import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; -import org.opensaml.xml.signature.Signature; -import org.opensaml.xml.signature.SignatureException; -import org.opensaml.xml.signature.Signer; -import org.springframework.stereotype.Service; -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.config.MOADefaultBootstrap; -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; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ - -@Service("PVPMetadataBuilder") -public class PVPMetadataBuilder { - - X509KeyInfoGeneratorFactory keyInfoFactory = null; - - /** - * - */ - public PVPMetadataBuilder() { - keyInfoFactory = new X509KeyInfoGeneratorFactory(); - keyInfoFactory.setEmitEntityIDAsKeyName(true); - keyInfoFactory.setEmitEntityCertificate(true); - - } - - - /** - * - * Build PVP 2.1 conform SAML2 metadata - * - * @param config - * PVPMetadataBuilder configuration - * - * @return PVP metadata as XML String - * @throws SecurityException - * @throws ConfigurationException - * @throws CredentialsNotAvailableException - * @throws TransformerFactoryConfigurationError - * @throws MarshallingException - * @throws TransformerException - * @throws ParserConfigurationException - * @throws IOException - * @throws SignatureException - */ - public String buildPVPMetadata(IPVPMetadataBuilderConfiguration config) throws CredentialsNotAvailableException, ConfigurationException, SecurityException, TransformerFactoryConfigurationError, MarshallingException, TransformerException, ParserConfigurationException, IOException, SignatureException { - DateTime date = new DateTime(); - EntityDescriptor entityDescriptor = SAML2Utils - .createSAMLObject(EntityDescriptor.class); - - //set entityID - entityDescriptor.setEntityID(config.getEntityID()); - - //set contact and organisation information - List<ContactPerson> contactPersons = config.getContactPersonInformation(); - if (contactPersons != null) - entityDescriptor.getContactPersons().addAll(contactPersons); - - Organization organisation = config.getOrgansiationInformation(); - if (organisation != null) - entityDescriptor.setOrganization(organisation); - - //set IDP metadata - if (config.buildIDPSSODescriptor()) { - RoleDescriptor idpSSODesc = generateIDPMetadata(config); - if (idpSSODesc != null) - entityDescriptor.getRoleDescriptors().add(idpSSODesc); - - } - - //set SP metadata for interfederation - if (config.buildSPSSODescriptor()) { - RoleDescriptor spSSODesc = generateSPMetadata(config); - if (spSSODesc != null) - entityDescriptor.getRoleDescriptors().add(spSSODesc); - - } - - //set metadata signature parameters - Credential metadataSignCred = config.getMetadataSigningCredentials(); - Signature signature = AbstractCredentialProvider.getIDPSignature(metadataSignCred); - SecurityHelper.prepareSignatureParams(signature, metadataSignCred, null, null); - - //initialize XML document builder - DocumentBuilder builder; - DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - - builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - - - //build entities descriptor - if (config.buildEntitiesDescriptorAsRootElement()) { - EntitiesDescriptor entitiesDescriptor = - SAML2Utils.createSAMLObject(EntitiesDescriptor.class); - entitiesDescriptor.setName(config.getEntityFriendlyName()); - entitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); - entitiesDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); - entitiesDescriptor.getEntityDescriptors().add(entityDescriptor); - - //load default PVP security configurations - MOADefaultBootstrap.initializeDefaultPVPConfiguration(); - entitiesDescriptor.setSignature(signature); - - - //marshall document - Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(entitiesDescriptor); - out.marshall(entitiesDescriptor, document); - - } else { - entityDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); - entityDescriptor.setID(SAML2Utils.getSecureIdentifier()); - - entityDescriptor.setSignature(signature); - - - - //marshall document - Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(entityDescriptor); - out.marshall(entityDescriptor, document); - - } - - //sign metadata - Signer.signObject(signature); - - //transform metadata object to XML string - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - - StringWriter sw = new StringWriter(); - StreamResult sr = new StreamResult(sw); - DOMSource source = new DOMSource(document); - transformer.transform(source, sr); - sw.close(); - - return sw.toString(); - } - - - private RoleDescriptor generateSPMetadata(IPVPMetadataBuilderConfiguration config) throws CredentialsNotAvailableException, SecurityException, ConfigurationException { - SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); - spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - spSSODescriptor.setAuthnRequestsSigned(config.wantAuthnRequestSigned()); - spSSODescriptor.setWantAssertionsSigned(config.wantAssertionSigned()); - - KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - - //Set AuthRequest Signing certificate - Credential authcredential = config.getRequestorResponseSigningCredentials(); - if (authcredential == null) { - Logger.warn("SP Metadata generation FAILED! --> Builder has NO request signing-credential. "); - return null; - - } else { - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); - spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - } - - //Set assertion encryption credentials - Credential authEncCredential = config.getEncryptionCredentials(); - - if (authEncCredential != null) { - KeyDescriptor encryKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - encryKeyDescriptor.setUse(UsageType.ENCRYPTION); - encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); - spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); - - } else { - Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); - - } - - //check nameID formates - if (config.getSPAllowedNameITTypes() == null || config.getSPAllowedNameITTypes().size() == 0) { - Logger.warn("SP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); - return null; - - } else { - for (String format : config.getSPAllowedNameITTypes()) { - NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - nameIDFormat.setFormat(format); - spSSODescriptor.getNameIDFormats().add(nameIDFormat); - - } - } - - - //add POST-Binding assertion consumer services - if (MiscUtil.isNotEmpty(config.getSPAssertionConsumerServicePostBindingURL())) { - AssertionConsumerService postassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - postassertionConsumerService.setIndex(0); - postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - postassertionConsumerService.setLocation(config.getSPAssertionConsumerServicePostBindingURL()); - postassertionConsumerService.setIsDefault(true); - spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); - - } - - //add POST-Binding assertion consumer services - if (MiscUtil.isNotEmpty(config.getSPAssertionConsumerServiceRedirectBindingURL())) { - AssertionConsumerService redirectassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - redirectassertionConsumerService.setIndex(1); - redirectassertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - redirectassertionConsumerService.setLocation(config.getSPAssertionConsumerServiceRedirectBindingURL()); - spSSODescriptor.getAssertionConsumerServices().add(redirectassertionConsumerService); - - } - - //validate WebSSO endpoints - if (spSSODescriptor.getAssertionConsumerServices().size() == 0) { - Logger.warn("SP Metadata generation FAILED! --> NO SAML2 AssertionConsumerService endpoint found. "); - return null; - - } - - //add POST-Binding SLO descriptor - if (MiscUtil.isNotEmpty(config.getSPSLOPostBindingURL())) { - SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - postSLOService.setLocation(config.getSPSLOPostBindingURL()); - postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(postSLOService); - - } - - //add POST-Binding SLO descriptor - if (MiscUtil.isNotEmpty(config.getSPSLORedirectBindingURL())) { - SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(config.getSPSLORedirectBindingURL()); - redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(redirectSLOService); - - } - - //add POST-Binding SLO descriptor - if (MiscUtil.isNotEmpty(config.getSPSLOSOAPBindingURL())) { - SingleLogoutService soapSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - soapSLOService.setLocation(config.getSPSLOSOAPBindingURL()); - soapSLOService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(soapSLOService); - - } - - - //add required attributes - List<RequestedAttribute> reqSPAttr = config.getSPRequiredAttributes(); - AttributeConsumingService attributeService = SAML2Utils.createSAMLObject(AttributeConsumingService.class); - - attributeService.setIndex(0); - attributeService.setIsDefault(true); - ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); - serviceName.setName(new LocalizedString("Default Service", "en")); - attributeService.getNames().add(serviceName); - - if (reqSPAttr != null && reqSPAttr.size() > 0) { - Logger.debug("Add " + reqSPAttr.size() + " attributes to SP metadata"); - attributeService.getRequestAttributes().addAll(reqSPAttr); - - } else { - Logger.debug("SP metadata contains NO requested attributes."); - - } - - spSSODescriptor.getAttributeConsumingServices().add(attributeService); - - return spSSODescriptor; - } - - private IDPSSODescriptor generateIDPMetadata(IPVPMetadataBuilderConfiguration config) throws ConfigurationException, CredentialsNotAvailableException, SecurityException { - //check response signing credential - Credential responseSignCred = config.getRequestorResponseSigningCredentials(); - if (responseSignCred == null) { - Logger.warn("IDP Metadata generation FAILED! --> Builder has NO Response signing credential. "); - return null; - - } - - //check nameID formates - if (config.getIDPPossibleNameITTypes() == null || config.getIDPPossibleNameITTypes().size() == 0) { - Logger.warn("IDP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); - return null; - - } - - // build SAML2 IDP-SSO descriptor element - IDPSSODescriptor idpSSODescriptor = SAML2Utils - .createSAMLObject(IDPSSODescriptor.class); - - idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - - //set ass default value, because PVP 2.x specification defines this feature as MUST - idpSSODescriptor.setWantAuthnRequestsSigned(config.wantAuthnRequestSigned()); - - // add WebSSO descriptor for POST-Binding - if (MiscUtil.isNotEmpty(config.getIDPWebSSOPostBindingURL())) { - SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); - postSingleSignOnService.setLocation(config.getIDPWebSSOPostBindingURL()); - postSingleSignOnService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); - - } - - // add WebSSO descriptor for Redirect-Binding - if (MiscUtil.isNotEmpty(config.getIDPWebSSORedirectBindingURL())) { - SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); - postSingleSignOnService.setLocation(config.getIDPWebSSORedirectBindingURL()); - postSingleSignOnService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); - - } - - //add Single LogOut POST-Binding endpoing - if (MiscUtil.isNotEmpty(config.getIDPSLOPostBindingURL())) { - SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - postSLOService.setLocation(config.getIDPSLOPostBindingURL()); - postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - idpSSODescriptor.getSingleLogoutServices().add(postSLOService); - - } - - //add Single LogOut Redirect-Binding endpoing - if (MiscUtil.isNotEmpty(config.getIDPSLORedirectBindingURL())) { - SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(config.getIDPSLORedirectBindingURL()); - redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleLogoutServices().add(redirectSLOService); - - } - - //validate WebSSO endpoints - if (idpSSODescriptor.getSingleSignOnServices().size() == 0) { - Logger.warn("IDP Metadata generation FAILED! --> NO SAML2 SingleSignOnService endpoint found. "); - return null; - - } - - //set assertion signing key - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(config.getRequestorResponseSigningCredentials())); - idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - //set IDP attribute set - idpSSODescriptor.getAttributes().addAll(config.getIDPPossibleAttributes()); - - //set providable nameID formats - for (String format : config.getIDPPossibleNameITTypes()) { - NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - nameIDFormat.setFormat(format); - idpSSODescriptor.getNameIDFormats().add(nameIDFormat); - - } - - return idpSSODescriptor; - - } - -} 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 4fef52aec..8229fb405 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 @@ -23,14 +23,20 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder; import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; +import java.util.Map.Entry; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; +import org.apache.commons.lang.SerializationUtils; import org.joda.time.DateTime; import org.opensaml.Configuration; import org.opensaml.common.SAMLObject; @@ -52,6 +58,8 @@ import org.opensaml.saml2.metadata.SingleLogoutService; import org.opensaml.saml2.metadata.impl.SingleLogoutServiceBuilder; import org.opensaml.saml2.metadata.provider.MetadataProviderException; import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.ws.soap.common.SOAPException; +import org.opensaml.xml.XMLObject; import org.opensaml.xml.io.Marshaller; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.x509.X509Credential; @@ -63,30 +71,48 @@ import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import org.w3c.dom.Document; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.gui.IGUIFormBuilder; +import at.gv.egiz.eaaf.core.api.idp.slo.ISLOInformationContainer; +import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.api.logging.IRevisionLogger; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.exceptions.GUIBuildException; +import at.gv.egiz.eaaf.core.exceptions.InvalidProtocolRequestException; +import at.gv.egiz.eaaf.core.impl.data.SLOInformationImpl; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.api.binding.IEncoder; +import at.gv.egiz.eaaf.modules.pvp2.exception.BindingNotSupportedException; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.exception.NoMetadataInformationException; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; +import at.gv.egiz.eaaf.modules.pvp2.idp.impl.PVPSProfilePendingRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.PostBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.binding.RedirectBinding; +import at.gv.egiz.eaaf.modules.pvp2.impl.message.PVPSProfileRequest; +import at.gv.egiz.eaaf.modules.pvp2.impl.opensaml.StringRedirectDeflateEncoder; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.TrustEngineFactory; +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.auth.frontend.builder.DefaultGUIFormBuilderConfiguration; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.data.ISLOInformationContainer; import at.gv.egovernment.moa.id.data.SLOInformationContainer; -import at.gv.egovernment.moa.id.data.SLOInformationImpl; -import at.gv.egovernment.moa.id.opemsaml.MOAStringRedirectDeflateEncoder; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.BindingNotSupportedException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NOSLOServiceDescriptorException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMetadataInformationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -98,6 +124,187 @@ public class SingleLogOutBuilder { @Autowired(required=true) private MOAMetadataProvider metadataProvider; @Autowired(required=true) ApplicationContext springContext; @Autowired private IDPCredentialProvider credentialProvider; + @Autowired private SAMLVerificationEngineSP samlVerificationEngine; + @Autowired private IGUIFormBuilder guiBuilder; + @Autowired(required=true) protected IRevisionLogger revisionsLogger; + @Autowired private ITransactionStorage transactionStorage; + @Autowired(required=true) IPVP2BasicConfiguration pvpBasicConfiguration; + + public static final int SLOTIMEOUT = 30 * 1000; //30 sec + + public void toTechnicalLogout(ISLOInformationContainer sloContainer, + HttpServletRequest httpReq, HttpServletResponse httpResp, String authUrl) throws EAAFException { + Logger.trace("Starting Service-Provider logout process ... "); + revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), MOAIDEventConstants.AUTHPROCESS_SLO_STARTED); + + //start service provider back channel logout process + Iterator<String> nextOAInterator = sloContainer.getNextBackChannelOA(); + while (nextOAInterator.hasNext()) { + SLOInformationInterface sloDescr = sloContainer.getBackChannelOASessionDescripten(nextOAInterator.next()); + LogoutRequest sloReq = buildSLORequestMessage(sloDescr); + + try { + Logger.trace("Send backchannel SLO Request to " + sloDescr.getSpEntityID()); + List<XMLObject> soapResp = MOASAMLSOAPClient.send(sloDescr.getServiceURL(), sloReq); + + LogoutResponse sloResp = null; + for (XMLObject el : soapResp) { + if (el instanceof LogoutResponse) + sloResp = (LogoutResponse) el; + } + + if (sloResp == null) { + Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() + + " FAILED. NO LogOut response received."); + sloContainer.putFailedOA(sloDescr.getSpEntityID()); + + } else { + samlVerificationEngine.verifySLOResponse(sloResp, + TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); + + } + + checkStatusCode(sloContainer, sloResp); + + } catch (SOAPException e) { + Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() + + " FAILED.", e); + sloContainer.putFailedOA(sloDescr.getSpEntityID()); + + } catch (SecurityException | InvalidProtocolRequestException e) { + Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() + + " FAILED.", e); + sloContainer.putFailedOA(sloDescr.getSpEntityID()); + + } + } + + IRequest pendingReq = null; + PVPSProfilePendingRequest pvpReq = null; + //start service provider front channel logout process + try { + if (sloContainer.hasFrontChannelOA()) { + String relayState = Random.nextRandom(); + + Collection<Entry<String, SLOInformationInterface>> sloDescr = sloContainer.getFrontChannelOASessionDescriptions(); + List<String> sloReqList = new ArrayList<String>(); + for (Entry<String, SLOInformationInterface> el : sloDescr) { + Logger.trace("Build frontChannel SLO Request for " + el.getValue().getSpEntityID()); + + LogoutRequest sloReq = buildSLORequestMessage(el.getValue()); + try { + sloReqList.add(getFrontChannelSLOMessageURL(el.getValue().getServiceURL(), el.getValue().getBinding(), + sloReq, httpReq, httpResp, relayState)); + + } catch (Exception e) { + Logger.warn("Failed to build SLO request for OA:" + el.getKey()); + sloContainer.putFailedOA(el.getKey()); + + } + } + + //put SLO process-information into transaction storage + AssertionStore rawContainer = new AssertionStore(); + rawContainer.setArtifact(relayState); + rawContainer.setDatatime(new Date()); + rawContainer.setAssertion(SerializationUtils.serialize(sloContainer)); + rawContainer.setType(sloContainer.getClass().getName()); + transactionStorage.putRaw(relayState, rawContainer); + + if (MiscUtil.isEmpty(authUrl)) + authUrl = sloContainer.getSloRequest().getAuthURL(); + + String timeOutURL = authUrl + + "/idpSingleLogout" + + "?restart=" + relayState; + + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authUrl, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + + config.putCustomParameterWithOutEscaption("redirectURLs", sloReqList); + config.putCustomParameterWithOutEscaption("timeoutURL", timeOutURL); + config.putCustomParameter("timeout", String.valueOf(SLOTIMEOUT)); + + guiBuilder.build(httpResp, config, "Single-LogOut GUI"); + + + } else { + pendingReq = sloContainer.getSloRequest(); + if (pendingReq != null && pendingReq instanceof PVPSProfilePendingRequest) { + //send SLO response to SLO request issuer + pvpReq = (PVPSProfilePendingRequest)pendingReq; + SingleLogoutService sloService = getResponseSLODescriptor(pvpReq); + LogoutResponse message = buildSLOResponseMessage(sloService, pvpReq, sloContainer.getSloFailedOAs()); + sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, pvpReq.getRequest().getRelayState(), pvpReq); + + } else { + //print SLO information directly + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authUrl, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + + if (sloContainer.getSloFailedOAs() == null || + sloContainer.getSloFailedOAs().size() == 0) { + revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); + config.putCustomParameter("successMsg", + MOAIDMessageProvider.getInstance().getMessage("slo.00", null)); + + } else { + revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); + config.putCustomParameterWithOutEscaption("errorMsg", + MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); + + } + guiBuilder.build(httpResp, config, "Single-LogOut GUI"); + + } + + } + + } catch (GUIBuildException e) { + Logger.warn("Can not build GUI:'Single-LogOut'. Msg:" + e.getMessage()); + throw new MOAIDException("builder.09", new Object[]{e.getMessage()}, e); + + } catch (MOADatabaseException e) { + Logger.error("MOA AssertionDatabase ERROR", e); + if (pvpReq != null) { + SingleLogoutService sloService = getResponseSLODescriptor(pvpReq); + LogoutResponse message = buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, pvpReq.getRequest().getRelayState(), pvpReq); + + revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); + + }else { + //print SLO information directly + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authUrl, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + + revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); + config.putCustomParameterWithOutEscaption("errorMsg", + MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); + + try { + guiBuilder.build(httpResp, config, "Single-LogOut GUI"); + + } catch (GUIBuildException e1) { + Logger.warn("Can not build GUI:'Single-LogOut'. Msg:" + e.getMessage()); + throw new MOAIDException("builder.09", new Object[]{e.getMessage()}, e); + + } + + } + + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + public void checkStatusCode(ISLOInformationContainer sloContainer, LogoutResponse logOutResp) { @@ -125,10 +332,11 @@ public class SingleLogOutBuilder { * @param httpResp * @param relayState * @return + * @throws CredentialsNotAvailableException */ public String getFrontChannelSLOMessageURL(String serviceURL, String bindingType, RequestAbstractType sloReq, HttpServletRequest httpReq, - HttpServletResponse httpResp, String relayState) throws MOAIDException { + HttpServletResponse httpResp, String relayState) throws MOAIDException, CredentialsNotAvailableException { try { X509Credential credentials = credentialProvider @@ -136,7 +344,7 @@ public class SingleLogOutBuilder { Logger.debug("create SAML RedirectBinding response"); - MOAStringRedirectDeflateEncoder encoder = new MOAStringRedirectDeflateEncoder(); + StringRedirectDeflateEncoder encoder = new StringRedirectDeflateEncoder(); BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); SingleLogoutService service = new SingleLogoutServiceBuilder() .buildObject(); @@ -160,7 +368,7 @@ public class SingleLogOutBuilder { public String getFrontChannelSLOMessageURL(SingleLogoutService service, StatusResponseType sloResp, HttpServletRequest httpReq, - HttpServletResponse httpResp, String relayState) throws MOAIDException { + HttpServletResponse httpResp, String relayState) throws MOAIDException, CredentialsNotAvailableException { try { X509Credential credentials = credentialProvider @@ -168,7 +376,7 @@ public class SingleLogOutBuilder { Logger.debug("create SAML RedirectBinding response"); - MOAStringRedirectDeflateEncoder encoder = new MOAStringRedirectDeflateEncoder(); + StringRedirectDeflateEncoder encoder = new StringRedirectDeflateEncoder(); BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject> context = new BasicSAMLMessageContext<SAMLObject, SAMLObject, SAMLObject>(); context.setOutboundSAMLMessageSigningCredential(credentials); context.setPeerEntityEndpoint(service); @@ -188,7 +396,7 @@ public class SingleLogOutBuilder { public void sendFrontChannelSLOMessage(SingleLogoutService consumerService, LogoutResponse sloResp, HttpServletRequest req, HttpServletResponse resp, - String relayState, PVPTargetConfiguration pvpReq) throws MOAIDException { + String relayState, PVPSProfilePendingRequest pvpReq) throws MOAIDException, PVP2Exception, CredentialsNotAvailableException { IEncoder binding = null; if (consumerService.getBinding().equals( SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { @@ -221,7 +429,7 @@ public class SingleLogOutBuilder { } - public LogoutRequest buildSLORequestMessage(SLOInformationImpl sloInfo) throws ConfigurationException, MOAIDException { + public LogoutRequest buildSLORequestMessage(SLOInformationInterface sloDescr) throws EAAFException { LogoutRequest sloReq = SAML2Utils.createSAMLObject(LogoutRequest.class); SecureRandomIdentifierGenerator gen; @@ -237,17 +445,17 @@ public class SingleLogOutBuilder { DateTime now = new DateTime(); Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - issuer.setValue(PVPConfiguration.getInstance().getIDPSSOMetadataService(sloInfo.getAuthURL())); + issuer.setValue(pvpBasicConfiguration.getIDPEntityId(sloDescr.getAuthURL())); issuer.setFormat(NameID.ENTITY); sloReq.setIssuer(issuer); sloReq.setIssueInstant(now); sloReq.setNotOnOrAfter(now.plusMinutes(5)); - sloReq.setDestination(sloInfo.getServiceURL()); + sloReq.setDestination(sloDescr.getServiceURL()); NameID nameID = SAML2Utils.createSAMLObject(NameID.class); - nameID.setFormat(sloInfo.getUserNameIDFormat()); - nameID.setValue(sloInfo.getUserNameIdentifier()); + nameID.setFormat(sloDescr.getUserNameIDFormat()); + nameID.setValue(sloDescr.getUserNameIdentifier()); sloReq.setNameID(nameID ); //sign message @@ -281,7 +489,7 @@ public class SingleLogOutBuilder { return sloReq; } - public LogoutResponse buildSLOErrorResponse(SingleLogoutService sloService, PVPTargetConfiguration spRequest, String firstLevelStatusCode) throws ConfigurationException, MOAIDException { + public LogoutResponse buildSLOErrorResponse(SingleLogoutService sloService, PVPSProfilePendingRequest spRequest, String firstLevelStatusCode) throws EAAFException { LogoutResponse sloResp = buildBasicResponse(sloService, spRequest); Status status = SAML2Utils.createSAMLObject(Status.class); @@ -298,7 +506,7 @@ public class SingleLogOutBuilder { return sloResp; } - public LogoutResponse buildSLOResponseMessage(SingleLogoutService sloService, PVPTargetConfiguration spRequest, List<String> failedOAs) throws MOAIDException { + public LogoutResponse buildSLOResponseMessage(SingleLogoutService sloService, PVPSProfilePendingRequest spRequest, List<String> failedOAs) throws EAAFException { LogoutResponse sloResp = buildBasicResponse(sloService, spRequest); Status status; @@ -323,11 +531,10 @@ public class SingleLogOutBuilder { } - private LogoutResponse buildBasicResponse(SingleLogoutService sloService, PVPTargetConfiguration spRequest) throws ConfigurationException, MOAIDException { + private LogoutResponse buildBasicResponse(SingleLogoutService sloService, PVPSProfilePendingRequest spRequest) throws EAAFException { LogoutResponse sloResp = SAML2Utils.createSAMLObject(LogoutResponse.class); Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - issuer.setValue(PVPConfiguration.getInstance().getIDPSSOMetadataService( - spRequest.getAuthURLWithOutSlash())); + issuer.setValue(pvpBasicConfiguration.getIDPEntityId(spRequest.getAuthURLWithOutSlash())); issuer.setFormat(NameID.ENTITY); sloResp.setIssuer(issuer); sloResp.setIssueInstant(new DateTime()); @@ -344,9 +551,9 @@ public class SingleLogOutBuilder { } - if (spRequest.getRequest() instanceof MOARequest && - ((MOARequest)spRequest.getRequest()).getSamlRequest() instanceof LogoutRequest) { - LogoutRequest sloReq = (LogoutRequest) ((MOARequest)spRequest.getRequest()).getSamlRequest(); + if (spRequest.getRequest() instanceof PVPSProfileRequest && + ((PVPSProfileRequest)spRequest.getRequest()).getSamlRequest() instanceof LogoutRequest) { + LogoutRequest sloReq = (LogoutRequest) ((PVPSProfileRequest)spRequest.getRequest()).getSamlRequest(); sloResp.setInResponseTo(sloReq.getID()); } @@ -396,8 +603,8 @@ public class SingleLogOutBuilder { } - public SingleLogoutService getResponseSLODescriptor(PVPTargetConfiguration spRequest) throws NoMetadataInformationException, NOSLOServiceDescriptorException { - MOARequest moaReq = (MOARequest) spRequest.getRequest(); + public SingleLogoutService getResponseSLODescriptor(PVPSProfilePendingRequest spRequest) throws NoMetadataInformationException, NOSLOServiceDescriptorException { + PVPSProfileRequest moaReq = (PVPSProfileRequest) spRequest.getRequest(); EntityDescriptor metadata = moaReq.getEntityMetadata(metadataProvider); SSODescriptor ssodesc = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); @@ -435,9 +642,9 @@ public class SingleLogOutBuilder { public void parseActiveOAs(SLOInformationContainer container, List<OASessionStore> dbOAs, String removeOAID) { if (container.getActiveBackChannelOAs() == null) - container.setActiveBackChannelOAs(new LinkedHashMap<String, SLOInformationImpl>()); + container.setActiveBackChannelOAs(new LinkedHashMap<String, SLOInformationInterface>()); if (container.getActiveFrontChannalOAs() == null) - container.setActiveFrontChannalOAs(new LinkedHashMap<String, SLOInformationImpl>()); + container.setActiveFrontChannalOAs(new LinkedHashMap<String, SLOInformationInterface>()); if (dbOAs != null) { @@ -459,7 +666,8 @@ public class SingleLogOutBuilder { oa.getUserNameID(), oa.getUserNameIDFormat(), oa.getProtocolType(), - sloDesc)); + sloDesc.getBinding(), + sloDesc.getLocation())); else container.getActiveFrontChannalOAs().put(oa.getOaurlprefix(), @@ -470,7 +678,8 @@ public class SingleLogOutBuilder { oa.getUserNameID(), oa.getUserNameIDFormat(), oa.getProtocolType(), - sloDesc)); + sloDesc.getBinding(), + sloDesc.getLocation())); } catch (NOSLOServiceDescriptorException e) { container.putFailedOA(oa.getOaurlprefix()); @@ -491,9 +700,9 @@ public class SingleLogOutBuilder { public void parseActiveIDPs(SLOInformationContainer container, List<InterfederationSessionStore> dbIDPs, String removeIDP) { if (container.getActiveBackChannelOAs() == null) - container.setActiveBackChannelOAs(new LinkedHashMap<String, SLOInformationImpl>()); + container.setActiveBackChannelOAs(new LinkedHashMap<String, SLOInformationInterface>()); if (container.getActiveFrontChannalOAs() == null) - container.setActiveFrontChannalOAs(new LinkedHashMap<String, SLOInformationImpl>()); + container.setActiveFrontChannalOAs(new LinkedHashMap<String, SLOInformationInterface>()); if (dbIDPs != null) { for (InterfederationSessionStore el : dbIDPs) { @@ -511,7 +720,8 @@ public class SingleLogOutBuilder { el.getUserNameID(), NameID.TRANSIENT, PVP2XProtocol.NAME, - sloDesc)); + sloDesc.getBinding(), + sloDesc.getLocation())); } catch (NOSLOServiceDescriptorException e) { container.putFailedOA(el.getIdpurlprefix()); 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 deleted file mode 100644 index 196aa47af..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ /dev/null @@ -1,536 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion; - -import java.security.MessageDigest; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.joda.time.DateTime; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.Assertion; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeQuery; -import org.opensaml.saml2.core.AttributeStatement; -import org.opensaml.saml2.core.Audience; -import org.opensaml.saml2.core.AudienceRestriction; -import org.opensaml.saml2.core.AuthnContext; -import org.opensaml.saml2.core.AuthnContextClassRef; -import org.opensaml.saml2.core.AuthnRequest; -import org.opensaml.saml2.core.AuthnStatement; -import org.opensaml.saml2.core.Conditions; -import org.opensaml.saml2.core.Issuer; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.core.RequestedAuthnContext; -import org.opensaml.saml2.core.Subject; -import org.opensaml.saml2.core.SubjectConfirmation; -import org.opensaml.saml2.core.SubjectConfirmationData; -import org.opensaml.saml2.core.impl.AuthnRequestImpl; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.AttributeConsumingService; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.NameIDFormat; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.w3c.dom.Element; - -import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; -import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; -import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; -import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; -import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; -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.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.Pair; -import at.gv.egovernment.moa.id.data.SLOInformationImpl; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMandateDataAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.QAANotSupportedException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttributeException; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.id.util.MandateBuilder; -import at.gv.egovernment.moa.id.util.QAALevelVerifier; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Base64Utils; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.MiscUtil; - -public class PVP2AssertionBuilder implements PVPConstants { - - /** - * Build a PVP assertion as response for a SAML2 AttributeQuery request - * - * @param issuerEntityID EnitiyID, which should be used for this IDP response - * @param attrQuery AttributeQuery request from Service-Provider - * @param attrList List of PVP response attributes - * @param now Current time - * @param validTo ValidTo time of the assertion - * @param qaaLevel QAA level of the authentication - * @param sessionIndex SAML2 SessionIndex, which should be included * - * @return PVP 2.1 Assertion - * @throws ConfigurationException - */ - public static Assertion buildAssertion(String issuerEntityID, AttributeQuery attrQuery, - List<Attribute> attrList, DateTime now, DateTime validTo, String qaaLevel, String sessionIndex) throws ConfigurationException { - - AuthnContextClassRef authnContextClassRef = SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - authnContextClassRef.setAuthnContextClassRef(qaaLevel); - - NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); - subjectNameID.setFormat(attrQuery.getSubject().getNameID().getFormat()); - subjectNameID.setValue(attrQuery.getSubject().getNameID().getValue()); - - SubjectConfirmationData subjectConfirmationData = null; - - return buildGenericAssertion(issuerEntityID, attrQuery.getIssuer().getValue(), now, - authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, - validTo); - } - - - /** - * Build a PVP 2.1 assertion as response of a SAML2 AuthnRequest - * - * @param issuerEntityID EnitiyID, which should be used for this IDP response - * @param pendingReq Current processed pendingRequest DAO - * @param authnRequest Current processed PVP AuthnRequest - * @param authData AuthenticationData of the user, which is already authenticated - * @param peerEntity SAML2 EntityDescriptor of the service-provider, which receives the response - * @param date TimeStamp - * @param assertionConsumerService SAML2 endpoint of the service-provider, which should be used - * @param sloInformation Single LogOut information DAO - * @return - * @throws MOAIDException - */ - public static Assertion buildAssertion(String issuerEntityID, PVPTargetConfiguration pendingReq, AuthnRequest authnRequest, - IAuthData authData, EntityDescriptor peerEntity, DateTime date, - AssertionConsumerService assertionConsumerService, SLOInformationImpl sloInformation) - throws MOAIDException { - - RequestedAuthnContext reqAuthnContext = authnRequest - .getRequestedAuthnContext(); - - AuthnContextClassRef authnContextClassRef = SAML2Utils - .createSAMLObject(AuthnContextClassRef.class); - - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - - if (reqAuthnContext == null) { - authnContextClassRef.setAuthnContextClassRef(authData.getQAALevel()); - - } else { - - boolean stork_qaa_1_4_found = false; - - List<AuthnContextClassRef> reqAuthnContextClassRefIt = reqAuthnContext - .getAuthnContextClassRefs(); - - if (reqAuthnContextClassRefIt.size() == 0) { - - QAALevelVerifier.verifyQAALevel(authData.getQAALevel(), - STORK_QAA_1_4); - - stork_qaa_1_4_found = true; - authnContextClassRef.setAuthnContextClassRef(STORK_QAA_1_4); - - } else { - for (AuthnContextClassRef authnClassRef : reqAuthnContextClassRefIt) { - String qaa_uri = authnClassRef.getAuthnContextClassRef(); - if (qaa_uri.trim().equals(STORK_QAA_1_4) - || qaa_uri.trim().equals(STORK_QAA_1_3) - || qaa_uri.trim().equals(STORK_QAA_1_2) - || qaa_uri.trim().equals(STORK_QAA_1_1)) { - - if (authData.isForeigner()) { - QAALevelVerifier.verifyQAALevel(authData.getQAALevel(), - STORK_QAA_PREFIX + oaParam.getQaaLevel()); - - stork_qaa_1_4_found = true; - authnContextClassRef.setAuthnContextClassRef(authData.getQAALevel()); - - } else { - - QAALevelVerifier.verifyQAALevel(authData.getQAALevel(), - qaa_uri.trim()); - - stork_qaa_1_4_found = true; - authnContextClassRef.setAuthnContextClassRef(authData.getQAALevel()); - - } - break; - } - } - } - - if (!stork_qaa_1_4_found) { - throw new QAANotSupportedException(STORK_QAA_1_4); - } - } - - - - SPSSODescriptor spSSODescriptor = peerEntity - .getSPSSODescriptor(SAMLConstants.SAML20P_NS); - - //add Attributes to Assertion - List<Attribute> attrList = new ArrayList<Attribute>(); - if (spSSODescriptor.getAttributeConsumingServices() != null && - spSSODescriptor.getAttributeConsumingServices().size() > 0) { - - Integer aIdx = authnRequest.getAttributeConsumingServiceIndex(); - int idx = 0; - - AttributeConsumingService attributeConsumingService = null; - if (aIdx != null) { - idx = aIdx.intValue(); - attributeConsumingService = spSSODescriptor - .getAttributeConsumingServices().get(idx); - - } else { - List<AttributeConsumingService> attrConsumingServiceList = spSSODescriptor.getAttributeConsumingServices(); - for (AttributeConsumingService el : attrConsumingServiceList) { - if (el.isDefault()) - attributeConsumingService = el; - } - } - - /* - * TODO: maybe use first AttributeConsumingService if no is selected - * in request or on service is marked as default - * - */ - if (attributeConsumingService == null ) { - List<AttributeConsumingService> attrConsumingServiceList = spSSODescriptor.getAttributeConsumingServices(); - if (attrConsumingServiceList != null && !attrConsumingServiceList.isEmpty()) - attributeConsumingService = attrConsumingServiceList.get(0); - - } - - - if (attributeConsumingService != null) { - Iterator<RequestedAttribute> it = attributeConsumingService - .getRequestAttributes().iterator(); - while (it.hasNext()) { - RequestedAttribute reqAttribut = it.next(); - try { - Attribute attr = PVPAttributeBuilder.buildAttribute( - reqAttribut.getName(), oaParam, authData); - if (attr == null) { - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); - } - } else { - attrList.add(attr); - } - - } catch (UnavailableAttributeException e) { - Logger.info( - "Attribute generation for " - + reqAttribut.getFriendlyName() + " not possible."); - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); - } - - - } catch (PVP2Exception e) { - Logger.info( - "Attribute generation failed! for " - + reqAttribut.getFriendlyName()); - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); - } - - } catch (Exception e) { - Logger.warn( - "General Attribute generation failed! for " - + reqAttribut.getFriendlyName(), e); - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); - } - - } - } - } - } - - NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); - - //build nameID and nameID Format from moasession - //TODO: nameID generation - if (authData.isUseMandate()) { - String bpktype = null; - String bpk = null; - - Element mandate = authData.getMandate(); - if(mandate != null) { - Logger.debug("Read mandator bPK|baseID from full-mandate ... "); - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAvailableException(); - } - CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); - PhysicalPersonType pysicalperson = mandateObject.getMandator().getPhysicalPerson(); - - IdentificationType id; - if(corporation != null && corporation.getIdentification().size() > 0) - id = corporation.getIdentification().get(0); - - - else if (pysicalperson != null && pysicalperson.getIdentification().size() > 0) - id = pysicalperson.getIdentification().get(0); - - else { - Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAvailableException(); - } - - bpktype = id.getType(); - bpk = id.getValue().getValue(); - - } else { - Logger.debug("Read mandator bPK|baseID from PVP attributes ... "); - bpk = authData.getGenericData(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME, String.class); - bpktype = authData.getGenericData(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME, String.class); - - if (MiscUtil.isEmpty(bpk)) { - //no sourcePin is included --> search for bPK - bpk = authData.getGenericData(PVPConstants.MANDATE_NAT_PER_BPK_NAME, String.class); - - try { - if (bpk.contains(":")) - bpk = bpk.split(":")[1]; - - } catch (Exception e) { - Logger.warn("Can not split bPK from mandator attribute!", e); - - } - - //set bPK-Type from configuration, because it MUST be equal to service-provider type - bpktype = oaParam.getAreaSpecificTargetIdentifier(); - - } else { - //sourcePin is include --> check sourcePinType - if (MiscUtil.isEmpty(bpktype)) - bpktype = Constants.URN_PREFIX_BASEID; - - } - } - - if (MiscUtil.isEmpty(bpk) || MiscUtil.isEmpty(bpktype)) { - throw new NoMandateDataAvailableException(); - - } - - if (bpktype.equals(Constants.URN_PREFIX_BASEID)) { - Pair<String, String> calcbPK = new BPKBuilder().generateAreaSpecificPersonIdentifier(bpk, oaParam.getAreaSpecificTargetIdentifier()); - subjectNameID.setValue(calcbPK.getFirst()); - subjectNameID.setNameQualifier(calcbPK.getSecond()); - - - } else { - subjectNameID.setNameQualifier(bpktype); - subjectNameID.setValue(bpk); - } - - } else { - subjectNameID.setNameQualifier(authData.getBPKType()); - subjectNameID.setValue(authData.getBPK()); - } - - String nameIDFormat = NameID.TRANSIENT; - - //get NameIDFormat from request - AuthnRequest authnReq = (AuthnRequestImpl) authnRequest; - if (authnReq.getNameIDPolicy() != null && - MiscUtil.isNotEmpty(authnReq.getNameIDPolicy().getFormat())) { - nameIDFormat = authnReq.getNameIDPolicy().getFormat(); - - } else { - //get NameIDFormat from metadata - List<NameIDFormat> metadataNameIDFormats = spSSODescriptor.getNameIDFormats(); - - if (metadataNameIDFormats != null) { - - for (NameIDFormat el : metadataNameIDFormats) { - if (NameID.PERSISTENT.equals(el.getFormat())) { - nameIDFormat = NameID.PERSISTENT; - break; - - } else if (NameID.TRANSIENT.equals(el.getFormat()) || - NameID.UNSPECIFIED.equals(el.getFormat())) - break; - - } - } - } - - if (NameID.TRANSIENT.equals(nameIDFormat) || NameID.UNSPECIFIED.equals(nameIDFormat)) { - String random = Random.nextRandom(); - String nameID = subjectNameID.getValue(); - - try { - MessageDigest md = MessageDigest.getInstance("SHA-1"); - byte[] hash = md.digest((nameID + random).getBytes("ISO-8859-1")); - subjectNameID.setValue(Base64Utils.encode(hash)); - subjectNameID.setNameQualifier(null); - subjectNameID.setFormat(NameID.TRANSIENT); - - } catch (Exception e) { - Logger.warn("PVP2 subjectNameID error", e); - throw new MOAIDException("pvp2.13", null, e); - } - - } else - subjectNameID.setFormat(nameIDFormat); - - - String sessionIndex = null; - - //if request is a reauthentication and NameIDFormat match reuse old session information - if (MiscUtil.isNotEmpty(authData.getNameID()) && - MiscUtil.isNotEmpty(authData.getNameIDFormat()) && - nameIDFormat.equals(authData.getNameIDFormat())) { - subjectNameID.setValue(authData.getNameID()); - sessionIndex = authData.getSessionIndex(); - - } - - // - if (MiscUtil.isEmpty(sessionIndex)) - sessionIndex = SAML2Utils.getSecureIdentifier(); - - SubjectConfirmationData subjectConfirmationData = SAML2Utils - .createSAMLObject(SubjectConfirmationData.class); - subjectConfirmationData.setInResponseTo(authnRequest.getID()); - 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()); - sloInformation.setSessionIndex(sessionIndex); - - return buildGenericAssertion(issuerEntityID, peerEntity.getEntityID(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, subjectConfirmationData.getNotOnOrAfter()); - } - - /** - * - * @param issuer IDP EntityID - * @param entityID Service Provider EntityID - * @param date - * @param authnContextClassRef - * @param attrList - * @param subjectNameID - * @param subjectConfirmationData - * @param sessionIndex - * @param isValidTo - * @return - * @throws ConfigurationException - */ - - public static Assertion buildGenericAssertion(String issuer, String entityID, DateTime date, - AuthnContextClassRef authnContextClassRef, List<Attribute> attrList, - NameID subjectNameID, SubjectConfirmationData subjectConfirmationData, - String sessionIndex, DateTime isValidTo) throws ConfigurationException { - Assertion assertion = SAML2Utils.createSAMLObject(Assertion.class); - - AuthnContext authnContext = SAML2Utils - .createSAMLObject(AuthnContext.class); - authnContext.setAuthnContextClassRef(authnContextClassRef); - - AuthnStatement authnStatement = SAML2Utils - .createSAMLObject(AuthnStatement.class); - - authnStatement.setAuthnInstant(date); - authnStatement.setSessionIndex(sessionIndex); - authnStatement.setAuthnContext(authnContext); - - assertion.getAuthnStatements().add(authnStatement); - - AttributeStatement attributeStatement = SAML2Utils - .createSAMLObject(AttributeStatement.class); - attributeStatement.getAttributes().addAll(attrList); - if (attributeStatement.getAttributes().size() > 0) { - assertion.getAttributeStatements().add(attributeStatement); - } - - Subject subject = SAML2Utils.createSAMLObject(Subject.class); - subject.setNameID(subjectNameID); - - SubjectConfirmation subjectConfirmation = SAML2Utils - .createSAMLObject(SubjectConfirmation.class); - subjectConfirmation.setMethod(SubjectConfirmation.METHOD_BEARER); - subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData); - - subject.getSubjectConfirmations().add(subjectConfirmation); - - Conditions conditions = SAML2Utils.createSAMLObject(Conditions.class); - AudienceRestriction audienceRestriction = SAML2Utils - .createSAMLObject(AudienceRestriction.class); - Audience audience = SAML2Utils.createSAMLObject(Audience.class); - - audience.setAudienceURI(entityID); - audienceRestriction.getAudiences().add(audience); - conditions.setNotBefore(date); - conditions.setNotOnOrAfter(isValidTo); - - conditions.getAudienceRestrictions().add(audienceRestriction); - - assertion.setConditions(conditions); - - Issuer issuerObj = SAML2Utils.createSAMLObject(Issuer.class); - - if (issuer.endsWith("/")) - issuer = issuer.substring(0, issuer.length()-1); - issuerObj.setValue(issuer); - issuerObj.setFormat(NameID.ENTITY); - - assertion.setIssuer(issuerObj); - assertion.setSubject(subject); - assertion.setID(SAML2Utils.getSecureIdentifier()); - assertion.setIssueInstant(date); - - return assertion; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java deleted file mode 100644 index e462b277e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/SamlAttributeGenerator.java +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; - -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeValue; -import org.opensaml.xml.Configuration; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.schema.XSInteger; -import org.opensaml.xml.schema.XSString; -import org.opensaml.xml.schema.impl.XSIntegerBuilder; -import org.opensaml.xml.schema.impl.XSStringBuilder; - -import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; - -public class SamlAttributeGenerator implements IAttributeGenerator<Attribute> { - - private XMLObject buildAttributeStringValue(String value) { - XSStringBuilder stringBuilder = (XSStringBuilder) Configuration.getBuilderFactory().getBuilder(XSString.TYPE_NAME); - XSString stringValue = stringBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSString.TYPE_NAME); - stringValue.setValue(value); - return stringValue; - } - - private XMLObject buildAttributeIntegerValue(int value) { - XSIntegerBuilder integerBuilder = (XSIntegerBuilder) Configuration.getBuilderFactory().getBuilder(XSInteger.TYPE_NAME); - XSInteger integerValue = integerBuilder.buildObject(AttributeValue.DEFAULT_ELEMENT_NAME, XSInteger.TYPE_NAME); - integerValue.setValue(value); - return integerValue; - } - - public Attribute buildStringAttribute(final String friendlyName, final String name, final String value) { - Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - attribute.getAttributeValues().add(buildAttributeStringValue(value)); - return attribute; - } - - public Attribute buildIntegerAttribute(final String friendlyName, final String name, final int value) { - Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - attribute.getAttributeValues().add(buildAttributeIntegerValue(value)); - return attribute; - } - - public Attribute buildEmptyAttribute(final String friendlyName, final String name) { - Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - return attribute; - } - - public Attribute buildLongAttribute(String friendlyName, String name, long value) { - Attribute attribute = SAML2Utils.createSAMLObject(Attribute.class); - attribute.setFriendlyName(friendlyName); - attribute.setName(name); - attribute.setNameFormat(Attribute.URI_REFERENCE); - attribute.getAttributeValues().add(buildAttributeIntegerValue((int) value)); - return attribute; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributeException.java deleted file mode 100644 index 9f13b8270..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributeException.java +++ /dev/null @@ -1,33 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions; - -public class AttributeException extends Exception { - - private static final long serialVersionUID = 1L; - - public AttributeException(String message) { - super(message); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributePolicyException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributePolicyException.java deleted file mode 100644 index 1e0e2ee51..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/AttributePolicyException.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions; - -public class AttributePolicyException extends AttributeException { - - private static final long serialVersionUID = 1L; - - private String attributeName; - - public AttributePolicyException(String attributeName) { - super("Attribute " + attributeName + " is restricted by IDP policy."); - this.attributeName = attributeName; - } - - public String getAttributeName() { - return attributeName; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/InvalidDateFormatAttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/InvalidDateFormatAttributeException.java deleted file mode 100644 index dd251f0cd..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/InvalidDateFormatAttributeException.java +++ /dev/null @@ -1,35 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions; - -public class InvalidDateFormatAttributeException extends AttributeException { - - private static final long serialVersionUID = 1L; - - public InvalidDateFormatAttributeException() { - super("Date format is invalid."); - } - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/NoMandateDataAttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/NoMandateDataAttributeException.java index 066330a2d..ad505efa5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/NoMandateDataAttributeException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/NoMandateDataAttributeException.java @@ -22,7 +22,9 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions; -public class NoMandateDataAttributeException extends AttributeException { +import at.gv.egiz.eaaf.core.exceptions.AttributeBuilderException; + +public class NoMandateDataAttributeException extends AttributeBuilderException { private static final long serialVersionUID = 1L; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/UnavailableAttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/UnavailableAttributeException.java deleted file mode 100644 index f63edf909..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/exceptions/UnavailableAttributeException.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions; - -public class UnavailableAttributeException extends AttributeException { - - private static final long serialVersionUID = 1L; - - private String attributeName; - - public UnavailableAttributeException(String attributeName) { - super("Attribute " + attributeName + " is not available."); - this.attributeName = attributeName; - } - - public String getAttributeName() { - return attributeName; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java index c0fb5bf5b..d4c94e5c5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java @@ -32,11 +32,12 @@ import org.opensaml.saml2.metadata.Organization; import org.opensaml.saml2.metadata.RequestedAttribute; import org.opensaml.xml.security.credential.Credential; +import at.gv.egiz.eaaf.modules.pvp2.PVPConstants; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataBuilderConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.impl.builder.PVPAttributeBuilder; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.logging.Logger; /** @@ -48,16 +49,18 @@ public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfigura private static final int VALIDUNTIL_IN_HOURS = 24; private String authURL; - private IDPCredentialProvider credentialProvider; + private AbstractCredentialProvider credentialProvider; + private PVPConfiguration pvpBasicConfiguration; - public IDPPVPMetadataConfiguration(String authURL, IDPCredentialProvider credentialProvider) { + public IDPPVPMetadataConfiguration(String authURL, AbstractCredentialProvider pvpIDPCredentials, PVPConfiguration pvpBasicConfiguration) { this.authURL = authURL; - this.credentialProvider = credentialProvider; + this.credentialProvider = pvpIDPCredentials; + this.pvpBasicConfiguration = pvpBasicConfiguration; } public String getDefaultActionName() { - return (PVP2XProtocol.METADATA); + return (PVPConstants.METADATA); } /* (non-Javadoc) @@ -98,7 +101,7 @@ public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfigura @Override public String getEntityID() { try { - return PVPConfiguration.getInstance().getIDPSSOMetadataService(authURL); + return pvpBasicConfiguration.getIDPSSOMetadataService(authURL); } catch (ConfigurationException e) { Logger.error("Can not load Metadata entry: EntityID", e); @@ -113,7 +116,7 @@ public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfigura @Override public String getEntityFriendlyName() { try { - return PVPConfiguration.getInstance().getIDPIssuerName(); + return pvpBasicConfiguration.getIDPIssuerName(); } catch (ConfigurationException e) { Logger.error("Can not load Metadata entry: EntityID friendlyName.", e); @@ -129,7 +132,7 @@ public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfigura @Override public List<ContactPerson> getContactPersonInformation() { try { - return PVPConfiguration.getInstance().getIDPContacts(); + return pvpBasicConfiguration.getIDPContacts(); } catch (ConfigurationException e) { Logger.warn("Can not load Metadata entry: Contect Person", e); @@ -145,7 +148,7 @@ public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfigura @Override public Organization getOrgansiationInformation() { try { - return PVPConfiguration.getInstance().getIDPOrganisation(); + return pvpBasicConfiguration.getIDPOrganisation(); } catch (ConfigurationException e) { Logger.warn("Can not load Metadata entry: Organisation", e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java deleted file mode 100644 index 814a2387d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.config; - -import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.xml.security.credential.Credential; -import org.w3c.dom.Element; - -/** - * @author tlenz - * - */ -public interface IPVPAuthnRequestBuilderConfiguruation { - - /** - * Defines a unique name for this PVP Service-provider, which is used for logging - * - * @return - */ - public String getSPNameForLogging(); - - /** - * If true, the SAML2 isPassive flag is set in the AuthnRequest - * - * @return - */ - public Boolean isPassivRequest(); - - /** - * Define the ID of the AssertionConsumerService, - * which defines the required attributes in service-provider metadata. - * - * @return - */ - public Integer getAssertionConsumerServiceId(); - - /** - * Define the SAML2 EntityID of the service provider. - * - * @return - */ - public String getSPEntityID(); - - /** - * Define the SAML2 NameIDPolicy - * - * @return Service-Provider EntityID, but never null - */ - public String getNameIDPolicyFormat(); - - /** - * Define the AuthnContextClassRefernece of this request - * - * Example: - * http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3 - * http://www.stork.gov.eu/1.0/citizenQAALevel/4 - * - * - * @return - */ - public String getAuthnContextClassRef(); - - /** - * Define the AuthnContextComparison model, which should be used - * - * @return - */ - public AuthnContextComparisonTypeEnumeration getAuthnContextComparison(); - - - /** - * Define the credential, which should be used to sign the AuthnRequest - * - * @return - */ - public Credential getAuthnRequestSigningCredential(); - - - /** - * Define the SAML2 EntityDescriptor of the IDP, which should receive the AuthnRequest - * - * @return Credential, but never null. - */ - public EntityDescriptor getIDPEntityDescriptor(); - - /** - * Set the SAML2 NameIDPolicy allow-creation flag - * - * @return EntityDescriptor, but never null. - */ - public boolean getNameIDPolicyAllowCreation(); - - - /** - * Set the requested SubjectNameID - * - * @return SubjectNameID, or null if no SubjectNameID should be used - */ - public String getSubjectNameID(); - - /** - * Define the qualifier of the <code>SubjectNameID</code> - * <br><br> - * Like: 'urn:publicid:gv.at:cdid+BF' - * - * @return qualifier, or null if no qualifier should be set - */ - public String getSubjectNameIDQualifier(); - - /** - * Define the format of the subjectNameID, which is included in authn-request - * - * - * @return nameIDFormat, of SAML2 'transient' if nothing is defined - */ - public String getSubjectNameIDFormat(); - - /** - * Define a SP specific SAML2 requestID - * - * @return requestID, or null if the requestID should be generated automatically - */ - public String getRequestID(); - - /** - * Defines the 'method' attribute in 'SubjectConformation' element - * - * @return method, or null if no method should set - */ - public String getSubjectConformationMethode(); - - /** - * Define the information, which should be added as 'subjectConformationDate' - * in 'SubjectConformation' element - * - * @return subjectConformation information or null if no subjectConformation should be set - */ - public Element getSubjectConformationDate(); - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java deleted file mode 100644 index 3a8404cae..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.config; - -import java.util.List; - -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.Organization; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.xml.security.credential.Credential; - -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; - -/** - * @author tlenz - * - */ -public interface IPVPMetadataBuilderConfiguration { - - - /** - * Defines a unique name for this PVP Service-provider, which is used for logging - * - * @return - */ - public String getSPNameForLogging(); - - /** - * Set metadata valid area - * - * @return valid until in hours [h] - */ - public int getMetadataValidUntil(); - - /** - * Build a SAML2 Entities element as metadata root element - * - * @return true, if the metadata should start with entities element - */ - public boolean buildEntitiesDescriptorAsRootElement(); - - /** - * - * - * @return true, if an IDP SSO-descriptor element should be generated - */ - public boolean buildIDPSSODescriptor(); - - /** - * - * - * @return true, if an SP SSO-descriptor element should be generated - */ - public boolean buildSPSSODescriptor(); - - /** - * Set the PVP entityID for this SAML2 metadata. - * The entityID must be an URL and must be start with the public-URL prefix of the server - * - * @return PVP entityID postfix as String - */ - public String getEntityID(); - - /** - * Set a friendlyName for this PVP entity - * - * @return - */ - public String getEntityFriendlyName(); - - /** - * Set the contact information for this metadata entity - * - * @return - */ - public List<ContactPerson> getContactPersonInformation(); - - /** - * Set organisation information for this metadata entity - * - * @return - */ - public Organization getOrgansiationInformation(); - - - /** - * Set the credential for metadata signing - * - * @return - * @throws CredentialsNotAvailableException - */ - public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException; - - /** - * Set the credential for request/response signing - * IDP metadata: this credential is used for SAML2 response signing - * SP metadata: this credential is used for SAML2 response signing - * - * @return - * @throws CredentialsNotAvailableException - */ - public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException; - - /** - * Set the credential for response encryption - * - * @return - * @throws CredentialsNotAvailableException - */ - public Credential getEncryptionCredentials() throws CredentialsNotAvailableException; - - /** - * Set the IDP Post-Binding URL for WebSSO - * - * @return - */ - public String getIDPWebSSOPostBindingURL(); - - /** - * Set the IDP Redirect-Binding URL for WebSSO - * - * @return - */ - public String getIDPWebSSORedirectBindingURL(); - - /** - * Set the IDP Post-Binding URL for Single LogOut - * - * @return - */ - public String getIDPSLOPostBindingURL(); - - /** - * Set the IDP Redirect-Binding URL for Single LogOut - * - * @return - */ - public String getIDPSLORedirectBindingURL(); - - /** - * Set the SP Post-Binding URL for for the Assertion-Consumer Service - * - * @return - */ - public String getSPAssertionConsumerServicePostBindingURL(); - - /** - * Set the SP Redirect-Binding URL for the Assertion-Consumer Service - * - * @return - */ - public String getSPAssertionConsumerServiceRedirectBindingURL(); - - /** - * Set the SP Post-Binding URL for Single LogOut - * - * @return - */ - public String getSPSLOPostBindingURL(); - - /** - * Set the SP Redirect-Binding URL for Single LogOut - * - * @return - */ - public String getSPSLORedirectBindingURL(); - - /** - * Set the SP SOAP-Binding URL for Single LogOut - * - * @return - */ - public String getSPSLOSOAPBindingURL(); - - - /** - * Set all SAML2 attributes which could be provided by this IDP - * - * @return - */ - public List<Attribute> getIDPPossibleAttributes(); - - /** - * Set all nameID types which could be provided by this IDP - * - * @return a List of SAML2 nameID types - */ - public List<String> getIDPPossibleNameITTypes(); - - /** - * Set all SAML2 attributes which are required by the SP - * - * @return - */ - public List<RequestedAttribute> getSPRequiredAttributes(); - - /** - * Set all nameID types which allowed from the SP - * - * @return a List of SAML2 nameID types - */ - public List<String> getSPAllowedNameITTypes(); - - /** - * Set the 'wantAssertionSigned' attribute in SP metadata - * - * @return - */ - public boolean wantAssertionSigned(); - - /** - * Set the 'wantAuthnRequestSigned' attribute - * - * @return - */ - public boolean wantAuthnRequestSigned(); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultBootstrap.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultBootstrap.java deleted file mode 100644 index b731e2a95..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultBootstrap.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.config; - -import org.opensaml.Configuration; -import org.opensaml.DefaultBootstrap; -import org.opensaml.common.binding.BasicSAMLMessageContext; -import org.opensaml.saml2.binding.encoding.BaseSAML2MessageEncoder; -import org.opensaml.xml.ConfigurationException; - -/** - * @author tlenz - * - */ -public class MOADefaultBootstrap extends DefaultBootstrap { - - public static synchronized void bootstrap() throws ConfigurationException { - - initializeXMLSecurity(); - - initializeXMLTooling(); - - initializeArtifactBuilderFactories(); - - initializeGlobalSecurityConfiguration(); - - initializeParserPool(); - - initializeESAPI(); - - } - - public static void initializeDefaultPVPConfiguration() { - initializeGlobalSecurityConfiguration(); - - } - - /** - * Initializes the default global security configuration. - */ - protected static void initializeGlobalSecurityConfiguration() { - Configuration.setGlobalSecurityConfiguration(MOADefaultSecurityConfigurationBootstrap.buildDefaultConfig()); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultSecurityConfigurationBootstrap.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultSecurityConfigurationBootstrap.java deleted file mode 100644 index f878b95d3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultSecurityConfigurationBootstrap.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.config; - -import org.opensaml.xml.encryption.EncryptionConstants; -import org.opensaml.xml.security.BasicSecurityConfiguration; -import org.opensaml.xml.security.DefaultSecurityConfigurationBootstrap; -import org.opensaml.xml.security.credential.BasicKeyInfoGeneratorFactory; -import org.opensaml.xml.security.keyinfo.KeyInfoGeneratorManager; -import org.opensaml.xml.security.keyinfo.NamedKeyInfoGeneratorManager; -import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; -import org.opensaml.xml.signature.SignatureConstants; - -/** - * @author tlenz - * - */ -public class MOADefaultSecurityConfigurationBootstrap extends - DefaultSecurityConfigurationBootstrap { - - public static BasicSecurityConfiguration buildDefaultConfig() { - BasicSecurityConfiguration config = new BasicSecurityConfiguration(); - - populateSignatureParams(config); - populateEncryptionParams(config); - populateKeyInfoCredentialResolverParams(config); - populateKeyInfoGeneratorManager(config); - populateKeyParams(config); - - return config; - } - - protected static void populateKeyInfoGeneratorManager( - BasicSecurityConfiguration config) { - NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); - config.setKeyInfoGeneratorManager(namedManager); - - namedManager.setUseDefaultManager(true); - KeyInfoGeneratorManager defaultManager = namedManager - .getDefaultManager(); - - BasicKeyInfoGeneratorFactory basicFactory = new BasicKeyInfoGeneratorFactory(); - basicFactory.setEmitPublicKeyValue(true); - - X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); - x509Factory.setEmitEntityCertificate(true); - - defaultManager.registerFactory(basicFactory); - defaultManager.registerFactory(x509Factory); - } - - protected static void populateSignatureParams( - BasicSecurityConfiguration config) { - - //use SHA256 instead of SHA1 - config.registerSignatureAlgorithmURI("RSA", - SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); - - config.registerSignatureAlgorithmURI("DSA", - "http://www.w3.org/2000/09/xmldsig#dsa-sha1"); - - //use SHA256 instead of SHA1 - config.registerSignatureAlgorithmURI("EC", - SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA256); - - //use SHA256 instead of SHA1 - config.registerSignatureAlgorithmURI("AES", - SignatureConstants.ALGO_ID_MAC_HMAC_SHA256); - - - config.registerSignatureAlgorithmURI("DESede", - SignatureConstants.ALGO_ID_MAC_HMAC_SHA256); - - config.setSignatureCanonicalizationAlgorithm("http://www.w3.org/2001/10/xml-exc-c14n#"); - config.setSignatureHMACOutputLength(null); - - //use SHA256 instead of SHA1 - config.setSignatureReferenceDigestMethod(SignatureConstants.ALGO_ID_DIGEST_SHA256); - } - - protected static void populateEncryptionParams( - BasicSecurityConfiguration config) { - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(128), - "http://www.w3.org/2001/04/xmlenc#aes128-cbc"); - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(192), - "http://www.w3.org/2001/04/xmlenc#aes192-cbc"); - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(256), - "http://www.w3.org/2001/04/xmlenc#aes256-cbc"); - - //support GCM mode - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(128), - EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128_GCM); - - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(192), - EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES192_GCM); - - config.registerDataEncryptionAlgorithmURI("AES", Integer.valueOf(256), - EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES256_GCM); - - - config.registerDataEncryptionAlgorithmURI("DESede", - Integer.valueOf(168), - "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"); - config.registerDataEncryptionAlgorithmURI("DESede", - Integer.valueOf(192), - "http://www.w3.org/2001/04/xmlenc#tripledes-cbc"); - - config.registerKeyTransportEncryptionAlgorithmURI("RSA", null, "AES", - "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"); - - config.registerKeyTransportEncryptionAlgorithmURI("RSA", null, - "DESede", "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"); - - config.registerKeyTransportEncryptionAlgorithmURI("AES", - Integer.valueOf(128), null, - "http://www.w3.org/2001/04/xmlenc#kw-aes128"); - config.registerKeyTransportEncryptionAlgorithmURI("AES", - Integer.valueOf(192), null, - "http://www.w3.org/2001/04/xmlenc#kw-aes192"); - config.registerKeyTransportEncryptionAlgorithmURI("AES", - Integer.valueOf(256), null, - "http://www.w3.org/2001/04/xmlenc#kw-aes256"); - config.registerKeyTransportEncryptionAlgorithmURI("DESede", - Integer.valueOf(168), null, - "http://www.w3.org/2001/04/xmlenc#kw-tripledes"); - config.registerKeyTransportEncryptionAlgorithmURI("DESede", - Integer.valueOf(192), null, - "http://www.w3.org/2001/04/xmlenc#kw-tripledes"); - - config.setAutoGeneratedDataEncryptionKeyAlgorithmURI("http://www.w3.org/2001/04/xmlenc#aes128-cbc"); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOAPVPMetadataConfigurationFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOAPVPMetadataConfigurationFactory.java new file mode 100644 index 000000000..54940a9d3 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOAPVPMetadataConfigurationFactory.java @@ -0,0 +1,21 @@ +package at.gv.egovernment.moa.id.protocols.pvp2x.config; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataBuilderConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.api.metadata.IPVPMetadataConfigurationFactory; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; + +@Service("MOAPVPMetadataConfigurationFactory") +public class MOAPVPMetadataConfigurationFactory implements IPVPMetadataConfigurationFactory { + + @Autowired(required=true) PVPConfiguration pvpBasicConfiguration; + + @Override + public IPVPMetadataBuilderConfiguration generateMetadataBuilderConfiguration(String authURL, + AbstractCredentialProvider pvpIDPCredentials) { + return new IDPPVPMetadataConfiguration(authURL, pvpIDPCredentials, pvpBasicConfiguration); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java index 480656e30..5f39af7a4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java @@ -22,9 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.config; -import java.io.IOException; import java.net.URL; -import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -43,28 +41,19 @@ import org.opensaml.saml2.metadata.OrganizationName; import org.opensaml.saml2.metadata.OrganizationURL; import org.opensaml.saml2.metadata.SurName; import org.opensaml.saml2.metadata.TelephoneNumber; +import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egiz.eaaf.modules.pvp2.api.IPVP2BasicConfiguration; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; 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.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; -import iaik.x509.X509Certificate; -public class PVPConfiguration { +@Service("MOAPVP2Configuration") +public class PVPConfiguration implements IPVP2BasicConfiguration { - private static PVPConfiguration instance; - - public static PVPConfiguration getInstance() { - if (instance == null) { - instance = new PVPConfiguration(); - } - return instance; - } - public static final String PVP2_METADATA = "/pvp2/metadata"; public static final String PVP2_IDP_REDIRECT = "/pvp2/redirect"; public static final String PVP2_IDP_POST = "/pvp2/post"; @@ -89,22 +78,7 @@ public class PVPConfiguration { public static final String IDP_CONTACT_PHONE = "phone"; private static String moaIDVersion = null; - - //PVP2 generalpvpconfigdb; - //Properties props; - //String rootDir = null; - - private PVPConfiguration() { -// try { -// //generalpvpconfigdb = AuthConfigurationProvider.getInstance().getGeneralPVP2DBConfig(); -// //props = AuthConfigurationProviderFactory.getInstance().getGeneralPVP2ProperiesConfig(); -// //rootDir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); -// -// } catch (ConfigurationException e) { -// e.printStackTrace(); -// } - } - + public List<String> getIDPPublicPath() throws ConfigurationException { List<String> publicPath = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); List<String> returnvalue = new ArrayList<String>(); @@ -138,15 +112,17 @@ public class PVPConfiguration { public String getIDPSSOSOAPService(String publicURLPrefix) throws ConfigurationException { return publicURLPrefix + PVP2_IDP_SOAP; } - - public String getIDPAttributeQueryService(String publicURLPrefix) throws ConfigurationException { - return publicURLPrefix + PVP2_IDP_ATTRIBUTEQUERY; - } public String getIDPSSOMetadataService(String publicURLPrefix) throws ConfigurationException { return publicURLPrefix + PVP2_METADATA; } + @Override + public String getIDPEntityId(String authURL) throws ConfigurationException { + return getIDPSSOMetadataService(authURL); + + } + public String getIDPIssuerName() throws ConfigurationException { if (moaIDVersion == null) { @@ -156,42 +132,6 @@ public class PVPConfiguration { return AuthConfigurationProviderFactory.getInstance().getConfigurationWithKey( MOAIDConfigurationConstants.GENERAL_PROTOCOLS_PVP2X_METADATA_SERVICENAMME) + moaIDVersion; } - - public iaik.x509.X509Certificate getTrustEntityCertificate(String entityID) { - - try { - Logger.trace("Load metadata signing certificate for online application " + entityID); - IOAAuthParameters oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(entityID); - if (oaParam == null) { - Logger.info("Online Application with ID " + entityID + " not found!"); - return null; - } - - String pvp2MetadataCertificateString = - oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); - if (MiscUtil.isEmpty(pvp2MetadataCertificateString)) { - Logger.info("Online Application with ID " + entityID + " include not PVP2X metadata signing certificate!"); - return null; - - } - - X509Certificate cert = new X509Certificate(Base64Utils.decode(pvp2MetadataCertificateString, false)); - Logger.debug("Metadata signing certificate is loaded for ("+entityID+") is loaded."); - return cert; - - } catch (CertificateException e) { - Logger.warn("Metadata signer certificate is not parsed.", e); - return null; - - } catch (ConfigurationException e) { - Logger.error("Configuration is not accessable.", e); - return null; - - } catch (IOException e) { - Logger.warn("Metadata signer certificate is not decodeable.", e); - return null; - } - } public List<ContactPerson> getIDPContacts() throws ConfigurationException { List<ContactPerson> list = new ArrayList<ContactPerson>(); @@ -354,4 +294,5 @@ public class PVPConfiguration { } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AssertionAttributeExtractorExeption.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AssertionAttributeExtractorExeption.java deleted file mode 100644 index 69ca4e8f5..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AssertionAttributeExtractorExeption.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -/** - * @author tlenz - * - */ -public class AssertionAttributeExtractorExeption extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = -6459000942830951492L; - - public AssertionAttributeExtractorExeption(String attributeName) { - super("Parse PVP2.1 assertion FAILED: Attribute " + attributeName - + " can not extract.", null); - } - - public AssertionAttributeExtractorExeption(String messageId, - Object[] parameters) { - super(messageId, parameters); - } - - public AssertionAttributeExtractorExeption() { - super("Parse PVP2.1 assertion FAILED. Interfederation not possible", null); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AssertionValidationExeption.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AssertionValidationExeption.java deleted file mode 100644 index 1e029f567..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AssertionValidationExeption.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; - -/** - * @author tlenz - * - */ -public class AssertionValidationExeption extends PVP2Exception { - - private static final long serialVersionUID = -3987805399122286259L; - - public AssertionValidationExeption(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - /** - * @param string - * @param object - * @param e - */ - public AssertionValidationExeption(String string, Object[] parameters, - Throwable e) { - super(string, parameters, e); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AttributQueryException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AttributQueryException.java deleted file mode 100644 index 9008a7183..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AttributQueryException.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -/** - * @author tlenz - * - */ -public class AttributQueryException extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = -4302422507173728748L; - - public AttributQueryException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - public AttributQueryException(String messageId, Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestBuildException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestBuildException.java deleted file mode 100644 index eebaf6c9e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestBuildException.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -/** - * @author tlenz - * - */ -public class AuthnRequestBuildException extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = -1375451065455859354L; - - /** - * @param messageId - * @param parameters - */ - public AuthnRequestBuildException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - public AuthnRequestBuildException(String messageId, Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestValidatorException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestValidatorException.java deleted file mode 100644 index f65c4d265..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestValidatorException.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import at.gv.egovernment.moa.id.commons.api.IRequest; - -/** - * @author tlenz - * - */ -public class AuthnRequestValidatorException extends PVP2Exception { - - private IRequest errorRequest = null; - - /** - * - */ - private static final long serialVersionUID = 4939651000658508576L; - - /** - * @param messageId - * @param parameters - */ - public AuthnRequestValidatorException(String messageId, Object[] parameters) { - super(messageId, parameters); - - } - - public AuthnRequestValidatorException(String messageId, Object[] parameters, IRequest errorRequest) { - super(messageId, parameters); - this.errorRequest = errorRequest; - - } - - /** - * @return the errorRequest - */ - public IRequest getErrorRequest() { - return errorRequest; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnResponseValidationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnResponseValidationException.java deleted file mode 100644 index 957f9af1d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnResponseValidationException.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -/** - * @author tlenz - * - */ -public class AuthnResponseValidationException extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = 8023812861029406575L; - - /** - * @param messageId - * @param parameters - */ - public AuthnResponseValidationException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - public AuthnResponseValidationException(String messageId, Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/BindingNotSupportedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/BindingNotSupportedException.java deleted file mode 100644 index 9f4c7fed3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/BindingNotSupportedException.java +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class BindingNotSupportedException extends PVP2Exception { - - public BindingNotSupportedException(String binding) { - super("pvp2.11", new Object[] {binding}); - this.statusCodeValue = StatusCode.UNSUPPORTED_BINDING_URI; - } - - /** - * - */ - private static final long serialVersionUID = -7227603941387879360L; - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionConsumerServiceException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionConsumerServiceException.java deleted file mode 100644 index 392569366..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionConsumerServiceException.java +++ /dev/null @@ -1,48 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class InvalidAssertionConsumerServiceException extends PVP2Exception { - - public InvalidAssertionConsumerServiceException(int idx) { - super("pvp2.00", new Object[]{idx}); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - /** - * - */ - public InvalidAssertionConsumerServiceException(String wrongURL) { - super("pvp2.23", new Object[]{wrongURL}); - this.statusCodeValue = StatusCode.REQUESTER_URI; - - } - - /** - * - */ - private static final long serialVersionUID = 7861790149343943091L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionEncryptionException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionEncryptionException.java deleted file mode 100644 index b49070bd6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidAssertionEncryptionException.java +++ /dev/null @@ -1,36 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class InvalidAssertionEncryptionException extends PVP2Exception { - - private static final long serialVersionUID = 6513388841485355549L; - - public InvalidAssertionEncryptionException() { - super("pvp2.16", new Object[]{}); - this.statusCodeValue = StatusCode.RESPONDER_URI; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidDateFormatException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidDateFormatException.java deleted file mode 100644 index 252539bf5..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/InvalidDateFormatException.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class InvalidDateFormatException extends PVP2Exception { - - public InvalidDateFormatException() { - super("pvp2.02", null); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - /** - * - */ - private static final long serialVersionUID = -6867976890237846085L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/MandateAttributesNotHandleAbleException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/MandateAttributesNotHandleAbleException.java index 15a0ccf72..0e48dfbd6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/MandateAttributesNotHandleAbleException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/MandateAttributesNotHandleAbleException.java @@ -24,6 +24,8 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; import org.opensaml.saml2.core.StatusCode; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; + public class MandateAttributesNotHandleAbleException extends PVP2Exception { public MandateAttributesNotHandleAbleException() { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NOSLOServiceDescriptorException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NOSLOServiceDescriptorException.java index 204e1c2a5..94e1874a5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NOSLOServiceDescriptorException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NOSLOServiceDescriptorException.java @@ -22,6 +22,8 @@ */ package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; + /** * @author tlenz * diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NameIDFormatNotSupportedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NameIDFormatNotSupportedException.java deleted file mode 100644 index 87e443930..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NameIDFormatNotSupportedException.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class NameIDFormatNotSupportedException extends AuthnRequestValidatorException { - - public NameIDFormatNotSupportedException(String nameIDFormat) { - super("pvp2.12", new Object[] {nameIDFormat}); - statusCodeValue = StatusCode.INVALID_NAMEID_POLICY_URI; - - } - - /** - * - */ - private static final long serialVersionUID = -2270762519437873336L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoCredentialsException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoCredentialsException.java index 333ef9765..58c2a032d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoCredentialsException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoCredentialsException.java @@ -24,6 +24,8 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; import org.opensaml.saml2.core.StatusCode; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; + public class NoCredentialsException extends PVP2Exception { public static final String MOA_IDP_TARGET = "MOA-ID"; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMandateDataAvailableException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMandateDataAvailableException.java index ce80ac5cb..821813b69 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMandateDataAvailableException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMandateDataAvailableException.java @@ -22,6 +22,8 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2Exception; + public class NoMandateDataAvailableException extends PVP2Exception { public NoMandateDataAvailableException() { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMetadataInformationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMetadataInformationException.java deleted file mode 100644 index 50a1af6ad..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NoMetadataInformationException.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class NoMetadataInformationException extends PVP2Exception { - - public NoMetadataInformationException() { - super("pvp2.15", null); - this.statusCodeValue = StatusCode.UNKNOWN_PRINCIPAL_URI; - } - - /** - * - */ - private static final long serialVersionUID = -4608068445208032193L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/PVP2Exception.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/PVP2Exception.java deleted file mode 100644 index 00fb97151..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/PVP2Exception.java +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; - -public abstract class PVP2Exception extends MOAIDException { - - protected String statusCodeValue = StatusCode.RESPONDER_URI; - protected String statusMessageValue = null; - - public PVP2Exception(String messageId, Object[] parameters, - Throwable wrapped) { - super(messageId, parameters, wrapped); - this.statusMessageValue = this.getMessage(); - } - - public PVP2Exception(String messageId, Object[] parameters) { - super(messageId, parameters); - this.statusMessageValue = this.getMessage(); - } - - - public String getStatusCodeValue() { - return (this.statusCodeValue); - } - - public String getStatusMessageValue() { - return (this.statusMessageValue); - } - - /** - * - */ - private static final long serialVersionUID = 7669537952484421069L; - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/QAANotAllowedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/QAANotAllowedException.java deleted file mode 100644 index 63f42cbe5..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/QAANotAllowedException.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - - -public class QAANotAllowedException extends PVP2Exception { - - public QAANotAllowedException(String qaa_auth, String qaa_request) { - super("pvp2.17", new Object[] {qaa_auth, qaa_request}); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - /** - * - */ - private static final long serialVersionUID = -3964192953884089323L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/QAANotSupportedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/QAANotSupportedException.java deleted file mode 100644 index fdf1063c0..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/QAANotSupportedException.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - - -public class QAANotSupportedException extends PVP2Exception { - - public QAANotSupportedException(String qaa) { - super("pvp2.05", new Object[] {qaa}); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - /** - * - */ - private static final long serialVersionUID = -3964192953884089323L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/RequestDeniedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/RequestDeniedException.java deleted file mode 100644 index 8f12f3cce..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/RequestDeniedException.java +++ /dev/null @@ -1,39 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class RequestDeniedException extends PVP2Exception { - - public RequestDeniedException() { - super("pvp2.14", null); - this.statusCodeValue = StatusCode.REQUEST_DENIED_URI; - } - - /** - * - */ - private static final long serialVersionUID = 4415896615794730553L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/ResponderErrorException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/ResponderErrorException.java deleted file mode 100644 index fe921f8b5..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/ResponderErrorException.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class ResponderErrorException extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = -425416760138285446L; - - public ResponderErrorException(String messageId, Object[] parameters, - Throwable wrapped) { - super(messageId, parameters, wrapped); - this.statusCodeValue = StatusCode.RESPONDER_URI; - } - - public ResponderErrorException(String messageId, Object[] parameters) { - super(messageId, parameters); - this.statusCodeValue = StatusCode.RESPONDER_URI; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSignedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSignedException.java deleted file mode 100644 index 65def4602..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSignedException.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class SAMLRequestNotSignedException extends PVP2Exception { - - public SAMLRequestNotSignedException() { - super("pvp2.07", null); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - public SAMLRequestNotSignedException(Throwable e) { - super("pvp2.07", null, e); - this.statusCodeValue = StatusCode.REQUESTER_URI; - } - - /** - * - */ - private static final long serialVersionUID = 1L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSupported.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSupported.java deleted file mode 100644 index 8a386c951..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SAMLRequestNotSupported.java +++ /dev/null @@ -1,40 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - - -public class SAMLRequestNotSupported extends PVP2Exception { - - public SAMLRequestNotSupported() { - super("pvp2.09", null); - this.statusCodeValue = StatusCode.REQUEST_UNSUPPORTED_URI; - } - - /** - * - */ - private static final long serialVersionUID = 1244883178458802767L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SLOException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SLOException.java deleted file mode 100644 index 9f1b6168e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SLOException.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -/** - * @author tlenz - * - */ -public class SLOException extends PVP2Exception { - private static final long serialVersionUID = -5284624715788385022L; - - /** - * @param messageId - * @param parameters - */ - public SLOException(String messageId, Object[] parameters) { - super(messageId, parameters); - // TODO Auto-generated constructor stub - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SchemaValidationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SchemaValidationException.java deleted file mode 100644 index fc4ed1f28..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/SchemaValidationException.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -/** - * @author tlenz - * - */ -public class SchemaValidationException extends PVP2Exception { - - /** - * - */ - private static final long serialVersionUID = 1L; - - /** - * @param messageId - * @param parameters - */ - public SchemaValidationException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - /** - * @param messageId - * @param parameters - */ - public SchemaValidationException(String messageId, Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/UnprovideableAttributeException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/UnprovideableAttributeException.java deleted file mode 100644 index a8bfe1070..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/UnprovideableAttributeException.java +++ /dev/null @@ -1,37 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; - -import org.opensaml.saml2.core.StatusCode; - -public class UnprovideableAttributeException extends PVP2Exception { - /** - * - */ - private static final long serialVersionUID = 3972197758163647157L; - - public UnprovideableAttributeException(String attributeName) { - super("pvp2.10", new Object[] {attributeName}); - this.statusCodeValue = StatusCode.UNKNOWN_ATTR_PROFILE_URI; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SchemaValidationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SchemaValidationException.java deleted file mode 100644 index 8da5edeed..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SchemaValidationException.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter; - -import org.opensaml.saml2.metadata.provider.FilterException; - -/** - * @author tlenz - * - */ -public class SchemaValidationException extends FilterException { - - /** - * @param string - */ - public SchemaValidationException(String string) { - super(string); - - } - - private static final long serialVersionUID = 1L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SignatureValidationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SignatureValidationException.java deleted file mode 100644 index 86a6a777b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/filter/SignatureValidationException.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter; - -import org.opensaml.saml2.metadata.provider.FilterException; - -/** - * @author tlenz - * - */ -public class SignatureValidationException extends FilterException { - - /** - * @param string - */ - public SignatureValidationException(String string) { - super(string); - - } - - /** - * @param e - */ - public SignatureValidationException(Exception e) { - super(e); - } - - /** - * @param string - * @param object - */ - public SignatureValidationException(String string, Exception e) { - super(string, e); - } - - private static final long serialVersionUID = 1L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/loginFormFull.html b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/loginFormFull.html deleted file mode 100644 index 5ae76ed96..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/loginFormFull.html +++ /dev/null @@ -1,851 +0,0 @@ -<!DOCTYPE html> -<html> -<head> -<meta content="text/html; charset=utf-8" http-equiv="Content-Type"> - -<!-- MOA-ID 2.x BKUSelection Layout CSS --> -<style type="text/css"> -@media screen and (min-width: 650px) { - body { - margin: 0; - padding: 0; - color: #000; - background-color: #fff; - text-align: center; - background-color: #6B7B8B; - } - #localBKU p { - font-size: 0.7em; - } - #localBKU input { - font-size: 0.7em; - /*border-radius: 5px;*/ - } - #bkuselectionarea input[type=button] { - font-size: 0.85em; - /*border-radius: 7px;*/ - margin-bottom: 25px; - min-width: 80px; - } - #mandateLogin { - font-size: 0.85em; - } - #bku_header h2 { - font-size: 0.8em; - } - #page { - display: block; - border: 2px solid rgb(0, 0, 0); - width: 650px; - height: 440px; - margin: 0 auto; - margin-top: 5%; - position: relative; - border-radius: 25px; - background: rgb(255, 255, 255); - } - #page1 { - text-align: center; - } - #main { - /* clear:both; */ - position: relative; - margin: 0 auto; - width: 250px; - text-align: center; - } - .OA_header { - /* background-color: white;*/ - font-size: 20pt; - margin-bottom: 25px; - margin-top: 25px; - } - #leftcontent { - /*float:left; */ - width: 250px; - margin-bottom: 25px; - text-align: left; - border: 1px solid rgb(0, 0, 0); - } - #selectArea { - font-size: 15px; - padding-bottom: 65px; - } - #leftcontent { - width: 300px; - margin-top: 30px; - } - #bku_header { - height: 5%; - padding-bottom: 3px; - padding-top: 3px; - } - #bkulogin { - overflow: hidden; - min-width: 190px; - min-height: 180px; - /*height: 260px;*/ - } - h2#tabheader { - font-size: 1.1em; - padding-left: 2%; - padding-right: 2%; - position: relative; - } - .setAssertionButton_full { - background: #efefef; - cursor: pointer; - margin-top: 15px; - width: 100px; - height: 30px - } - #leftbutton { - width: 30%; - float: left; - margin-left: 40px; - } - #rightbutton { - width: 30%; - float: right; - margin-right: 45px; - text-align: right; - } - button { - height: 25px; - width: 75px; - margin-bottom: 10px; - } - #validation { - position: absolute; - bottom: 0px; - margin-left: 270px; - padding-bottom: 10px; - } -} - -@media screen and (max-width: 205px) { - #localBKU p { - font-size: 0.6em; - } - #localBKU input { - font-size: 0.6em; - min-width: 60px; - /* max-width: 65px; */ - min-height: 1.0em; - /* border-radius: 5px; */ - } - #bkuselectionarea input[type=button] { - font-size: 0.7em; - min-width: 55px; - /*min-height: 1.1em; - border-radius: 5px;*/ - margin-bottom: 2% - } - #mandateLogin { - font-size: 0.65em; - } - #bku_header h2 { - font-size: 0.8em; - margin-top: -0.4em; - padding-top: 0.4em; - } - #bkulogin { - min-height: 150px; - } -} - -@media screen and (max-width: 249px) and (min-width: 206px) { - #localBKU p { - font-size: 0.7em; - } - #localBKU input { - font-size: 0.7em; - min-width: 70px; - /* max-width: 75px; */ - min-height: 0.95em; - /* border-radius: 6px; */ - } - #bkuselectionarea input[type=button] { - font-size: 0.75em; - min-width: 60px; - /* min-height: 0.95em; - border-radius: 6px; */ - margin-bottom: 5% - } - #mandateLogin { - font-size: 0.75em; - } - #bku_header h2 { - font-size: 0.9em; - margin-top: -0.45em; - padding-top: 0.45em; - } - #bkulogin { - min-height: 180px; - } -} - -@media screen and (max-width: 299px) and (min-width: 250px) { - #localBKU p { - font-size: 0.9em; - } - #localBKU input { - font-size: 0.8em; - min-width: 70px; - /* max-width: 75px; */ - /* border-radius: 6px; */ - } - #bkuselectionarea input[type=button] { - font-size: 0.85em; - /* min-height: 1.05em; - border-radius: 7px; */ - margin-bottom: 10%; - } - #mandateLogin { - font-size: 1em; - } - #bku_header h2 { - font-size: 1.0em; - margin-top: -0.50em; - padding-top: 0.50em; - } -} - -@media screen and (max-width: 399px) and (min-width: 300px) { - #localBKU p { - font-size: 0.9em; - } - #localBKU input { - font-size: 0.8em; - min-width: 70px; - /* max-width: 75px; */ - /* border-radius: 6px; */ - } - #bkuselectionarea input[type=button] { - font-size: 0.9em; - /* min-height: 1.2em; - border-radius: 8px; */ - margin-bottom: 10%; - max-width: 80px; - } - #mandateLogin { - font-size: 1em; - } - #bku_header h2 { - font-size: 1.1em; - margin-top: -0.55em; - padding-top: 0.55em; - } -} - -@media screen and (max-width: 649px) and (min-width: 400px) { - #localBKU p { - font-size: 0.9em; - } - #localBKU input { - font-size: 0.8em; - min-width: 70px; - /* max-width: 80px; */ - /* border-radius: 6px; */ - } - #bkuselectionarea input[type=button] { - font-size: 1.0em; - /* min-height: 1.3em; - border-radius: 10px; */ - margin-bottom: 10%; - max-width: 85px; - } - #mandateLogin { - font-size: 1.2em; - } - #bku_header h2 { - font-size: 1.3em; - margin-top: -0.65em; - padding-top: 0.65em; - } -} - -@media screen and (max-width: 649px) { - body { - margin: 0; - padding: 0; - color: #000; - text-align: center; - font-size: 100%; - background-color: #MAIN_BACKGOUNDCOLOR#; - } - #page { - visibility: hidden; - margin-top: 0%; - } - #page1 { - visibility: hidden; - } - #main { - visibility: hidden; - } - #validation { - visibility: hidden; - display: none; - } - .OA_header { - margin-bottom: 0px; - margin-top: 0px; - font-size: 0pt; - visibility: hidden; - } - #leftcontent { - visibility: visible; - margin-bottom: 0px; - text-align: left; - border: none; - vertical-align: middle; - min-height: 173px; - min-width: 204px; - } - #bku_header { - height: 10%; - min-height: 1.2em; - margin-top: 1%; - } - h2#tabheader { - padding-left: 2%; - padding-right: 2%; - position: relative; - top: 50%; - } - #bkulogin { - min-width: 190px; - min-height: 155px; - } - .setAssertionButton_full { - background: #efefef; - cursor: pointer; - margin-top: 15px; - width: 70px; - height: 25px; - } - input[type=button] { - /* height: 11%; */ - width: 70%; - } -} - - - @media screen and (max-width: 649px) { - - body { - margin:0; - padding:0; - color : #000; - text-align: center; - font-size: 100%; - background-color: #MAIN_BACKGOUNDCOLOR#; - } - - #page { - visibility: hidden; - margin-top: 0%; - } - - #page1 { - visibility: hidden; - } - - #main { - visibility: hidden; - } - - #validation { - visibility: hidden; - display: none; - } - - .OA_header { - margin-bottom: 0px; - margin-top: 0px; - font-size: 0pt; - visibility: hidden; - } - - #leftcontent { - visibility: visible; - margin-bottom: 0px; - text-align: left; - border:none; - vertical-align: middle; - min-height: 173px; - min-width: 204px; - - } - - #bku_header { - height: 10%; - min-height: 1.2em; - margin-top: 1%; - } - - h2#tabheader{ - padding-left: 2%; - padding-right: 2%; - position: relative; - top: 50%; - } - - #bkulogin { - min-width: 190px; - min-height: 155px; - } - - .setAssertionButton_full { - background: #efefef; - cursor: pointer; - margin-top: 15px; - width: 70px; - height: 25px; - } - - input[type=button] { -/* height: 11%; */ - width: 70%; - } - } - - * { - margin: 0; - padding: 0; - font-family: #FONTTYPE#; - } - - #selectArea { - padding-top: 10px; - padding-bottom: 55px; - padding-left: 10px; - } - - .setAssertionButton { - background: #efefef; - cursor: pointer; - margin-top: 15px; - width: 70px; - height: 25px; - } - - #leftbutton { - width: 35%; - float:left; - margin-left: 15px; - } - - #rightbutton { - width: 35%; - float:right; - margin-right: 25px; - text-align: right; - } - - #mandateLogin { - padding-bottom: 4%; - padding-top: 4%; - height: 10%; - position: relative; - text-align: center; - } - - .verticalcenter { - vertical-align: middle; - } - - #mandateLogin div { - clear: both; - margin-top: -1%; - position: relative; - top: 50%; - } - - #bkuselectionarea { - position: relative; - display: block; - } - - #localBKU { - padding-left: 5%; - padding-right: 2%; - padding-bottom: 4%; - padding-top: 4%; - position: relative; - clear: both; - } - - #bkukarte { - float:left; - text-align:center; - width:40%; - min-height: 70px; - padding-left: 5%; - padding-top: 2%; - } - - #bkuhandy { - float:right; - text-align:center; - width:40%; - min-height: 90px; - padding-right: 5%; - padding-top: 2%; - } - - .bkuimage { - width: 90%; - height: auto; - } - - #mandate{ - text-align:center; - padding : 5px 5px 5px 5px; - } - -/* input[type=button], .sendButton { - background: #BUTTON_BACKGROUNDCOLOR#; - color: #BUTTON_COLOR#; -/* border:1px solid #000; */ -/* cursor: pointer; -/* box-shadow: 3px 3px 3px #222222; */ -/* } - -/* button:hover, button:focus, button:active, - .sendButton:hover , .sendButton:focus, .sendButton:active, - #mandateCheckBox:hover, #mandateCheckBox:focus, #mandateCheckBox:active { - background: #BUTTON_BACKGROUNDCOLOR_FOCUS#; - color: #BUTTON_COLOR#; -/* border:1px solid #000; */ -/* cursor: pointer; -/* box-shadow: -1px -1px 3px #222222; */ -/* } - -*/ -input { - /*border:1px solid #000;*/ - cursor: pointer; -} - -#localBKU input { - /* color: #BUTTON_COLOR#; */ - border: 0px; - display: inline-block; -} - -#localBKU input:hover,#localBKU input:focus,#localBKU input:active { - text-decoration: underline; -} - -#installJava,#BrowserNOK { - clear: both; - font-size: 0.8em; - padding: 4px; -} - -.selectText { - -} - -.selectTextHeader { - -} - -.sendButton { - width: 30%; - margin-bottom: 1%; -} - -#leftcontent a { - text-decoration: none; - color: #000; - /* display:block;*/ - padding: 4px; -} - -#leftcontent a:hover,#leftcontent a:focus,#leftcontent a:active { - text-decoration: underline; - color: #000; -} - -.infobutton { - background-color: #005a00; - color: white; - font-family: serif; - text-decoration: none; - padding-top: 2px; - padding-right: 4px; - padding-bottom: 2px; - padding-left: 4px; - font-weight: bold; -} - -.hell { - background-color: #MAIN_BACKGOUNDCOLOR#; - color: #MAIN_COLOR#; -} - -.dunkel { - background-color: #HEADER_BACKGROUNDCOLOR#; - color: #HEADER_COLOR#; -} - -.main_header { - color: black; - font-size: 32pt; - position: absolute; - right: 10%; - top: 40px; -} -</style> -<!-- MOA-ID 2.x BKUSelection JavaScript fucnctions--> -<script type="text/javascript"> - function isIE() { - return (/MSIE (\d+\.\d+);/.test(navigator.userAgent)); - } - function isFullscreen() { - try { - return ((top.innerWidth == screen.width) && (top.innerHeight == screen.height)); - } catch (e) { - return false; - } - } - function isActivexEnabled() { - var supported = null; - try { - supported = !!new ActiveXObject("htmlfile"); - } catch (e) { - supported = false; - } - return supported; - } - function isMetro() { - if (!isIE()) - return false; - return !isActivexEnabled() && isFullscreen(); - } - window.onload=function() { - document.getElementById("localBKU").style.display="block"; - return; - } - function bkuOnlineClicked() { - if (isMetro()) - document.getElementById("metroDetected").style.display="block"; - document.getElementById("localBKU").style.display="block"; -/* if (checkMandateSSO()) - return; */ - - setMandateSelection(); -/* setSSOSelection(); */ - - var iFrameURL = "#AUTH_URL#" + "?"; - iFrameURL += "bkuURI=" + "#ONLINE#"; - iFrameURL += "&useMandate=" + document.getElementById("useMandate").value; -/* iFrameURL += "&SSO=" + document.getElementById("useSSO").value; */ - iFrameURL += "&MODUL=" + "#MODUL#"; - iFrameURL += "&ACTION=" + "#ACTION#"; - iFrameURL += "&MOASessionID=" + "#SESSIONID#"; - generateIFrame(iFrameURL); - } - function bkuHandyClicked() { - document.getElementById("localBKU").style.display="none"; -/* if (checkMandateSSO()) - return; */ - - setMandateSelection(); -/* setSSOSelection(); */ - - var iFrameURL = "#AUTH_URL#" + "?"; - iFrameURL += "bkuURI=" + "#HANDY#"; - iFrameURL += "&useMandate=" + document.getElementById("useMandate").value; -/* iFrameURL += "&SSO=" + document.getElementById("useSSO").value; */ - iFrameURL += "&MODUL=" + "#MODUL#"; - iFrameURL += "&ACTION=" + "#ACTION#"; - iFrameURL += "&MOASessionID=" + "#SESSIONID#"; - generateIFrame(iFrameURL); - } - function storkClicked() { - document.getElementById("localBKU").style.display="none"; -/* if (checkMandateSSO()) - return; */ - - setMandateSelection(); -/* setSSOSelection(); */ - - var ccc = "AT"; - var countrySelection = document.getElementById("cccSelection"); - if (countrySelection != null) { - ccc = document.getElementById("cccSelection").value; - } - var iFrameURL = "#AUTH_URL#" + "?"; - iFrameURL += "bkuURI=" + "#ONLINE#"; - iFrameURL += "&useMandate=" + document.getElementById("useMandate").value; - iFrameURL += "&CCC=" + ccc; -/* iFrameURL += "&SSO=" + document.getElementById("useSSO").value; */ - iFrameURL += "&MODUL=" + "#MODUL#"; - iFrameURL += "&ACTION=" + "#ACTION#"; - iFrameURL += "&MOASessionID=" + "#SESSIONID#"; - generateIFrame(iFrameURL); - } - function generateIFrame(iFrameURL) { - var el = document.getElementById("bkulogin"); - var width = el.clientWidth; - var heigth = el.clientHeight - 20; - var parent = el.parentNode; - - iFrameURL += "&heigth=" + heigth; - iFrameURL += "&width=" + width; - - var iframe = document.createElement("iframe"); - iframe.setAttribute("src", iFrameURL); - iframe.setAttribute("width", el.clientWidth - 1); - iframe.setAttribute("height", el.clientHeight - 1); - iframe.setAttribute("frameborder", "0"); - iframe.setAttribute("scrolling", "no"); - iframe.setAttribute("title", "Login"); - parent.replaceChild(iframe, el); - } - function setMandateSelection() { - document.getElementById("moaidform").action = "#AUTH_URL#"; - document.getElementById("useMandate").value = "false"; - var checkbox = document.getElementById("mandateCheckBox"); - if (checkbox != null) { - if (document.getElementById("mandateCheckBox").checked) { - document.getElementById("useMandate").value = "true"; - } - } - } - function onChangeChecks() { - if (top.innerWidth < 650) { - document.getElementById("moaidform").setAttribute("target","_parent"); - } else { - document.getElementById("moaidform").removeAttribute("target"); - } - - } -/* function setSSOSelection() { - document.getElementById("useSSO").value = "false"; - var checkbox = document.getElementById("SSOCheckBox"); - if (checkbox != null) { - if (document.getElementById("SSOCheckBox").checked) { - document.getElementById("useSSO").value = "true"; - } - } - } */ - -/* function checkMandateSSO() { - var sso = document.getElementById("SSOCheckBox"); - var mandate = document.getElementById("mandateCheckBox"); - - - if (sso.checked && mandate.checked) { - alert("Anmeldung in Vertretung in kombination mit Single Sign-On wird aktuell noch nicht unterstützt!") - mandate.checked = false; - sso.checked = false; - return true; - } else { - return false; - } - } */ - </script> -<title>Anmeldung mittels Bürgerkarte oder Handy-Signatur</title> -</head> -<body onload="onChangeChecks();" onresize="onChangeChecks();"> - <div id="page"> - <div id="page1" class="case selected-case" role="main"> - <h2 class="OA_header" role="heading">Anmeldung an: #OAName#</h2> - <div id="main"> - <div id="leftcontent" class="hell" role="application"> - <div id="bku_header" class="dunkel"> - <h2 id="tabheader" class="dunkel" role="heading">#HEADER_TEXT#</h2> - </div> - <div id="bkulogin" class="hell" role="form"> - <div id="mandateLogin" style=""> - <div> - <input tabindex="1" type="checkbox" name="Mandate" - id="mandateCheckBox" class="verticalcenter" role="checkbox" - onClick='document.getElementById("mandateCheckBox").setAttribute("aria-checked", document.getElementById("mandateCheckBox").checked);'#MANDATECHECKED#> - <label for="mandateCheckBox" class="verticalcenter">in - Vertretung anmelden</label> - <!--a href="info_mandates.html" - target="_blank" - class="infobutton verticalcenter" - tabindex="5">i</a--> - </div> - </div> - <div id="bkuselectionarea"> - <div id="bkukarte"> - <img class="bkuimage" src="#CONTEXTPATH#/img/online-bku.png" - alt="OnlineBKU" /> <input name="bkuButtonOnline" type="button" - onClick="bkuOnlineClicked();" tabindex="2" role="button" - value="Karte" /> - </div> - <div id="bkuhandy"> - <img class="bkuimage" src="#CONTEXTPATH#/img/mobile-bku.png" - alt="HandyBKU" /> <input name="bkuButtonHandy" type="button" - onClick="bkuHandyClicked();" tabindex="3" role="button" - value="HANDY" /> - </div> - </div> - <div id="localBKU"> - <form method="get" id="moaidform" action="#AUTH_URL#" - class="verticalcenter" target="_parent"> - <input type="hidden" name="bkuURI" value="#LOCAL#"> <input - type="hidden" name="useMandate" id="useMandate"> <input - type="hidden" name="SSO" id="useSSO"> <input - type="hidden" name="CCC" id="ccc"> <input type="hidden" - name="MODUL" value="#MODUL#"> <input type="hidden" - name="ACTION" value="#ACTION#"> <input type="hidden" - name="MOASessionID" value="#SESSIONID#"> <input - type="submit" value=">lokale Bürgerkartenumgebung" tabindex="4" - role="button" class="hell"> - <!--p> - <small>Alternativ können Sie eine lokal installierte BKU verwenden.</small> - </p--> - </form> - </div> - <div id="stork" align="center" style="#STORKVISIBLE#"> - <h2 id="tabheader" class="dunkel">Home Country Selection</h2> - <p> - <select name="cccSelection" id="cccSelection" size="1" style="width: 120px; margin-right: 5px;" > - <option value="BE">België/Belgique</option> - <option value="EE">Eesti</option> - <option value="ES">España</option> - <option value="IS">Ísland</option> - <option value="IT">Italia</option> - <option value="LI">Liechtenstein</option> - <option value="LT">Lithuania</option> - <option value="PT">Portugal</option> - <option value="SI">Slovenija</option> - <option value="FI">Suomi</option> - <option value="SE">Sverige</option> - </select> - <button name="bkuButton" type="button" onClick="storkClicked();">Proceed</button> - <a href="info_stork.html" target="_blank" class="infobutton" style="color:#FFF">i</a> - </p> - </div> - - <div id="metroDetected" style="display: none"> - <p>Anscheinend verwenden Sie Internet Explorer im - Metro-Modus. Wählen Sie bitte "Auf dem Desktop anzeigen" aus den - Optionen um die Karten-Anmeldung starten zu können.</p> - </div> - </div> - </div> - </div> - </div> - <div id="validation"> - <a href="http://validator.w3.org/check?uri="> <img - style="border: 0; width: 88px; height: 31px" - src="#CONTEXTPATH#/img/valid-html5-blue.png" alt="HTML5 ist valide!" /> - </a> <a href="http://jigsaw.w3.org/css-validator/"> <img - style="border: 0; width: 88px; height: 31px" - src="https://jigsaw.w3.org/css-validator/images/vcss-blue" - alt="CSS ist valide!" /> - </a> - </div> - </div> -</body> -</html>
\ No newline at end of file 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 deleted file mode 100644 index 8c8345bbf..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/InboundMessage.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.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.logging.Logger; - -/** - * @author tlenz - * - */ -public class InboundMessage implements InboundMessageInterface, Serializable{ - - private static final long serialVersionUID = 2395131650841669663L; - - private Element samlMessage = null; - private boolean verified = false; - private String entityID = null; - private String relayState = null; - - - public EntityDescriptor getEntityMetadata(MetadataProvider metadataProvider) throws NoMetadataInformationException { - try { - 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); - throw new NoMetadataInformationException(); - } - } - - /** - * @param entitiyID the entitiyID to set - */ - public void setEntityID(String entitiyID) { - this.entityID = entitiyID; - } - - public void setVerified(boolean verified) { - this.verified = verified; - } - - /** - * @param relayState the relayState to set - */ - public void setRelayState(String relayState) { - this.relayState = relayState; - } - - public void setSAMLMessage(Element msg) { - this.samlMessage = msg; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#getRelayState() - */ - @Override - public String getRelayState() { - return relayState; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#getEntityID() - */ - @Override - public String getEntityID() { - return entityID; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#isVerified() - */ - @Override - public boolean isVerified() { - return verified; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.messages.PVP21InboundMessage#getInboundMessage() - */ - @Override - public Element getInboundMessage() { - return samlMessage; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/InboundMessageInterface.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/InboundMessageInterface.java deleted file mode 100644 index 60a6f069a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/InboundMessageInterface.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.messages; - -import org.w3c.dom.Element; - -/** - * @author tlenz - * - */ -public interface InboundMessageInterface { - - public String getRelayState(); - public String getEntityID(); - public boolean isVerified(); - public Element getInboundMessage(); - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/MOARequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/MOARequest.java deleted file mode 100644 index 7679e74a6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/MOARequest.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.messages; - - -import org.opensaml.Configuration; -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.xml.io.Unmarshaller; -import org.opensaml.xml.io.UnmarshallerFactory; -import org.opensaml.xml.io.UnmarshallingException; -import org.opensaml.xml.signature.SignableXMLObject; - -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; -import at.gv.egovernment.moa.logging.Logger; - -public class MOARequest extends InboundMessage{ - - private static final long serialVersionUID = 8613921176727607896L; - - private String binding = null; - - public MOARequest(SignableXMLObject inboundMessage, String binding) { - setSAMLMessage(inboundMessage.getDOM()); - this.binding = binding; - - } - - public String getRequestBinding() { - return binding; - } - - public SignableXMLObject getSamlRequest() { - UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); - Unmarshaller unmashaller = unmarshallerFactory.getUnmarshaller(getInboundMessage()); - - try { - return (SignableXMLObject) unmashaller.unmarshall(getInboundMessage()); - - } catch (UnmarshallingException e) { - Logger.warn("AuthnRequest Unmarshaller error", e); - return null; - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/MOAResponse.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/MOAResponse.java deleted file mode 100644 index f2512b122..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/messages/MOAResponse.java +++ /dev/null @@ -1,56 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.messages; - -import org.opensaml.Configuration; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.xml.io.Unmarshaller; -import org.opensaml.xml.io.UnmarshallerFactory; -import org.opensaml.xml.io.UnmarshallingException; - -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; -import at.gv.egovernment.moa.logging.Logger; - -public class MOAResponse extends InboundMessage { - - private static final long serialVersionUID = -1133012928130138501L; - - public MOAResponse(StatusResponseType response) { - setSAMLMessage(response.getDOM()); - } - - public StatusResponseType getResponse() { - UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); - Unmarshaller unmashaller = unmarshallerFactory.getUnmarshaller(getInboundMessage()); - - try { - return (StatusResponseType) unmashaller.unmarshall(getInboundMessage()); - - } catch (UnmarshallingException e) { - Logger.warn("AuthnResponse Unmarshaller error", e); - return null; - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java deleted file mode 100644 index 3da4dc18a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.metadata; - -/** - * @author tlenz - * - */ -public interface IMOARefreshableMetadataProvider { - - /** - * Refresh a entity or load a entity in a metadata provider - * - * @param entityID - * @return true, if refresh is success, otherwise false - */ - public boolean refreshMetadataProvider(String entityID); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java index 7f6f9b88c..1fa17c683 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 @@ -23,397 +23,91 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.metadata; import java.io.IOException; +import java.net.MalformedURLException; import java.security.cert.CertificateException; import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Timer; -import javax.xml.namespace.QName; - -import org.opensaml.saml2.metadata.EntitiesDescriptor; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.RoleDescriptor; -import org.opensaml.saml2.metadata.provider.BaseMetadataProvider; -import org.opensaml.saml2.metadata.provider.ChainingMetadataProvider; -import org.opensaml.saml2.metadata.provider.HTTPMetadataProvider; -import org.opensaml.saml2.metadata.provider.MetadataFilter; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.MOAHttpClient; +import org.apache.commons.httpclient.params.HttpClientParams; 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.opensaml.xml.parse.BasicParserPool; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.auth.IDestroyableObject; -import at.gv.egovernment.moa.id.auth.IGarbageCollectorProcessing; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.AbstractChainingMetadataProvider; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.MetadataFilterChain; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.PVPEntityCategoryFilter; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.SchemaValidationFilter; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -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.commons.ex.MOAHttpProtocolSocketFactoryException; +import at.gv.egovernment.moa.id.commons.utils.MOAHttpProtocolSocketFactory; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameterDecorator; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.InterfederatedIDPPublicServiceFilter; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.PVPEntityCategoryFilter; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.PVPMetadataFilterChain; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.SchemaValidationFilter; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.MetadataSignatureFilter; 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, IDestroyableObject { +public class MOAMetadataProvider extends AbstractChainingMetadataProvider { - //private static final int METADATA_GARBAGE_TIMEOUT_SEC = 604800; //7 days - -// private static MOAMetadataProvider instance = null; - MetadataProvider internalProvider = null; - private Timer timer = null; - private static Object mutex = new Object(); - //private Map<String, Date> lastAccess = null; - - - public MOAMetadataProvider() { - internalProvider = new ChainingMetadataProvider(); - //lastAccess = new HashMap<String, Date>(); + @Autowired(required=true) AuthConfiguration moaAuthConfig; - } - -// 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() { - synchronized (mutex) { - - /**add new Metadataprovider or remove Metadataprovider which are not in use any more.**/ - try { - Logger.trace("Check consistence of PVP2X metadata"); - addAndRemoveMetadataProvider(); - - } catch (ConfigurationException e) { - Logger.error("Access to MOA-ID configuration FAILED.", e); - - } - } + protected String getMetadataURL(String entityId) throws EAAFConfigurationException { + ISPConfiguration oaParam = authConfig.getServiceProviderConfiguration(entityId); + if (oaParam != null) + return oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); - } - - -// 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.debug("Can not process PVP2X metadata: NO onlineApplication with Id: " + entityId); + return null; + } + } - - @Override - public synchronized boolean refreshMetadataProvider(String entityID) { - try { - //check if metadata provider is already loaded - try { - if (internalProvider.getEntityDescriptor(entityID) != null) - return true; - - } catch (MetadataProviderException e) {} - + protected MetadataProvider createNewMetadataProvider(String entityId) throws EAAFConfigurationException, IOException, CertificateException { + ISPConfiguration oaParam = authConfig.getServiceProviderConfiguration(entityId); + if (oaParam != null) { + String metadataURL = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); + String certBase64 = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); + if (MiscUtil.isNotEmpty(certBase64)) { + byte[] cert = Base64Utils.decode(certBase64, false); + String oaFriendlyName = oaParam.getUniqueIdentifier(); + + return createNewSimpleMetadataProvider(metadataURL, + buildMetadataFilterChain(oaParam, metadataURL, cert), + oaFriendlyName, + getTimer(), + new BasicParserPool(), + createHttpClient(metadataURL)); - //reload metadata provider - IOAAuthParameters oaParam = - authConfig.getOnlineApplicationParameter(entityID); - if (oaParam != null) { - String metadataURL = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); - if (MiscUtil.isNotEmpty(metadataURL)) { - Map<String, HTTPMetadataProvider> actuallyLoadedProviders = getAllActuallyLoadedProviders(); - - // check if MetadataProvider is actually loaded - if (actuallyLoadedProviders.containsKey(metadataURL)) { - actuallyLoadedProviders.get(metadataURL).refresh(); - Logger.info("PVP2X metadata for onlineApplication: " - + entityID + " is refreshed."); - return true; - - } else { - //load new Metadata Provider - String certBase64 = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); - if (MiscUtil.isNotEmpty(certBase64)) { - byte[] cert = Base64Utils.decode(certBase64, false); - String oaFriendlyName = oaParam.getFriendlyName(); - - if (timer == null) - timer = new Timer(true); - - ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - MetadataProvider newMetadataProvider = createNewMoaMetadataProvider(metadataURL, - buildMetadataFilterChain(oaParam, metadataURL, cert), - oaFriendlyName, - timer, - new BasicParserPool()); - - chainProvider.addMetadataProvider(newMetadataProvider); - - emitChangeEvent(); - - Logger.info("PVP2X metadata for onlineApplication: " - + entityID + " is added."); - return true; - - } else - Logger.debug("Can not refresh PVP2X metadata: NO PVP2X metadata certificate for OA with Id: " + entityID); - - } - - } else - Logger.debug("Can not refresh PVP2X metadata: NO PVP2X metadata URL for OA with Id: " + entityID); - } else - Logger.debug("Can not refresh PVP2X metadata: NO onlineApplication with Id: " + entityID); - - - } catch (MetadataProviderException e) { - Logger.warn("Refresh PVP2X metadata for onlineApplication: " - + entityID + " FAILED.", e); - - } catch (IOException e) { - Logger.warn("Refresh PVP2X metadata for onlineApplication: " - + entityID + " FAILED.", e); - - } catch (CertificateException e) { - Logger.warn("Refresh PVP2X metadata for onlineApplication: " - + entityID + " FAILED.", e); + Logger.debug("Can not refresh PVP2X metadata: NO PVP2X metadata certificate for OA with Id: " + entityId); - } catch (ConfigurationException e) { - Logger.warn("Refresh PVP2X metadata for onlineApplication: " - + entityID + " FAILED.", e); } - return false; - - } - - private Map<String, HTTPMetadataProvider> getAllActuallyLoadedProviders() { - Map<String, HTTPMetadataProvider> loadedproviders = new HashMap<String, HTTPMetadataProvider>(); - ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - - //make a Map of all actually loaded HTTPMetadataProvider - List<MetadataProvider> providers = chainProvider.getProviders(); - for (MetadataProvider provider : providers) { - if (provider instanceof HTTPMetadataProvider) { - HTTPMetadataProvider httpprovider = (HTTPMetadataProvider) provider; - loadedproviders.put(httpprovider.getMetadataURI(), httpprovider); - - } - } - - return loadedproviders; - } - - - private void addAndRemoveMetadataProvider() throws ConfigurationException { - if (internalProvider != null && internalProvider instanceof ChainingMetadataProvider) { - Logger.info("Reload MOAMetaDataProvider."); - - /*OpenSAML ChainingMetadataProvider can not remove a MetadataProvider (UnsupportedOperationException) - *The ChainingMetadataProvider use internal a unmodifiableList to hold all registrated MetadataProviders.*/ - Map<String, MetadataProvider> providersinuse = new HashMap<String, MetadataProvider>(); - ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - - //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 = authConfig.getConfigurationWithWildCard( - MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES - + ".%." - + MOAIDConfigurationConstants.SERVICE_UNIQUEIDENTIFIER); - - if (allOAs != null) { - Iterator<Entry<String, String>> oaInterator = allOAs.entrySet().iterator(); - while (oaInterator.hasNext()) { - Entry<String, String> oaKeyPair = oaInterator.next(); - - IOAAuthParameters oaParam = - authConfig.getOnlineApplicationParameter(oaKeyPair.getValue()); - if (oaParam != null) { - String metadataurl = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); - - HTTPMetadataProvider httpProvider = null; - try { - if (MiscUtil.isNotEmpty(metadataurl)) { - if (loadedproviders.containsKey(metadataurl)) { - // PVP2 OA is actually loaded, to nothing - providersinuse.put(metadataurl, loadedproviders.get(metadataurl)); - loadedproviders.remove(metadataurl); - - - //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); -// } + Logger.debug("Can not process PVP2X metadata: NO onlineApplication with Id: " + entityId); + return null; - } - } - } catch (Throwable e) { - Logger.error( - "Failed to add Metadata (unhandled reason: " - + e.getMessage(), e); - - if (httpProvider != null) { - Logger.debug("Destroy failed Metadata provider"); - httpProvider.destroy(); - } - - } - } - } - } - - //remove all actually loaded MetadataProviders with are not in ConfigurationDB any more - Collection<HTTPMetadataProvider> notusedproviders = loadedproviders.values(); - for (HTTPMetadataProvider provider : notusedproviders) { - String metadataurl = provider.getMetadataURI(); - - try { - - provider.destroy(); - - /*OpenSAML ChainingMetadataProvider can not remove a MetadataProvider (UnsupportedOperationException) - *The ChainingMetadataProvider use internal a unmodifiableList to hold all registrated MetadataProviders.*/ - //chainProvider.removeMetadataProvider(provider); - - Logger.info("Remove not used MetadataProvider with MetadataURL " + metadataurl); - - } catch (Throwable e) { - Logger.error("HTTPMetadataProvider with URL " + metadataurl - + " can not be removed from the list of actually loaded Providers.", e); - - } - - } - - try { - chainProvider.setProviders(new ArrayList<MetadataProvider>(providersinuse.values())); - - emitChangeEvent(); - - } catch (MetadataProviderException e) { - Logger.warn("ReInitalize MOAMetaDataProvider is not possible! MOA-ID Instance has to be restarted manualy", e); - - } - - - - } else { - Logger.warn("ReInitalize MOAMetaDataProvider is not possible! MOA-ID Instance has to be restarted manualy"); - } - } - - public void internalDestroy() { - if (internalProvider != null && internalProvider instanceof ChainingMetadataProvider) { - Logger.info("Destrorying PVP-Authentication MetaDataProvider."); - ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - - List<MetadataProvider> providers = chainProvider.getProviders(); - for (MetadataProvider provider : providers) { - if (provider instanceof HTTPMetadataProvider) { - HTTPMetadataProvider httpprovider = (HTTPMetadataProvider) provider; - Logger.debug("Destroy HTTPMetadataProvider +" + httpprovider.getMetadataURI()); - httpprovider.destroy(); - - } else { - Logger.warn("MetadataProvider can not be destroyed."); - } - } - - internalProvider = new ChainingMetadataProvider(); - - if (timer != null) - timer.cancel(); - - } else { - Logger.warn("ReInitalize MOAMetaDataProvider is not possible! MOA-ID Instance has to be restarted manualy"); - } - } - - @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>(); - Map<String, String> allOAs = authConfig.getConfigurationWithWildCard( + @Override + protected List<String> getAllMetadataURLsFromConfiguration() throws EAAFConfigurationException { + List<String> metadataURLs = new ArrayList<String>(); + + Map<String, String> allOAs = moaAuthConfig.getConfigurationWithWildCard( MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES + ".%." + MOAIDConfigurationConstants.SERVICE_UNIQUEIDENTIFIER); @@ -423,81 +117,67 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider while (oaInterator.hasNext()) { Entry<String, String> oaKeyPair = oaInterator.next(); - IOAAuthParameters oaParam = - authConfig.getOnlineApplicationParameter(oaKeyPair.getValue()); + ISPConfiguration oaParam = authConfig.getServiceProviderConfiguration(oaKeyPair.getValue()); if (oaParam != null) { String metadataurl = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); - String oaFriendlyName = oaParam.getFriendlyName(); - MetadataProvider httpProvider = null; - - try { - String certBase64 = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); - if (MiscUtil.isNotEmpty(certBase64) && MiscUtil.isNotEmpty(metadataurl)) { - byte[] cert = Base64Utils.decode(certBase64, false); - - - if (timer == null) - timer = new Timer(true); - - Logger.info("Loading metadata for: " + oaFriendlyName); - if (!providersinuse.containsKey(metadataurl)) { - httpProvider = createNewMoaMetadataProvider( - metadataurl, - buildMetadataFilterChain(oaParam, metadataurl, cert), - oaFriendlyName, - timer, - new BasicParserPool()); + if (MiscUtil.isNotEmpty(metadataurl)) + metadataURLs.add(metadataurl); + else + Logger.trace("OA: " + oaParam.getUniqueIdentifier() + " has NO PVP2 metadata URL"); - if (httpProvider != null) - providersinuse.put(metadataurl, httpProvider); - - } else { - Logger.info(metadataurl + " are already added."); - } - - } else { - Logger.info(oaFriendlyName - + " is not a PVP2 Application skipping"); - } - } catch (Throwable e) { - Logger.error( - "Failed to add Metadata (unhandled reason: " - + e.getMessage(), e); - - if (httpProvider != null && httpProvider instanceof BaseMetadataProvider) { - Logger.debug("Destroy failed Metadata provider"); - ((BaseMetadataProvider)httpProvider).destroy(); - - } - } - } + } else + Logger.warn("Something is suspect! OA is in Set of OAs, but no specific OA configuration is found."); } - } else - Logger.info("No Online-Application configuration found. PVP 2.1 metadata provider initialization failed!"); - - try { - chainProvider.setProviders(new ArrayList<MetadataProvider>(providersinuse.values())); + } else + Logger.debug("No OA configuration found."); + + return metadataURLs; + } - } catch (MetadataProviderException e) { - Logger.error( - "Failed to add Metadata (unhandled reason: " - + e.getMessage(), e); + private HttpClient createHttpClient(String metadataURL) { + MOAHttpClient httpClient = new MOAHttpClient(); + HttpClientParams httpClientParams = new HttpClientParams(); + httpClientParams.setSoTimeout(AuthConfiguration.CONFIG_PROPS_METADATA_SOCKED_TIMEOUT); + httpClient.setParams(httpClientParams); + + if (metadataURL.startsWith("https:")) { + try { + //FIX: change hostname validation default flag to true when httpClient is updated to > 4.4 + MOAHttpProtocolSocketFactory protoSocketFactory = new MOAHttpProtocolSocketFactory( + PVPConstants.SSLSOCKETFACTORYNAME, + moaAuthConfig.getTrustedCACertificates(), + null, + AuthConfiguration.DEFAULT_X509_CHAININGMODE, + moaAuthConfig.isTrustmanagerrevoationchecking(), + moaAuthConfig.getRevocationMethodOrder(), + moaAuthConfig.getBasicMOAIDConfigurationBoolean( + AuthConfiguration.PROP_KEY_SSL_HOSTNAME_VALIDATION, false)); + + httpClient.setCustomSSLTrustStore(metadataURL, protoSocketFactory); + + } catch (MOAHttpProtocolSocketFactoryException | MalformedURLException e) { + Logger.warn("MOA SSL-TrustStore can not initialized. Use default Java TrustStore.", e); + + } } - internalProvider = chainProvider; + return httpClient; } - - private PVPMetadataFilterChain buildMetadataFilterChain(IOAAuthParameters oaParam, String metadataURL, byte[] certificate) throws CertificateException, ConfigurationException { - PVPMetadataFilterChain filterChain = new PVPMetadataFilterChain(metadataURL, certificate); - filterChain.getFilters().add(new SchemaValidationFilter()); + + private MetadataFilterChain buildMetadataFilterChain(ISPConfiguration oaParam, String metadataURL, byte[] certificate) throws CertificateException{ + MetadataFilterChain filterChain = new MetadataFilterChain(); + filterChain.getFilters().add(new SchemaValidationFilter(moaAuthConfig.isPVPSchemaValidationActive())); + filterChain.getFilters().add(new MetadataSignatureFilter(metadataURL, certificate)); filterChain.getFilters().add( new PVPEntityCategoryFilter(authConfig.getBasicMOAIDConfigurationBoolean( AuthConfiguration.PROP_KEY_PROTOCOL_PVP_METADATA_ENTITYCATEGORY_RESOLVER, false))); - if (oaParam.isInderfederationIDP()) { + + + if ((new OAAuthParameterDecorator(oaParam)).isInderfederationIDP()) { Logger.info("Online-Application is an interfederated IDP. Add addional Metadata policies"); filterChain.getFilters().add(new InterfederatedIDPPublicServiceFilter(metadataURL, oaParam.hasBaseIdTransferRestriction())); @@ -506,116 +186,4 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider return filterChain; } - public boolean requireValidMetadata() { - return internalProvider.requireValidMetadata(); - } - - public void setRequireValidMetadata(boolean requireValidMetadata) { - internalProvider.setRequireValidMetadata(requireValidMetadata); - } - - public MetadataFilter getMetadataFilter() { - return internalProvider.getMetadataFilter(); - } - - public void setMetadataFilter(MetadataFilter newFilter) - throws MetadataProviderException { - internalProvider.setMetadataFilter(newFilter); - } - - public XMLObject getMetadata() throws MetadataProviderException { - return internalProvider.getMetadata(); - } - - public EntitiesDescriptor getEntitiesDescriptor(String entitiesID) - throws MetadataProviderException { - EntitiesDescriptor entitiesDesc = null; - try { - entitiesDesc = internalProvider.getEntitiesDescriptor(entitiesID); - - if (entitiesDesc == null) { - Logger.debug("Can not find PVP metadata for entityID: " + entitiesID - + " Start refreshing process ..."); - if (refreshMetadataProvider(entitiesID)) - return internalProvider.getEntitiesDescriptor(entitiesID); - - } - - } catch (MetadataProviderException e) { - Logger.debug("Can not find PVP metadata for entityID: " + entitiesID - + " Start refreshing process ..."); - if (refreshMetadataProvider(entitiesID)) - return internalProvider.getEntitiesDescriptor(entitiesID); - - } - - return entitiesDesc; - } - - public EntityDescriptor getEntityDescriptor(String entityID) - throws MetadataProviderException { - EntityDescriptor entityDesc = null; - try { - entityDesc = internalProvider.getEntityDescriptor(entityID); - if (entityDesc == null) { - Logger.debug("Can not find PVP metadata for entityID: " + entityID - + " Start refreshing process ..."); - if (refreshMetadataProvider(entityID)) - return internalProvider.getEntityDescriptor(entityID); - - } - - } catch (MetadataProviderException e) { - Logger.debug("Can not find PVP metadata for entityID: " + entityID - + " Start refreshing process ..."); - if (refreshMetadataProvider(entityID)) - return internalProvider.getEntityDescriptor(entityID); - - } - -// if (entityDesc != null) -// lastAccess.put(entityID, new Date()); - - return entityDesc; - } - - public List<RoleDescriptor> getRole(String entityID, QName 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 { - RoleDescriptor result = internalProvider.getRole(entityID, roleName, supportedProtocol); - -// if (result != null) -// lastAccess.put(entityID, new Date()); - - return result; - } - - /* (non-Javadoc) - * @see org.opensaml.saml2.metadata.provider.ObservableMetadataProvider#getObservers() - */ - @Override - public List<Observer> getObservers() { - return ((ChainingMetadataProvider) internalProvider).getObservers(); - } - - protected void emitChangeEvent() { - if ((getObservers() == null) || (getObservers().size() == 0)) { - return; - } - - List<Observer> tempObserverList = new ArrayList<Observer>(getObservers()); - for (ObservableMetadataProvider.Observer observer : tempObserverList) - if (observer != null) - observer.onEvent(this); - } - } 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 deleted file mode 100644 index 6c2235654..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.metadata; - -import java.io.File; -import java.util.Timer; - -import javax.net.ssl.SSLHandshakeException; - -import org.apache.commons.httpclient.MOAHttpClient; -import org.apache.commons.httpclient.params.HttpClientParams; -import org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider; -import org.opensaml.saml2.metadata.provider.HTTPMetadataProvider; -import org.opensaml.saml2.metadata.provider.MetadataFilter; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.xml.parse.ParserPool; -import org.springframework.beans.factory.annotation.Autowired; - -import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.id.commons.ex.MOAHttpProtocolSocketFactoryException; -import at.gv.egovernment.moa.id.commons.utils.MOAHttpProtocolSocketFactory; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SchemaValidationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SignatureValidationException; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.FileUtils; - -/** - * @author tlenz - * - */ -public abstract class SimpleMOAMetadataProvider implements MetadataProvider{ - - private static final String URI_PREFIX_HTTP = "http:"; - private static final String URI_PREFIX_HTTPS = "https:"; - private static final String URI_PREFIX_FILE = "file:"; - - - @Autowired - protected AuthConfiguration authConfig; - - /** - * Create a single SAML2 MOA specific metadata provider - * - * @param metadataLocation where the metadata should be loaded, but never null. If the location starts with http(s):, than a http - * based metadata provider is used. If the location starts with file:, than a filesystem based metadata provider is used - * @param filter Filters, which should be used to validate the metadata - * @param IdForLogging Id, which is used for Logging - * @param timer {@link Timer} which is used to schedule metadata refresh operations - * - * @return SAML2 Metadata Provider, or null if the metadata provider can not initialized - */ - protected MetadataProvider createNewMoaMetadataProvider(String metadataLocation, MetadataFilter filter, - String IdForLogging, Timer timer, ParserPool pool) { - if (metadataLocation.startsWith(URI_PREFIX_HTTP) || metadataLocation.startsWith(URI_PREFIX_HTTPS)) - return createNewHTTPMetaDataProvider(metadataLocation, filter, IdForLogging, timer, pool); - - else { - String absoluteMetadataLocation = FileUtils.makeAbsoluteURL( - metadataLocation, - authConfig.getRootConfigFileDir()); - - if (absoluteMetadataLocation.startsWith(URI_PREFIX_FILE)) { - File metadataFile = new File(absoluteMetadataLocation); - if (metadataFile.exists()) - return createNewFileSystemMetaDataProvider(metadataFile, filter, IdForLogging, timer, pool); - - else { - Logger.warn("SAML2 metadata file: " + absoluteMetadataLocation + " not found or not exist"); - return null; - } - - } - } - - Logger.warn("SAML2 metadata has an unsupported metadata location prefix: " + metadataLocation); - return null; - - } - - - /** - * Create a single SAML2 filesystem based metadata provider - * - * @param metadataFile File, where the metadata should be loaded - * @param filter Filters, which should be used to validate the metadata - * @param IdForLogging Id, which is used for Logging - * @param timer {@link Timer} which is used to schedule metadata refresh operations - * @param pool - * - * @return SAML2 Metadata Provider - */ - private MetadataProvider createNewFileSystemMetaDataProvider(File metadataFile, MetadataFilter filter, String IdForLogging, Timer timer, ParserPool pool) { - FilesystemMetadataProvider fileSystemProvider = null; - try { - fileSystemProvider = new FilesystemMetadataProvider(timer, metadataFile); - fileSystemProvider.setParserPool(pool); - fileSystemProvider.setRequireValidMetadata(true); - fileSystemProvider.setMinRefreshDelay(1000*60*15); //15 minutes - fileSystemProvider.setMaxRefreshDelay(1000*60*60*24); //24 hours - //httpProvider.setRefreshDelayFactor(0.1F); - - fileSystemProvider.setMetadataFilter(filter); - fileSystemProvider.initialize(); - - fileSystemProvider.setRequireValidMetadata(true); - - return fileSystemProvider; - - } catch (Exception e) { - Logger.warn( - "Failed to load Metadata file for " - + IdForLogging + "[ " - + "File: " + metadataFile.getAbsolutePath() - + " Msg: " + e.getMessage() + " ]", e); - - - Logger.warn("Can not initialize SAML2 metadata provider from filesystem: " + metadataFile.getAbsolutePath() - + " Reason: " + e.getMessage(), e); - - if (fileSystemProvider != null) - fileSystemProvider.destroy(); - - } - - return null; - - } - - - - /** - * Create a single SAML2 HTTP metadata provider - * - * @param metadataURL URL, where the metadata should be loaded - * @param filter Filters, which should be used to validate the metadata - * @param IdForLogging Id, which is used for Logging - * @param timer {@link Timer} which is used to schedule metadata refresh operations - * @param pool - * - * @return SAML2 Metadata Provider - */ - private MetadataProvider createNewHTTPMetaDataProvider(String metadataURL, MetadataFilter filter, String IdForLogging, Timer timer, ParserPool pool) { - HTTPMetadataProvider httpProvider = null; - //Timer timer= null; - MOAHttpClient httpClient = null; - try { - httpClient = new MOAHttpClient(); - - HttpClientParams httpClientParams = new HttpClientParams(); - httpClientParams.setSoTimeout(AuthConfiguration.CONFIG_PROPS_METADATA_SOCKED_TIMEOUT); - httpClient.setParams(httpClientParams); - - if (metadataURL.startsWith("https:")) { - try { - //FIX: change hostname validation default flag to true when httpClient is updated to > 4.4 - MOAHttpProtocolSocketFactory protoSocketFactory = new MOAHttpProtocolSocketFactory( - PVPConstants.SSLSOCKETFACTORYNAME, - authConfig.getTrustedCACertificates(), - null, - AuthConfiguration.DEFAULT_X509_CHAININGMODE, - authConfig.isTrustmanagerrevoationchecking(), - authConfig.getRevocationMethodOrder(), - authConfig.getBasicMOAIDConfigurationBoolean( - AuthConfiguration.PROP_KEY_SSL_HOSTNAME_VALIDATION, false)); - - httpClient.setCustomSSLTrustStore(metadataURL, protoSocketFactory); - - } catch (MOAHttpProtocolSocketFactoryException e) { - Logger.warn("MOA SSL-TrustStore can not initialized. Use default Java TrustStore."); - - } - } - -// timer = new Timer(true); - httpProvider = new HTTPMetadataProvider(timer, httpClient, - metadataURL); - httpProvider.setParserPool(pool); - httpProvider.setRequireValidMetadata(true); - httpProvider.setMinRefreshDelay(1000*60*15); //15 minutes - httpProvider.setMaxRefreshDelay(1000*60*60*24); //24 hours - //httpProvider.setRefreshDelayFactor(0.1F); - - httpProvider.setMetadataFilter(filter); - httpProvider.initialize(); - - httpProvider.setRequireValidMetadata(true); - - return httpProvider; - - } catch (Throwable e) { - if (e.getCause() != null && e.getCause().getCause() instanceof SSLHandshakeException) { - Logger.warn("SSL-Server certificate for metadata " - + metadataURL + " not trusted.", e); - - } if (e.getCause() != null && e.getCause().getCause() instanceof SignatureValidationException) { - Logger.warn("Signature verification for metadata" - + metadataURL + " FAILED.", e); - - } if (e.getCause() != null && e.getCause().getCause() instanceof SchemaValidationException) { - Logger.warn("Schema validation for metadata " - + metadataURL + " FAILED.", e); - } - - Logger.warn( - "Failed to load Metadata file for " - + IdForLogging + "[ " - + e.getMessage() + " ]", e); - - if (httpProvider != null) { - Logger.debug("Destroy failed Metadata provider"); - httpProvider.destroy(); - } - -// if (timer != null) { -// Logger.debug("Destroy Timer."); -// timer.cancel(); -// } - - - } - - return null; - } - -} 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 deleted file mode 100644 index af9ba0180..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java +++ /dev/null @@ -1,216 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.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; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.x509.X509Credential; -import org.opensaml.xml.signature.Signature; -import org.opensaml.xml.signature.SignatureConstants; - -import at.gv.egovernment.moa.id.opemsaml.MOAKeyStoreX509CredentialAdapter; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.KeyStoreUtils; -import at.gv.egovernment.moa.util.MiscUtil; - -public abstract class AbstractCredentialProvider { - - private KeyStore keyStore = null; - - /** - * Get a friendlyName for this keyStore implementation - * This friendlyName is used for logging - * - * @return keyStore friendlyName - */ - public abstract String getFriendlyName(); - - /** - * Get KeyStore - * - * @return URL to the keyStore - */ - public abstract String getKeyStoreFilePath(); - - /** - * Get keyStore password - * - * @return Password of the keyStore - */ - public abstract String getKeyStorePassword(); - - /** - * Get alias of key for metadata signing - * - * @return key alias - */ - public abstract String getMetadataKeyAlias(); - - /** - * Get password of key for metadata signing - * - * @return key password - */ - public abstract String getMetadataKeyPassword(); - - /** - * Get alias of key for request/response signing - * - * @return key alias - */ - public abstract String getSignatureKeyAlias(); - - /** - * Get password of key for request/response signing - * - * @return key password - */ - public abstract String getSignatureKeyPassword(); - - /** - * Get alias of key for IDP response encryption - * - * @return key alias - */ - public abstract String getEncryptionKeyAlias(); - - /** - * Get password of key for IDP response encryption - * - * @return key password - */ - public abstract String getEncryptionKeyPassword(); - - - public X509Credential getIDPMetaDataSigningCredential() - throws CredentialsNotAvailableException { - try { - - if (keyStore == null) - keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), - getKeyStorePassword()); - - MOAKeyStoreX509CredentialAdapter credentials = new MOAKeyStoreX509CredentialAdapter( - keyStore, getMetadataKeyAlias(), getMetadataKeyPassword().toCharArray()); - - credentials.setUsageType(UsageType.SIGNING); - if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { - Logger.error(getFriendlyName() + " Metadata Signing credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException("config.27", new Object[]{getFriendlyName() + " Assertion Signing credentials (Alias: " - + getMetadataKeyAlias() + ") is not found or contains no PrivateKey."}); - - } - return credentials; - } catch (Exception e) { - Logger.error("Failed to generate " + getFriendlyName() + " Metadata Signing credentials"); - e.printStackTrace(); - throw new CredentialsNotAvailableException("config.27", new Object[]{e.getMessage()}, e); - } - } - - public X509Credential getIDPAssertionSigningCredential() - throws CredentialsNotAvailableException { - try { - if (keyStore == null) - keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), - getKeyStorePassword()); - - MOAKeyStoreX509CredentialAdapter credentials = new MOAKeyStoreX509CredentialAdapter( - keyStore, getSignatureKeyAlias(), getSignatureKeyPassword().toCharArray()); - - credentials.setUsageType(UsageType.SIGNING); - if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { - Logger.error(getFriendlyName() + " Assertion Signing credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException("config.27", new Object[]{getFriendlyName() + " Assertion Signing credentials (Alias: " - + getSignatureKeyAlias() + ") is not found or contains no PrivateKey."}); - - } - - return (X509Credential) credentials; - } catch (Exception e) { - Logger.error("Failed to generate " + getFriendlyName() + " Assertion Signing credentials"); - e.printStackTrace(); - throw new CredentialsNotAvailableException("config.27", new Object[]{e.getMessage()}, e); - } - } - - public X509Credential getIDPAssertionEncryptionCredential() - throws CredentialsNotAvailableException { - try { - if (keyStore == null) - keyStore = KeyStoreUtils.loadKeyStore(getKeyStoreFilePath(), - getKeyStorePassword()); - - //if no encryption key is configured return null - if (MiscUtil.isEmpty(getEncryptionKeyAlias())) - return null; - - MOAKeyStoreX509CredentialAdapter credentials = new MOAKeyStoreX509CredentialAdapter( - keyStore, getEncryptionKeyAlias(), getEncryptionKeyPassword().toCharArray()); - - credentials.setUsageType(UsageType.ENCRYPTION); - - if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { - Logger.error(getFriendlyName() + " Assertion Encryption credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException("config.27", new Object[]{getFriendlyName() + " Assertion Encryption credentials (Alias: " - + getEncryptionKeyAlias() + ") is not found or contains no PrivateKey."}); - - } - - return (X509Credential) credentials; - - } catch (Exception e) { - Logger.error("Failed to generate " + getFriendlyName() + " Assertion Encryption credentials"); - e.printStackTrace(); - throw new CredentialsNotAvailableException("config.27", new Object[]{e.getMessage()}, e); - } - } - - public static 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 ECPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA256); - - } 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/signer/CredentialsNotAvailableException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialsNotAvailableException.java deleted file mode 100644 index 85de666c9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialsNotAvailableException.java +++ /dev/null @@ -1,44 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.signer; - -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; - -public class CredentialsNotAvailableException extends MOAIDException { - - public CredentialsNotAvailableException(String messageId, - Object[] parameters) { - super(messageId, parameters); - } - - public CredentialsNotAvailableException(String messageId, - Object[] parameters, Throwable e) { - super(messageId, parameters, e); - } - - /** - * - */ - private static final long serialVersionUID = -2564476345552842599L; - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/IDPCredentialProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/IDPCredentialProvider.java index 381289824..389d97b18 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/IDPCredentialProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/IDPCredentialProvider.java @@ -25,13 +25,14 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.signer; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.core.impl.utils.FileUtils; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.AbstractCredentialProvider; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; -import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; -@Service("IDPCredentialProvider") +//@Service("PVPIDPCredentialProvider") public class IDPCredentialProvider extends AbstractCredentialProvider { public static final String IDP_JAVAKEYSTORE = "idp.ks.file"; public static final String IDP_KS_PASS = "idp.ks.kspassword"; @@ -53,14 +54,14 @@ public class IDPCredentialProvider extends AbstractCredentialProvider { * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getKeyStoreFilePath() */ @Override - public String getKeyStoreFilePath() { + public String getKeyStoreFilePath() throws EAAFException { if (props == null) props = authConfig.getGeneralPVP2ProperiesConfig(); + return FileUtils.makeAbsoluteURL( - props.getProperty(IDP_JAVAKEYSTORE), - authConfig.getRootConfigFileDir()); - + props.getProperty(IDP_JAVAKEYSTORE), + authConfig.getRootConfigFileDir()); } /* (non-Javadoc) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/SAMLSigner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/SAMLSigner.java deleted file mode 100644 index ef64efb56..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/SAMLSigner.java +++ /dev/null @@ -1,27 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.signer; - -public class SAMLSigner { - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java deleted file mode 100644 index 106be8a09..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java +++ /dev/null @@ -1,286 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.utils; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.opensaml.saml2.core.Assertion; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.AttributeStatement; -import org.opensaml.saml2.core.AuthnContextClassRef; -import org.opensaml.saml2.core.AuthnStatement; -import org.opensaml.saml2.core.Response; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.core.Subject; -import org.opensaml.xml.XMLObject; - -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public class AssertionAttributeExtractor { - - private Assertion assertion = null; - private Map<String, List<String>> attributs = new HashMap<String, List<String>>(); - //private PersonalAttributeList storkAttributes = new PersonalAttributeList(); - - private final List<String> minimalAttributeNameList = Arrays.asList( - PVPConstants.PRINCIPAL_NAME_NAME, - PVPConstants.GIVEN_NAME_NAME, - PVPConstants.ENC_BPK_LIST_NAME, - PVPConstants.BPK_NAME); - - /** - * Parse the SAML2 Response element and extracts included information - * <br><br> - * <b>INFO:</b> Actually, only the first SAML2 Assertion of the SAML2 Response is used! - * - * @param samlResponse SAML2 Response - * @throws AssertionAttributeExtractorExeption - */ - public AssertionAttributeExtractor(StatusResponseType samlResponse) throws AssertionAttributeExtractorExeption { - if (samlResponse != null && samlResponse instanceof Response) { - List<Assertion> assertions = ((Response) samlResponse).getAssertions(); - if (assertions.size() == 0) - throw new AssertionAttributeExtractorExeption("Assertion"); - - else if (assertions.size() > 1) - Logger.warn("Found more then ONE PVP2.1 assertions. Only the First is used."); - - assertion = assertions.get(0); - - if (assertion.getAttributeStatements() != null && - assertion.getAttributeStatements().size() > 0) { - AttributeStatement attrStat = assertion.getAttributeStatements().get(0); - for (Attribute attr : attrStat.getAttributes()) { - if (attr.getName().startsWith(PVPConstants.STORK_ATTRIBUTE_PREFIX)) { - List<String> storkAttrValues = new ArrayList<String>(); - for (XMLObject el : attr.getAttributeValues()) - storkAttrValues.add(el.getDOM().getTextContent()); - -// PersonalAttribute storkAttr = new PersonalAttribute(attr.getName(), -// false, storkAttrValues , "Available"); -// storkAttributes.put(attr.getName(), storkAttr ); - - } else { - List<String> attrList = new ArrayList<String>(); - for (XMLObject el : attr.getAttributeValues()) - attrList.add(el.getDOM().getTextContent()); - - attributs.put(attr.getName(), attrList); - - } - } - - } - - } else - throw new AssertionAttributeExtractorExeption(); - } - - /** - * Get all SAML2 attributes from first SAML2 AttributeStatement element - * - * @return List of SAML2 Attributes - */ - public List<Attribute> getAllResponseAttributesFromFirstAttributeStatement() { - return assertion.getAttributeStatements().get(0).getAttributes(); - - } - - /** - * Get all SAML2 attributes of specific SAML2 AttributeStatement element - * - * @param attrStatementID List ID of the AttributeStatement element - * @return List of SAML2 Attributes - */ - public List<Attribute> getAllResponseAttributes(int attrStatementID) { - return assertion.getAttributeStatements().get(attrStatementID).getAttributes(); - - } - - /** - * check attributes from assertion with minimal required attribute list - * @return - */ - public boolean containsAllRequiredAttributes() { - return containsAllRequiredAttributes(minimalAttributeNameList); - - } - - /** - * check attributes from assertion with attributeNameList - * bPK or enc_bPK are always needed - * - * @param List of attributes which are required - * - * @return - */ - public boolean containsAllRequiredAttributes(Collection<String> attributeNameList) { - - //first check if a bPK or an encrypted bPK is available - boolean flag = true; - for (String attr : attributeNameList) { - if (!attributs.containsKey(attr)) { - flag = false; - Logger.debug("Assertion contains no Attribute " + attr); - - } - - } - - if (flag) - return flag; - - else { - Logger.debug("Assertion contains no bPK or encryptedbPK."); - return false; - - } - } - - public boolean containsAttribute(String attributeName) { - return attributs.containsKey(attributeName); - - } - - public String getSingleAttributeValue(String attributeName) { - if (attributs.containsKey(attributeName) && attributs.get(attributeName).size() > 0) - return attributs.get(attributeName).get(0); - else - return null; - - } - - public List<String> getAttributeValues(String attributeName) { - return attributs.get(attributeName); - - } - - /** - * Return all include PVP attribute names - * - * @return - */ - public Set<String> getAllIncludeAttributeNames() { - return attributs.keySet(); - - } - -// public PersonalAttributeList getSTORKAttributes() { -// return storkAttributes; -// } - - - public String getNameID() throws AssertionAttributeExtractorExeption { - if (assertion.getSubject() != null) { - Subject subject = assertion.getSubject(); - - if (subject.getNameID() != null) { - if (MiscUtil.isNotEmpty(subject.getNameID().getValue())) - return subject.getNameID().getValue(); - - else - Logger.error("SAML2 NameID Element is empty."); - } - } - - throw new AssertionAttributeExtractorExeption("nameID"); - } - - public String getSessionIndex() throws AssertionAttributeExtractorExeption { - AuthnStatement authn = getAuthnStatement(); - - if (MiscUtil.isNotEmpty(authn.getSessionIndex())) - return authn.getSessionIndex(); - - else - throw new AssertionAttributeExtractorExeption("SessionIndex"); - } - - /** - * @return - * @throws AssertionAttributeExtractorExeption - */ - public String getQAALevel() throws AssertionAttributeExtractorExeption { - AuthnStatement authn = getAuthnStatement(); - if (authn.getAuthnContext() != null && authn.getAuthnContext().getAuthnContextClassRef() != null) { - AuthnContextClassRef qaaClass = authn.getAuthnContext().getAuthnContextClassRef(); - - if (MiscUtil.isNotEmpty(qaaClass.getAuthnContextClassRef())) - return qaaClass.getAuthnContextClassRef(); - - else - throw new AssertionAttributeExtractorExeption("AuthnContextClassRef (QAALevel)"); - } - - throw new AssertionAttributeExtractorExeption("AuthnContextClassRef"); - } - - public Assertion getFullAssertion() { - return assertion; - } - - - /** - * Get the Assertion validTo period - * - * Primarily, the 'SessionNotOnOrAfter' attribute in the SAML2 'AuthnStatment' element is used. - * If this is empty, this method returns value of SAML 'Conditions' element. - * - * @return Date, until this SAML2 assertion is valid - */ - public Date getAssertionNotOnOrAfter() { - if (getFullAssertion().getAuthnStatements() != null - && getFullAssertion().getAuthnStatements().size() > 0) { - for (AuthnStatement el : getFullAssertion().getAuthnStatements()) { - if (el.getSessionNotOnOrAfter() != null) - return (el.getSessionNotOnOrAfter().toDate()); - } - - } - - return getFullAssertion().getConditions().getNotOnOrAfter().toDate(); - - } - - private AuthnStatement getAuthnStatement() throws AssertionAttributeExtractorExeption { - List<AuthnStatement> authnList = assertion.getAuthnStatements(); - if (authnList.size() == 0) - throw new AssertionAttributeExtractorExeption("AuthnStatement"); - - else if (authnList.size() > 1) - Logger.warn("Found more then ONE AuthnStatements in PVP2.1 assertions. Only the First is used."); - - return authnList.get(0); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/MOASAMLSOAPClient.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/MOASAMLSOAPClient.java index e02ecb662..d7ada1f36 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/MOASAMLSOAPClient.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/MOASAMLSOAPClient.java @@ -35,6 +35,7 @@ import org.opensaml.xml.XMLObject; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; +import at.gv.egiz.eaaf.modules.pvp2.impl.utils.SAML2Utils; 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.ex.MOAHttpProtocolSocketFactoryException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java deleted file mode 100644 index 28a85b4af..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/SAML2Utils.java +++ /dev/null @@ -1,145 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.utils; - -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.util.List; - -import javax.xml.namespace.QName; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.TransformerException; - -import org.opensaml.Configuration; -import org.opensaml.common.impl.SecureRandomIdentifierGenerator; -import org.opensaml.saml2.core.Status; -import org.opensaml.saml2.core.StatusCode; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.ws.soap.soap11.Body; -import org.opensaml.ws.soap.soap11.Envelope; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.XMLObjectBuilderFactory; -import org.opensaml.xml.io.Marshaller; -import org.opensaml.xml.io.MarshallingException; -import org.w3c.dom.Document; - -import at.gv.egovernment.moa.id.util.Random; - -public class SAML2Utils { - - public static <T> T createSAMLObject(final Class<T> clazz) { - try { - XMLObjectBuilderFactory builderFactory = Configuration - .getBuilderFactory(); - - QName defaultElementName = (QName) clazz.getDeclaredField( - "DEFAULT_ELEMENT_NAME").get(null); - @SuppressWarnings("unchecked") - T object = (T) builderFactory.getBuilder(defaultElementName) - .buildObject(defaultElementName); - return object; - } catch (Throwable e) { - e.printStackTrace(); - return null; - } - } - - public static String getSecureIdentifier() { - return "_".concat(Random.nextHexRandom16()); - - /*Bug-Fix: There are open problems with RandomNumberGenerator via Java SPI and Java JDK 8.121 - * Generation of a 16bit Random identifier FAILES with an Caused by: java.lang.ArrayIndexOutOfBoundsException - * Caused by: java.lang.ArrayIndexOutOfBoundsException - at iaik.security.random.o.engineNextBytes(Unknown Source) - at iaik.security.random.SecRandomSpi.engineNextBytes(Unknown Source) - at java.security.SecureRandom.nextBytes(SecureRandom.java:468) - at org.opensaml.common.impl.SecureRandomIdentifierGenerator.generateIdentifier(SecureRandomIdentifierGenerator.java:62) - at org.opensaml.common.impl.SecureRandomIdentifierGenerator.generateIdentifier(SecureRandomIdentifierGenerator.java:56) - at at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils.getSecureIdentifier(SAML2Utils.java:69) - */ - //return idGenerator.generateIdentifier(); - } - - private static SecureRandomIdentifierGenerator idGenerator; - - private static DocumentBuilder builder; - static { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - factory.setNamespaceAware(true); - try { - builder = factory.newDocumentBuilder(); - } catch (ParserConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - try { - idGenerator = new SecureRandomIdentifierGenerator(); - } catch(NoSuchAlgorithmException e) { - e.printStackTrace(); - } - } - - public static Document asDOMDocument(XMLObject object) throws IOException, - MarshallingException, TransformerException { - Document document = builder.newDocument(); - Marshaller out = Configuration.getMarshallerFactory().getMarshaller( - object); - out.marshall(object, document); - return document; - } - - public static Status getSuccessStatus() { - Status status = SAML2Utils.createSAMLObject(Status.class); - StatusCode statusCode = SAML2Utils.createSAMLObject(StatusCode.class); - statusCode.setValue(StatusCode.SUCCESS_URI); - status.setStatusCode(statusCode); - return status; - } - - public static int getDefaultAssertionConsumerServiceIndex(SPSSODescriptor spSSODescriptor) { - - List<AssertionConsumerService> assertionConsumerList = spSSODescriptor.getAssertionConsumerServices(); - - for (AssertionConsumerService el : assertionConsumerList) { - if (el.isDefault()) - return el.getIndex(); - - } - - return 0; - } - - public static Envelope buildSOAP11Envelope(XMLObject payload) { - XMLObjectBuilderFactory bf = Configuration.getBuilderFactory(); - Envelope envelope = (Envelope) bf.getBuilder(Envelope.DEFAULT_ELEMENT_NAME).buildObject(Envelope.DEFAULT_ELEMENT_NAME); - Body body = (Body) bf.getBuilder(Body.DEFAULT_ELEMENT_NAME).buildObject(Body.DEFAULT_ELEMENT_NAME); - - body.getUnknownXMLObjects().add(payload); - envelope.setBody(body); - - return envelope; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java deleted file mode 100644 index 86ca591ee..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.validation; - -import javax.xml.namespace.QName; -import javax.xml.transform.dom.DOMSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; - -import org.opensaml.common.SignableSAMLObject; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.security.MetadataCriteria; -import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.ws.message.MessageContext; -import org.opensaml.ws.security.SecurityPolicyException; -import org.opensaml.ws.security.SecurityPolicyRule; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.security.CriteriaSet; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.criteria.EntityIDCriteria; -import org.opensaml.xml.security.criteria.UsageCriteria; -import org.opensaml.xml.signature.SignatureTrustEngine; -import org.opensaml.xml.validation.ValidationException; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ -public abstract class AbstractRequestSignedSecurityPolicyRule implements SecurityPolicyRule { - - private SignatureTrustEngine trustEngine = null; - private QName peerEntityRole = null; - /** - * @param peerEntityRole - * - */ - public AbstractRequestSignedSecurityPolicyRule(SignatureTrustEngine trustEngine, QName peerEntityRole) { - this.trustEngine = trustEngine; - this.peerEntityRole = peerEntityRole; - - } - - - /** - * Reload the PVP metadata for a given entity - * - * @param entityID for which the metadata should be refreshed. - * @return true if the refresh was successful, otherwise false - */ - protected abstract boolean refreshMetadataProvider(String entityID); - - - protected abstract SignableSAMLObject getSignedSAMLObject(XMLObject inboundData); - - /* (non-Javadoc) - * @see org.opensaml.ws.security.SecurityPolicyRule#evaluate(org.opensaml.ws.message.MessageContext) - */ - @Override - public void evaluate(MessageContext context) throws SecurityPolicyException { - try { - verifySignature(context); - - } catch (SecurityPolicyException e) { - if (MiscUtil.isEmpty(context.getInboundMessageIssuer())) { - throw e; - - } - Logger.debug("PVP2X message validation FAILED. Reload metadata for entityID: " + context.getInboundMessageIssuer()); - if (!refreshMetadataProvider(context.getInboundMessageIssuer())) - throw e; - - else { - Logger.trace("PVP2X metadata reload finished. Check validate message again."); - verifySignature(context); - - } - Logger.trace("Second PVP2X message validation finished"); - - } - - - } - - private void verifySignature(MessageContext context) throws SecurityPolicyException { - SignableSAMLObject samlObj = getSignedSAMLObject(context.getInboundMessage()); - if (samlObj != null && samlObj.getSignature() != null) { - - SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); - performSchemaValidation(samlObj.getDOM()); - - } catch (ValidationException e) { - Logger.warn("Signature is not conform to SAML signature profile", e); - throw new SecurityPolicyException("Signature is not conform to SAML signature profile"); - - } catch (SchemaValidationException e) { - Logger.warn("Signature is not conform to SAML signature profile", e); - throw new SecurityPolicyException("Signature is not conform to SAML signature profile"); - - } - - - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(context.getInboundMessageIssuer()) ); - criteriaSet.add( new MetadataCriteria(peerEntityRole, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - - try { - if (!trustEngine.validate(samlObj.getSignature(), criteriaSet)) { - throw new SecurityPolicyException("Signature validation FAILED."); - - } - Logger.debug("PVP message signature valid."); - - } catch (org.opensaml.xml.security.SecurityException e) { - Logger.info("PVP2x message signature validation FAILED. Message:" + e.getMessage()); - throw new SecurityPolicyException("Signature validation FAILED."); - - } - - } else { - throw new SecurityPolicyException("PVP Message is not signed."); - - } - - } - - private void performSchemaValidation(Element source) throws SchemaValidationException { - - String err = null; - try { - Schema test = SAMLSchemaBuilder.getSAML11Schema(); - Validator val = test.newValidator(); - val.validate(new DOMSource(source)); - Logger.debug("Schema validation check done OK"); - return; - - } catch (SAXException e) { - err = e.getMessage(); - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) - Logger.warn("Schema validation FAILED with exception:", e); - else - Logger.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } catch (Exception e) { - err = e.getMessage(); - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) - Logger.warn("Schema validation FAILED with exception:", e); - else - Logger.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } - - throw new SchemaValidationException("pvp2.22", new Object[]{err}); - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AuthnRequestValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AuthnRequestValidator.java index 4ae89466d..b42a1de28 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AuthnRequestValidator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AuthnRequestValidator.java @@ -1,52 +1,44 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ +/******************************************************************************* + *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.validation; +import javax.servlet.http.HttpServletRequest; + import org.opensaml.saml2.core.AuthnRequest; import org.opensaml.saml2.core.NameID; import org.opensaml.saml2.core.NameIDPolicy; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.springframework.stereotype.Service; + +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.exceptions.AuthnRequestValidatorException; +import at.gv.egiz.eaaf.modules.pvp2.api.validation.IAuthnRequestValidator; +import at.gv.egiz.eaaf.modules.pvp2.exception.NameIDFormatNotSupportedException; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.MandateAttributesNotHandleAbleException; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.CheckMandateAttributes; +import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NameIDFormatNotSupportedException; -import at.gv.egovernment.moaspss.logging.Logger; /** * @author tlenz * */ -public class AuthnRequestValidator { - - public static void validate(AuthnRequest req) throws AuthnRequestValidatorException{ +@Service("MOAAuthnRequestValidator") +public class AuthnRequestValidator implements IAuthnRequestValidator { + + public void validate(HttpServletRequest httpReq, IRequest pendingReq, AuthnRequest authnReq, SPSSODescriptor spSSODescriptor) throws AuthnRequestValidatorException{ //validate NameIDPolicy - NameIDPolicy nameIDPolicy = req.getNameIDPolicy(); + NameIDPolicy nameIDPolicy = authnReq.getNameIDPolicy(); if (nameIDPolicy != null) { String nameIDFormat = nameIDPolicy.getFormat(); if (nameIDFormat != null) { if ( !(NameID.TRANSIENT.equals(nameIDFormat) || NameID.PERSISTENT.equals(nameIDFormat) || NameID.UNSPECIFIED.equals(nameIDFormat)) ) { - + throw new NameIDFormatNotSupportedException(nameIDFormat); } @@ -55,8 +47,32 @@ public class AuthnRequestValidator { Logger.trace("Find NameIDPolicy, but NameIDFormat is 'null'"); } else Logger.trace("AuthnRequest includes no 'NameIDPolicy'"); - + + //select AttributeConsumingService from request + AttributeConsumingService attributeConsumer = null; + Integer aIdx = authnReq.getAttributeConsumingServiceIndex(); + int attributeIdx = 0; + + if(aIdx != null) { + attributeIdx = aIdx.intValue(); + } + + if (spSSODescriptor.getAttributeConsumingServices() != null && + spSSODescriptor.getAttributeConsumingServices().size() > 0) { + attributeConsumer = spSSODescriptor.getAttributeConsumingServices().get(attributeIdx); + } + + String useMandate = httpReq.getParameter(MOAIDAuthConstants.PARAM_USEMANDATE); + if(useMandate != null) { + if(useMandate.equals("true") && attributeConsumer != null) { + if(!CheckMandateAttributes.canHandleMandate(attributeConsumer)) { + MandateAttributesNotHandleAbleException e = new MandateAttributesNotHandleAbleException(); + throw new AuthnRequestValidatorException(e.getErrorId(), e.getParams(), e.getMessage(), pendingReq, e); + } + } + } } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/ChainSAMLValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/ChainSAMLValidator.java index a9f9b206e..91de943d5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/ChainSAMLValidator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/ChainSAMLValidator.java @@ -28,7 +28,8 @@ import java.util.List; import org.opensaml.saml2.core.RequestAbstractType; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.modules.pvp2.api.validation.ISAMLValidator; public class ChainSAMLValidator implements ISAMLValidator { @@ -39,7 +40,7 @@ private List<ISAMLValidator> validator = new ArrayList<ISAMLValidator>(); } public void validateRequest(RequestAbstractType request) - throws MOAIDException { + throws EAAFException { Iterator<ISAMLValidator> validatorIterator = validator.iterator(); while(validatorIterator.hasNext()) { ISAMLValidator validator = validatorIterator.next(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/ISAMLValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/ISAMLValidator.java deleted file mode 100644 index 4f697d986..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/ISAMLValidator.java +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.validation; - -import org.opensaml.saml2.core.RequestAbstractType; - -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; - -public interface ISAMLValidator { - public void validateRequest(RequestAbstractType request) throws MOAIDException; -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java deleted file mode 100644 index 7b3f890e9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.validation; - -import javax.xml.namespace.QName; - -import org.opensaml.common.SignableSAMLObject; -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.xml.XMLObject; -import org.opensaml.xml.signature.SignatureTrustEngine; - -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IMOARefreshableMetadataProvider; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -public class MOAPVPSignedRequestPolicyRule extends - AbstractRequestSignedSecurityPolicyRule { - - private IMOARefreshableMetadataProvider metadataProvider = null; - - /** - * @param metadataProvider - * @param trustEngine - * @param peerEntityRole - */ - public MOAPVPSignedRequestPolicyRule(MetadataProvider metadataProvider, SignatureTrustEngine trustEngine, - QName peerEntityRole) { - super(trustEngine, peerEntityRole); - if (metadataProvider instanceof IMOARefreshableMetadataProvider) - this.metadataProvider = (IMOARefreshableMetadataProvider) metadataProvider; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.validation.AbstractRequestSignedSecurityPolicyRule#refreshMetadataProvider(java.lang.String) - */ - @Override - protected boolean refreshMetadataProvider(String entityID) { - if (metadataProvider != null) - return metadataProvider.refreshMetadataProvider(entityID); - - return false; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.validation.AbstractRequestSignedSecurityPolicyRule#getSignedSAMLObject(org.opensaml.xml.XMLObject) - */ - @Override - protected SignableSAMLObject getSignedSAMLObject(XMLObject inboundData) { - if (inboundData instanceof SignableSAMLObject) - return (SignableSAMLObject) inboundData; - - else - return null; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOASAML2AuthRequestSignedRole.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOASAML2AuthRequestSignedRole.java deleted file mode 100644 index efcf21b50..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOASAML2AuthRequestSignedRole.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.validation; - -import org.opensaml.common.binding.SAMLMessageContext; -import org.opensaml.saml2.binding.security.SAML2AuthnRequestsSignedRule; -import org.opensaml.ws.transport.http.HTTPInTransport; -import org.opensaml.xml.util.DatatypeHelper; - -/** - * @author tlenz - * - */ -public class MOASAML2AuthRequestSignedRole extends SAML2AuthnRequestsSignedRule { - - @Override - protected boolean isMessageSigned(SAMLMessageContext messageContext) { - // This handles HTTP-Redirect and HTTP-POST-SimpleSign bindings. - HTTPInTransport inTransport = (HTTPInTransport) messageContext.getInboundMessageTransport(); - String sigParam = inTransport.getParameterValue("Signature"); - boolean isSigned = !DatatypeHelper.isEmpty(sigParam); - - String sigAlgParam = inTransport.getParameterValue("SigAlg"); - boolean isSigAlgExists = !DatatypeHelper.isEmpty(sigAlgParam); - - return isSigned && isSigAlgExists; - - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/SAMLSignatureValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/SAMLSignatureValidator.java index 952a6024a..9abaf9330 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/SAMLSignatureValidator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/SAMLSignatureValidator.java @@ -27,13 +27,14 @@ import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.security.SAMLSignatureProfileValidator; import org.opensaml.xml.validation.ValidationException; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SAMLRequestNotSignedException; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.modules.pvp2.api.validation.ISAMLValidator; +import at.gv.egiz.eaaf.modules.pvp2.idp.exception.SAMLRequestNotSignedException; public class SAMLSignatureValidator implements ISAMLValidator { public void validateRequest(RequestAbstractType request) - throws MOAIDException { + throws EAAFException { if (request.getSignature() == null) { throw new SAMLRequestNotSignedException(); } @@ -48,7 +49,7 @@ public class SAMLSignatureValidator implements ISAMLValidator { } public static void validateSignable(SignableSAMLObject signableObject) - throws MOAIDException { + throws EAAFException { if (signableObject.getSignature() == null) { throw new SAMLRequestNotSignedException(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/EntityVerifier.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/EntityVerifier.java index d05d180e1..1286c2351 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/EntityVerifier.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/EntityVerifier.java @@ -23,7 +23,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.verification; import java.io.IOException; -import java.util.List; +import java.security.cert.CertificateException; import org.opensaml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml2.metadata.EntityDescriptor; @@ -34,82 +34,38 @@ import org.opensaml.xml.security.x509.BasicX509Credential; import org.opensaml.xml.signature.SignatureValidator; import org.opensaml.xml.validation.ValidationException; -import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egiz.eaaf.core.api.idp.ISPConfiguration; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.modules.pvp2.exception.CredentialsNotAvailableException; +import at.gv.egiz.eaaf.modules.pvp2.exception.SAMLMetadataSignatureException; 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.MOAIDConfigurationConstants; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoCredentialsException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SAMLRequestNotSignedException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; +import iaik.x509.X509Certificate; public class EntityVerifier { - public static byte[] fetchSavedCredential(String entityID) { -// List<OnlineApplication> oaList = ConfigurationDBRead -// .getAllActiveOnlineApplications(); - try { - IOAAuthParameters oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(entityID); - - if (oa == null) { - Logger.debug("No OnlineApplication with EntityID: " + entityID); - return null; - - } - - String certBase64 = oa.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); - if (MiscUtil.isNotEmpty(certBase64)) { - return Base64Utils.decode(certBase64, false); - - } - - } catch (ConfigurationException e) { - Logger.error("Access MOA-ID configuration FAILED.", e); - - } catch (IOException e) { - Logger.warn("Decoding PVP2X metadata certificate FAILED.", e); - - } - - return null; - } - public static void verify(EntityDescriptor entityDescriptor) - throws MOAIDException { - if (entityDescriptor.getSignature() == null) { - throw new SAMLRequestNotSignedException(); - } - - try { - SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator(); - sigValidator.validate(entityDescriptor.getSignature()); - } catch (ValidationException e) { - Logger.error("Failed to validate Signature", e); - throw new SAMLRequestNotSignedException(e); - } - + throws EAAFException { + Credential credential = getSPTrustedCredential(entityDescriptor.getEntityID()); if (credential == null) { throw new NoCredentialsException(entityDescriptor.getEntityID()); } - - SignatureValidator sigValidator = new SignatureValidator(credential); - try { - sigValidator.validate(entityDescriptor.getSignature()); - } catch (ValidationException e) { - Logger.error("Failed to verfiy Signature", e); - throw new SAMLRequestNotSignedException(e); - } + + verify(entityDescriptor, credential); + } public static void verify(EntityDescriptor entityDescriptor, Credential cred) - throws MOAIDException { + throws EAAFException { if (entityDescriptor.getSignature() == null) { - throw new SAMLRequestNotSignedException(); + throw new SAMLMetadataSignatureException(); } try { @@ -117,7 +73,7 @@ public class EntityVerifier { sigValidator.validate(entityDescriptor.getSignature()); } catch (ValidationException e) { Logger.error("Failed to validate Signature", e); - throw new SAMLRequestNotSignedException(e); + throw new SAMLMetadataSignatureException(e); } SignatureValidator sigValidator = new SignatureValidator(cred); @@ -125,14 +81,14 @@ public class EntityVerifier { sigValidator.validate(entityDescriptor.getSignature()); } catch (ValidationException e) { Logger.error("Failed to verfiy Signature", e); - throw new SAMLRequestNotSignedException(e); + throw new SAMLMetadataSignatureException(e); } } public static void verify(EntitiesDescriptor entityDescriptor, - Credential cred) throws MOAIDException { + Credential cred) throws EAAFException { if (entityDescriptor.getSignature() == null) { - throw new SAMLRequestNotSignedException(); + throw new SAMLMetadataSignatureException(); } try { @@ -140,7 +96,7 @@ public class EntityVerifier { sigValidator.validate(entityDescriptor.getSignature()); } catch (ValidationException e) { Logger.error("Failed to validate Signature", e); - throw new SAMLRequestNotSignedException(e); + throw new SAMLMetadataSignatureException(e); } SignatureValidator sigValidator = new SignatureValidator(cred); @@ -149,58 +105,14 @@ public class EntityVerifier { } catch (ValidationException e) { Logger.error("Failed to verfiy Signature", e); - throw new SAMLRequestNotSignedException(e); - } - } - - public static void verify(EntitiesDescriptor entityDescriptor) - throws MOAIDException { - if (entityDescriptor.getSignature() == null) { - throw new SAMLRequestNotSignedException(); - } - - try { - SAMLSignatureProfileValidator sigValidator = new SAMLSignatureProfileValidator(); - sigValidator.validate(entityDescriptor.getSignature()); - } catch (ValidationException e) { - Logger.error("Failed to validate Signature", e); - throw new SAMLRequestNotSignedException(e); - } - - List<EntityDescriptor> entities = entityDescriptor - .getEntityDescriptors(); - - if (entities.size() > 0) { - - if (entities.size() > 1) { - Logger.warn("More then one EntityID in Metadatafile with Name " - + entityDescriptor.getName() - + " defined. Actually only the first" - + " entryID is used to select the certificate to perform Metadata verification."); - } - - Credential credential = getSPTrustedCredential(entities.get(0).getEntityID()); - - if (credential == null) { - throw new NoCredentialsException("moaID IDP"); - } - - SignatureValidator sigValidator = new SignatureValidator(credential); - try { - sigValidator.validate(entityDescriptor.getSignature()); - - } catch (ValidationException e) { - Logger.error("Failed to verfiy Signature", e); - throw new SAMLRequestNotSignedException(e); - } + throw new SAMLMetadataSignatureException(e); } } - + public static Credential getSPTrustedCredential(String entityID) throws CredentialsNotAvailableException { - iaik.x509.X509Certificate cert = PVPConfiguration.getInstance() - .getTrustEntityCertificate(entityID); + iaik.x509.X509Certificate cert = getTrustEntityCertificate(entityID); if (cert == null) { throw new CredentialsNotAvailableException("ServiceProvider Certificate can not be loaded from Database", null); @@ -213,5 +125,46 @@ public class EntityVerifier { return credential; } + + private static iaik.x509.X509Certificate getTrustEntityCertificate(String entityID) { + + try { + Logger.trace("Load metadata signing certificate for online application " + entityID); + ISPConfiguration oaParam = AuthConfigurationProviderFactory.getInstance().getServiceProviderConfiguration(entityID); + if (oaParam == null) { + Logger.info("Online Application with ID " + entityID + " not found!"); + return null; + } + + String pvp2MetadataCertificateString = + oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); + if (MiscUtil.isEmpty(pvp2MetadataCertificateString)) { + Logger.info("Online Application with ID " + entityID + " include not PVP2X metadata signing certificate!"); + return null; + + } + + X509Certificate cert = new X509Certificate(Base64Utils.decode(pvp2MetadataCertificateString, false)); + Logger.debug("Metadata signing certificate is loaded for ("+entityID+") is loaded."); + return cert; + + } catch (CertificateException e) { + Logger.warn("Metadata signer certificate is not parsed.", e); + return null; + + } catch (ConfigurationException e) { + Logger.error("Configuration is not accessable.", e); + return null; + + } catch (IOException e) { + Logger.warn("Metadata signer certificate is not decodeable.", e); + return null; + + } catch (EAAFConfigurationException e) { + Logger.error("Configuration is not accessable.", e); + return null; + + } + } } 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 deleted file mode 100644 index f6104bdeb..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ /dev/null @@ -1,197 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.verification; - -import javax.xml.namespace.QName; -import javax.xml.transform.dom.DOMSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; - -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.metadata.IDPSSODescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.security.MetadataCriteria; -import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.xml.security.CriteriaSet; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.criteria.EntityIDCriteria; -import org.opensaml.xml.security.criteria.UsageCriteria; -import org.opensaml.xml.signature.SignatureTrustEngine; -import org.opensaml.xml.validation.ValidationException; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.logging.Logger; -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 { - if (msg instanceof MOARequest && - ((MOARequest)msg).getSamlRequest() instanceof RequestAbstractType) - verifyRequest(((RequestAbstractType)((MOARequest)msg).getSamlRequest()), sigTrustEngine); - - else - verifyIDPResponse(((MOAResponse)msg).getResponse(), sigTrustEngine); - - } catch (InvalidProtocolRequestException e) { - if (MiscUtil.isEmpty(msg.getEntityID())) { - throw e; - - } - Logger.debug("PVP2X message validation FAILED. Relead metadata for entityID: " + msg.getEntityID()); - - if (metadataProvider == null || !metadataProvider.refreshMetadataProvider(msg.getEntityID())) - throw e; - - else { - Logger.trace("PVP2X metadata reload finished. Check validate message again."); - - if (msg instanceof MOARequest && - ((MOARequest)msg).getSamlRequest() instanceof RequestAbstractType) - verifyRequest(((RequestAbstractType)((MOARequest)msg).getSamlRequest()), sigTrustEngine); - - else - verifyIDPResponse(((MOAResponse)msg).getResponse(), sigTrustEngine); - - } - Logger.trace("Second PVP2X message validation finished"); - } - } - - public void verifyIDPResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine) throws InvalidProtocolRequestException{ - verifyResponse(samlObj, sigTrustEngine, IDPSSODescriptor.DEFAULT_ELEMENT_NAME); - - } - - public void verifySLOResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine ) throws InvalidProtocolRequestException { - verifyResponse(samlObj, sigTrustEngine, SPSSODescriptor.DEFAULT_ELEMENT_NAME); - - } - - private void verifyResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine, QName defaultElementName) throws InvalidProtocolRequestException{ - SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); - performSchemaValidation(samlObj.getDOM()); - - } catch (ValidationException e) { - Logger.warn("Signature is not conform to SAML signature profile", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SchemaValidationException e) { - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(samlObj.getIssuer().getValue()) ); - criteriaSet.add( new MetadataCriteria(defaultElementName, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - - try { - if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } catch (org.opensaml.xml.security.SecurityException e) { - Logger.warn("PVP2x message signature validation FAILED.", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } - - public void verifyRequest(RequestAbstractType samlObj, SignatureTrustEngine sigTrustEngine ) throws InvalidProtocolRequestException { - SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); - try { - profileValidator.validate(samlObj.getSignature()); - performSchemaValidation(samlObj.getDOM()); - - } catch (ValidationException e) { - Logger.warn("Signature is not conform to SAML signature profile", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - - } catch (SchemaValidationException e) { - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - - } - - CriteriaSet criteriaSet = new CriteriaSet(); - criteriaSet.add( new EntityIDCriteria(samlObj.getIssuer().getValue()) ); - criteriaSet.add( new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS) ); - criteriaSet.add( new UsageCriteria(UsageType.SIGNING) ); - - try { - if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } catch (org.opensaml.xml.security.SecurityException e) { - Logger.warn("PVP2x message signature validation FAILED.", e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); - } - } - - protected void performSchemaValidation(Element source) throws SchemaValidationException { - - String err = null; - try { - Schema test = SAMLSchemaBuilder.getSAML11Schema(); - Validator val = test.newValidator(); - val.validate(new DOMSource(source)); - Logger.debug("Schema validation check done OK"); - return; - - } catch (SAXException e) { - err = e.getMessage(); - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) - Logger.warn("Schema validation FAILED with exception:", e); - else - Logger.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } catch (Exception e) { - err = e.getMessage(); - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) - Logger.warn("Schema validation FAILED with exception:", e); - else - Logger.warn("Schema validation FAILED with message: "+ e.getMessage()); - - } - - throw new SchemaValidationException("pvp2.22", new Object[]{err}); - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java index 385fe90fb..d1d8c9368 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java @@ -47,11 +47,12 @@ import org.opensaml.xml.validation.ValidationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import at.gv.egiz.eaaf.modules.pvp2.exception.SchemaValidationException; +import at.gv.egiz.eaaf.modules.pvp2.impl.verification.SAMLVerificationEngine; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionValidationExeption; import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; 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.protocols.pvp2x.exceptions.AssertionValidationExeption; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; import at.gv.egovernment.moa.logging.Logger; /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/TrustEngineFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/TrustEngineFactory.java deleted file mode 100644 index 3ea124db6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/TrustEngineFactory.java +++ /dev/null @@ -1,87 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.pvp2x.verification; - -import java.util.ArrayList; -import java.util.List; - -import org.opensaml.saml2.metadata.provider.MetadataProvider; -import org.opensaml.security.MetadataCredentialResolver; -import org.opensaml.xml.security.keyinfo.BasicProviderKeyInfoCredentialResolver; -import org.opensaml.xml.security.keyinfo.KeyInfoCredentialResolver; -import org.opensaml.xml.security.keyinfo.KeyInfoProvider; -import org.opensaml.xml.security.keyinfo.provider.DSAKeyValueProvider; -import org.opensaml.xml.security.keyinfo.provider.InlineX509DataProvider; -import org.opensaml.xml.security.keyinfo.provider.RSAKeyValueProvider; -import org.opensaml.xml.signature.SignatureTrustEngine; -import org.opensaml.xml.signature.impl.ExplicitKeySignatureTrustEngine; -//import org.opensaml.xml.signature.impl.PKIXSignatureTrustEngine; -//import edu.internet2.middleware.shibboleth.common.security.MetadataPKIXValidationInformationResolver; - -public class TrustEngineFactory { - -// public static SignatureTrustEngine getSignatureTrustEngine() { -// try { -// MetadataPKIXValidationInformationResolver mdResolver = new MetadataPKIXValidationInformationResolver( -// MOAMetadataProvider.getInstance()); -// -// List<KeyInfoProvider> keyInfoProvider = new ArrayList<KeyInfoProvider>(); -// keyInfoProvider.add(new DSAKeyValueProvider()); -// keyInfoProvider.add(new RSAKeyValueProvider()); -// keyInfoProvider.add(new InlineX509DataProvider()); -// -// KeyInfoCredentialResolver keyInfoResolver = new BasicProviderKeyInfoCredentialResolver( -// keyInfoProvider); -// -// PKIXSignatureTrustEngine engine = new PKIXSignatureTrustEngine( -// mdResolver, keyInfoResolver); -// -// return engine; -// -// } catch (Exception e) { -// e.printStackTrace(); -// return null; -// } -// } - - public static SignatureTrustEngine getSignatureKnownKeysTrustEngine(MetadataProvider provider) { - MetadataCredentialResolver resolver; - - resolver = new MetadataCredentialResolver(provider); - - List<KeyInfoProvider> keyInfoProvider = new ArrayList<KeyInfoProvider>(); - keyInfoProvider.add(new DSAKeyValueProvider()); - keyInfoProvider.add(new RSAKeyValueProvider()); - keyInfoProvider.add(new InlineX509DataProvider()); - - KeyInfoCredentialResolver keyInfoResolver = new BasicProviderKeyInfoCredentialResolver( - keyInfoProvider); - - ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine( - resolver, keyInfoResolver); - - return engine; - - } - -} 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 16b179d89..75ca2ccdf 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 @@ -33,11 +33,11 @@ import org.opensaml.saml2.metadata.provider.FilterException; import org.opensaml.saml2.metadata.provider.MetadataFilter; import org.opensaml.xml.XMLObject; +import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; import at.gv.egovernment.moa.id.auth.builder.SignatureVerificationUtils; import at.gv.egovernment.moa.id.commons.api.data.IVerifiyXMLSignatureResponse; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.MiscUtil; /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataSignatureFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataSignatureFilter.java index 589713c4b..57f1c2f9a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataSignatureFilter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataSignatureFilter.java @@ -23,23 +23,20 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata; import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; import org.opensaml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.provider.MetadataFilter; -import org.opensaml.xml.XMLObject; +import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.x509.BasicX509Credential; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SignatureValidationException; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; +import at.gv.egiz.eaaf.modules.pvp2.exception.PVP2MetadataException; +import at.gv.egiz.eaaf.modules.pvp2.impl.validation.metadata.AbstractMetadataSignatureFilter; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.EntityVerifier; import at.gv.egovernment.moa.logging.Logger; import iaik.x509.X509Certificate; -public class MetadataSignatureFilter implements MetadataFilter { +public class MetadataSignatureFilter extends AbstractMetadataSignatureFilter { private String metadataURL; private BasicX509Credential savedCredential; @@ -52,111 +49,52 @@ public class MetadataSignatureFilter implements MetadataFilter { savedCredential.setEntityCertificate(cert); } - public void processEntityDescriptorr(EntityDescriptor desc) throws MOAIDException { - -// String entityID = desc.getEntityID(); - - EntityVerifier.verify(desc); - } - - public void processEntitiesDescriptor(EntitiesDescriptor desc) throws MOAIDException { - Iterator<EntitiesDescriptor> entID = desc.getEntitiesDescriptors().iterator(); - - if(desc.getSignature() != null) { - EntityVerifier.verify(desc, this.savedCredential); + @Override + protected void verify(EntityDescriptor desc) throws PVP2MetadataException { + try { + EntityVerifier.verify(desc); + + } catch (EAAFException e) { + Logger.info("PVP2 metadata verification FAILED for entity: " + desc.getEntityID() + + " Reason: " + e.getMessage()); + throw new PVP2MetadataException("PVP2 metadata verification FAILED for entity: " + desc.getEntityID(), null, e); } - while(entID.hasNext()) { - processEntitiesDescriptor(entID.next()); - } - - Iterator<EntityDescriptor> entIT = desc.getEntityDescriptors().iterator(); + } - List<EntityDescriptor> verifiedEntIT = new ArrayList<EntityDescriptor>(); - - //check every Entity - - while(entIT.hasNext()) { - - EntityDescriptor entity = entIT.next(); - - String entityID = entity.getEntityID(); - - //CHECK if Entity also match MetaData signature. - /*This check is necessary to prepend declaration of counterfeit OA metadata!!*/ - Logger.debug("Validate metadata for entityID: " + entityID + " ..... "); - byte[] entityCert = EntityVerifier.fetchSavedCredential(entityID); - - if (entityCert != null) { + @Override + protected void verify(EntitiesDescriptor desc) throws PVP2MetadataException { + try { + EntityVerifier.verify(desc, this.savedCredential); - X509Certificate cert; - try { - cert = new X509Certificate(entityCert); - BasicX509Credential entityCrendential = new BasicX509Credential(); - entityCrendential.setEntityCertificate(cert); - - EntityVerifier.verify(desc, entityCrendential); - - //add entity to verified entity-list - verifiedEntIT.add(entity); - Logger.debug("Metadata for entityID: " + entityID + " valid"); - - - } catch (Exception e) { - - //remove entity of signature can not be verified. - Logger.info("Entity " + entityID + " is removed from metadata " - + desc.getName() + ". Entity verification error: " + e.getMessage()); -// throw new MOAIDException("The App", null, e); - } - - } else { - //remove entity if it is not registrated as OA - Logger.info("Entity " + entityID + " is removed from metadata " - + desc.getName() + ". Entity is not registrated or no certificate is found!"); -// throw new NoCredentialsException("NO Certificate found for OA " + entityID); - } + } catch (EAAFException e) { + Logger.info("PVP2 metadata verification FAILED for metadata from URL: " + metadataURL + + " Reason: " + e.getMessage()); + throw new PVP2MetadataException("PVP2 metadata verification FAILED for metadata from URL: " + metadataURL, null, e); - //TODO: insert to support signed Entity-Elements - //processEntityDescriptorr(entIT.next()); - } + } - //set only verified entity elements - desc.getEntityDescriptors().clear(); - desc.getEntityDescriptors().addAll(verifiedEntIT); } - - public void doFilter(XMLObject metadata) throws SignatureValidationException { + + @Override + protected void verify(EntityDescriptor entity, EntitiesDescriptor entities) throws PVP2MetadataException { try { - if (metadata instanceof EntitiesDescriptor) { - EntitiesDescriptor entitiesDescriptor = (EntitiesDescriptor) metadata; - if(entitiesDescriptor.getSignature() == null) { - throw new MOAIDException("Root element of metadata file has to be signed", null); - } - processEntitiesDescriptor(entitiesDescriptor); - - - if (entitiesDescriptor.getEntityDescriptors().size() == 0) { - throw new MOAIDException("No valid entity in metadata " - + entitiesDescriptor.getName() + ". Metadata is not loaded.", null); - } - - - } else if (metadata instanceof EntityDescriptor) { - EntityDescriptor entityDescriptor = (EntityDescriptor) metadata; - processEntityDescriptorr(entityDescriptor); + if (entity.isSigned()) { + Logger.debug("EntityDescriptor: " + entity.getEntityID() + " is signed. Starting signature verification ... "); + EntityVerifier.verify(entity); } else { - throw new MOAIDException("Invalid Metadata file Root element is no EntitiesDescriptor", null); + Logger.debug("EntityDescriptor: " + entity.getEntityID() + " is not signed. Verify EntitiesDescriptor by using 'Entity' certificate ... "); + Credential entityCredential = EntityVerifier.getSPTrustedCredential(entity.getEntityID()); + EntityVerifier.verify(entities, entityCredential); + } + } catch (EAAFException e) { + Logger.info("PVP2 metadata verification FAILED for metadata from URL: " + metadataURL + + " Reason: " + e.getMessage()); + throw new PVP2MetadataException("PVP2 metadata verification FAILED for metadata from URL: " + metadataURL, null, e); - - Logger.info("Metadata signature policy check done OK"); - } catch (MOAIDException e) { - Logger.warn("Metadata signature policy check FAILED.", e); - throw new SignatureValidationException(e); } } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPEntityCategoryFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPEntityCategoryFilter.java deleted file mode 100644 index caabfea30..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPEntityCategoryFilter.java +++ /dev/null @@ -1,230 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata; - -import java.util.ArrayList; -import java.util.List; - -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.common.Extensions; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.metadata.AttributeConsumingService; -import org.opensaml.saml2.metadata.EntitiesDescriptor; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.LocalizedString; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.ServiceName; -import org.opensaml.saml2.metadata.provider.FilterException; -import org.opensaml.saml2.metadata.provider.MetadataFilter; -import org.opensaml.samlext.saml2mdattr.EntityAttributes; -import org.opensaml.xml.XMLObject; - -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.data.Trible; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moaspss.logging.Logger; - -/** - * @author tlenz - * - */ -public class PVPEntityCategoryFilter implements MetadataFilter { - - - private boolean isUsed = false; - - /** - * Filter to map PVP EntityCategories into a set of single PVP attributes - * - * @param isUsed if true PVP EntityCategories are mapped, otherwise they are ignored - * - */ - public PVPEntityCategoryFilter(boolean isUsed) { - this.isUsed = isUsed; - } - - - /* (non-Javadoc) - * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) - */ - @Override - public void doFilter(XMLObject metadata) throws FilterException { - - if (isUsed) { - Logger.trace("Map PVP EntityCategory to single PVP Attributes ... "); - String entityId = null; - try { - if (metadata instanceof EntitiesDescriptor) { - Logger.trace("Find EnitiesDescriptor ... "); - EntitiesDescriptor entitiesDesc = (EntitiesDescriptor) metadata; - if (entitiesDesc.getEntityDescriptors() != null) { - for (EntityDescriptor el : entitiesDesc.getEntityDescriptors()) - resolveEntityCategoriesToAttributes(el); - - } - - } else if (metadata instanceof EntityDescriptor) { - Logger.trace("Find EntityDescriptor"); - resolveEntityCategoriesToAttributes((EntityDescriptor)metadata); - - - } else - throw new MOAIDException("Invalid Metadata file Root element is no Entities- or EntityDescriptor", null); - - - - } catch (Exception e) { - Logger.warn("SAML2 Metadata processing FAILED: Can not resolve EntityCategories for metadata: " + entityId, e); - - } - - } else - Logger.trace("Filter to map PVP EntityCategory to single PVP Attributes is deactivated"); - - } - - private void resolveEntityCategoriesToAttributes(EntityDescriptor metadata) { - Logger.debug("Resolving EntityCategorie for Entity: " + metadata.getEntityID() + " ..."); - Extensions extensions = metadata.getExtensions(); - if (extensions != null) { - List<XMLObject> listOfExt = extensions.getUnknownXMLObjects(); - if (listOfExt != null && !listOfExt.isEmpty()) { - Logger.trace("Find #" + listOfExt.size() + " 'Extension' elements "); - for (XMLObject el : listOfExt) { - Logger.trace("Find ExtensionElement: " + el.getElementQName().toString()); - if (el instanceof EntityAttributes) { - EntityAttributes entityAttrElem = (EntityAttributes)el; - if (entityAttrElem.getAttributes() != null) { - Logger.trace("Find EntityAttributes. Start attribute processing ..."); - for (Attribute entityAttr : entityAttrElem.getAttributes()) { - if (entityAttr.getName().equals(PVPConstants.ENTITY_CATEGORY_ATTRIBITE)) { - if (!entityAttr.getAttributeValues().isEmpty()) { - String entityAttrValue = entityAttr.getAttributeValues().get(0).getDOM().getTextContent(); - if (PVPConstants.EGOVTOKEN.equals(entityAttrValue)) { - Logger.debug("Find 'EGOVTOKEN' EntityAttribute. Adding single pvp attributes ... "); - addAttributesToEntityDescriptor(metadata, - buildAttributeList(PVPConstants.EGOVTOKEN_PVP_ATTRIBUTES), - entityAttrValue); - - - } else if (PVPConstants.CITIZENTOKEN.equals(entityAttrValue)) { - Logger.debug("Find 'CITIZENTOKEN' EntityAttribute. Adding single pvp attributes ... "); - addAttributesToEntityDescriptor(metadata, - buildAttributeList(PVPConstants.CITIZENTOKEN_PVP_ATTRIBUTES), - entityAttrValue); - - } else - Logger.info("EntityAttributeValue: " + entityAttrValue + " is UNKNOWN!"); - - } else - Logger.info("EntityAttribute: No attribute value"); - - } else - Logger.info("EntityAttribute: " + entityAttr.getName() + " is NOT supported"); - - } - - } else - Logger.info("Can NOT resolve EntityAttributes! Reason: Only EntityAttributes are supported!"); - - } - } - - } else - Logger.trace("'Extension' element is 'null' or empty"); - - } else - Logger.trace("No 'Extension' element found"); - - } - - /** - * @param metadata - * @param attrList - */ - private void addAttributesToEntityDescriptor(EntityDescriptor metadata, List<RequestedAttribute> attrList, String entityAttr) { - SPSSODescriptor spSSODesc = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); - if (spSSODesc != null) { - if (spSSODesc.getAttributeConsumingServices() == null || - spSSODesc.getAttributeConsumingServices().isEmpty()) { - Logger.trace("No 'AttributeConsumingServices' found. Added it ..."); - - AttributeConsumingService attributeService = SAML2Utils.createSAMLObject(AttributeConsumingService.class); - attributeService.setIndex(0); - attributeService.setIsDefault(true); - ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); - serviceName.setName(new LocalizedString("Default Service", "en")); - attributeService.getNames().add(serviceName); - - if (attrList != null && !attrList.isEmpty()) { - attributeService.getRequestAttributes().addAll(attrList); - Logger.info("Add " + attrList.size() + " attributes for 'EntityAttribute': " + entityAttr); - - } - - spSSODesc.getAttributeConsumingServices().add(attributeService); - - } else { - Logger.debug("Find 'AttributeConsumingServices'. Starting updating process ... "); - for (AttributeConsumingService el : spSSODesc.getAttributeConsumingServices()) { - Logger.debug("Update 'AttributeConsumingService' with Index: " + el.getIndex()); - - //load currently requested attributes - List<String> currentlyReqAttr = new ArrayList<String>(); - for (RequestedAttribute reqAttr : el.getRequestAttributes()) - currentlyReqAttr.add(reqAttr.getName()); - - - //check against EntityAttribute List - for (RequestedAttribute entityAttrListEl : attrList) { - if (!currentlyReqAttr.contains(entityAttrListEl.getName())) { - el.getRequestAttributes().add(entityAttrListEl); - - } else - Logger.debug("'AttributeConsumingService' already contains attr: " + entityAttrListEl.getName()); - - } - - } - - } - - } else - Logger.info("Can ONLY add 'EntityAttributes' to 'SPSSODescriptor'"); - - } - - private List<RequestedAttribute> buildAttributeList(List<Trible<String, String, Boolean>> attrSet) { - List<RequestedAttribute> requestedAttributes = new ArrayList<RequestedAttribute>(); - for (Trible<String, String, Boolean> el : attrSet) - requestedAttributes.add(PVPAttributeBuilder.buildReqAttribute(el.getFirst(), el.getSecond(), el.getThird())); - - return requestedAttributes; - - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPMetadataFilterChain.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPMetadataFilterChain.java index 4c1da747b..615a0eaa7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPMetadataFilterChain.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPMetadataFilterChain.java @@ -24,7 +24,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata; import java.security.cert.CertificateException; -import at.gv.egovernment.moa.id.saml2.MetadataFilterChain; +import at.gv.egiz.eaaf.modules.pvp2.impl.metadata.MetadataFilterChain; /** * @author tlenz diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java deleted file mode 100644 index 83a2b61d2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/SchemaValidationFilter.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata; - -import javax.xml.transform.dom.DOMSource; -import javax.xml.validation.Schema; -import javax.xml.validation.Validator; - -import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.saml2.metadata.provider.MetadataFilter; -import org.opensaml.xml.XMLObject; -import org.xml.sax.SAXException; - -import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SchemaValidationException; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -public class SchemaValidationFilter implements MetadataFilter { - - private boolean isActive = true; - - public SchemaValidationFilter() { - try { - isActive = AuthConfigurationProviderFactory.getInstance().isPVPSchemaValidationActive(); - - } catch (ConfigurationException e) { - e.printStackTrace(); - } - } - - /** - * - */ - public SchemaValidationFilter(boolean useSchemaValidation) { - this.isActive = useSchemaValidation; - } - - - /* (non-Javadoc) - * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) - */ - @Override - public void doFilter(XMLObject arg0) throws SchemaValidationException { - - String errString = null; - - if (isActive) { - try { - Schema test = SAMLSchemaBuilder.getSAML11Schema(); - Validator val = test.newValidator(); - DOMSource source = new DOMSource(arg0.getDOM()); - val.validate(source); - Logger.info("Metadata Schema validation check done OK"); - return; - - } catch (SAXException e) { - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) - Logger.warn("Metadata Schema validation FAILED with exception:", e); - else - Logger.warn("Metadata Schema validation FAILED with message: "+ e.getMessage()); - - errString = e.getMessage(); - - } catch (Exception e) { - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) - Logger.warn("Metadata Schema validation FAILED with exception:", e); - else - Logger.warn("Metadata Schema validation FAILED with message: "+ e.getMessage()); - - errString = e.getMessage(); - - } - - throw new SchemaValidationException("Metadata Schema validation FAILED with message: "+ errString); - - } else - Logger.info("Metadata Schema validation check is DEACTIVATED!"); - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/saml2/MetadataFilterChain.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/saml2/MetadataFilterChain.java deleted file mode 100644 index e7412a0fc..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/saml2/MetadataFilterChain.java +++ /dev/null @@ -1,73 +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.saml2; - -import java.util.ArrayList; -import java.util.List; - -import org.opensaml.saml2.metadata.provider.FilterException; -import org.opensaml.saml2.metadata.provider.MetadataFilter; -import org.opensaml.xml.XMLObject; - -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -public class MetadataFilterChain implements MetadataFilter { - - private List<MetadataFilter> filters = new ArrayList<MetadataFilter>(); - - /** - * Return all actually used Metadata filters - * - * @return List of Metadata filters - */ - public List<MetadataFilter> getFilters() { - return filters; - } - - /** - * Add a new Metadata filter to filterchain - * - * @param filter - */ - public void addFilter(MetadataFilter filter) { - filters.add(filter); - } - - - /* (non-Javadoc) - * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) - */ - @Override - public void doFilter(XMLObject arg0) throws FilterException { - for (MetadataFilter filter : filters) { - Logger.trace("Use MOAMetadataFilter " + filter.getClass().getName()); - filter.doFilter(arg0); - } - - } - -} 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 0df6379b0..405e44112 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 @@ -40,13 +40,19 @@ import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.core.JsonProcessingException; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.core.impl.utils.Random; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionAttributeExtractorExeption; +import at.gv.egiz.eaaf.modules.pvp2.sp.impl.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionWrapper; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; 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.data.IAuthenticationSession; import at.gv.egovernment.moa.id.commons.db.dao.session.AuthenticatedSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; @@ -54,11 +60,8 @@ import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OldSSOSessionIDStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.commons.utils.JsonMapper; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameterDecorator; import at.gv.egovernment.moa.id.data.EncryptedData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; -import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.id.util.SessionEncrytionUtil; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -68,35 +71,18 @@ import at.gv.egovernment.moa.util.MiscUtil; public class DBAuthenticationSessionStoreage implements IAuthenticationSessionStoreage{ @PersistenceContext(unitName="session") - private EntityManager entityManager; + private EntityManager entityManager; @Autowired AuthConfiguration authConfig; private static JsonMapper mapper = new JsonMapper(); - - //@Autowired MOASessionDBUtils moaSessionDBUtils; - - @Override - public boolean isAuthenticated(String internalSsoSessionID) { - - AuthenticatedSessionStore session; - try { - session = searchInDatabase(internalSsoSessionID); - return session.isAuthenticated(); - - } catch (MOADatabaseException e) { - return false; - } - } - @Override public AuthenticationSession createInternalSSOSession(IRequest target) throws MOADatabaseException, BuildException { String id = Random.nextLongRandom(); try { AuthenticatedSessionStore dbsession = new AuthenticatedSessionStore(); dbsession.setSessionid(id); - dbsession.setAuthenticated(false); //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1 Date now = new Date(); @@ -106,9 +92,10 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt //set additional session informations AuthenticationSessionExtensions sessionExt = new AuthenticationSessionExtensions(); sessionExt.setUniqueSessionId(target.getUniqueSessionIdentifier()); - dbsession.setAdditionalInformation(mapper.serialize(sessionExt).getBytes("UTF-8")); + dbsession.setAdditionalInformationBytes(mapper.serialize(sessionExt).getBytes("UTF-8")); - AuthenticationSession session = new AuthenticationSession(id, now, target.getMOASession()); + AuthenticationSession session = new AuthenticationSession(id, now, + (IAuthenticationSession)target.getSessionData(AuthenticationSessionWrapper.class)); encryptSession(session, dbsession); //store AssertionStore element to Database @@ -123,7 +110,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } catch (JsonProcessingException | UnsupportedEncodingException e) { Logger.warn("Extended session information can not be stored.", e); - throw new MOADatabaseException(e); + throw new MOADatabaseException("Extended session information can not be stored.", e); } @@ -153,9 +140,9 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt public AuthenticationSessionExtensions getAuthenticationSessionExtensions(String sessionID) throws MOADatabaseException { AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); - if (MiscUtil.isNotEmpty(dbsession.getAdditionalInformation())) { + if (dbsession.getAdditionalInformationBytes() != null) { try { - return (AuthenticationSessionExtensions)mapper.deserialize(new String(dbsession.getAdditionalInformation(), "UTF-8"), + return (AuthenticationSessionExtensions)mapper.deserialize(new String(dbsession.getAdditionalInformationBytes(), "UTF-8"), AuthenticationSessionExtensions.class); } catch (Exception e) { @@ -171,7 +158,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt try { AuthenticatedSessionStore dbsession = searchInDatabase(sessionID); - dbsession.setAdditionalInformation( + dbsession.setAdditionalInformationBytes( mapper.serialize(sessionExtensions).getBytes("UTF-8")); entityManager.merge(dbsession); @@ -180,7 +167,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } catch (MOADatabaseException e) { Logger.warn("MOASession could not be stored."); - throw new MOADatabaseException(e); + throw new MOADatabaseException("MOASession could not be stored.", e); } catch (JsonProcessingException | UnsupportedEncodingException e) { Logger.warn("Extended session information can not be stored.", e); @@ -228,12 +215,12 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } @Override - public AuthenticationSession getInternalMOASessionWithSSOID(String SSOSessionID) throws MOADatabaseException { - MiscUtil.assertNotNull(SSOSessionID, "SSOsessionID"); - Logger.trace("Get authenticated session with SSOID " + SSOSessionID + " from database."); + public String getInternalSSOSessionWithSSOID(String externelSSOId) throws MOADatabaseException { + MiscUtil.assertNotNull(externelSSOId, "SSOsessionID"); + Logger.trace("Get authenticated session with SSOID " + externelSSOId + " from database."); Query query = entityManager.createNamedQuery("getSessionWithSSOID"); - query.setParameter("sessionid", SSOSessionID); + query.setParameter("sessionid", externelSSOId); List<AuthenticatedSessionStore> results = query.getResultList(); Logger.trace("Found entries: " + results.size()); @@ -245,7 +232,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } else try { - return decryptSession(results.get(0)); + return decryptSession(results.get(0)).getSSOSessionID(); } catch (Throwable e) { Logger.warn("MOASession deserialization-exception by using internal MOASessionID=" + results.get(0).getSessionid(), e); @@ -290,11 +277,11 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } @Override - public void addSSOInformation(String moaSessionID, String SSOSessionID, + public void addSSOInformation(String internalSSOSessionID, String externalSSOSessionID, SLOInformationInterface SLOInfo, IRequest protocolRequest) throws AuthenticationException { Query query = entityManager.createNamedQuery("getSessionWithID"); - query.setParameter("sessionid", moaSessionID); + query.setParameter("sessionid", internalSSOSessionID); List<AuthenticatedSessionStore> results = query.getResultList(); Logger.trace("Found entries: " + results.size()); @@ -312,7 +299,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt //check if OA already has an active OA session if (dbsession.getActiveOAsessions() != null) { for (OASessionStore el : dbsession.getActiveOAsessions()) { - if (el.getOaurlprefix().equals(protocolRequest.getOAURL())) + if (el.getOaurlprefix().equals(protocolRequest.getSPEntityId())) activeOA = el; } } @@ -321,7 +308,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt activeOA = new OASessionStore(); //set active OA applications - activeOA.setOaurlprefix(protocolRequest.getOAURL()); + activeOA.setOaurlprefix(protocolRequest.getSPEntityId()); activeOA.setMoasession(dbsession); activeOA.setCreated(new Date()); @@ -353,28 +340,28 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } dbsession.setSSOSession(true); - dbsession.setSSOsessionid(SSOSessionID); - dbsession.setAuthenticated(false); + dbsession.setSSOsessionid(externalSSOSessionID); + dbsession.setAuthenticated(true); //Store MOASession entityManager.merge(dbsession); if (SLOInfo != null) - Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getOAURL() + Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getSPEntityId() + " and AssertionID: " + SLOInfo.getSessionIndex()); else - Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getOAURL()); + Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getSPEntityId()); } @Override - public List<OASessionStore> getAllActiveOAFromMOASession(IAuthenticationSession moaSession) { - MiscUtil.assertNotNull(moaSession, "MOASession"); + public List<OASessionStore> getAllActiveOAFromMOASession(String ssoSessionId) { + MiscUtil.assertNotNull( ssoSessionId, "MOASession"); - Logger.trace("Get OAs for moaSession " + moaSession.getSessionID() + " from database."); + Logger.trace("Get OAs for moaSession " + ssoSessionId + " from database."); Query query = entityManager.createNamedQuery("getAllActiveOAsForSessionID"); - query.setParameter("sessionID", moaSession.getSessionID()); + query.setParameter("sessionID", ssoSessionId); List<OASessionStore> results = query.getResultList(); Logger.trace("Found entries: " + results.size()); @@ -384,13 +371,13 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } @Override - public List<InterfederationSessionStore> getAllActiveIDPsFromMOASession(IAuthenticationSession moaSession) { - MiscUtil.assertNotNull(moaSession, "MOASession"); + public List<InterfederationSessionStore> getAllActiveIDPsFromMOASession(String ssoSessionId) { + MiscUtil.assertNotNull( ssoSessionId, "MOASession"); - Logger.trace("Get active IDPs for moaSession " + moaSession.getSessionID() + " from database."); + Logger.trace("Get active IDPs for moaSession " + ssoSessionId + " from database."); Query query = entityManager.createNamedQuery("getAllActiveIDPsForSessionID"); - query.setParameter("sessionID", moaSession.getSessionID()); + query.setParameter("sessionID", ssoSessionId); List<InterfederationSessionStore> results = query.getResultList(); Logger.trace("Found entries: " + results.size()); @@ -399,7 +386,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } @Override - public IAuthenticationSession searchMOASessionWithNameIDandOAID(String oaID, String userNameID) { + public String searchSSOSessionWithNameIDandOAID(String oaID, String userNameID) { MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier"); MiscUtil.assertNotNull(userNameID, "userNameID"); Logger.trace("Get moaSession for userNameID " + userNameID + " and OA " @@ -419,8 +406,10 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } - try { - return decryptSession(results.get(0)); + try { + AuthenticationSession decrytedSession = decryptSession(results.get(0)); + + return decrytedSession.getSSOSessionID(); } catch (BuildException e) { Logger.warn("MOASession deserialization-exception by using MOASessionID=" + results.get(0).getSessionid(), e); @@ -434,11 +423,11 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt MiscUtil.assertNotNull(moaSession, "MOASession"); MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier"); MiscUtil.assertNotNull(protocolType, "usedProtocol"); - Logger.trace("Get active OnlineApplication for sessionID " + moaSession.getSessionID() + " with OAID " + Logger.trace("Get active OnlineApplication for sessionID " + moaSession.getSSOSessionID() + " with OAID " + oaID + " from database."); Query query = entityManager.createNamedQuery("getActiveOAWithSessionIDandOAIDandProtocol"); - query.setParameter("sessionID", moaSession.getSessionID()); + query.setParameter("sessionID", moaSession.getSSOSessionID()); query.setParameter("oaID", oaID); query.setParameter("protocol", protocolType); List<AuthenticatedSessionStore> results = query.getResultList(); @@ -545,25 +534,25 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } @Override - public void addFederatedSessionInformation(IRequest req, String idpEntityID, AssertionAttributeExtractor extractor) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException { + public void addFederatedSessionInformation(IRequest req, String idpEntityID, AssertionAttributeExtractor extractor) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException, EAAFConfigurationException { AuthenticatedSessionStore dbsession = null; - AuthenticationSession moaSession = null; + String internalSSOSessionId = null; Date now = new Date(); //search for active session if (MiscUtil.isNotEmpty(req.getInternalSSOSessionIdentifier())) { Logger.debug("Internal SSO-Session object: " + req.getInternalSSOSessionIdentifier() + " used for federated SSO"); - moaSession = getInternalMOASessionWithSSOID(req.getInternalSSOSessionIdentifier()); + internalSSOSessionId = req.getInternalSSOSessionIdentifier(); } else { Logger.debug("No internal SSO-Session object exists for federated SSO --> create new session object"); - moaSession = createInternalSSOSession(req); + internalSSOSessionId = createInternalSSOSession(req).getSSOSessionID(); } - if (moaSession != null) { + if (MiscUtil.isNotEmpty(internalSSOSessionId)) { try { - dbsession = searchInDatabase(moaSession.getSessionID()); + dbsession = searchInDatabase(internalSSOSessionId); }catch (MOADatabaseException e) { Logger.error("NO MOASession found but MOASession MUST already exist!"); @@ -617,7 +606,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt idp.setIdpurlprefix(idpEntityID); idp.setAuthURL(req.getAuthURL()); - IOAAuthParameters oa = authConfig.getOnlineApplicationParameter(idp.getIdpurlprefix()); + IOAAuthParameters oa = authConfig.getServiceProviderConfiguration(idp.getIdpurlprefix(), OAAuthParameterDecorator.class); idp.setStoreSSOInformation(oa.isInterfederationSSOStorageAllowed()); idp.setMoasession(dbsession); idpList.add(idp); @@ -793,7 +782,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt Query query = entityManager.createNamedQuery("getSSOSessionWithOldSessionID"); query.setParameter("sessionid", ssoId); List<OldSSOSessionIDStore> results = query.getResultList(); - + Logger.trace("Found entries: " + results.size()); // Assertion requires an unique artifact 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 2395b913d..61c83aaf2 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 @@ -37,6 +37,7 @@ import org.hibernate.HibernateException; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; @@ -240,15 +241,22 @@ public class DBTransactionStorage implements ITransactionStorage { } } - public Object getAssertionStore(String key) throws MOADatabaseException{ + @Override + public Object getRaw(String key) throws MOADatabaseException { return searchInDatabase(key); } @Override - public void putAssertionStore(Object element) throws MOADatabaseException{ - entityManager.merge(element); + public void putRaw(String key, Object element) throws MOADatabaseException { + if (element instanceof AssertionStore) + entityManager.merge(element); + else { + Logger.error("Can not persist Object of type: " + element.getClass().getName()); + throw new RuntimeException("Can not persist Object of type: " + element.getClass().getName()); + + } } private void cleanDelete(AssertionStore element) { @@ -310,7 +318,7 @@ public class DBTransactionStorage implements ITransactionStorage { } catch (BuildException e) { Logger.warn("Sessioninformation could not be stored."); - throw new MOADatabaseException(e); + throw new MOADatabaseException("Can not store data into transaction-storage", e); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IAuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IAuthenticationSessionStoreage.java index c8d09e17e..add697a85 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IAuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IAuthenticationSessionStoreage.java @@ -25,34 +25,27 @@ package at.gv.egovernment.moa.id.storage; import java.util.Date; import java.util.List; +import at.gv.egiz.eaaf.core.api.IRequest; +import at.gv.egiz.eaaf.core.api.idp.slo.SLOInformationInterface; +import at.gv.egiz.eaaf.core.exceptions.EAAFConfigurationException; +import at.gv.egiz.eaaf.modules.pvp2.sp.exception.AssertionAttributeExtractorExeption; +import at.gv.egiz.eaaf.modules.pvp2.sp.impl.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.id.commons.api.IRequest; import at.gv.egovernment.moa.id.commons.api.data.IAuthenticationSession; import at.gv.egovernment.moa.id.commons.db.dao.session.AuthenticatedSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OldSSOSessionIDStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; /** * @author tlenz * */ public interface IAuthenticationSessionStoreage { - - /** - * Check if the stored MOASession is already authenticated - * - * @param internalSsoSessionID Internal MOA SSO-Session identifier - * @return true if the MOASession is authenticated, otherwise false - */ - public boolean isAuthenticated(String internalSsoSessionID); /** * Create a new MOA SSO-Session object in database @@ -110,13 +103,13 @@ public interface IAuthenticationSessionStoreage { public void setAuthenticated(String internalSsoSessionID, boolean isAuthenticated); /** - * Find the MOASessionId of an active Single Sign-On session + * Find the internal SSO session identifier of an active Single Sign-On session * - * @param SSOSessionID Single Sign-On sessionID - * @return internal MOA SSO-Session of the associated SSO-Session Id + * @param externelSSOId external Single Sign-On sessionID + * @return internal SSO-Session identifier * @throws MOADatabaseException */ - public AuthenticationSession getInternalMOASessionWithSSOID(String SSOSessionID) throws MOADatabaseException; + public String getInternalSSOSessionWithSSOID(String externelSSOId) throws MOADatabaseException; /** * Check if a MOASession is an active Single Sign-On session @@ -151,28 +144,28 @@ public interface IAuthenticationSessionStoreage { /** * Get all Single Sign-On authenticated Service-Provider of a MOASession * - * @param moaSession MOASession data object + * @param ssoSessionId SSO session id * @return List of Service-Provider information */ - public List<OASessionStore> getAllActiveOAFromMOASession(IAuthenticationSession moaSession); + public List<OASessionStore> getAllActiveOAFromMOASession(String ssoSessionId); /** * Get all active interfederation connections for a MOASession * - * @param moaSession MOASession data object + * @param ssoSessionId SSO session id * @return List of Interfederation-IDP information */ - public List<InterfederationSessionStore> getAllActiveIDPsFromMOASession(IAuthenticationSession moaSession); + public List<InterfederationSessionStore> getAllActiveIDPsFromMOASession(String ssoSessionId); /** - * Search a MOASession by using already transfered authentication information + * Search a SSO session by using already transfered authentication information * * @param oaID Service-Provider identifier, which has received the authentication information * @param userNameID UserId (bPK), which was send to this Service-Provider - * @return MOASession, or null if no corresponding MOASession is found + * @return SSO-session identifier, or null if no corresponding SSO session is found */ - public IAuthenticationSession searchMOASessionWithNameIDandOAID(String oaID, String userNameID); + public String searchSSOSessionWithNameIDandOAID(String oaID, String userNameID); /** * Search a active Single Sign-On session for a specific Service-Provider @@ -220,8 +213,9 @@ public interface IAuthenticationSessionStoreage { * @throws MOADatabaseException * @throws AssertionAttributeExtractorExeption * @throws BuildException + * @throws EAAFConfigurationException */ - public void addFederatedSessionInformation(IRequest req, String idpEntityID, AssertionAttributeExtractor extractor) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException; + public void addFederatedSessionInformation(IRequest req, String idpEntityID, AssertionAttributeExtractor extractor) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException, EAAFConfigurationException; /** * Search an active federation IDP which could be used for federated Single Sign-On by using an AttributeQuery 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 deleted file mode 100644 index 51a36d426..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java +++ /dev/null @@ -1,135 +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.storage; - -import java.util.Date; -import java.util.List; - -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; - -/** - * @author tlenz - * - */ -public interface ITransactionStorage { - - /** - * Check if transaction storage contains a data object with a specific key - * - * @param key Key, which identifies a data object - * @return true if key is found, otherwise false - */ - public boolean containsKey(String key); - - /** - * Store a data object with a key to transaction storage - * - * @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, int timeout_ms) throws MOADatabaseException; - - /** - * Get a data object from transaction storage - * - * @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 get(String key) throws MOADatabaseException; - - /** - * Get a data object from transaction storage - * - * @param key Id which identifiers the data object - * @param clazz The class type which is stored with this key - * @return The transaction-data object from type class, or null - * @throws MOADatabaseException In case of load operation failed - */ - public <T> T get(String key, final Class<T> clazz) throws MOADatabaseException; - - /** - * Get a data object from transaction storage - * - * @param key Id which identifiers the data object - * @param clazz The class type which is stored with this key - * @param Data-object timeout in [ms] - * @return The transaction-data object from type class, or null - * @throws MOADatabaseException In case of load operation failed - * @throws AuthenticationException In case of data-object timeout occurs - */ - public <T> T get(String key, final Class<T> clazz, long dataTimeOut) throws MOADatabaseException, AuthenticationException; - - - /** - * Change the key of a data object and store it under the new key - * - * @param oldKey Old key of the data object - * @param newKey New key, which should be used to store the data object - * @param value Data object which should be stored - * @throws MOADatabaseException In case of store operation failed - */ - public void changeKey(String oldKey, String newKey, Object value) throws MOADatabaseException; - - /** - * Remove a data object from transaction storage - * - * @param key Id which identifiers the data object - */ - public void remove(String key); - - /** - * Get all entries for Clean-up the transaction storage - * - * @param now Current time - * @param dataTimeOut Data-object timeout in [ms] - * @return List of entry-keys which as a timeout - */ - public List<String> clean(Date now, long dataTimeOut); - - - /** - * Get whole AssertionStoreObject, required for SLO - * <br> - * <b>IMPORTANT:</b> This method does NOT decrypt information before storage - * - * @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 - * <br> - * <b>IMPORTANT:</b> This method does NOT encrypt information before storage - * - * @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 index 2b9a6656b..8d36e81bb 100644 --- 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 @@ -39,6 +39,8 @@ import org.springframework.data.redis.core.SessionCallback; import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer; import org.springframework.stereotype.Service; +import at.gv.egiz.eaaf.core.api.storage.ITransactionStorage; +import at.gv.egiz.eaaf.core.exceptions.EAAFException; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; @@ -351,12 +353,13 @@ private AssertionStore prepareAssertion(AssertionStore element, String key, Obje } @Override -public Object getAssertionStore(String key) throws MOADatabaseException { +public Object getRaw(String key) throws EAAFException { return searchInDatabase(key); + } @Override -public void putAssertionStore(Object element) throws MOADatabaseException { +public void putRaw(String key, Object element) throws EAAFException { // TODO Auto-generated method stub AssertionStore as = (AssertionStore)element; final int expTime = redisTemplate.getExpire(as.getArtifact(), TimeUnit.MILLISECONDS).intValue(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/AbstractEncrytionUtil.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/AbstractEncrytionUtil.java index 84d40f619..8fdf1eab8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/AbstractEncrytionUtil.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/AbstractEncrytionUtil.java @@ -37,6 +37,7 @@ import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; +import at.gv.egiz.eaaf.core.impl.utils.Random; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.auth.exception.DatabaseEncryptionException; import at.gv.egovernment.moa.id.data.EncryptedData; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ErrorResponseUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ErrorResponseUtils.java deleted file mode 100644 index 655675f00..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ErrorResponseUtils.java +++ /dev/null @@ -1,105 +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.util; - -import java.util.Locale; - -import at.gv.egovernment.moa.id.auth.exception.BKUException; -import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; -import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.util.Messages; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ -public class ErrorResponseUtils { - - public static final String INTERNALERRORCODE = "9199"; - - private static ErrorResponseUtils instance = null; - private static final String[] DEFAULT_MESSAGE_RESOURCES = - { "resources/properties/protocol_response_statuscodes" }; - private static final Locale[] DEFAULT_MESSAGE_LOCALES = - new Locale[] { new Locale("de", "AT") }; - private Messages messages = null; - - - public static ErrorResponseUtils getInstance() { - if (instance == null) { - instance = new ErrorResponseUtils(DEFAULT_MESSAGE_RESOURCES, DEFAULT_MESSAGE_LOCALES); - - } - return instance; - } - - private ErrorResponseUtils(String[] resourceNames, Locale[] locales) { - this.messages = new Messages(resourceNames, locales); - } - - public String getResponseErrorCode(Throwable throwable) { - String errorCode = null; - - if (throwable instanceof BKUException) { - BKUException error = (BKUException) throwable; - errorCode = mapInternalErrorToExternalError(error.getMessageId()) + - error.getBkuErrorCode(); - - } else if (throwable instanceof MISSimpleClientException) { - MISSimpleClientException error = (MISSimpleClientException) throwable; - - if (MiscUtil.isNotEmpty(error.getMISErrorCode())) - errorCode = mapInternalErrorToExternalError(error.getMessageId()) + - error.getMISErrorCode(); - else - errorCode = mapInternalErrorToExternalError(error.getMessageId()); - - } else if (throwable instanceof MOAIDException) { - MOAIDException error = (MOAIDException) throwable; - errorCode = mapInternalErrorToExternalError(error.getMessageId()); - - } else if (throwable instanceof ProcessExecutionException) { - errorCode = "1100"; - - } else { - errorCode = INTERNALERRORCODE; - - } - - return errorCode; - - } - - public String mapInternalErrorToExternalError(String intErrorCode) { - String extErrorCode = messages.getMessage(intErrorCode, null); - - if (MiscUtil.isEmpty(extErrorCode)) - extErrorCode = INTERNALERRORCODE; - - return extErrorCode; - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/HTTPUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/HTTPUtils.java deleted file mode 100644 index 4cb6af127..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/HTTPUtils.java +++ /dev/null @@ -1,196 +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. - ******************************************************************************/ -/* - * 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; - -/** - * HTTP Utilities - * - * @author Rudolf Schamberger - * @version $Id$ - */ - -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.net.HttpURLConnection; -import java.net.URL; - -import javax.servlet.http.HttpServletRequest; - -import org.apache.regexp.RE; -import org.apache.regexp.RESyntaxException; - -import at.gv.egovernment.moa.util.StringUtils; - -/** - * - * @author Rudolf Schamberger - * - */ -public class HTTPUtils { - - /** - * Utility used to obtainin correct encoded HTTP content. - * Reads a given Content adressed by HTTP-URL into String. - * Content encoding is considered by using the Content-Type HTTP header charset value. - * @param URL HTTP URL to read from. - * @return String representation of content - * @throws IOException on data-reading problems - */ - public static String readHttpURL(String URL) - throws IOException { - - URL url = new URL(URL); - HttpURLConnection conn = (HttpURLConnection)url.openConnection(); - conn.setRequestMethod("GET"); - String contentType = conn.getContentType(); - RE regExp = null; - try { - regExp = new RE("(;.*charset=)(\"*)(.*[^\"])"); - } catch (RESyntaxException e) { - //RESyntaxException is not possible = expr. is costant - } - boolean charsetSupplied = regExp.match(contentType); - String encoding = "ISO-8859-1"; //default HTTP encoding - if (charsetSupplied) { - encoding = regExp.getParen(3); - } - InputStream instream = new BufferedInputStream(conn.getInputStream()); - InputStreamReader isr = new InputStreamReader(instream, encoding); - Reader in = new BufferedReader(isr); - int ch; - StringBuffer buffer = new StringBuffer(); - while ((ch = in.read()) > -1) { - buffer.append((char)ch); - } - in.close(); - conn.disconnect(); - return buffer.toString(); - } - - /** - * Helper method to retrieve server URL including context path - * @param request HttpServletRequest - * @return Server URL including context path (e.g. http://localhost:8443/moa-id-auth - */ - public static String getBaseURL(HttpServletRequest request) { - StringBuffer buffer = new StringBuffer(getServerURL(request)); - - // add context path if available - String contextPath = request.getContextPath(); - if (!StringUtils.isEmpty(contextPath)) { - buffer.append(contextPath); - } - - return buffer.toString(); - } - - /** - * Helper method to retrieve server URL - * @param request HttpServletRequest - * @return Server URL (e.g. http://localhost:8443) - */ - public static String getServerURL(HttpServletRequest request) { - StringBuffer buffer = new StringBuffer(); - - // get protocol - String protocol = request.getScheme(); - buffer.append(protocol).append("://"); - - // server name - buffer.append(request.getServerName()); - - // add port if necessary - int port = request.getServerPort(); - if ((protocol.equals("http") && port != 80) || (protocol.equals("https") && port != 443)) { - buffer.append(':'); - buffer.append(port); - } - - return buffer.toString(); - } - - /** - * Extract the IDP PublicURLPrefix from authrequest - * - * @param req HttpServletRequest - * @return PublicURLPrefix <String> which ends always without / - */ - public static String extractAuthURLFromRequest(HttpServletRequest req) { - String authURL = req.getScheme() + "://" + req.getServerName(); - if ((req.getScheme().equalsIgnoreCase("https") && req.getServerPort()!=443) || (req.getScheme().equalsIgnoreCase("http") && req.getServerPort()!=80)) { - authURL = authURL.concat(":" + req.getServerPort()); - } - authURL = authURL.concat(req.getContextPath()); - return authURL; - - } - - /** - * Extract the IDP requested URL from authrequest - * - * @param req HttpServletRequest - * @return RequestURL <String> which ends always without / - */ - public static String extractAuthServletPathFromRequest(HttpServletRequest req) { - return extractAuthURLFromRequest(req).concat(req.getServletPath()); - - } - - public static String addURLParameter(String url, String paramname, - String paramvalue) { - String param = paramname + "=" + paramvalue; - if (url.indexOf("?") < 0) - return url + "?" + param; - else - return url + "&" + param; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/IdentityLinkReSigner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/IdentityLinkReSigner.java index 81041260c..d8114f19d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/IdentityLinkReSigner.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/IdentityLinkReSigner.java @@ -35,6 +35,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import at.gv.egiz.eaaf.core.impl.utils.DOMUtils; 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.config.auth.AuthConfigurationProviderFactory; @@ -57,7 +58,6 @@ import at.gv.egovernment.moa.spss.api.xmlsign.ErrorResponse; import at.gv.egovernment.moa.spss.api.xmlsign.SignatureEnvironmentResponse; import at.gv.egovernment.moa.spss.api.xmlsign.SingleSignatureInfo; import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.MiscUtil; public class IdentityLinkReSigner { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/LoALevelMapper.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/LoALevelMapper.java new file mode 100644 index 000000000..10e22c806 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/LoALevelMapper.java @@ -0,0 +1,205 @@ +/* + * 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.util; + +import java.io.IOException; +import java.util.Properties; + +import org.springframework.stereotype.Service; + +import at.gv.egiz.eaaf.core.api.data.ILoALevelMapper; +import at.gv.egovernment.moa.id.data.AuthenticationRole; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +@Service("MOAIDLoALevelMapper") +public class LoALevelMapper implements ILoALevelMapper{ + + private static final String PVP_SECCLASS_PREFIX = "http://www.ref.gv.at/ns/names/agiz/pvp/"; + private static final String STORK_QAA_PREFIX = "http://www.stork.gov.eu/1.0/"; + private static final String eIDAS_QAA_PREFIX = "http://eidas.europa.eu/"; + + private static final String MAPPING_RESOURCE = + "resources/properties/pvp-stork_mapping.properties"; + + private static final String MAPPING_SECCLASS_PREFIX = "secclass_"; + private static final String MAPPING_EIDAS_PREFIX = "eidas_"; + + private Properties mapping = null; + + public LoALevelMapper() { + try { + mapping = new Properties(); + mapping.load(this.getClass().getClassLoader().getResourceAsStream(MAPPING_RESOURCE)); + Logger.debug("PVP -> STORK Role mapping initialisation finished."); + + } catch (IOException e) { + Logger.error("PVP -> STORK Role mapping initialisation FAILED." , e); + mapping = null; + + } + + + } + + public String mapToeIDASLoA(String qaa) { + if (qaa.startsWith(STORK_QAA_PREFIX)) + return mapSTORKQAAToeIDASQAA(qaa); + + else if (qaa.startsWith(PVP_SECCLASS_PREFIX)) + return mapSTORKQAAToeIDASQAA(mapSecClassToQAALevel(qaa)); + + else if (qaa.startsWith(MAPPING_EIDAS_PREFIX)) + return qaa; + + else { + Logger.info("QAA: " + qaa + " is NOT supported by LoA level mapper"); + return null; + + } + + } + + public String mapToSecClass(String qaa) { + if (qaa.startsWith(STORK_QAA_PREFIX)) + return mapStorkQAAToSecClass(qaa); + + else if (qaa.startsWith(MAPPING_EIDAS_PREFIX)) + return mapStorkQAAToSecClass(mapeIDASQAAToSTORKQAA(qaa)); + + else if (qaa.startsWith(PVP_SECCLASS_PREFIX)) + return qaa; + + else { + Logger.info("QAA: " + qaa + " is NOT supported by LoA level mapper"); + return null; + + } + + } + + + /** + * Map STORK QAA level to eIDAS QAA level + * + * @param storkQAA STORK QAA level + * @return + */ + public String mapSTORKQAAToeIDASQAA(String storkQAA) { + if (mapping != null) { + String input = storkQAA.substring(STORK_QAA_PREFIX.length()); + String mappedQAA = mapping.getProperty(MAPPING_EIDAS_PREFIX + input); + if (MiscUtil.isNotEmpty(mappedQAA)) { + Logger.info("Map STORK-QAA " + storkQAA + " to eIDAS-QAA " + mappedQAA); + return mappedQAA; + + } + } + Logger.warn("No eIDAS-QAA mapping for STORK-QAA " + storkQAA +" !"); + return null; + + } + + /** + * Map eIDAS QAA-level to STORK QAA-level + * + * @param qaaLevel eIDAS QAA-level + * @return STORK QAA-level + */ + public String mapeIDASQAAToSTORKQAA(String qaaLevel) { + if (mapping != null) { + String input = qaaLevel.substring(eIDAS_QAA_PREFIX.length()); + String mappedQAA = mapping.getProperty(input); + if (MiscUtil.isNotEmpty(mappedQAA)) { + Logger.info("Map eIDAS-QAA " + qaaLevel + " to STORK-QAA " + mappedQAA); + return mappedQAA; + + } + } + Logger.warn("No eIDAS-QAA mapping for eIDAS-QAA " + qaaLevel +" !"); + return null; + } + + /**Map a STORK QAA level to PVP SecClass + * + * @param STORK-QAA level + * @return PVP SecClass pvpQAALevel + */ + public String mapStorkQAAToSecClass(String storkQAALevel) { + if (mapping != null) { + String input = storkQAALevel.substring(STORK_QAA_PREFIX.length()); + String mappedQAA = mapping.getProperty(MAPPING_SECCLASS_PREFIX + input); + if (MiscUtil.isNotEmpty(mappedQAA)) { + Logger.info("Map STORK-QAA " + storkQAALevel + " to PVP SecClass " + mappedQAA); + return mappedQAA; + + } + } + Logger.warn("No mapping for STORK-QAA " + storkQAALevel +" !"); + return null; + } + + /**Map a PVP SecClass to STORK QAA level + * + * @param PVP SecClass pvpQAALevel + * @return STORK-QAA level + */ + public String mapSecClassToQAALevel(String pvpQAALevel) { + if (mapping != null) { + String input = pvpQAALevel.substring(PVP_SECCLASS_PREFIX.length()); + String mappedQAA = mapping.getProperty(input); + if (MiscUtil.isNotEmpty(mappedQAA)) { + Logger.info("Map PVP SecClass " + pvpQAALevel + " to STORK-QAA " + mappedQAA); + return mappedQAA; + + } + } + Logger.warn("No mapping for PVP SecClass " + pvpQAALevel +" !"); + return null; + } + + /**Map a PVP Role attribute to STORK ECAuthenticationRole attribute values + * + * @param PVP Role attribute + * @return STORK ECAuthenticationRole attribute value + */ + public String map(AuthenticationRole el) { + if (mapping != null) { + //String ecRole = mapping.getProperty(el.getRawRoleString()); + String ecRole = mapping.getProperty(el.getRoleName()); + if (MiscUtil.isNotEmpty(ecRole)) { + //Logger.info("Map PVPRole " + el.getRawRoleString() + " to ECRole " + ecRole); + Logger.info("Map PVPRole " + el.getRoleName() + " to ECRole " + ecRole); + return ecRole; + } + } + //Logger.warn("NO mapping for PVPRole "+ el.getRawRoleString() + " !"); + Logger.warn("NO mapping for PVPRole "+ el.getRoleName() + " !"); + return null; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ParamValidatorUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ParamValidatorUtils.java index 885d03fd8..a44d8c1b6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ParamValidatorUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ParamValidatorUtils.java @@ -62,13 +62,13 @@ import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.SAXException;
+import at.gv.egiz.eaaf.core.impl.utils.DOMUtils;
import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants;
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.config.auth.AuthConfigurationProviderFactory;
import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.DOMUtils;
import at.gv.egovernment.moa.util.MiscUtil;
import at.gv.egovernment.moa.util.StringUtils;
@@ -522,6 +522,7 @@ public class ParamValidatorUtils extends MOAIDAuthConstants{ String bkuURL = req.getParameter(PARAM_BKU);
String useMandate = req.getParameter(PARAM_USEMANDATE);
String ccc = req.getParameter(PARAM_CCC);
+ String useeIDAS = req.getParameter("useeIDAS");
// check parameter
@@ -532,6 +533,8 @@ public class ParamValidatorUtils extends MOAIDAuthConstants{ throw new WrongParametersException("StartAuthentication", PARAM_BKU, "auth.12");
if (!ParamValidatorUtils.isValidUseMandate(useMandate))
throw new WrongParametersException("StartAuthentication", PARAM_USEMANDATE, "auth.12");
+ if (!ParamValidatorUtils.isValidUseMandate(useeIDAS))
+ throw new WrongParametersException("StartAuthentication", "useeIDAS", "auth.12");
if (!ParamValidatorUtils.isValidCCC(ccc))
throw new WrongParametersException("StartAuthentication", PARAM_CCC, "auth.12");
@@ -539,7 +542,7 @@ public class ParamValidatorUtils extends MOAIDAuthConstants{ return false;
}
- if (StringUtils.isEmpty(bkuURL))
+ if (StringUtils.isEmpty(bkuURL) && StringUtils.isEmpty(useeIDAS))
return false;
else
return true;
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/QAALevelVerifier.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/QAALevelVerifier.java deleted file mode 100644 index 88a64bd07..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/QAALevelVerifier.java +++ /dev/null @@ -1,43 +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.util; - -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.QAANotAllowedException; - -/** - * @author tlenz - * - */ -public class QAALevelVerifier { - - public static void verifyQAALevel(String qaaAuth, String qaaRequest) throws QAANotAllowedException { - - Integer qaaA = Integer.valueOf(qaaAuth.substring(PVPConstants.STORK_QAA_PREFIX.length())); - Integer qaaR = Integer.valueOf(qaaRequest.substring(PVPConstants.STORK_QAA_PREFIX.length())); - - if (qaaA < qaaR) - throw new QAANotAllowedException(qaaAuth, qaaRequest); - - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/Random.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/Random.java deleted file mode 100644 index 38c384c3a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/Random.java +++ /dev/null @@ -1,187 +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. - ******************************************************************************/ -/* - * 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 java.nio.ByteBuffer; -import java.security.SecureRandom; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; - -import org.apache.commons.codec.binary.Hex; - -import com.google.common.primitives.Bytes; - -import iaik.security.random.SeedGenerator; - - -/** - * Random number generator used to generate ID's - * @author Paul Ivancsics - * @version $Id$ - */ -public class Random { - - - private final static char[] allowedPreFix = - {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', - 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; - private static final DateFormat dateFormater = new SimpleDateFormat("yyyyddMM"); - - /** random number generator used */ - //private static SecureRandom random = new SecureRandom(); - private static SecureRandom random; - private static SeedGenerator seedgenerator; - - static { - random = iaik.security.random.SHA256FIPS186Random.getDefault(); - seedgenerator = iaik.security.random.AutoSeedGenerator.getDefault(); - - } - - /** - * Generate a unique process reference-value [160bit], which always starts with a letter - * <br> - * This unique ID consists of single letter, a 64bit date String[yyyyddMM], - * and a 88bit random value. - * - * @return 160bit ID, which is hex encoded - */ - public static String nextProcessReferenceValue() { - //pre-process all three parts of a unique reference value - String now = dateFormater.format(new Date()); //8 bytes = 64bit - byte[] randValue = nextByteRandom(11); - char preFix = allowedPreFix[Math.abs(random.nextInt() % allowedPreFix.length)]; - - //generate ID - String returnValue = preFix + new String(Hex.encodeHex(Bytes.concat(now.getBytes(), randValue))); // 20 bytes = 160 bits - if (returnValue.length() > 40) - return returnValue.substring(0, 40); - else - return returnValue; - - } - - - - /** - * Creates a new random number [256bit], and encode it as hex value. - * - * @return random hex encoded value [256bit] - */ - public static String nextHexRandom32() { - return new String(Hex.encodeHex(nextByteRandom(32))); // 32 bytes = 256 bits - - } - - /** - * Creates a new random number [128bit], and encode it as hex value. - * - * @return random hex encoded value [128bit] - */ - public static String nextHexRandom16() { - return new String(Hex.encodeHex(nextByteRandom(16))); // 16 bytes = 128 bits - - } - - /** - * Creates a new random number [64bit], to be used as an ID. - * - * @return random long as a String [64bit] - */ - public static String nextLongRandom() { - return "".concat(String.valueOf(Math.abs(generateLongRandom(32)))); // 32 bytes = 256 bits - - } - - /** - * Creates a new random number, to be used as an ID. - * - * @return random long as a String [64bit] - */ - @Deprecated - public static String nextRandom() { - long l = ByteBuffer.wrap(nextByteRandom(32)).getLong(); // 32 bytes = 256 bits - return "" + Math.abs(l); - - } - -/** - * Creates a new random byte[] - * - * @param size Size of random number in byte - * @return - */ -public static byte[] nextBytes(int size) { - return nextByteRandom(size); - -} - - public static void seedRandom() { - - if (seedgenerator.seedAvailable()) - random.setSeed(seedgenerator.getSeed()); - } - - private static long generateLongRandom(int size) { - return ByteBuffer.wrap(nextByteRandom(size)).getLong(); - } - - /** - * Generate a new random number - * - * @param size Size of random number in byte - * @return - */ - private static synchronized byte[] nextByteRandom(int size) { - byte[] b = new byte[size]; - random.nextBytes(b); - return b; - - } -} 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 cd700c74a..611dff3b1 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 @@ -89,6 +89,43 @@ public class SSLUtils { } + public static SSLSocketFactory getSSLSocketFactory( + ConfigurationProvider conf, String url ) + throws IOException, GeneralSecurityException, ConfigurationException, PKIException { + + // else create new SSLSocketFactory + String trustStoreURL = conf.getTrustedCACertificates(); + + if (trustStoreURL == null) + throw new ConfigurationException( + "config.08", new Object[] {"TrustedCACertificates"}); + + String acceptedServerCertURL = ""; + + //INFO: MOA-ID 2.x always use defaultChainingMode + + try { + SSLSocketFactory ssf = at.gv.egovernment.moa.id.commons.utils.ssl.SSLUtils.getSSLSocketFactory( + url, + null, + trustStoreURL, + acceptedServerCertURL, + AuthConfigurationProviderFactory.getInstance().getDefaultChainingMode(), + AuthConfigurationProviderFactory.getInstance().isTrustmanagerrevoationchecking(), + AuthConfigurationProviderFactory.getInstance().getRevocationMethodOrder(), + null, + null, + "pkcs12"); + + return ssf; + + } catch (SSLConfigurationException e) { + throw new ConfigurationException(e.getErrorID(), e.getParameters(), e.getE()); + + } + } + + /** * Creates an <code>SSLSocketFactory</code> which utilizes an * <code>IAIKX509TrustManager</code> for the given trust store, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java deleted file mode 100644 index a4d79ac05..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ServletUtils.java +++ /dev/null @@ -1,69 +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. - ******************************************************************************/ -/* - * 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 javax.servlet.http.HttpServletRequest; - -public class ServletUtils { - - - public static String getBaseUrl( HttpServletRequest request ) { - if ( ( request.getServerPort() == 80 ) || - ( request.getServerPort() == 443 ) ) - return request.getScheme() + "://" + - request.getServerName() + - request.getContextPath(); - else - return request.getScheme() + "://" + - request.getServerName() + ":" + request.getServerPort() + - request.getContextPath(); - } - -} |