From 3314af0442eba4bce469b21585a75c1a327f53b5 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 18 Dec 2015 13:00:30 +0100 Subject: add first untested parts for eIDAS SAML-engine configuration --- .../at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java | 8 ++++++++ .../id/config/auth/PropertyBasedAuthConfigurationProvider.java | 5 +++++ 2 files changed, 13 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java index c98a7d537..ad3268b90 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java @@ -25,6 +25,14 @@ public interface AuthConfiguration extends ConfigurationProvider{ public String getConfigurationWithKey(final String key); + /** + * Get a configuration value from basic file based MOA-ID configuration + * + * @param key configuration key + * @return configuration value + */ + public String getBasicMOAIDConfiguration(final String key); + public int getTransactionTimeOut(); public int getSSOCreatedTimeOut(); public int getSSOUpdatedTimeOut(); 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 645831479..dce7de526 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 @@ -173,6 +173,11 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } } + public String getBasicMOAIDConfiguration(final String key) { + return properties.getProperty(key); + + } + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getPropertyWithKey(java.lang.String) */ -- cgit v1.2.3 From 74e36f95b4fb49b37b05d5e93c9404f795c964df Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 12 Jan 2016 10:43:11 +0100 Subject: refactor MOASession data-object to store generice information from authentication modules --- .../moa/id/auth/data/AuthenticationSession.java | 374 ++++++--------------- .../AuthenticationSessionStorageConstants.java | 38 +++ .../exception/SessionDataStorageException.java | 45 +++ .../moa/id/data/AuthenticationData.java | 122 ++++--- .../at/gv/egovernment/moa/id/data/IAuthData.java | 8 +- 5 files changed, 256 insertions(+), 331 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/SessionDataStorageException.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java index 59482c4a8..ae3ec9a9b 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 @@ -44,13 +44,15 @@ import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Date; import java.util.List; +import java.util.Map; +import org.apache.commons.collections4.map.HashedMap; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAuthnRequest; +import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; +import at.gv.egovernment.moa.util.MiscUtil; /** * Session data to be stored between AuthenticationServer API calls. @@ -215,129 +217,28 @@ public class AuthenticationSession implements Serializable { * accept. The infobox identifiers are comma separated. */ private String pushInfobox; - - /** - * The STORK AuthRequest to be sent to the C-PEPS - */ - private STORKAuthnRequest storkAuthnRequest; - - private String storkAuthnResponse; - + // private AuthenticationData authData; // protocol selection private String action; private String modul; + private String processInstanceId; + private boolean authenticated; private boolean authenticatedUsed = false; private boolean ssoRequested = false; - + private String QAALevel = null; - -// private OAuth20SessionObject oAuth20SessionObject; - - // /** - // * Indicates if target from configuration is used or not - // */ - // private boolean useTargetFromConfig; - - // /** - // * Authentication data for the assertion - // */ - // private AuthenticationData assertionAuthData; - // - // /** - // * Persondata for the assertion - // */ - // private String assertionPrPerson; - // - // /** - // * Authblock for the assertion - // */ - // private String assertionAuthBlock; - // - // /** - // * Identitylink assertion for the (MOA) assertion - // */ - // private String assertionIlAssertion; - // - // /** - // * Signer certificate (base64 encoded) for the assertion - // */ - // private String assertionSignerCertificateBase64; - // - // /** - // * bussiness service for the assertion - // */ - // boolean assertionBusinessService; - // - // /** - // * timestamp logging when authentication session has been created - // */ - // private Date timestampStart; - // private CreateXMLSignatureResponse XMLCreateSignatureResponse; - + private VerifyXMLSignatureResponse XMLVerifySignatureResponse; private boolean isForeigner; - - private IPersonalAttributeList storkAttributes; + private Map genericSessionDataStorate = new HashedMap(); - //Temporary store SignRequest for local processing - private String signedDoc; - //Temporary store SAMLResponse for processing after user signed signedDoc locally - private String SAMLResponse; - // - private StringBuffer returnURL; - private IPersonalAttributeList authnResponseGetPersonalAttributeList; - private String authnContextClassRef; - // private String requestedProtocolURL = null; - - private String processInstanceId; - - public String getAuthnContextClassRef() { - return authnContextClassRef; - } - - public void setAuthnContextClassRef(String authnContextClassRef) { - this.authnContextClassRef = authnContextClassRef; - } - - public IPersonalAttributeList getAuthnResponseGetPersonalAttributeList() { - return authnResponseGetPersonalAttributeList; - } - - public void setAuthnResponseGetPersonalAttributeList(IPersonalAttributeList authnResponseGetPersonalAttributeList) { - this.authnResponseGetPersonalAttributeList = authnResponseGetPersonalAttributeList; - } - - public String getSAMLResponse() { - return SAMLResponse; - } - - public void setSAMLResponse(String samlResponse) { - SAMLResponse = samlResponse; - } - - public StringBuffer getReturnURL() { - return returnURL; - } - - public void setReturnURL(StringBuffer returnURL) { - this.returnURL = returnURL; - } - - public String getSignedDoc() { - return signedDoc; - } - - public void setSignedDoc(String signedDoc) { - this.signedDoc = signedDoc; - } - public String getModul() { return modul; } @@ -353,15 +254,7 @@ public class AuthenticationSession implements Serializable { public void setAction(String action) { this.action = action; } - - // public AuthenticationData getAuthData() { - // return authData; - // } - // - // public void setAuthData(AuthenticationData authData) { - // this.authData = authData; - // } - + public boolean isAuthenticatedUsed() { return authenticatedUsed; } @@ -378,14 +271,6 @@ public class AuthenticationSession implements Serializable { this.authenticated = authenticated; } - // public String getRequestedProtocolURL() { - // return requestedProtocolURL; - // } - // - // public void setRequestedProtocolURL(String requestedProtocolURL) { - // this.requestedProtocolURL = requestedProtocolURL; - // } - /** * Constructor for AuthenticationSession. * @@ -395,8 +280,7 @@ public class AuthenticationSession implements Serializable { public AuthenticationSession(String id, Date created) { sessionID = id; sessionCreated = created; - // setTimestampStart(); -// infoboxValidators = new ArrayList(); + } public X509Certificate getSignerCertificate() { @@ -760,98 +644,7 @@ public class AuthenticationSession implements Serializable { public void setIssueInstant(String issueInstant) { this.issueInstant = issueInstant; } - -// /** -// * Returns the iterator to the stored infobox validators. -// * -// * @return Iterator -// */ -// public Iterator getInfoboxValidatorIterator() { -// if (infoboxValidators == null) return null; -// return infoboxValidators.iterator(); -// } - - // /** - // * Adds an infobox validator class to the stored infobox validators. - // * - // * @param infoboxIdentifier - // * the identifier of the infobox the validator belongs to - // * @param infoboxFriendlyName - // * the friendly name of the infobox - // * @param infoboxValidator - // * the infobox validator to add - // */ - // public Iterator addInfoboxValidator(String infoboxIdentifier, - // String infoboxFriendlyName, InfoboxValidator infoboxValidator) { - // if (infoboxValidators == null) - // infoboxValidators = new ArrayList(); - // Vector v = new Vector(3); - // v.add(infoboxIdentifier); - // v.add(infoboxFriendlyName); - // v.add(infoboxValidator); - // infoboxValidators.add(v); - // return infoboxValidators.iterator(); - // } - -// /** -// * Tests for pending input events of the infobox validators. -// * -// * @return true if a validator has a form to show -// */ -// public boolean isValidatorInputPending() { -// boolean result = false; -// Iterator iter = getInfoboxValidatorIterator(); -// if (iter != null) { -// while (!result && iter.hasNext()) { -// Vector infoboxValidatorVector = (Vector) iter.next(); -// InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector.get(2); -// if (!ParepUtils.isEmpty(infoboxvalidator.getForm())) result = true; -// } -// } -// return result; -// } - - // /** - // * Returns the first pending infobox validator. - // * - // * @return the infobox validator class - // */ - // public InfoboxValidator getFirstPendingValidator() { - // Iterator iter = getInfoboxValidatorIterator(); - // if (iter != null) { - // while (iter.hasNext()) { - // Vector infoboxValidatorVector = (Vector) iter.next(); - // InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector - // .get(2); - // String form = infoboxvalidator.getForm(); - // if (!ParepUtils.isEmpty(form)) - // return infoboxvalidator; - // } - // } - // return null; - // } - - // /** - // * Returns the input form of the first pending infobox validator input - // * processor. - // * - // * @return the form to show - // */ - // public String getFirstValidatorInputForm() { - // Iterator iter = getInfoboxValidatorIterator(); - // if (iter != null) { - // while (iter.hasNext()) { - // Vector infoboxValidatorVector = (Vector) iter.next(); - // InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector - // .get(2); - // String form = infoboxvalidator.getForm(); - // if (!ParepUtils.isEmpty(form)) - // return form; - // } - // } - // return null; - // } - + /** * Returns domain identifier (the register and number in the register parameter). * null in the case of not a business service. @@ -954,26 +747,7 @@ public class AuthenticationSession implements Serializable { public void setMandateReferenceValue(String mandateReferenceValue) { this.mandateReferenceValue = mandateReferenceValue; } - - /** - * Gets the STORK SAML AuthnRequest - * - * @return STORK SAML AuthnRequest - */ - public STORKAuthnRequest getStorkAuthnRequest() { - return storkAuthnRequest; - } - - /** - * Sets the STORK SAML AuthnRequest - * - * @param storkAuthnRequest - * STORK SAML AuthnRequest - */ - public void setStorkAuthnRequest(STORKAuthnRequest storkAuthnRequest) { - this.storkAuthnRequest = storkAuthnRequest; - } - + public String getCcc() { return ccc; } @@ -1054,24 +828,8 @@ public class AuthenticationSession implements Serializable { } /** - * Memorizes the stork attribute list. - * - * @param personalAttributeList the new stork attributes - */ - public void setStorkAttributes(IPersonalAttributeList personalAttributeList) { - this.storkAttributes = personalAttributeList; - } - - /** - * Recalls the stork attribute list. - * - * @return the stork attributes - */ - public IPersonalAttributeList getStorkAttributes() { - return this.storkAttributes; - } - - /** + * eIDAS QAA level + * * @return the qAALevel */ public String getQAALevel() { @@ -1079,26 +837,14 @@ public class AuthenticationSession implements Serializable { } /** + * set QAA level in eIDAS form + * * @param qAALevel the qAALevel to set */ public void setQAALevel(String qAALevel) { QAALevel = qAALevel; } - /** - * @return the storkAuthnResponse - */ - public String getStorkAuthnResponse() { - return storkAuthnResponse; - } - - /** - * @param storkAuthnResponse the storkAuthnResponse to set - */ - public void setStorkAuthnResponse(String storkAuthnResponse) { - this.storkAuthnResponse = storkAuthnResponse; - } - /** * @return the sessionCreated */ @@ -1121,5 +867,89 @@ public class AuthenticationSession implements Serializable { public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } + + public Map getGenericSessionDataStorage() { + return genericSessionDataStorate; + } + + /** + * Returns a generic session-data object with is stored with a specific identifier + * + * @param key The specific identifier of the session-data object + * @return The session-data object or null if no data is found with this key + */ + public Object getGenericDataFromSession(String key) { + if (MiscUtil.isNotEmpty(key)) { + return genericSessionDataStorate.get(key); + + } + + Logger.warn("Can not load generic session-data with key='null'"); + return null; + + } + + /** + * Returns a generic session-data object with is stored with a specific identifier + * + * @param key The specific identifier of the session-data object + * @param clazz The class type which is stored with this key + * @return The session-data object or null if no data is found with this key + */ + public T getGenericDataFromSession(String key, final Class clazz) { + if (MiscUtil.isNotEmpty(key)) { + Object data = genericSessionDataStorate.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 setGenericDataToSession(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 session-data can not be stored with a 'null' key", null); + + } + + 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); + + } + } + + if (genericSessionDataStorate.containsKey(key)) + Logger.debug("Overwrite generic session-data with key:" + key); + else + Logger.trace("Add generic session-data with key:" + key + " to session."); + + genericSessionDataStorate.put(key, object); + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java new file mode 100644 index 000000000..f67f41dd3 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java @@ -0,0 +1,38 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.data; + +/** + * @author tlenz + * + */ +public class AuthenticationSessionStorageConstants { + + public static final String PREFIX_STORK = "stork_"; + public static final String PREFIX_eIDAS = "eIDAS_"; + + public static final String STORK_ATTRIBUTELIST = PREFIX_STORK + "attributelist"; + public static final String STORK_REQUEST = PREFIX_STORK + "request"; + public static final String STORK_RESPONSE = PREFIX_STORK + "response"; + public static final String STORK_CCC = PREFIX_STORK + "ccc"; +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/SessionDataStorageException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/SessionDataStorageException.java new file mode 100644 index 000000000..203be784e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/SessionDataStorageException.java @@ -0,0 +1,45 @@ +/* + * 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; + +/** + * @author tlenz + * + */ +public class SessionDataStorageException extends MOAIDException { + + /** + * + */ + private static final long serialVersionUID = 5743057708136365929L; + + /** + * @param messageId + * @param parameters + */ + public SessionDataStorageException(String messageId, Object[] parameters) { + super(messageId, parameters); + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java index e2892e70a..a5dfe7524 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java @@ -29,13 +29,13 @@ 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 eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAuthnRequest; - import at.gv.egovernment.moa.id.auth.data.IdentityLink; +import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.DateTimeUtils; @@ -122,9 +122,8 @@ public class AuthenticationData implements IAuthData, Serializable { * STORK attributes from response */ private String ccc = null; - private IPersonalAttributeList storkAttributes = null; - private String storkAuthnResponse; - private STORKAuthnRequest storkRequest = null; + + private Map genericDataStorate = new HashedMap(); private byte[] signerCertificate = null; @@ -397,23 +396,6 @@ public class AuthenticationData implements IAuthData, Serializable { this.identityLink = identityLink; } - - /** - * @return the storkAttributes - */ - public IPersonalAttributeList getStorkAttributes() { - return storkAttributes; - } - - - /** - * @param storkAttributes the storkAttributes to set - */ - public void setStorkAttributes(IPersonalAttributeList storkAttributes) { - this.storkAttributes = storkAttributes; - } - - /** * @return the signerCertificate */ @@ -538,35 +520,6 @@ public class AuthenticationData implements IAuthData, Serializable { this.ssoSession = ssoSession; } - /** - * @param storkRequest the storkRequest to set - */ - public void setStorkRequest(STORKAuthnRequest storkRequest) { - this.storkRequest = storkRequest; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.IAuthData#getStorkAuthnRequest() - */ - @Override - public STORKAuthnRequest getStorkAuthnRequest() { - return this.storkRequest; - } - - /** - * @return the storkAuthnResponse - */ - public String getStorkAuthnResponse() { - return storkAuthnResponse; - } - - /** - * @param storkAuthnResponse the storkAuthnResponse to set - */ - public void setStorkAuthnResponse(String storkAuthnResponse) { - this.storkAuthnResponse = storkAuthnResponse; - } - /** * @return the mandateReferenceValue */ @@ -743,5 +696,68 @@ public class AuthenticationData implements IAuthData, Serializable { public void setIsBusinessService(boolean flag) { this.businessService = flag; - } + } + + /** + * 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 getGenericData(String key, final Class 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/IAuthData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java index 09b0d7971..915242787 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java @@ -27,9 +27,6 @@ import java.util.List; import org.w3c.dom.Element; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAuthnRequest; - import at.gv.egovernment.moa.id.auth.data.IdentityLink; /** @@ -89,8 +86,7 @@ public interface IAuthData { boolean isForeigner(); String getCcc(); - STORKAuthnRequest getStorkAuthnRequest(); - String getStorkAuthnResponse(); - IPersonalAttributeList getStorkAttributes(); + + public T getGenericData(String key, final Class clazz); } -- cgit v1.2.3 From 68017565392861db4958716971d5be38faf5fff6 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 12 Jan 2016 10:44:13 +0100 Subject: refactore STORK authentication module to use generic MOASession data-storage --- .../id/auth/builder/AuthenticationDataBuilder.java | 55 ++++++++++++++++------ .../builder/attributes/EIDSTORKTOKEN.java | 4 +- .../pvp2x/utils/AssertionAttributeExtractor.java | 17 +++---- 3 files changed, 51 insertions(+), 25 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 998fa495f..b79b99a65 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 @@ -32,7 +32,9 @@ import java.security.PrivateKey; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; +import java.util.Iterator; import java.util.List; +import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -62,6 +64,7 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.PersonNameTy import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPersonType; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; @@ -69,6 +72,7 @@ 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.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; +import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; 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.db.MOASessionDBUtils; @@ -788,16 +792,24 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { //set STORK attributes if (extractor.containsAttribute(PVPConstants.EID_STORK_TOKEN_NAME)) { - authData.setStorkAuthnResponse(extractor.getSingleAttributeValue(PVPConstants.EID_STORK_TOKEN_NAME)); - authData.setForeigner(true); + try { + authData.setGenericData(AuthenticationSessionStorageConstants.STORK_RESPONSE, + extractor.getSingleAttributeValue(PVPConstants.EID_STORK_TOKEN_NAME)); + authData.setForeigner(true); + + } catch (SessionDataStorageException e) { + Logger.warn("STORK Response can not stored into generic authData.", e); + + } - } - - if (!extractor.getSTORKAttributes().isEmpty()) { - authData.setStorkAttributes(extractor.getSTORKAttributes()); - authData.setForeigner(true); } + +// if (!extractor.getSTORKAttributes().isEmpty()) { +// authData.setStorkAttributes(extractor.getSTORKAttributes()); +// authData.setForeigner(true); +// +// } authData.setSsoSession(true); authData.setInterfederatedSSOSession(true); @@ -887,10 +899,22 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { authData.setBkuURL(session.getBkuURL()); - authData.setStorkAttributes(session.getStorkAttributes()); - authData.setStorkAuthnResponse(session.getStorkAuthnResponse()); - authData.setStorkRequest(session.getStorkAuthnRequest()); - + //copy all generic authentication information to authData + if (session.getGenericSessionDataStorage() != null && + !session.getGenericSessionDataStorage().isEmpty()) { + Iterator> copyInterator = session.getGenericSessionDataStorage().entrySet().iterator(); + while (copyInterator.hasNext()) { + Entry element = copyInterator.next(); + try { + authData.setGenericData(element.getKey(), element.getValue()); + + } catch (SessionDataStorageException e) { + Logger.warn("Can not add generic authData with key:" + element.getKey(), e); + + } + } + } + authData.setSignerCertificate(session.getEncodedSignerCertificate()); authData.setAuthBlock(session.getAuthBlock()); @@ -921,9 +945,12 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } if (MiscUtil.isEmpty(authData.getCcc())) { - if (authData.getStorkAuthnRequest() != null) { - authData.setCcc(authData.getStorkAuthnRequest().getCitizenCountryCode()); - Logger.info("Can not extract country from certificate -> Use country from STORK request."); + String storkCCC = authData.getGenericData( + AuthenticationSessionStorageConstants.STORK_CCC, String.class); + + if (MiscUtil.isNotEmpty(storkCCC)) { + authData.setCcc(storkCCC); + Logger.info("Can not extract country from certificate -> Use country:" + storkCCC + " from STORK request."); } 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 84b791708..43a0458cb 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 @@ -24,6 +24,7 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; @@ -47,7 +48,8 @@ public class EIDSTORKTOKEN implements IPVPAttributeBuilder { throw new UnavailableAttributeException(EID_STORK_TOKEN_NAME); } else { - String storkResponse = authData.getStorkAuthnResponse(); + String storkResponse = authData.getGenericData( + AuthenticationSessionStorageConstants.STORK_RESPONSE, String.class); if ( MiscUtil.isEmpty(storkResponse) ) { throw new UnavailableAttributeException(EID_STORK_TOKEN_NAME); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java index 26b3bfbd1..9c294245f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java @@ -38,9 +38,6 @@ import org.opensaml.saml2.core.StatusResponseType; import org.opensaml.saml2.core.Subject; import org.opensaml.xml.XMLObject; -import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.commons.PersonalAttributeList; - 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; @@ -50,7 +47,7 @@ public class AssertionAttributeExtractor { private Assertion assertion = null; private Map> attributs = new HashMap>(); - private PersonalAttributeList storkAttributes = new PersonalAttributeList(); + //private PersonalAttributeList storkAttributes = new PersonalAttributeList(); private final List minimalAttributeNameList = Arrays.asList( PVPConstants.PRINCIPAL_NAME_NAME, @@ -77,9 +74,9 @@ public class AssertionAttributeExtractor { for (XMLObject el : attr.getAttributeValues()) storkAttrValues.add(el.getDOM().getTextContent()); - PersonalAttribute storkAttr = new PersonalAttribute(attr.getName(), - false, storkAttrValues , "Available"); - storkAttributes.put(attr.getName(), storkAttr ); +// PersonalAttribute storkAttr = new PersonalAttribute(attr.getName(), +// false, storkAttrValues , "Available"); +// storkAttributes.put(attr.getName(), storkAttr ); } else { List attrList = new ArrayList(); @@ -155,9 +152,9 @@ public class AssertionAttributeExtractor { } - public PersonalAttributeList getSTORKAttributes() { - return storkAttributes; - } +// public PersonalAttributeList getSTORKAttributes() { +// return storkAttributes; +// } public String getNameID() throws AssertionAttributeExtractorExeption { -- cgit v1.2.3 From 2683e6eee3b6f820fe5fa4ef1b76a94cdfcd846d Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 13 Jan 2016 08:48:15 +0100 Subject: add STORK-QAA <--> eIdAS-QAA level mapper --- .../moa/id/data/AuthenticationData.java | 50 ++++++++++++++++++++-- .../at/gv/egovernment/moa/id/data/IAuthData.java | 1 + .../moa/id/protocols/pvp2x/PVPConstants.java | 5 +++ .../egovernment/moa/id/util/PVPtoSTORKMapper.java | 48 ++++++++++++++++++++- 4 files changed, 100 insertions(+), 4 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java index a5dfe7524..53be0881b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java @@ -36,6 +36,9 @@ import org.w3c.dom.Element; import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.exception.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; @@ -477,9 +480,47 @@ public class AuthenticationData implements IAuthData, Serializable { * @return */ public String getQAALevel() { - return this.QAALevel; + 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 @@ -498,13 +539,16 @@ public class AuthenticationData implements IAuthData, Serializable { /** + * Store QAA level in eIDAS format to authentication Data + * * @param qAALevel the qAALevel to set + * @throws AssertionAttributeExtractorExeption */ public void setQAALevel(String qAALevel) { - QAALevel = qAALevel; + QAALevel = qAALevel; + } - /** * @return the ssoSession */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java index 915242787..91d40fcc3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java @@ -79,6 +79,7 @@ public interface IAuthData { String getMandateReferenceValue(); String getQAALevel(); + public String getEIDASQAALevel(); String getSessionIndex(); String getNameID(); 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 168f2362a..dc0cab8c3 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 @@ -41,6 +41,11 @@ public interface PVPConstants { public static final String STORK_QAA_1_3 = "http://www.stork.gov.eu/1.0/citizenQAALevel/3"; public static final String STORK_QAA_1_4 = "http://www.stork.gov.eu/1.0/citizenQAALevel/4"; + public static final String EIDAS_QAA_PREFIX = "http://eidas.europa.eu/LoA/"; + 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:"; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java index 5ef9494f4..d0da0003f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java @@ -37,10 +37,14 @@ public class PVPtoSTORKMapper { 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; private static PVPtoSTORKMapper instance = null; @@ -68,6 +72,47 @@ public class PVPtoSTORKMapper { } + /** + * 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(MAPPING_EIDAS_PREFIX + 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 @@ -76,7 +121,7 @@ public class PVPtoSTORKMapper { public String mapToSecClass(String storkQAALevel) { if (mapping != null) { String input = storkQAALevel.substring(STORK_QAA_PREFIX.length()); - String mappedQAA = mapping.getProperty(input); + String mappedQAA = mapping.getProperty(MAPPING_SECCLASS_PREFIX + input); if (MiscUtil.isNotEmpty(mappedQAA)) { Logger.info("Map STORK-QAA " + storkQAALevel + " to PVP SecClass " + mappedQAA); return mappedQAA; @@ -125,4 +170,5 @@ public class PVPtoSTORKMapper { Logger.warn("NO mapping for PVPRole "+ el.getRoleName() + " !"); return null; } + } -- cgit v1.2.3 From 22820de6b6fa074be1d9990766fa631a6f7f5818 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 13 Jan 2016 08:57:23 +0100 Subject: add test IDL generation --- .../moa/id/auth/data/AuthenticationSessionStorageConstants.java | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java index f67f41dd3..648dcf6f1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java @@ -35,4 +35,8 @@ public class AuthenticationSessionStorageConstants { public static final String STORK_REQUEST = PREFIX_STORK + "request"; public static final String STORK_RESPONSE = PREFIX_STORK + "response"; public static final String STORK_CCC = PREFIX_STORK + "ccc"; + + public static final String eIDAS_ATTRIBUTELIST = PREFIX_eIDAS + "attributeList"; + public static final String eIDAS_RESPONSE = PREFIX_eIDAS + "response"; } + -- cgit v1.2.3 From 320485ae06e93da206049f4c3706db4e4fec554b Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 13 Jan 2016 14:03:03 +0100 Subject: refactor PVP Metadata provider functionality --- .../auth/builder/SignatureVerificationUtils.java | 172 +++++++++++++++++ .../auth/invoke/SignatureVerificationInvoker.java | 142 ++++++++++++++ .../parser/VerifyXMLSignatureResponseParser.java | 211 +++++++++++++++++++++ .../pvp2x/metadata/MOAMetadataProvider.java | 10 +- .../verification/metadata/MetadataFilterChain.java | 82 -------- .../metadata/PVPMetadataFilterChain.java | 54 ++++++ .../moa/id/saml2/MetadataFilterChain.java | 73 +++++++ 7 files changed, 657 insertions(+), 87 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SignatureVerificationUtils.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataFilterChain.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPMetadataFilterChain.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/saml2/MetadataFilterChain.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SignatureVerificationUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SignatureVerificationUtils.java new file mode 100644 index 000000000..e321c9d05 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SignatureVerificationUtils.java @@ -0,0 +1,172 @@ +/* + * 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.builder; + +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.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; +import at.gv.egovernment.moa.id.auth.exception.BuildException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.ParseException; +import at.gv.egovernment.moa.id.auth.exception.ServiceException; +import at.gv.egovernment.moa.id.auth.invoke.SignatureVerificationInvoker; +import at.gv.egovernment.moa.id.auth.parser.VerifyXMLSignatureResponseParser; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.Base64Utils; +import at.gv.egovernment.moa.util.Constants; + +/** + * @author tlenz + * + */ +public class SignatureVerificationUtils { + /** 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 VerifyXMLsignatureRequest */ + private Document requestDoc_; + /** the VerifyXMLsignatureRequest root element */ + private Element requestElem_; + + + public SignatureVerificationUtils() 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); + } + } + + public VerifyXMLSignatureResponse verify(byte[] signature, String trustProfileID) throws MOAIDException { + try { + //build signature-verification request + Element domVerifyXMLSignatureRequest = build(signature, trustProfileID); + + //send signature-verification to MOA-SP + Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() + .verifyXMLSignature(domVerifyXMLSignatureRequest); + + // parses the + VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( + domVerifyXMLSignatureResponse).parseData(); + + return verifyXMLSignatureResponse; + + } catch (ParseException e) { + Logger.error("Build signature-verification request FAILED." ,e); + throw e; + + } catch (ServiceException e) { + Logger.error("MOA-SP signature verification FAILED." ,e); + throw e; + + } + + } + + /** + * Builds a <VerifyXMLSignatureRequest> + * from an IdentityLink with a known trustProfileID which + * has to exist in MOA-SP + * @param signature - The XML signature as byte[] + * @param trustProfileID - a preconfigured TrustProfile at MOA-SP + * + * @return Element - The complete request as Dom-Element + * + * @throws ParseException + */ + private Element build(byte[] signature, String trustProfileID) + throws ParseException + { + try { + // build the request + 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 signature + String base64EncodedAssertion = Base64Utils.encode(signature); + //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"); + + Element returnHashInputDataElem = + requestDoc_.createElementNS(MOA_NS_URI, "ReturnHashInputData"); + requestElem_.appendChild(returnHashInputDataElem); + + //add trustProfileID + 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_; + } +} 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 new file mode 100644 index 000000000..72a7d3ba1 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java @@ -0,0 +1,142 @@ +/******************************************************************************* + * 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.invoke; + +import java.util.Vector; + +import javax.xml.namespace.QName; +import javax.xml.rpc.Call; +import javax.xml.rpc.Service; +import javax.xml.rpc.ServiceFactory; + +import org.apache.axis.message.SOAPBodyElement; +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.config.ConnectionParameter; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.spss.api.SignatureVerificationService; +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; + +/** + * Invoker of the SignatureVerification web service of MOA-SPSS.
+ * Either invokes the web service, or calls the corresponding API, depending on configuration data. + * + * @author Stefan Knirsch + * @version $Id$ + */ +public class SignatureVerificationInvoker { + /** This QName Object identifies the SignatureVerification endpoint of the web service */ + private static final QName SERVICE_QNAME = new QName("SignatureVerification"); + + /** + * Method verifyXMLSignature. + * @param request to be sent + * @return Element with the answer + * @throws ServiceException if an error occurs + */ + public Element verifyXMLSignature(Element request) throws ServiceException { + return doCall(SERVICE_QNAME, request); + } + + /** + * Method doCall. + * @param serviceName the name of the service + * @param request the request to be sent + * @return Element the answer + * @throws ServiceException if an error occurs + */ + protected Element doCall(QName serviceName, Element request) throws ServiceException { + ConnectionParameter authConnParam = null; + try { + Service service = ServiceFactory.newInstance().createService(serviceName); + Call call = service.createCall(); + SOAPBodyElement body = new SOAPBodyElement(request); + SOAPBodyElement[] params = new SOAPBodyElement[] { body }; + Vector responses; + SOAPBodyElement response; + + String endPoint; + 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()); + endPoint = authConnParam.getUrl(); + call.setTargetEndpointAddress(endPoint); + 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 { + SignatureVerificationService svs = SignatureVerificationService.getInstance(); + VerifyXMLSignatureRequest vsrequest = new VerifyXMLSignatureRequestParser().parse(request); + + VerifyXMLSignatureResponse vsresponse = svs.verifyXMLSignature(vsrequest); + Document result = new VerifyXMLSignatureResponseBuilder().build(vsresponse); + + //Logger.setHierarchy("moa.id.auth"); + return result.getDocumentElement(); + } + } + catch (Exception ex) { + if (authConnParam != null) { + throw new ServiceException("service.00", new Object[] { ex.toString()}, ex); + } else { + throw new ServiceException("service.03", new Object[] { ex.toString()}, ex); + } + } + } +} 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 new file mode 100644 index 000000000..7bce406e0 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java @@ -0,0 +1,211 @@ +/******************************************************************************* + * 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.parser; + +import iaik.utils.Base64InputStream; +import iaik.x509.X509Certificate; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; + +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; +import at.gv.egovernment.moa.id.auth.exception.ParseException; +import at.gv.egovernment.moa.util.Constants; +import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.egovernment.moa.util.XPathUtils; + +/** + * Parses a <VerifyXMLSignatureResponse> returned by + * MOA-SPSS. + * This class implements the Singleton pattern + * + * @author Stefan Knirsch + * @version $Id$ + */ + + +public class VerifyXMLSignatureResponseParser { + // + // XPath namespace prefix shortcuts + // + /** Xpath prefix for reaching MOA Namespaces */ + private static final String MOA = Constants.MOA_PREFIX + ":"; + /** Xpath prefix for reaching DSIG Namespaces */ + private static final String DSIG = Constants.DSIG_PREFIX + ":"; + /** Xpath expression to the root element */ + private static final String ROOT = "/" + MOA + "VerifyXMLSignatureResponse/"; + + /** Xpath expression to the X509SubjectName element */ + private static final String DSIG_SUBJECT_NAME_XPATH = + ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + + DSIG + "X509SubjectName"; + /** Xpath expression to the X509Certificate element */ + private static final String DSIG_X509_CERTIFICATE_XPATH = + ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + + DSIG + "X509Certificate"; + /** Xpath expression to the PublicAuthority element */ + private static final String PUBLIC_AUTHORITY_XPATH = + ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + + MOA + "PublicAuthority"; + /** Xpath expression to the PublicAuthorityCode element */ + private static final String PUBLIC_AUTHORITY_CODE_XPATH = + PUBLIC_AUTHORITY_XPATH + "/" + MOA + "Code"; + /** Xpath expression to the QualifiedCertificate element */ + private static final String QUALIFIED_CERTIFICATE_XPATH = + ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + + MOA + "QualifiedCertificate"; + + /** Xpath expression to the SignatureCheckCode element */ + private static final String SIGNATURE_CHECK_CODE_XPATH = + ROOT + MOA + "SignatureCheck/" + MOA + "Code"; + /** Xpath expression to the XMLDSIGManifestCheckCode element */ + private static final String XMLDSIG_MANIFEST_CHECK_CODE_XPATH = + ROOT + MOA + "XMLDSIGManifestCheck/" + MOA + "Code"; + /** Xpath expression to the SignatureManifestCheckCode element */ + private static final String SIGNATURE_MANIFEST_CHECK_CODE_XPATH = + ROOT + MOA + "SignatureManifestCheck/" + MOA + "Code"; + /** Xpath expression to the CertificateCheckCode element */ + private static final String CERTIFICATE_CHECK_CODE_XPATH = + ROOT + MOA + "CertificateCheck/" + MOA + "Code"; + + + /** This is the root element of the XML-Document provided by the Security Layer Card*/ + private Element verifyXMLSignatureResponse; + + /** + * Constructor for VerifyXMLSignatureResponseParser. + * A DOM-representation of the incoming String will be created + * @param xmlResponse <InfoboxReadResponse> as String + * @throws ParseException on any parsing error + */ + public VerifyXMLSignatureResponseParser(String xmlResponse) throws ParseException{ + try { + InputStream s = new ByteArrayInputStream(xmlResponse.getBytes("UTF-8")); + + verifyXMLSignatureResponse = DOMUtils.parseXmlValidating(s); + } + catch (Throwable t) { + throw new ParseException("parser.01", new Object[] { t.toString() }, t); + } + } + + /** + * Constructor for VerifyXMLSignatureResponseParser. + * A DOM-representation of the incoming Inputstream will be created + * @param xmlResponse <InfoboxReadResponse> as InputStream + * @throws Exception on any parsing error + */ + public VerifyXMLSignatureResponseParser(InputStream xmlResponse) throws Exception + { + try { + verifyXMLSignatureResponse = DOMUtils.parseXmlValidating(xmlResponse); + } + catch (Throwable t) { + throw new ParseException("parser.01", null, t); + } + } + + /** + * Constructor for VerifyXMLSignatureResponseParser. + * The incoming Element will be used for further operations + * @param xmlResponse <InfoboxReadResponse> as Element + */ + public VerifyXMLSignatureResponseParser(Element xmlResponse) + { + verifyXMLSignatureResponse =xmlResponse; + + } + + /** + * Parse identity link from <InfoboxReadResponse> + * @return Identity link + * @throws ParseException on any parsing error + */ + + public VerifyXMLSignatureResponse parseData() throws ParseException { + + VerifyXMLSignatureResponse respData=new VerifyXMLSignatureResponse(); + + try { + + String s = DOMUtils.serializeNode(verifyXMLSignatureResponse); + respData.setXmlDsigSubjectName(XPathUtils.getElementValue(verifyXMLSignatureResponse,DSIG_SUBJECT_NAME_XPATH,"")); + Element e = (Element)XPathUtils.selectSingleNode(verifyXMLSignatureResponse,QUALIFIED_CERTIFICATE_XPATH); + respData.setQualifiedCertificate(e!=null); + + Base64InputStream in = new Base64InputStream(new ByteArrayInputStream(XPathUtils.getElementValue( + verifyXMLSignatureResponse,DSIG_X509_CERTIFICATE_XPATH,"").getBytes("UTF-8")),true); + + respData.setX509certificate(new X509Certificate(in)); + Element publicAuthority = (Element)XPathUtils.selectSingleNode(verifyXMLSignatureResponse,PUBLIC_AUTHORITY_XPATH); + respData.setPublicAuthority(publicAuthority != null); + respData.setPublicAuthorityCode(XPathUtils.getElementValue(verifyXMLSignatureResponse,PUBLIC_AUTHORITY_CODE_XPATH,"")); + respData.setSignatureCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNATURE_CHECK_CODE_XPATH,"")).intValue()); + + String xmlDsigCheckCode = XPathUtils.getElementValue(verifyXMLSignatureResponse,XMLDSIG_MANIFEST_CHECK_CODE_XPATH,null); + if (xmlDsigCheckCode!=null) { + respData.setXmlDSIGManigest(true); + respData.setXmlDSIGManifestCheckCode(new Integer(xmlDsigCheckCode).intValue()); + } else { + respData.setXmlDSIGManigest(false); + } + String signatureManifestCheckCode = XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNATURE_MANIFEST_CHECK_CODE_XPATH,null); + if (signatureManifestCheckCode != null) { + respData.setSignatureManifestCheckCode(new Integer(signatureManifestCheckCode).intValue()); + } + respData.setCertificateCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,CERTIFICATE_CHECK_CODE_XPATH,"")).intValue()); + } + catch (Throwable t) { + throw new ParseException("parser.01", null, t); + } + return respData; + } + + +} 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 f33cadc41..f4c099878 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 @@ -60,7 +60,7 @@ 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.id.protocols.pvp2x.verification.metadata.InterfederatedIDPPublicServiceFilter; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.MetadataFilterChain; +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.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; @@ -422,8 +422,8 @@ public class MOAMetadataProvider implements ObservableMetadataProvider{ internalProvider = chainProvider; } - private MetadataFilterChain buildMetadataFilterChain(OAAuthParameter oaParam, String metadataURL, byte[] certificate) throws CertificateException { - MetadataFilterChain filterChain = new MetadataFilterChain(metadataURL, certificate); + private PVPMetadataFilterChain buildMetadataFilterChain(OAAuthParameter oaParam, String metadataURL, byte[] certificate) throws CertificateException { + PVPMetadataFilterChain filterChain = new PVPMetadataFilterChain(metadataURL, certificate); filterChain.getFilters().add(new SchemaValidationFilter()); if (oaParam.isInderfederationIDP()) { @@ -435,7 +435,7 @@ public class MOAMetadataProvider implements ObservableMetadataProvider{ return filterChain; } - private HTTPMetadataProvider createNewHTTPMetaDataProvider(String metadataURL, byte[] certificate, String oaName, MetadataFilterChain filter) { + private HTTPMetadataProvider createNewHTTPMetaDataProvider(String metadataURL, byte[] certificate, String oaName, PVPMetadataFilterChain filter) { HTTPMetadataProvider httpProvider = null; Timer timer= null; MOAHttpClient httpClient = null; @@ -470,7 +470,7 @@ public class MOAMetadataProvider implements ObservableMetadataProvider{ //httpProvider.setRefreshDelayFactor(0.1F); if (filter == null) { - filter = new MetadataFilterChain(metadataURL, certificate); + filter = new PVPMetadataFilterChain(metadataURL, certificate); } httpProvider.setMetadataFilter(filter); httpProvider.initialize(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataFilterChain.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataFilterChain.java deleted file mode 100644 index 4e1d939ff..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MetadataFilterChain.java +++ /dev/null @@ -1,82 +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.security.cert.CertificateException; -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 filters = new ArrayList(); - - /** - * @throws CertificateException - * - */ - public MetadataFilterChain(String url, byte[] certificate) throws CertificateException { - addDefaultFilters(url, certificate); - } - - public void addDefaultFilters(String url, byte[] certificate) throws CertificateException { - filters.add(new MetadataSignatureFilter(url, certificate)); - - } - - /** - * @return the filter - */ - public List getFilters() { - return filters; - } - - - /* (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/protocols/pvp2x/verification/metadata/PVPMetadataFilterChain.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPMetadataFilterChain.java new file mode 100644 index 000000000..4c1da747b --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/PVPMetadataFilterChain.java @@ -0,0 +1,54 @@ +/* + * 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.security.cert.CertificateException; + +import at.gv.egovernment.moa.id.saml2.MetadataFilterChain; + +/** + * @author tlenz + * + */ +public class PVPMetadataFilterChain extends MetadataFilterChain { + + + /** + * @throws CertificateException + * + */ + public PVPMetadataFilterChain(String url, byte[] certificate) throws CertificateException { + addDefaultFilters(url, certificate); + } + + public void addDefaultFilters(String url, byte[] certificate) throws CertificateException { + addFilter(new MetadataSignatureFilter(url, certificate)); + + } + + + + + + +} 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 new file mode 100644 index 000000000..e7412a0fc --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/saml2/MetadataFilterChain.java @@ -0,0 +1,73 @@ +/* + * 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 filters = new ArrayList(); + + /** + * Return all actually used Metadata filters + * + * @return List of Metadata filters + */ + public List 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); + } + + } + +} -- cgit v1.2.3 From ced2df85fa74ea2db9949b18e075e20af6168df0 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 13 Jan 2016 14:03:37 +0100 Subject: add JavaDoc --- .../java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java index ad3268b90..1d8ea4cd4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java @@ -89,6 +89,11 @@ public interface AuthConfiguration extends ConfigurationProvider{ public boolean isAdvancedLoggingActive(); + /** + * Returns the PublicURLPrefix. NOTE: returns {@code null} if no PublicURLPrefix is set. + * + * @return the PublicURLPrefix without trailing slash or {@code null} + */ public String getPublicURLPrefix(); public boolean isPVP2AssertionEncryptionActive(); -- cgit v1.2.3 From be6c425ea5a82ecc3d57ae365ea2c49866d29705 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 14 Jan 2016 08:58:44 +0100 Subject: temporary problem fix for default security definitions (PVP / eIDAS SAML-engine) --- .../moa/id/opemsaml/MOAStringRedirectDeflateEncoder.java | 4 ++++ .../egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java | 8 ++++++++ .../moa/id/protocols/pvp2x/binding/RedirectBinding.java | 8 ++++++++ .../egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java | 5 +++++ .../moa/id/protocols/pvp2x/config/MOADefaultBootstrap.java | 5 ++++- 5 files changed, 29 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 index ece1a805d..acbb67b34 100644 --- 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 @@ -27,6 +27,7 @@ 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; /** @@ -45,6 +46,9 @@ public class MOAStringRedirectDeflateEncoder extends HTTPRedirectDeflateEncoder "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(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index 5402e3dce..65400444d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -28,6 +28,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.velocity.app.VelocityEngine; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.binding.SAMLMessageContext; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.decoding.HTTPPostDecoder; import org.opensaml.saml2.binding.encoding.HTTPPostEncoder; @@ -51,6 +52,7 @@ import org.opensaml.xml.security.x509.X509Credential; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; @@ -74,6 +76,9 @@ public class PostBinding implements IDecoder, IEncoder { X509Credential credentials = CredentialProvider .getIDPAssertionSigningCredential(); + //load default PVP security configurations + MOADefaultBootstrap.initializeDefaultPVPConfiguration(); + VelocityEngine engine = VelocityProvider.getClassPathVelocityEngine(); HTTPPostEncoder encoder = new HTTPPostEncoder(engine, "resources/templates/pvp_postbinding_template.html"); @@ -109,6 +114,9 @@ public class PostBinding implements IDecoder, IEncoder { X509Credential credentials = CredentialProvider .getIDPAssertionSigningCredential(); + //load default PVP security configurations + MOADefaultBootstrap.initializeDefaultPVPConfiguration(); + Logger.debug("create SAML POSTBinding response"); VelocityEngine engine = VelocityProvider.getClassPathVelocityEngine(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 81863f48f..9a505a7b0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletResponse; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.binding.SAMLMessageContext; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.decoding.HTTPRedirectDeflateDecoder; import org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder; @@ -51,6 +52,7 @@ import org.opensaml.xml.security.x509.X509Credential; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; @@ -73,6 +75,9 @@ public class RedirectBinding implements IDecoder, IEncoder { X509Credential credentials = CredentialProvider .getIDPAssertionSigningCredential(); + //load default PVP security configurations + MOADefaultBootstrap.initializeDefaultPVPConfiguration(); + Logger.debug("create SAML RedirectBinding response"); HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); @@ -103,6 +108,9 @@ public class RedirectBinding implements IDecoder, IEncoder { X509Credential credentials = CredentialProvider .getIDPAssertionSigningCredential(); + //load default PVP security configurations + MOADefaultBootstrap.initializeDefaultPVPConfiguration(); + Logger.debug("create SAML RedirectBinding response"); HTTPRedirectDeflateEncoder encoder = new HTTPRedirectDeflateEncoder(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index a2583c706..fee508d33 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -29,6 +29,7 @@ import javax.servlet.http.HttpServletResponse; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; +import org.opensaml.common.binding.SAMLMessageContext; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.encoding.HTTPSOAP11Encoder; import org.opensaml.saml2.core.RequestAbstractType; @@ -48,6 +49,7 @@ import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.signature.SignableXMLObject; 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.BindingNotSupportedException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; @@ -130,6 +132,9 @@ public class SoapBinding implements IDecoder, IEncoder { Credential credentials = CredentialProvider .getIDPAssertionSigningCredential(); + //load default PVP security configurations + MOADefaultBootstrap.initializeDefaultPVPConfiguration(); + HTTPSOAP11Encoder encoder = new HTTPSOAP11Encoder(); HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( resp, true); 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 index 80789cd12..b731e2a95 100644 --- 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 @@ -50,7 +50,10 @@ public class MOADefaultBootstrap extends DefaultBootstrap { } - + public static void initializeDefaultPVPConfiguration() { + initializeGlobalSecurityConfiguration(); + + } /** * Initializes the default global security configuration. -- cgit v1.2.3 From 78c50331e83269f25286e172fdfd4f8ae32c8633 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 14 Jan 2016 09:28:59 +0100 Subject: fix problem with eIDAS QAA to STORK QAA mapping --- .../src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java index d0da0003f..099a70470 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/PVPtoSTORKMapper.java @@ -102,7 +102,7 @@ public class PVPtoSTORKMapper { public String mapeIDASQAAToSTORKQAA(String qaaLevel) { if (mapping != null) { String input = qaaLevel.substring(eIDAS_QAA_PREFIX.length()); - String mappedQAA = mapping.getProperty(MAPPING_EIDAS_PREFIX + input); + String mappedQAA = mapping.getProperty(input); if (MiscUtil.isNotEmpty(mappedQAA)) { Logger.info("Map eIDAS-QAA " + qaaLevel + " to STORK-QAA " + mappedQAA); return mappedQAA; -- cgit v1.2.3 From 135583cbc0b9041648ab24456d6cf7081705b814 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 15 Jan 2016 13:48:58 +0100 Subject: add garbage collector to remove unsed SAML2 metadata provider (influence PVP and eIDAS metadata) --- .../moa/id/auth/MOAIDAuthInitializer.java | 5 +- .../moa/id/config/auth/AuthConfigLoader.java | 60 ----------------- .../config/auth/IGarbageCollectorProcessing.java | 36 ++++++++++ .../moa/id/config/auth/MOAGarbageCollector.java | 77 ++++++++++++++++++++++ .../pvp2x/metadata/MOAMetadataProvider.java | 22 ++++++- 5 files changed, 134 insertions(+), 66 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IGarbageCollectorProcessing.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/MOAGarbageCollector.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index 953a478be..b3055eb34 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 @@ -4,7 +4,6 @@ package at.gv.egovernment.moa.id.auth; import iaik.pki.PKIException; -import iaik.pki.jsse.IAIKX509TrustManager; import iaik.security.ecc.provider.ECCProvider; import iaik.security.provider.IAIK; @@ -17,9 +16,9 @@ import javax.net.ssl.SSLSocketFactory; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.AuthConfigLoader; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; import at.gv.egovernment.moa.id.util.AxisSecureSocketFactory; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.SSLUtils; @@ -184,7 +183,7 @@ public class MOAIDAuthInitializer { // Starts the session cleaner thread to remove unpicked authentication data AuthenticationSessionCleaner.start(); - AuthConfigLoader.start(); + MOAGarbageCollector.start(); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java deleted file mode 100644 index 1f43a0d8a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java +++ /dev/null @@ -1,60 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.config.auth; - - -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.logging.Logger; - - -public class AuthConfigLoader implements Runnable { - - private static final long INTERVAL = 24 * 60 * 60; // 24 hours - - public void run() { - while (true) { - try { - Thread.sleep(INTERVAL * 1000); - Logger.trace("Check consistence of PVP2X metadata"); - MOAMetadataProvider.reInitialize(); - - - } catch (Throwable e) { - Logger.warn("MOA-ID Configuration validation is not possible, actually. Reuse old configuration.", e); - - } finally { - - - } - } - } - - public static void start() { - // start the session cleanup thread - Thread configLoader = new Thread(new AuthConfigLoader(), "ConfigurationChecker"); - configLoader.setName("ConfigurationChecker"); - configLoader.setDaemon(true); - configLoader.setPriority(Thread.MIN_PRIORITY); - configLoader.start(); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IGarbageCollectorProcessing.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IGarbageCollectorProcessing.java new file mode 100644 index 000000000..a1008e883 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IGarbageCollectorProcessing.java @@ -0,0 +1,36 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.config.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/config/auth/MOAGarbageCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/MOAGarbageCollector.java new file mode 100644 index 000000000..1072bec5c --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/MOAGarbageCollector.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.config.auth; + + +import java.util.ArrayList; +import java.util.List; + +import at.gv.egovernment.moa.logging.Logger; + +public class MOAGarbageCollector implements Runnable { + + private static final long INTERVAL = 24 * 60 * 60; // 24 hours + private static final List processModules = + new ArrayList(); + + public void run() { + while (true) { + try { + Thread.sleep(INTERVAL * 1000); + + try { + for (IGarbageCollectorProcessing element : processModules) + element.runGarbageCollector(); + + } catch (Throwable e1) { + Logger.warn("Garbage collection FAILED in some module.", e1); + } + + } catch (Throwable e) { + Logger.warn("MOA-ID garbage collection is not possible, actually.", e); + + } finally { + + } + } + } + + /** + * Add a module to MOA internal garbage collector. Every module is executed once a day + * + * @param modul Module which should be executed by the garbage collector. + */ + public static void addModulForGarbageCollection(IGarbageCollectorProcessing modul) { + processModules.add(modul); + + } + + public static void start() { + // start the session cleanup thread + Thread configLoader = new Thread(new MOAGarbageCollector(), "MOAGarbageCollector"); + configLoader.setName("MOAGarbageCollectorr"); + configLoader.setDaemon(true); + configLoader.setPriority(Thread.MIN_PRIORITY); + configLoader.start(); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java index f4c099878..03fa686f9 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 @@ -55,6 +55,8 @@ import at.gv.egovernment.moa.id.commons.utils.MOAHttpProtocolSocketFactory; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing; +import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SchemaValidationException; @@ -66,7 +68,7 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; -public class MOAMetadataProvider implements ObservableMetadataProvider{ +public class MOAMetadataProvider implements ObservableMetadataProvider, IGarbageCollectorProcessing { private static MOAMetadataProvider instance = null; private static Object mutex = new Object(); @@ -77,18 +79,32 @@ public class MOAMetadataProvider implements ObservableMetadataProvider{ synchronized (mutex) { if (instance == null) { instance = new MOAMetadataProvider(); + + //add this to MOA garbage collector + MOAGarbageCollector.addModulForGarbageCollection(instance); + } } } return instance; } - public static void reInitialize() { + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing#runGarbageCollector() + */ + @Override + public void runGarbageCollector() { + reInitialize(); + + } + + private static void reInitialize() { synchronized (mutex) { /**add new Metadataprovider or remove Metadataprovider which are not in use any more.**/ if (instance != null) - try { + try { + Logger.trace("Check consistence of PVP2X metadata"); instance.addAndRemoveMetadataProvider(); } catch (ConfigurationException e) { -- cgit v1.2.3 From 1848868d2d5a139696c4a6ae25a5c6b528354b4c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 2 Feb 2016 14:48:18 +0100 Subject: add missing log message in PVP authentication-protocol preprocessing --- .../java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java | 2 ++ 1 file changed, 2 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') 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 ee5685e5f..c0ec086ed 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 @@ -296,6 +296,8 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { } } catch (PVP2Exception e) { + String samlRequest = request.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); throw e; } catch (SecurityPolicyException e) { -- cgit v1.2.3 From 10b6016ef4d5830dd157f13f24230c712790d789 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 8 Feb 2016 10:04:28 +0100 Subject: fix possible NullPointerException if pendingRequest is not found any more --- .../id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') 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 index 8add03da7..712ebb731 100644 --- 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 @@ -59,6 +59,12 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { IRequest pendingReq = RequestStorage.getPendingRequest( (String) executionContext.get("pendingRequestID")); + if (pendingReq == null) { + Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); + throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); + + } + //get Session from context String moasessionid = (String) executionContext.get(PARAM_SESSIONID); AuthenticationSession session = null; -- cgit v1.2.3 From d0e4e457b349e7d4ffc7b9eb146d79c8100f9781 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 10 Feb 2016 16:25:06 +0100 Subject: switch to Spring based application initializer --- .../moa/id/auth/MOAIDAuthInitializer.java | 201 ++++++++++++++++----- .../id/auth/MOAIDAuthSpringResourceProvider.java | 64 +++++++ .../auth/AuthConfigurationProviderFactory.java | 27 +-- .../PropertyBasedAuthConfigurationProvider.java | 61 +++++-- .../moa/id/entrypoints/DispatcherServlet.java | 42 ++--- 5 files changed, 283 insertions(+), 112 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java index 038a35d42..efd8248f4 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 @@ -3,21 +3,31 @@ package at.gv.egovernment.moa.id.auth; -import iaik.pki.PKIException; -import iaik.security.ecc.provider.ECCProvider; -import iaik.security.provider.IAIK; - import java.io.IOException; import java.security.GeneralSecurityException; import javax.activation.CommandMap; import javax.activation.MailcapCommandMap; +import javax.servlet.ServletContext; +import javax.servlet.ServletException; +import javax.servlet.ServletRegistration; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.support.BeanDefinitionRegistry; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.context.support.GenericApplicationContext; +import org.springframework.web.WebApplicationInitializer; +import org.springframework.web.context.ContextLoaderListener; +import org.springframework.web.context.request.RequestContextListener; +import org.springframework.web.context.support.GenericWebApplicationContext; +import org.springframework.web.context.support.ServletContextResource; +import org.springframework.web.servlet.DispatcherServlet; +import at.gv.egiz.components.spring.api.SpringLoader; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; -import at.gv.egovernment.moa.id.util.AxisSecureSocketFactory; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.SSLUtils; import at.gv.egovernment.moa.logging.Logger; @@ -27,6 +37,9 @@ import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; import at.gv.egovernment.moa.spss.server.iaik.config.IaikConfigurator; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.MiscUtil; +import iaik.pki.PKIException; +import iaik.security.ecc.provider.ECCProvider; +import iaik.security.provider.IAIK; /** * Web application initializer @@ -34,66 +47,136 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author Paul Ivancsics * @version $Id$ */ -public class MOAIDAuthInitializer { +public class MOAIDAuthInitializer implements WebApplicationInitializer { + + private String[] rootServletContexts = null; + + private String[] servletContexts = null; + + private String[] activeProfiles = null; + + public MOAIDAuthInitializer() { + this.rootServletContexts = null; + this.servletContexts = new String[] { + "/WEB-INF/applicationContext.xml", + + }; + this.activeProfiles = null; + } + + + /* (non-Javadoc) + * @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext) + */ + @Override + public void onStartup(ServletContext servletContext) throws ServletException { + try { + Logger.info("=============== Loading Root Context! ==============="); + GenericWebApplicationContext rootContext = new GenericWebApplicationContext(); + rootContext.setServletContext(servletContext); + + Logger.info("=============== Setting active profiles! ==============="); + if (this.activeProfiles != null) { + for (String profile : this.activeProfiles) { + rootContext.getEnvironment().addActiveProfile(profile); + } + } + + Logger.info("=============== Loading Local Contexts! ==============="); + XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader( + rootContext); + if (rootServletContexts != null) { + for (String rootServletContext : rootServletContexts) { + Logger.debug("Loading: "+ rootServletContext); + xmlReader.loadBeanDefinitions(new ServletContextResource( + servletContext, rootServletContext)); + } + } + // Manage the lifecycle of the root application context + servletContext.addListener(new ContextLoaderListener(rootContext)); + + // logger.debug("Beans after logAMQP in {}", rootContext); + // dumpBeanDefinitions(rootContext); + + Logger.info("=============== Loading SPI Context! ==============="); + // logger.debug("Startup with context {}", rootContext); + if (rootContext instanceof BeanDefinitionRegistry) { + Logger.debug("Loading EGIZ components"); + SpringLoader + .loadSpringServices(rootContext); + } else { + Logger.warn("Failed to load external Spring since no BeanDefinitionRegistry"); + } + + Logger.trace("Beans after SPI in "+ rootContext); + dumpBeanDefinitions(rootContext); - /** a boolean identifying if the MOAIDAuthInitializer has been startet */ - public static boolean initialized = false; + Logger.debug("Loading servlet config in "+ rootContext); + if (servletContexts != null) { + for (String servletContextString : servletContexts) { + xmlReader.loadBeanDefinitions(new ServletContextResource( + servletContext, servletContextString)); + } + } + Logger.debug("Refreshing context "+ rootContext); + rootContext.refresh(); + Logger.info("=============== Register Dispatcher Servlet! ==============="); + + Logger.trace("Final Beans in "+ rootContext); + dumpBeanDefinitions(rootContext); + + + Logger.info("Registering dispatcher configuration"); + ServletRegistration.Dynamic dispatcher = servletContext.addServlet( + "dispatcher", new DispatcherServlet(rootContext)); + if (dispatcher != null) { + dispatcher.setLoadOnStartup(1); + dispatcher.addMapping("/*"); + dispatcher.setAsyncSupported(true); + } else { + Logger.error("Failed to register dispatcher server in servlet context!"); + } + + Logger.info("=============== Register RequestContextListener! ==============="); + servletContext.addListener(new RequestContextListener()); + + Logger.info("Basic Context initalisation finished --> Start MOA-ID-Auth initialisation process ..."); + MOAIDAuthInitializer.initialize(rootContext); + Logger.info(MOAIDMessageProvider.getInstance().getMessage( + "init.00", null)); + Logger.info("MOA-ID-Auth initialization finished."); + + + } catch (Throwable e) { + Logger.fatal( + MOAIDMessageProvider.getInstance().getMessage("init.02", + null), e); + + } + + } + + + /** * Initializes the web application components which need initialization: * logging, JSSE, MOA-ID Auth configuration, Axis, session cleaner. + * @param rootContext */ - public static void initialize() throws ConfigurationException, + public static void initialize(GenericWebApplicationContext rootContext) throws ConfigurationException, PKIException, IOException, GeneralSecurityException { - if (initialized) return; - initialized = true; Logger.setHierarchy("moa.id.auth"); Logger.info("Default java file.encoding: " + System.getProperty("file.encoding")); - - Logger.info("Loading security providers."); - IAIK.addAsProvider(); - - -// Security.insertProviderAt(new IAIK(), 1); -// Security.insertProviderAt(new ECCProvider(), 1); - + //JDK bug workaround according to: // http://jce.iaik.tugraz.at/products/03_cms/faq/index.php#JarVerifier // register content data handlers for S/MIME types MailcapCommandMap mc = new MailcapCommandMap(); CommandMap.setDefaultCommandMap(mc); - // create some properties and get the default Session -// Properties props = new Properties(); -// props.put("mail.smtp.host", "localhost"); -// Session session = Session.getDefaultInstance(props, null); - - // Restricts TLS cipher suites -// System.setProperty( -// "https.cipherSuites", -// "SSL_RSA_WITH_RC4_128_SHA,SSL_RSA_WITH_RC4_128_MD5,SSL_RSA_WITH_3DES_EDE_CBC_SHA"); -// - // actual HIGH cipher suites from OpenSSL -// Mapping OpenSSL - Java -// OpenSSL Java -// http://www.openssl.org/docs/apps/ciphers.html http://docs.oracle.com/javase/6/docs/technotes/guides/security/SunProviders.html -// via !openssl ciphers -tls1 HIGH !v! -// -// ADH-AES256-SHA TLS_DH_anon_WITH_AES_256_CBC_SHA -// DHE-RSA-AES256-SHA TLS_DHE_RSA_WITH_AES_256_CBC_SHA -// DHE-DSS-AES256-SHA TLS_DHE_DSS_WITH_AES_256_CBC_SHA -// AES256-SHA TLS_RSA_WITH_AES_256_CBC_SHA -// ADH-AES128-SHA TLS_DH_anon_WITH_AES_128_CBC_SHA -// DHE-RSA-AES128-SHA TLS_DHE_RSA_WITH_AES_128_CBC_SHA -// DHE-DSS-AES128-SHA TLS_DHE_DSS_WITH_AES_128_CBC_SHA -// AES128-SHA TLS_RSA_WITH_AES_128_CBC_SHA -// ADH-DES-CBC3-SHA SSL_DH_anon_WITH_3DES_EDE_CBC_SHA -// EDH-RSA-DES-CBC3-SHA - -// EDH-DSS-DES-CBC3-SHA - -// DES-CBC3-SHA SSL_RSA_WITH_3DES_EDE_CBC_SHA - if (MiscUtil.isEmpty(System.getProperty("https.cipherSuites"))) System.setProperty( "https.cipherSuites", @@ -122,9 +205,11 @@ public class MOAIDAuthInitializer { "init.01", null), e); } + Logger.info("Loading security providers."); IAIK.addAsProvider(); ECCProvider.addAsProvider(); + // Initializes SSLSocketFactory store SSLUtils.initialize(); @@ -134,12 +219,15 @@ public class MOAIDAuthInitializer { "http://www.w3.org/2001/04/xmldsig-more#"); Constants.nSMap.put(Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); + // Initialize configuration provider - AuthConfiguration authConf = AuthConfigurationProviderFactory.reload(); + AuthConfiguration authConf = AuthConfigurationProviderFactory.reload(rootContext); - //test, if MOA-ID is already configured + + //test, if MOA-ID is already configured authConf.getPublicURLPrefix(); + // Initialize MOA-SP //MOA-SP is only use by API calls since MOA-ID 3.0.0 try { @@ -161,4 +249,17 @@ public class MOAIDAuthInitializer { MOAGarbageCollector.start(); } + private void dumpBeanDefinitions(GenericApplicationContext context) { + Logger.trace("Registered Bean in context " + context.toString()); + + String[] registeredBeans = context.getBeanDefinitionNames(); + for (String registeredBean : registeredBeans) { + BeanDefinition beanDefinition = context + .getBeanDefinition(registeredBean); + Logger.trace(registeredBean + " -> " + beanDefinition.getBeanClassName()); + + } + + Logger.trace("Registered Bean in context --"+ context); + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java new file mode 100644 index 000000000..06a1f0936 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java @@ -0,0 +1,64 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import at.gv.egiz.components.spring.api.SpringResourceProvider; + +/** + * @author tlenz + * + */ +public class MOAIDAuthSpringResourceProvider implements SpringResourceProvider { + + /* (non-Javadoc) + * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getResourcesToLoad() + */ + @Override + public Resource[] getResourcesToLoad() { + ClassPathResource moaidauthConfig = new ClassPathResource("/moaid.configuration.beans.xml", MOAIDAuthSpringResourceProvider.class); + ClassPathResource configurationDBConfig = new ClassPathResource("/configuration.beans.xml", MOAIDAuthSpringResourceProvider.class); + + return new Resource[] {configurationDBConfig, moaidauthConfig}; + } + + /* (non-Javadoc) + * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getPackagesToScan() + */ + @Override + public String[] getPackagesToScan() { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getName() + */ + @Override + public String getName() { + return "MOA-ID-Auth SpringResourceProvider"; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProviderFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProviderFactory.java index 9812f346d..a00d3d313 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProviderFactory.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProviderFactory.java @@ -22,12 +22,9 @@ */ package at.gv.egovernment.moa.id.config.auth; -import java.net.URI; -import java.net.URISyntaxException; +import org.springframework.context.ApplicationContext; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.ConfigurationProvider; import at.gv.egovernment.moa.logging.Logger; /** @@ -44,7 +41,8 @@ public class AuthConfigurationProviderFactory { throws ConfigurationException { if (instance == null) { - reload(); + Logger.fatal("MOA-ID-Auth Configuration is not initialized!!!!!"); + } return instance; } @@ -53,22 +51,9 @@ public class AuthConfigurationProviderFactory { * @return * @throws ConfigurationException */ - public static AuthConfiguration reload() throws ConfigurationException { - String fileName = System.getProperty(ConfigurationProvider.CONFIG_PROPERTY_NAME); - if (fileName == null) { - throw new ConfigurationException("config.01", null); - } - Logger.info("Loading MOA-ID-AUTH configuration " + fileName); - - try { - URI fileURI = new URI(fileName); - instance = new PropertyBasedAuthConfigurationProvider(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, fileName}); - - } + public static AuthConfiguration reload(ApplicationContext springContext) throws ConfigurationException { + instance = springContext.getBean("moaidauthconfig", AuthConfiguration.class); return instance; + } } 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 18926046c..d78b9b2ce 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 @@ -6,6 +6,7 @@ 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; @@ -17,9 +18,6 @@ import java.util.Map; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.AutowireCapableBeanFactory; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.MOAIDConstants; @@ -32,6 +30,7 @@ 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.ConfigurationException; +import at.gv.egovernment.moa.id.config.ConfigurationProvider; import at.gv.egovernment.moa.id.config.ConfigurationProviderImpl; import at.gv.egovernment.moa.id.config.ConfigurationUtils; import at.gv.egovernment.moa.id.config.ConnectionParameter; @@ -54,21 +53,44 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide private MOAIDConfiguration configuration; private final Properties properties = new Properties(); - private ApplicationContext context = null; private boolean requireJDBCBackupImplementation = false; - public PropertyBasedAuthConfigurationProvider() { + 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}); + + } } - /** - * 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 { +// /** +// * 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); +// +// } + + private void initialize(URI fileName) throws ConfigurationException { File propertiesFile = new File(fileName); rootConfigFileDir = propertiesFile.getParent(); try { @@ -87,12 +109,12 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide // 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); +// 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"); @@ -133,8 +155,9 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } } + } - + /** * Set the {@link Configuration} for this class. * @param configuration the configuration diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java index ce44db215..d1c3401a1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java @@ -25,7 +25,6 @@ package at.gv.egovernment.moa.id.entrypoints; import java.io.IOException; import java.util.Iterator; -import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -35,7 +34,6 @@ import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.MOAIDAuthInitializer; 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; @@ -78,26 +76,26 @@ public class DispatcherServlet extends AuthServlet{ public static final String PARAM_TARGET_ACTION = "action"; public static final String PARAM_TARGET_PENDINGREQUESTID = "pendingid"; - @Override - public void init(ServletConfig config) throws ServletException { - try { - super.init(config); - MOAIDAuthInitializer.initialize(); - Logger.info(MOAIDMessageProvider.getInstance().getMessage( - "init.00", null)); - - Logger.info("Dispatcher Servlet initialization finished."); - - } catch (Exception ex) { - Logger.fatal( - MOAIDMessageProvider.getInstance().getMessage("init.02", - null), ex); - - //throw new ServletException(ex); - - } - - } +// @Override +// public void init(ServletConfig config) throws ServletException { +// try { +// super.init(config); +// MOAIDAuthInitializer.initialize(); +// Logger.info(MOAIDMessageProvider.getInstance().getMessage( +// "init.00", null)); +// +// Logger.info("Dispatcher Servlet initialization finished."); +// +// } catch (Exception ex) { +// Logger.fatal( +// MOAIDMessageProvider.getInstance().getMessage("init.02", +// null), ex); +// +// //throw new ServletException(ex); +// +// } +// +// } protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { -- cgit v1.2.3 From dd2726d3260b99040eda458f46194012dccea58f Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 10 Feb 2016 17:04:18 +0100 Subject: fix problem with static content and Spring WebMVC controller --- .../main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 efd8248f4..4a004cdf0 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 @@ -132,7 +132,7 @@ public class MOAIDAuthInitializer implements WebApplicationInitializer { "dispatcher", new DispatcherServlet(rootContext)); if (dispatcher != null) { dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/*"); + dispatcher.addMapping("/"); dispatcher.setAsyncSupported(true); } else { Logger.error("Failed to register dispatcher server in servlet context!"); -- cgit v1.2.3 From ff8ae7727e4de105a1179288b129429a29bc07ca Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 10 Feb 2016 17:05:00 +0100 Subject: refactor LogOutServlet to Spring WebMVC implementation --- .../moa/id/auth/servlet/LogOutServlet.java | 137 +++++++++------------ 1 file changed, 56 insertions(+), 81 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 53187088e..a5504ec4c 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 @@ -48,11 +48,12 @@ package at.gv.egovernment.moa.id.auth.servlet; import java.io.IOException; -import javax.servlet.ServletConfig; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; @@ -64,97 +65,71 @@ import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -public class LogOutServlet extends AuthServlet { - - private static final long serialVersionUID = 3908001651893673395L; +@Controller +public class LogOutServlet { private static final String REDIRECT_URL = "redirect"; - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - Logger.debug("receive LogOut Request"); + @RequestMapping(value = "/LogOut", method = {RequestMethod.POST, RequestMethod.GET}) + public void performLogOut(HttpServletRequest req, HttpServletResponse resp) throws IOException { + Logger.debug("receive LogOut Request"); - String redirectUrl = (String) req.getParameter(REDIRECT_URL); - - SSOManager ssomanager = SSOManager.getInstance(); - - try { - //get SSO token from request - String ssoid = ssomanager.getSSOSessionID(req); + String redirectUrl = (String) req.getParameter(REDIRECT_URL); - if (MiscUtil.isEmpty(redirectUrl)) { - //set default redirect Target - Logger.debug("Set default RedirectURL back to MOA-ID-Auth"); - redirectUrl = HTTPUtils.extractAuthURLFromRequest(req); + SSOManager ssomanager = SSOManager.getInstance(); + + try { + //get SSO token from request + String ssoid = ssomanager.getSSOSessionID(req); - } else { - //return an error if RedirectURL is not a active Online-Applikation - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(redirectUrl); - if (oa == null) { - Logger.info("RedirctURL does not match to OA configuration. Set default RedirectURL back to MOA-ID-Auth"); + if (MiscUtil.isEmpty(redirectUrl)) { + //set default redirect Target + Logger.debug("Set default RedirectURL back to MOA-ID-Auth"); redirectUrl = HTTPUtils.extractAuthURLFromRequest(req); + } else { + //return an error if RedirectURL is not a active Online-Applikation + OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(redirectUrl); + if (oa == null) { + Logger.info("RedirctURL does not match to OA configuration. Set default RedirectURL back to MOA-ID-Auth"); + redirectUrl = HTTPUtils.extractAuthURLFromRequest(req); + + } + } - } - - if (ssomanager.isValidSSOSession(ssoid, null)) { - - //TODO: Single LogOut Implementation - - //delete SSO session and MOA session - AuthenticationManager authmanager = AuthenticationManager.getInstance(); - String moasessionid = AuthenticationSessionStoreage.getMOASessionSSOID(ssoid); - - RequestStorage.removePendingRequest(AuthenticationSessionStoreage.getPendingRequestID(moasessionid)); - - authmanager.performOnlyIDPLogOut(req, resp, moasessionid); - Logger.info("User with SSO Id " + ssoid + " 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; + if (ssomanager.isValidSSOSession(ssoid, null)) { - } finally { + //TODO: Single LogOut Implementation + //delete SSO session and MOA session + AuthenticationManager authmanager = AuthenticationManager.getInstance(); + String moasessionid = AuthenticationSessionStoreage.getMOASessionSSOID(ssoid); + RequestStorage.removePendingRequest(AuthenticationSessionStoreage.getPendingRequestID(moasessionid)); + + authmanager.performOnlyIDPLogOut(req, resp, moasessionid); + Logger.info("User with SSO Id " + ssoid + " 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; + + } finally { + + + } + + //Redirect to Application + resp.setStatus(302); + resp.addHeader("Location", redirectUrl); + } - - //Redirect to Application - resp.setStatus(302); - resp.addHeader("Location", redirectUrl); - } - - - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - doGet(req, resp); - } - - - /** - * Calls the web application initializer. - * - * @see javax.servlet.Servlet#init(ServletConfig) - */ - public void init(ServletConfig servletConfig) throws ServletException { -// try { -// super.init(servletConfig); -// MOAIDAuthInitializer.initialize(); -// Logger.info(MOAIDMessageProvider.getInstance().getMessage("init.00", null)); -// } -// catch (Exception ex) { -// Logger.fatal(MOAIDMessageProvider.getInstance().getMessage("init.02", null), ex); -// throw new ServletException(ex); -// } - } - + } -- cgit v1.2.3 From 1b7401488933f031a68dfe929b25db86279b52d2 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 15 Feb 2016 18:12:06 +0100 Subject: First untested part: Refactor authentication modules and process management to Spring --- .../moa/id/advancedlogging/MOAReversionLogger.java | 46 +- .../moa/id/advancedlogging/StatisticLogger.java | 108 +- .../moa/id/auth/AuthenticationSessionCleaner.java | 43 +- .../moa/id/auth/BaseAuthenticationServer.java | 64 +- .../moa/id/auth/MOAIDAuthConstants.java | 5 +- .../moa/id/auth/MOAIDAuthInitializer.java | 5 +- .../id/auth/MOAIDAuthSpringResourceProvider.java | 6 +- .../id/auth/builder/AuthenticationDataBuilder.java | 63 +- .../moa/id/auth/builder/DataURLBuilder.java | 23 +- .../moa/id/auth/builder/LoginFormBuilder.java | 3 +- .../moa/id/auth/data/AuthenticationSession.java | 52 +- .../id/auth/modules/AbstractAuthServletTask.java | 87 +- .../id/auth/modules/BKUSelectionModuleImpl.java | 68 ++ .../tasks/CreateInterfedeartionRequestTask.java | 20 +- .../internal/tasks/EvaluateBKUSelectionTask.java | 119 ++ .../internal/tasks/FinalizeAuthenticationTask.java | 50 +- .../tasks/GenerateBKUSelectionFrameTask.java | 102 ++ .../tasks/ReceiveInterfederationResponseTask.java | 3 + .../tasks/RestartAuthProzessManagement.java | 123 ++ .../StartAuthentificationParameterParser.java | 30 +- .../moa/id/auth/servlet/AbstractController.java | 238 ++++ .../AbstractProcessEngineSignalController.java | 84 ++ .../moa/id/auth/servlet/AuthServlet.java | 883 ++++++-------- .../GeneralProcessEngineSignalController.java | 51 + .../servlet/GenerateIFrameTemplateServlet.java | 336 +++--- .../id/auth/servlet/IDPSingleLogOutServlet.java | 57 +- .../moa/id/auth/servlet/LogOutServlet.java | 20 +- .../auth/servlet/ProcessEngineSignalServlet.java | 122 -- .../moa/id/auth/servlet/RedirectServlet.java | 28 +- .../servlet/SAML2InterfederationSignalServlet.java | 4 +- .../id/auth/servlet/SSOSendAssertionServlet.java | 353 +++--- .../moa/id/config/auth/IOAAuthParameters.java | 2 + .../config/auth/data/DynamicOAAuthParameters.java | 9 + .../moa/id/entrypoints/DispatcherServlet.java | 1234 ++++++++++---------- .../moa/id/moduls/AuthenticationManager.java | 668 ++++------- .../at/gv/egovernment/moa/id/moduls/IAction.java | 2 - .../gv/egovernment/moa/id/moduls/IModulInfo.java | 12 +- .../at/gv/egovernment/moa/id/moduls/IRequest.java | 159 ++- .../egovernment/moa/id/moduls/IRequestStorage.java | 41 + .../gv/egovernment/moa/id/moduls/ModulUtils.java | 92 +- .../gv/egovernment/moa/id/moduls/RequestImpl.java | 266 +++-- .../egovernment/moa/id/moduls/RequestStorage.java | 78 +- .../gv/egovernment/moa/id/moduls/SSOManager.java | 85 +- .../egovernment/moa/id/process/ProcessEngine.java | 11 + .../moa/id/process/ProcessEngineImpl.java | 42 +- .../process/dao/ProcessInstanceStoreDAOImpl.java | 8 +- .../protocols/AbstractProtocolModulController.java | 268 +++++ .../protocols/ProtocolFinalizationController.java | 199 ++++ .../UniqueSessionIdentifierInterceptor.java | 93 ++ .../id/protocols/pvp2x/AttributQueryAction.java | 15 +- .../id/protocols/pvp2x/AuthenticationAction.java | 6 +- .../moa/id/protocols/pvp2x/MetadataAction.java | 9 +- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 446 +++---- .../id/protocols/pvp2x/PVPAssertionStorage.java | 27 +- .../id/protocols/pvp2x/PVPTargetConfiguration.java | 1 - .../moa/id/protocols/pvp2x/SingleLogOutAction.java | 22 +- .../protocols/pvp2x/binding/ArtifactBinding.java | 121 -- .../id/protocols/pvp2x/binding/PostBinding.java | 3 +- .../pvp2x/requestHandler/ArtifactResolution.java | 82 -- .../pvp2x/requestHandler/AuthnRequestHandler.java | 12 +- .../pvp2x/requestHandler/RequestManager.java | 5 +- .../moa/id/storage/AssertionStorage.java | 227 ---- .../id/storage/AuthenticationSessionStoreage.java | 1130 ------------------ .../storage/DBAuthenticationSessionStoreage.java | 1049 +++++++++++++++++ .../moa/id/storage/DBExceptionStoreImpl.java | 175 --- .../moa/id/storage/DBTransactionStorage.java | 215 ++++ .../moa/id/storage/ExceptionStoreImpl.java | 58 - .../id/storage/IAuthenticationSessionStoreage.java | 281 +++++ .../moa/id/storage/IExceptionStore.java | 29 - .../moa/id/storage/ITransactionStorage.java | 90 ++ .../at/gv/egovernment/moa/id/util/HTTPUtils.java | 9 + 71 files changed, 5759 insertions(+), 4718 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractProcessEngineSignalController.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GeneralProcessEngineSignalController.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/ProtocolFinalizationController.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/UniqueSessionIdentifierInterceptor.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBExceptionStoreImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ExceptionStoreImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IAuthenticationSessionStoreage.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IExceptionStore.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java (limited to 'id/server/idserverlib/src/main/java/at') 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 7ac026888..17e39f766 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 @@ -27,10 +27,12 @@ import java.util.Arrays; import java.util.Date; import java.util.List; +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.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.id.moduls.IRequest; @@ -42,9 +44,10 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author tlenz * */ +@Service("MOAReversionLogger") public class MOAReversionLogger { - - private static MOAReversionLogger instance = null; + + @Autowired protected AuthConfiguration authConfig; private static final List defaultEventCodes = Arrays.asList( MOAIDEventConstants.SESSION_CREATED, @@ -69,17 +72,6 @@ public class MOAReversionLogger { MOAIDEventConstants.AUTHPROCESS_STORK_REQUESTED, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER ); - - - public static synchronized MOAReversionLogger getInstance() { - if (instance == null) { - instance = new MOAReversionLogger(); - MOAIDEventLog.reload(); - - } - - return instance; - } public void logEvent(IOAAuthParameters oaConfig, int eventCode, String message) { @@ -91,8 +83,8 @@ public class MOAReversionLogger { int eventCode) { if (selectOASpecificEventCodes(oaConfig).contains(eventCode)) MOAIDEventLog.logEvent(MOAIDEventLog.createNewEvent(new Date().getTime(), eventCode, - pendingRequest.getSessionIdentifier(), - pendingRequest.getRequestID())); + pendingRequest.getUniqueSessionIdentifier(), + pendingRequest.getUniqueTransactionIdentifier())); } @@ -101,8 +93,8 @@ public class MOAReversionLogger { if (selectOASpecificEventCodes(oaConfig).contains(eventCode)) MOAIDEventLog.logEvent(MOAIDEventLog.createNewEvent(new Date().getTime(), eventCode, message, - pendingRequest.getSessionIdentifier(), - pendingRequest.getRequestID() + pendingRequest.getUniqueSessionIdentifier(), + pendingRequest.getUniqueTransactionIdentifier() )); } @@ -140,8 +132,8 @@ public class MOAReversionLogger { */ public void logEvent(IRequest pendingRequest, int eventCode) { MOAIDEventLog.logEvent(MOAIDEventLog.createNewEvent(new Date().getTime(), eventCode, - pendingRequest.getSessionIdentifier(), - pendingRequest.getRequestID())); + pendingRequest.getUniqueSessionIdentifier(), + pendingRequest.getUniqueTransactionIdentifier())); } @@ -249,15 +241,9 @@ public class MOAReversionLogger { } public List getDefaulttReversionsLoggingEventCodes() { - try { - List configuredDefaultEventCodes = AuthConfigurationProviderFactory.getInstance().getDefaultRevisionsLogEventCodes(); - if (configuredDefaultEventCodes != null) - return configuredDefaultEventCodes; - - } catch (ConfigurationException e) { - Logger.error("Access to configuration FAILED.", e); - - } + List configuredDefaultEventCodes = authConfig.getDefaultRevisionsLogEventCodes(); + if (configuredDefaultEventCodes != null) + return configuredDefaultEventCodes; return defaultEventCodes; } 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 5487152cf..87b3bc9ca 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 @@ -32,6 +32,8 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.commons.lang3.StringEscapeUtils; +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.e_government.reference.namespace.mandates._20040701_.Mandator; @@ -47,16 +49,16 @@ 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.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@Service("StatisticLogger") public class StatisticLogger { private static final String GENERIC_LOCALBKU = ":3496/https-security-layer-request"; @@ -73,45 +75,19 @@ public class StatisticLogger { private static final String ERRORTYPE_MANDATE = "mandate"; private static final String ERRORTYPE_MOAID = "moa-id"; private static final String ERRORTYPE_SZRGW = "szrgw"; - - private static StatisticLogger instance; - - private boolean isAktive = false; - - public static StatisticLogger getInstance() { - if (instance == null) - instance = new StatisticLogger(); - return instance; - } - - private StatisticLogger() { - try { - AuthConfiguration config = AuthConfigurationProviderFactory.getInstance(); - - if (config != null) - isAktive = config.isAdvancedLoggingActive(); - - } catch (ConfigurationException e) { - Logger.error("StatisticLogger can not be inizialized", e); - } - } - + @Autowired AuthConfiguration authConfig; + @Autowired IAuthenticationSessionStoreage authenticatedSessionStorage; + public void logSuccessOperation(IRequest protocolRequest, IAuthData authData, boolean isSSOSession) { - if ( isAktive && protocolRequest != null && authData != null) { + if ( authConfig.isAdvancedLoggingActive() && protocolRequest != null && authData != null) { - OAAuthParameter dbOA = null; - try { - dbOA = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(protocolRequest.getOAURL()); + IOAAuthParameters dbOA = null; + dbOA = protocolRequest.getOnlineApplicationConfiguration(); - if (dbOA == null) { - Logger.warn("Advanced logging failed: OA can not be found in database."); - return; - } - - } catch (ConfigurationException e1) { - Logger.error("Access MOA-ID configuration FAILED.", e1); + if (dbOA == null) { + Logger.warn("Advanced logging failed: OA can not be found in database."); return; } @@ -221,7 +197,7 @@ public class StatisticLogger { } public void logErrorOperation(Throwable throwable) { - if ( isAktive ) { + if ( authConfig.isAdvancedLoggingActive() ) { StatisticLog dblog = new StatisticLog(); //set actual date and time @@ -249,7 +225,7 @@ public class StatisticLogger { public void logErrorOperation(Throwable throwable, IRequest errorRequest) { - if (isAktive && throwable != null && errorRequest != null) { + if (authConfig.isAdvancedLoggingActive() && throwable != null && errorRequest != null) { StatisticLog dblog = new StatisticLog(); //set actual date and time @@ -260,44 +236,45 @@ public class StatisticLogger { dblog.setProtocoltype(errorRequest.requestedModule()); dblog.setProtocolsubtype(errorRequest.requestedAction()); - try { - OAAuthParameter dbOA = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(errorRequest.getOAURL()); - if (dbOA != null) { - dblog.setOafriendlyName(dbOA.getFriendlyName()); - dblog.setOatarget(dbOA.getTarget()); - //dblog.setOaID(dbOA.getHjid()); - dblog.setBusinessservice(isBusinessService(dbOA)); - - - AuthenticationSession moasession = AuthenticationSessionStoreage.getSessionWithPendingRequestID(errorRequest.getRequestID()); + IOAAuthParameters dbOA = errorRequest.getOnlineApplicationConfiguration(); + if (dbOA != null) { + dblog.setOafriendlyName(dbOA.getFriendlyName()); + dblog.setOatarget(dbOA.getTarget()); + //dblog.setOaID(dbOA.getHjid()); + dblog.setBusinessservice(isBusinessService(dbOA)); + + try { + AuthenticationSession moasession = authenticatedSessionStorage. + getSession(errorRequest.getMOASessionIdentifier()); if (moasession != null) { if (MiscUtil.isNotEmpty(moasession.getBkuURL())) { dblog.setBkuurl(moasession.getBkuURL()); dblog.setBkutype(findBKUType(moasession.getBkuURL(), dbOA)); } - + dblog.setMandatelogin(moasession.getUseMandate()); } - - generateErrorLogFormThrowable(throwable, dblog); + } catch (MOADatabaseException e) { + Logger.debug(e.getMessage() + " --> StatistikLog will not include MOASession information."); - - try { - StatisticLogDBUtils.saveOrUpdate(dblog); + } + + generateErrorLogFormThrowable(throwable, dblog); - } catch (MOADatabaseException e) { - Logger.warn("Statistic Log can not be stored into Database", e); - } + + + try { + StatisticLogDBUtils.saveOrUpdate(dblog); + + } catch (MOADatabaseException e) { + Logger.warn("Statistic Log can not be stored into Database", e); } - } catch (ConfigurationException e) { - Logger.error("Access MOA-ID configuration FAILED.", e); - return; } } } - private boolean isBusinessService(OAAuthParameter dbOA) { + private boolean isBusinessService(IOAAuthParameters dbOA) { if (dbOA.getOaType().equals("businessService")) return true; @@ -360,7 +337,7 @@ public class StatisticLogger { } - private String findBKUType(String bkuURL, OAAuthParameter dbOA) { + private String findBKUType(String bkuURL, IOAAuthParameters dbOA) { if (dbOA != null) { if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameter.HANDYBKU))) @@ -376,14 +353,13 @@ public class StatisticLogger { Logger.trace("Staticic Log search BKUType from DefaultBKUs"); try { - AuthConfiguration authconfig = AuthConfigurationProviderFactory.getInstance(); - if (bkuURL.equals(authconfig.getDefaultBKUURL(IOAAuthParameters.ONLINEBKU))) + if (bkuURL.equals(authConfig.getDefaultBKUURL(IOAAuthParameters.ONLINEBKU))) return IOAAuthParameters.ONLINEBKU; - if (bkuURL.equals(authconfig.getDefaultBKUURL(IOAAuthParameters.LOCALBKU))) + if (bkuURL.equals(authConfig.getDefaultBKUURL(IOAAuthParameters.LOCALBKU))) return IOAAuthParameters.LOCALBKU; - if (bkuURL.equals(authconfig.getDefaultBKUURL(IOAAuthParameters.HANDYBKU))) + if (bkuURL.equals(authConfig.getDefaultBKUURL(IOAAuthParameters.HANDYBKU))) return IOAAuthParameters.HANDYBKU; } catch (ConfigurationException e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java index 1f12675ca..a1ba00e02 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 @@ -3,6 +3,14 @@ package at.gv.egovernment.moa.id.auth; +import java.util.Date; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; @@ -13,22 +21,47 @@ import at.gv.egovernment.moa.logging.Logger; * @author Paul Ivancsics * @version $Id$ */ +@Service("AuthenticationSessionCleaner") public class AuthenticationSessionCleaner implements Runnable { + @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; + @Autowired private ITransactionStorage transactionStorage; + @Autowired protected AuthConfiguration authConfig; + /** interval the AuthenticationSessionCleaner is run in */ private static final long SESSION_CLEANUP_INTERVAL = 5 * 60; // 5 min /** * Runs the thread. Cleans the AuthenticationServer session store * and authentication data store from garbage, then sleeps for given interval, and restarts. + * + * Cleans up expired session and authentication data stores. + * */ public void run() { while (true) { try { Logger.debug("AuthenticationSessionCleaner run"); - BaseAuthenticationServer.cleanup(); - } - catch (Exception e) { + Date now = new Date(); + + try { + int sessionTimeOutCreated = authConfig.getSSOCreatedTimeOut() * 1000; + int sessionTimeOutUpdated = authConfig.getSSOUpdatedTimeOut() * 1000; + int authDataTimeOut = authConfig.getTransactionTimeOut() * 1000; + + //clean AuthenticationSessionStore + authenticationSessionStorage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); + + //clean TransactionStorage + transactionStorage.clean(now, authDataTimeOut); + + + } catch (Exception e) { + Logger.error("Session cleanUp FAILED!" , e); + + } + + } catch (Exception e) { Logger.error(MOAIDMessageProvider.getInstance().getMessage("cleaner.01", null), e); } try { @@ -42,10 +75,10 @@ public class AuthenticationSessionCleaner implements Runnable { /** * start the sessionCleaner */ - public static void start() { + public static void start(Runnable clazz) { // start the session cleanup thread Thread sessionCleaner = - new Thread(new AuthenticationSessionCleaner(), "AuthenticationSessionCleaner"); + new Thread(clazz, "AuthenticationSessionCleaner"); sessionCleaner.setName("SessionCleaner"); sessionCleaner.setDaemon(true); sessionCleaner.setPriority(Thread.MIN_PRIORITY); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java index 5e3b6653b..1ce6fa1e9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java @@ -1,37 +1,13 @@ package at.gv.egovernment.moa.id.auth; -import java.io.UnsupportedEncodingException; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -import org.opensaml.xml.util.XMLHelper; - -import org.w3c.dom.Element; +import org.springframework.beans.factory.annotation.Autowired; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.client.SZRGWClient; -import at.gv.egovernment.moa.id.client.SZRGWClientException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -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; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; /** * API for MOA ID Authentication Service.
{@link AuthenticationSession} is @@ -43,6 +19,9 @@ import at.gv.util.xsd.srzgw.MISType.Filters; */ public abstract class BaseAuthenticationServer extends MOAIDAuthConstants { + @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; + @Autowired protected AuthConfiguration authConfig; + /** * Retrieves a session from the session store. * @@ -50,11 +29,11 @@ public abstract class BaseAuthenticationServer extends MOAIDAuthConstants { * @return AuthenticationSession stored with given session ID (never {@code null}). * @throws AuthenticationException in case the session id does not reflect a valic, active session. */ - public static AuthenticationSession getSession(String id) + public AuthenticationSession getSession(String id) throws AuthenticationException { AuthenticationSession session; try { - session = AuthenticationSessionStoreage.getSession(id); + session = authenticationSessionStorage.getSession(id); if (session == null) throw new AuthenticationException("auth.02", new Object[]{id}); @@ -68,33 +47,4 @@ public abstract class BaseAuthenticationServer extends MOAIDAuthConstants { } } - /** - * Cleans up expired session and authentication data stores. - */ - public static void cleanup() { - long now = new Date().getTime(); - - try { - int sessionTimeOutCreated = AuthConfigurationProviderFactory.getInstance().getSSOCreatedTimeOut() * 1000; - int sessionTimeOutUpdated = AuthConfigurationProviderFactory.getInstance().getSSOUpdatedTimeOut() * 1000; - int authDataTimeOut = AuthConfigurationProviderFactory.getInstance().getTransactionTimeOut() * 1000; - - //clean AuthenticationSessionStore - AuthenticationSessionStoreage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); - - //clean AssertionStore - AssertionStorage assertionstore = AssertionStorage.getInstance(); - assertionstore.clean(now, authDataTimeOut); - - //clean ExeptionStore - DBExceptionStoreImpl exstore = DBExceptionStoreImpl.getStore(); - exstore.clean(now, authDataTimeOut); - - } catch (Exception e) { - Logger.error("Session cleanUp FAILED!" , e); - - } - - } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index fa30f9ffd..082ebcdcd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -10,8 +10,6 @@ import java.util.List; import java.util.Map; import at.gv.egovernment.moa.id.commons.MOAIDConstants; -import at.gv.egovernment.moa.id.commons.config.persistence.MOAIDConfiguration; - import iaik.asn1.ObjectID; @@ -35,6 +33,7 @@ public class MOAIDAuthConstants extends MOAIDConstants{ public static final String PARAM_ACTION = "ACTION"; public static final String PARAM_SSO = "SSO"; public static final String INTERFEDERATION_IDP = "interIDP"; + public static final String PARAM_TARGET_PENDINGREQUESTID = "pendingid"; public static final String PARAM_SLOSTATUS = "status"; public static final String PARAM_SLORESTART = "restart"; @@ -130,6 +129,8 @@ public class MOAIDAuthConstants extends MOAIDConstants{ public static final String REQ_BKU_TYPE_HANDY = "handy"; public static final List REQ_BKU_TYPES = Arrays.asList(REQ_BKU_TYPE_LOCAL, REQ_BKU_TYPE_ONLINE, REQ_BKU_TYPE_HANDY); + public static final List LEGACYPARAMETERWHITELIST + = Arrays.asList(PARAM_TARGET, PARAM_BKU, PARAM_OA, PARAM_TEMPLATE, PARAM_USEMANDATE, PARAM_CCC, PARAM_SOURCEID); public final static String EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION = "OIDTextualDescription"; public final static String EXT_SAML_MANDATE_OID = "OID"; 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 4a004cdf0..5968736f8 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 @@ -223,7 +223,6 @@ public class MOAIDAuthInitializer implements WebApplicationInitializer { // Initialize configuration provider AuthConfiguration authConf = AuthConfigurationProviderFactory.reload(rootContext); - //test, if MOA-ID is already configured authConf.getPublicURLPrefix(); @@ -245,7 +244,9 @@ public class MOAIDAuthInitializer implements WebApplicationInitializer { // Starts the session cleaner thread to remove unpicked authentication data - AuthenticationSessionCleaner.start(); + AuthenticationSessionCleaner sessioncleaner = rootContext.getBean("AuthenticationSessionCleaner", AuthenticationSessionCleaner.class); + AuthenticationSessionCleaner.start(sessioncleaner); + MOAGarbageCollector.start(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java index 06a1f0936..a82a958db 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java @@ -40,8 +40,10 @@ public class MOAIDAuthSpringResourceProvider implements SpringResourceProvider { public Resource[] getResourcesToLoad() { ClassPathResource moaidauthConfig = new ClassPathResource("/moaid.configuration.beans.xml", MOAIDAuthSpringResourceProvider.class); ClassPathResource configurationDBConfig = new ClassPathResource("/configuration.beans.xml", MOAIDAuthSpringResourceProvider.class); - - return new Resource[] {configurationDBConfig, moaidauthConfig}; + ClassPathResource moaIdAuthBeans = new ClassPathResource("/moaid.authentication.beans.xml", MOAIDAuthSpringResourceProvider.class); + + return new Resource[] {configurationDBConfig, moaidauthConfig, moaIdAuthBeans}; + } /* (non-Javadoc) 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 fe29dd2b7..5bde82899 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 @@ -22,8 +22,6 @@ */ package at.gv.egovernment.moa.id.auth.builder; -import iaik.x509.X509Certificate; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -51,6 +49,8 @@ import org.opensaml.saml2.core.Response; 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 org.w3c.dom.Element; import org.w3c.dom.Node; @@ -81,7 +81,6 @@ import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; @@ -89,6 +88,7 @@ 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.moduls.IRequest; +import at.gv.egovernment.moa.id.moduls.RequestImpl; 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; @@ -96,11 +96,12 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExt 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.messages.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; 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.SAMLVerificationEngine; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; @@ -114,14 +115,19 @@ import at.gv.util.config.EgovUtilPropertiesConfiguration; import at.gv.util.ex.EgovUtilException; import at.gv.util.wsdl.szr.SZRException; import at.gv.util.xsd.szr.PersonInfoType; +import iaik.x509.X509Certificate; /** * @author tlenz * */ +@Service("AuthenticationDataBuilder") public class AuthenticationDataBuilder extends MOAIDAuthConstants { - public static IAuthData buildAuthenticationData(IRequest protocolRequest, + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; + @Autowired protected AuthConfiguration authConfig; + + public IAuthData buildAuthenticationData(IRequest protocolRequest, AuthenticationSession session, List reqAttributes) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { @@ -166,7 +172,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } //reuse some parameters if it is a reauthentication - OASessionStore activeOA = AuthenticationSessionStoreage.searchActiveOASSOSession(session, oaID, protocolRequest.requestedModule()); + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, oaID, protocolRequest.requestedModule()); if (activeOA != null) { authdata.setSessionIndex(activeOA.getAssertionSessionID()); authdata.setNameID(activeOA.getUserNameID()); @@ -187,13 +193,12 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } - InterfederationSessionStore interfIDP = AuthenticationSessionStoreage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); + InterfederationSessionStore interfIDP = authenticatedSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); IOAAuthParameters oaParam = null; if (reqAttributes == null) { //get OnlineApplication from MOA-ID-Auth configuration - oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(oaID); + oaParam = authConfig.getOnlineApplicationParameter(oaID); //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway if (oaParam.isSTORKPVPGateway()) @@ -215,7 +220,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } else { //get attributes from interfederated IDP - OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(interfIDP.getIdpurlprefix()); + OAAuthParameter idp = authConfig.getOnlineApplicationParameter(interfIDP.getIdpurlprefix()); getAuthDataFromInterfederation(authdata, session, oaParam, protocolRequest, interfIDP, idp, reqAttributes); //mark attribute request as used @@ -248,7 +253,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { * @throws BuildException * @throws DynamicOABuildException */ - public static IAuthData buildAuthenticationData(IRequest req, + public IAuthData buildAuthenticationData(IRequest req, AuthenticationSession session) throws WrongParametersException, ConfigurationException, BuildException, DynamicOABuildException { return buildAuthenticationData(req, session, null); } @@ -263,7 +268,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { * @param reqQueryAttr * @throws ConfigurationException */ - private static void getAuthDataFromInterfederation( + private void getAuthDataFromInterfederation( AuthenticationData authdata, AuthenticationSession session, IOAAuthParameters oaParam, IRequest req, InterfederationSessionStore interfIDP, OAAuthParameter idp, List reqQueryAttr) throws BuildException, ConfigurationException{ @@ -280,11 +285,13 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { //IDP is a service provider IDP and request interfederated IDP to collect attributes } else { //get PVP 2.1 attributes from protocol specific requested attributes - attributs = req.getRequestedAttributes(); + attributs = (List) req.getGenericData(RequestImpl.DATAID_REQUESTED_ATTRIBUTES); } - Response intfResp = (Response) req.getInterfederationResponse().getResponse(); + Response intfResp = + (Response) req.getGenericData( + RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, MOAResponse.class).getResponse(); AssertionAttributeExtractor extractor = new AssertionAttributeExtractor(intfResp); @@ -362,7 +369,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } - private static void buildAuthDataFormInterfederationResponse( + private void buildAuthDataFormInterfederationResponse( AuthenticationData authData, AuthenticationSession session, AssertionAttributeExtractor extractor, @@ -500,7 +507,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { if (MiscUtil.isEmpty(authData.getIdentificationValue())) { Logger.info("No baseID found. Connect SZR to reveive baseID ..."); try { - EgovUtilPropertiesConfiguration eGovClientsConfig = AuthConfigurationProviderFactory.getInstance().geteGovUtilsConfig(); + EgovUtilPropertiesConfiguration eGovClientsConfig = authConfig.geteGovUtilsConfig(); if (eGovClientsConfig != null) { SZRClient szrclient = new SZRClient(eGovClientsConfig); @@ -534,11 +541,6 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } - } catch (ConfigurationException e) { - Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); - } catch (EgovUtilException e) { Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME @@ -843,7 +845,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { * @param authData * @return */ - private static boolean matchsReceivedbPKToOnlineApplication( + private boolean matchsReceivedbPKToOnlineApplication( IOAAuthParameters oaParam, AuthenticationData authData) { String oaTarget = null; @@ -870,7 +872,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { return false; } - private static void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, + private void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { IdentityLink identityLink = session.getIdentityLink(); @@ -964,11 +966,11 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } try { - authData.setSsoSession(AuthenticationSessionStoreage.isSSOSession(session.getSessionID())); + authData.setSsoSession(protocolRequest.needSingleSignOnFunctionality()); //set max. SSO session time if (authData.isSsoSession()) { - long maxSSOSessionTime = AuthConfigurationProviderFactory.getInstance().getSSOCreatedTimeOut() * 1000; + long maxSSOSessionTime = authConfig.getSSOCreatedTimeOut() * 1000; Date ssoSessionValidTo = new Date(session.getSessionCreated().getTime() + maxSSOSessionTime); authData.setSsoSessionValidTo(ssoSessionValidTo); @@ -1016,7 +1018,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } - private static void buildOAspecificIdentityLink(IOAAuthParameters oaParam, AuthenticationData authData, IdentityLink idl) throws MOAIDException { + private void buildOAspecificIdentityLink(IOAAuthParameters oaParam, AuthenticationData authData, IdentityLink idl) throws MOAIDException { if (oaParam.getBusinessService()) { Element idlassertion = idl.getSamlAssertion(); //set bpk/wpbk; @@ -1033,9 +1035,8 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); Element resignedilAssertion; - AuthConfiguration config = AuthConfigurationProviderFactory.getInstance(); - if (config.isIdentityLinkResigning()) { - resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion(), config.getIdentityLinkResigningKey()); + if (authConfig.isIdentityLinkResigning()) { + resignedilAssertion = identitylinkresigner.resignIdentityLink(businessServiceIdl.getSamlAssertion(), authConfig.getIdentityLinkResigningKey()); } else { resignedilAssertion = businessServiceIdl.getSamlAssertion(); } @@ -1050,7 +1051,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } - private static void buildOAspecificbPK(IRequest protocolRequest, IOAAuthParameters oaParam, AuthenticationData authData, String baseID, String baseIDType) throws BuildException { + private void buildOAspecificbPK(IRequest protocolRequest, IOAAuthParameters oaParam, AuthenticationData authData, String baseID, String baseIDType) throws BuildException { if (oaParam.getBusinessService()) { //since we have foreigner, wbPK is not calculated in BKU @@ -1082,7 +1083,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } if (saml1Requst != null && protocolRequest.getClass().isInstance(saml1Requst)) - target = protocolRequest.getTarget(); + target = protocolRequest.getGenericData("target", String.class); else target = oaParam.getTarget(); 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 index d4350f97b..9a2baf873 100644 --- 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 @@ -47,7 +47,6 @@ package at.gv.egovernment.moa.id.auth.builder; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; /** * Builds a DataURL parameter meant for the security layer implementation @@ -76,31 +75,13 @@ public class DataURLBuilder { * @return String */ public String buildDataURL(String authBaseURL, String authServletName, String sessionID) { - -// String individualDataURLPrefix = null; - String dataURL; - - //is removed from config in MOA-ID 2.0 - //check if an individual prefix is configured -// individualDataURLPrefix = AuthConfigurationProvider.getInstance(). -// getGenericConfigurationParameter(AuthConfigurationProvider.INDIVIDUAL_DATA_URL_PREFIX); -// -// if (null != individualDataURLPrefix) { -// -// //check individualDataURLPrefix -// if(!individualDataURLPrefix.startsWith("http")) -// throw(new ConfigurationException("config.13", new Object[] { individualDataURLPrefix})); -// -// //when ok then use it -// dataURL = individualDataURLPrefix + authServletName; -// } else - + String dataURL; if (!authBaseURL.endsWith("/")) authBaseURL += "/"; dataURL = authBaseURL + authServletName; - dataURL = addParameter(dataURL, MOAIDAuthConstants.PARAM_SESSIONID, sessionID); + dataURL = addParameter(dataURL, MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, sessionID); return dataURL; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java index 99ba49d26..c22432d0d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java @@ -36,7 +36,6 @@ import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.config.stork.CPEPS; import at.gv.egovernment.moa.id.util.FormBuildUtils; import at.gv.egovernment.moa.logging.Logger; @@ -119,7 +118,7 @@ public class LoginFormBuilder { return template; } - public static String buildLoginForm(String modul, String action, OAAuthParameter oaParam, String contextpath, String moaSessionID) { + public static String buildLoginForm(String modul, String action, IOAAuthParameters oaParam, String contextpath, String moaSessionID) { String value = null; 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 ae3ec9a9b..3849eb8a2 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 @@ -36,8 +36,6 @@ package at.gv.egovernment.moa.id.auth.data; -import iaik.x509.X509Certificate; - import java.io.Serializable; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; @@ -53,6 +51,7 @@ import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.MiscUtil; +import iaik.x509.X509Certificate; /** * Session data to be stored between AuthenticationServer API calls. @@ -218,16 +217,7 @@ public class AuthenticationSession implements Serializable { */ private String pushInfobox; - // private AuthenticationData authData; - - // protocol selection - private String action; - private String modul; - - private String processInstanceId; - private boolean authenticated; - private boolean authenticatedUsed = false; private boolean ssoRequested = false; @@ -238,31 +228,7 @@ public class AuthenticationSession implements Serializable { private boolean isForeigner; private Map genericSessionDataStorate = new HashedMap(); - - public String getModul() { - return modul; - } - - public void setModul(String modul) { - this.modul = modul; - } - - public String getAction() { - return action; - } - - public void setAction(String action) { - this.action = action; - } - public boolean isAuthenticatedUsed() { - return authenticatedUsed; - } - - public void setAuthenticatedUsed(boolean authenticatedUsed) { - this.authenticatedUsed = authenticatedUsed; - } - public boolean isAuthenticated() { return authenticated; } @@ -852,22 +818,6 @@ public class AuthenticationSession implements Serializable { return sessionCreated; } - /** - * Returns the identifier of the process instance associated with this moaid session. - * @return The process instance id (may be {@code null} if no process has been created yet). - */ - public String getProcessInstanceId() { - return processInstanceId; - } - - /** - * Sets the process instance identifier in order to associate a certain process instance with this moaid session. - * @param processInstanceId The process instance id. - */ - public void setProcessInstanceId(String processInstanceId) { - this.processInstanceId = processInstanceId; - } - public Map getGenericSessionDataStorage() { return genericSessionDataStorate; } 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 index 67ddd170a..a73fd6858 100644 --- 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 @@ -1,6 +1,12 @@ package at.gv.egovernment.moa.id.auth.modules; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_CACHE_CONTROL; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_EXPIRES; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_PRAGMA; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_EXPIRES; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_PRAGMA; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -24,17 +30,23 @@ 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.advancedlogging.StatisticLogger; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.moduls.IRequestStorage; import at.gv.egovernment.moa.id.process.springweb.MoaIdTask; -import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -import at.gv.egovernment.moa.id.storage.IExceptionStore; +import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController; +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.id.util.ServletUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -45,6 +57,13 @@ import at.gv.egovernment.moa.util.MiscUtil; */ public abstract class AbstractAuthServletTask extends MoaIdTask { + @Autowired private StatisticLogger statisticLogger; + @Autowired private ITransactionStorage transactionStorage; + @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 void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, @@ -66,11 +85,8 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { req.setAttribute("LogLevel", "debug"); } - - StatisticLogger logger = StatisticLogger.getInstance(); - logger.logErrorOperation(exceptionThrown); - - + statisticLogger.logErrorOperation(exceptionThrown); + // forward this to errorpage-auth.jsp where the HTML error page is // generated ServletContext context = req.getServletContext(); @@ -132,31 +148,42 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { Logger.error("Receive an internal error: Message=" + exceptionThrown.getMessage(), exceptionThrown); } + - IExceptionStore store = DBExceptionStoreImpl.getStore(); - String id = store.storeException(exceptionThrown); - - if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { - - String redirectURL = null; - - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id - + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - return; + try { + String key = Random.nextRandom(); + transactionStorage.put(key, exceptionThrown); - } else { + if (key != null && MiscUtil.isNotEmpty(pendingRequestID)) { + String redirectURL = null; + + redirectURL = ServletUtils.getBaseUrl(req) + "/"; + redirectURL += AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT + + "?" + ERROR_CODE_PARAM + "=" + key + + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - //Exception can not be stored in database + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + return; + + } else { + //Exception can not be stored in database + handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); + } + + } catch (MOADatabaseException e) { + Logger.warn("Exception can not be stored to Database.", e); handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); + } + + + + } /** 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 new file mode 100644 index 000000000..8b02a5bf6 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java @@ -0,0 +1,68 @@ +/* + * 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.process.api.ExecutionContext; + +/** + * @author tlenz + * + */ +public class BKUSelectionModuleImpl implements AuthModule { + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getPriority() + */ + @Override + public int getPriority() { + return 0; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#selectProcess(at.gv.egovernment.moa.id.process.api.ExecutionContext) + */ + @Override + public String selectProcess(ExecutionContext context) { + boolean performBKUSelection = false; + Object performBKUSelectionObj = context.get("performBKUSelection"); + if (performBKUSelectionObj != null && performBKUSelectionObj instanceof Boolean) + performBKUSelection = (boolean) performBKUSelectionObj; + + if (performBKUSelection) + return "BKUSelectionProcess"; + + else + return null; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getProcessDefinitions() + */ + @Override + public String[] getProcessDefinitions() { + return new String[] { "classpath:at/gv/egovernment/moa/id/auth/modules/internal/BKUSelection.process.xml" }; + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java index 4a6ecd56a..f1ab58ee0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java @@ -44,9 +44,9 @@ import org.opensaml.saml2.metadata.SingleSignOnService; import org.opensaml.saml2.metadata.provider.MetadataProviderException; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; @@ -55,13 +55,12 @@ import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; +import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.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.PVP2Exception; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; @@ -73,6 +72,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author tlenz * */ +@Service("CreateInterfedeartionRequestTask") public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { /* (non-Javadoc) @@ -84,8 +84,8 @@ public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { throws TaskExecutionException { boolean requiredLocalAuthentication = true; - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); + IRequest pendingReq = requestStoreage.getPendingRequest( + (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); String idpEntityID = (String) executionContext.get(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID); @@ -105,8 +105,10 @@ public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(idpEntityID); OAAuthParameter sp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(pendingReq.getOAURL()); + String requestedIDP = pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) { - Logger.info("Requested interfederation IDP " + pendingReq.getRequestedIDP() + " is not valid for interfederation."); + Logger.info("Requested interfederation IDP " + requestedIDP + " is not valid for interfederation."); Logger.debug("isInderfederationIDP:" + String.valueOf(idp.isInderfederationIDP()) + " isInboundSSOAllowed:" + String.valueOf(idp.isInboundSSOInterfederationAllowed())); Logger.info("Switch to local authentication on this IDP ... "); @@ -252,18 +254,18 @@ public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { //build and send request without an error requiredLocalAuthentication = false; - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_IDP, idpEntity.getEntityID()); } else { - Logger.warn("Requested IDP " + pendingReq.getRequestedIDP() + Logger.warn("Requested IDP " + requestedIDP + " does not support POST or Redirect Binding."); } } else { - Logger.warn("Requested IDP " + pendingReq.getRequestedIDP() + Logger.warn("Requested IDP " + requestedIDP + " is not found in InterFederation configuration"); } 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 new file mode 100644 index 000000000..fe3e8680c --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java @@ -0,0 +1,119 @@ +/* + * 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.Enumeration; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +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.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +@Service("EvaluateBKUSelectionTask") +public class EvaluateBKUSelectionTask 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 { + //load pending request + String pendingReqID = request.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); + pendingReqID = StringEscapeUtils.escapeHtml(pendingReqID); + IRequest pendingReq = requestStoreage.getPendingRequest(pendingReqID); + + if (pendingReq == null) { + Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); + throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); + + } + + //change pending-request ID + String newPendingRequestID = requestStoreage.changePendingRequestID(pendingReq); + executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, newPendingRequestID); + + AuthenticationSession moaSession = null; + String moaSessionID = pendingReq.getMOASessionIdentifier(); + try { + moaSession = authenticatedSessionStorage.getSession(moaSessionID); + + if (moaSession == null) { + Logger.info("MOASession with SessionID="+ moaSessionID + " is not found in Database"); + throw new MOAIDException("init.04", new Object[] { + moaSessionID}); + + } + + // set parameter execution context + Enumeration reqParamNames = request.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (MiscUtil.isNotEmpty(paramName)) + executionContext.put(paramName, request.getParameter(paramName)); + + } + + Logger.info("BKU is selected finished -> Start BKU communication ..."); + + } catch (MOADatabaseException e) { + Logger.info("MOASession with SessionID="+ moaSessionID + " is not found in Database"); + throw new MOAIDException("init.04", new Object[] { + moaSessionID}); + + } catch (Throwable e) { + Logger.info("No HTTP Session found!"); + throw new MOAIDException("auth.18", new Object[] {}); + } + + + + + } catch (MOAIDException e) { + throw new TaskExecutionException(e.getMessage(), e); + + } catch (Exception e) { + Logger.warn("EvaluateBKUSelectionTask has an internal error", e); + throw new TaskExecutionException(e.getMessage(), e); + + } + } + +} 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 index 712ebb731..ed309d85a 100644 --- 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 @@ -22,11 +22,12 @@ */ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -34,10 +35,9 @@ 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.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.moduls.RequestStorage; +import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -45,6 +45,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author tlenz * */ +@Service("FinalizeAuthenticationTask") public class FinalizeAuthenticationTask extends AbstractAuthServletTask { /* (non-Javadoc) @@ -56,8 +57,8 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { throws TaskExecutionException { try { - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); + IRequest pendingReq = requestStoreage.getPendingRequest( + (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); if (pendingReq == null) { Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); @@ -66,7 +67,7 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { } //get Session from context - String moasessionid = (String) executionContext.get(PARAM_SESSIONID); + String moasessionid = pendingReq.getMOASessionIdentifier(); AuthenticationSession session = null; if (MiscUtil.isEmpty(moasessionid)) { Logger.warn("MOASessionID is empty."); @@ -74,9 +75,14 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { } try { - session = AuthenticationSessionStoreage.getSession(moasessionid); - AuthenticationSessionStoreage.changeSessionID(session); - + session = authenticatedSessionStorage.getSession(moasessionid); + if (session == null) { + Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); + throw new MOAIDException("init.04", new Object[] { moasessionid }); + + } + + } catch (MOADatabaseException e) { Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); throw new MOAIDException("init.04", new Object[] { moasessionid }); @@ -86,25 +92,25 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { throw new MOAIDException("auth.18", new Object[] {}); } finally { - executionContext.remove(PARAM_SESSIONID); + executionContext.remove(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID); } - - session.setAuthenticatedUsed(false); - session.setAuthenticated(true); - - String oldsessionID = session.getSessionID(); + //set MOASession to authenticated and store MOASession + session.setAuthenticated(true); + String newMOASessionID = authenticatedSessionStorage.changeSessionID(session); - //Session is implicte stored in changeSessionID!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + //set pendingRequest to authenticated and set new MOASessionID + ((RequestImpl)pendingReq).setMOASessionIdentifier(newMOASessionID); + pendingReq.setAuthenticated(true); + requestStoreage.storePendingRequest(pendingReq); Logger.info("AuthProcess finished. Redirect to Protocol Dispatcher."); - String redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), - ModulUtils.buildAuthURL(pendingReq.requestedModule(), pendingReq.requestedAction(), pendingReq.getRequestID()), newMOASessionID); - + String redirectURL = new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), + AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT, pendingReq.getRequestID()); + response.setContentType("text/html"); response.setStatus(302); response.addHeader("Location", redirectURL); 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 new file mode 100644 index 000000000..1bdc132d9 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java @@ -0,0 +1,102 @@ +/* + * 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.io.PrintWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.LoginFormBuilder; +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +@Service("GenerateBKUSelectionFrameTask") +public class GenerateBKUSelectionFrameTask 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 { + IRequest pendingReq = requestStoreage.getPendingRequest( + (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); + + if (pendingReq == null) { + Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); + throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); + + } + + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUSELECTION_INIT); + + //load Parameters from OnlineApplicationConfiguration + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + + if (oaParam == null) { + throw new AuthenticationException("auth.00", new Object[] { pendingReq.getOAURL() }); + + } + + //Build authentication form + String publicURLPreFix = pendingReq.getAuthURL(); + if (publicURLPreFix.endsWith("/")) + publicURLPreFix = publicURLPreFix.substring(0, publicURLPreFix.length() - 1); + String loginForm = LoginFormBuilder.buildLoginForm(pendingReq.requestedModule(), + pendingReq.requestedAction(), oaParam, publicURLPreFix, MOAIDAuthConstants.PARAM_SESSIONID); + + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.print(loginForm); + out.flush(); + + + } catch (MOAIDException e) { + throw new TaskExecutionException(e.getMessage(), e); + + } catch (Exception e) { + Logger.warn("FinalizeAuthenticationTask has an internal error", e); + throw new TaskExecutionException(e.getMessage(), e); + + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java index f05ff07e9..77aab8ddb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java @@ -25,6 +25,8 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Service; + import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.process.api.ExecutionContext; @@ -33,6 +35,7 @@ import at.gv.egovernment.moa.id.process.api.ExecutionContext; * @author tlenz * */ +@Service("ReceiveInterfederationResponseTask") public class ReceiveInterfederationResponseTask extends AbstractAuthServletTask { /* (non-Javadoc) 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 new file mode 100644 index 000000000..d8b558846 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java @@ -0,0 +1,123 @@ +/* + * 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.Service; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.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.moduls.IRequest; +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 + * + */ +@Service("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 { + IRequest pendingReq = requestStoreage.getPendingRequest( + (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); + + if (pendingReq == null) { + Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); + throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); + + } + + //create a new execution context and copy all elements to new context + ExecutionContext newec = new ExecutionContextImpl(); + Set entries = executionContext.keySet(); + for (String key : entries) { + newec.put(key, executionContext.get(key)); + + } + + //remove BKU selection flag + newec.remove("performBKUSelection"); + + + Logger.debug("Swicht to specific authentication process after BKU is selected"); + + // 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("BKU is selected -> Start BKU communication ..."); + + // start process + processEngine.start(processInstanceId); + + + } catch (MOAIDException e) { + throw new TaskExecutionException(e.getMessage(), e); + + } catch (Exception e) { + Logger.warn("RestartAuthProzessManagement has an internal error", e); + throw new TaskExecutionException(e.getMessage(), e); + + } + + } + +} 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 e659c9447..8af8ed238 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 @@ -25,7 +25,6 @@ package at.gv.egovernment.moa.id.auth.parser; import java.util.List; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; @@ -54,8 +53,6 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ String templateURL, String useMandate, String ccc, - String module, - String action, HttpServletRequest req, IRequest protocolReq) throws WrongParametersException, MOAIDException { @@ -129,7 +126,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ if (!oaParam.getBusinessService()) { if (StringUtils.isEmpty(targetConfig) - || (module.equals("id_saml1") && + || (protocolReq.requestedModule().equals("at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol") && !StringUtils.isEmpty(target)) ) { //INFO: ONLY SAML1 legacy mode @@ -278,25 +275,8 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ public static void parse(ExecutionContext ec, HttpServletRequest req, AuthenticationSession moasession, IRequest request) throws WrongParametersException, MOAIDException { - - - String modul = request.requestedModule();//req.getParameter(PARAM_MODUL); - String action = request.requestedAction();//req.getParameter(PARAM_ACTION); - - modul = StringEscapeUtils.escapeHtml(modul); - action = StringEscapeUtils.escapeHtml(action); -// if(modul == null) { -// modul = SAML1Protocol.PATH; -// } -// -// if(action == null) { -// action = SAML1Protocol.GETARTIFACT; -// } - moasession.setModul(modul); - moasession.setAction(action); - + //get Parameters from request - String target = (String) ec.get(PARAM_TARGET); String oaURL = (String) ec.get(PARAM_OA); String bkuURL = (String) ec.get(PARAM_BKU); String templateURL = (String) ec.get(PARAM_TEMPLATE); @@ -312,9 +292,11 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ } oaURL = request.getOAURL(); - target = request.getTarget(); + + //only needed for SAML1 + String target = request.getGenericData("target", String.class); - parse(moasession, target, oaURL, bkuURL, templateURL, useMandate, ccc, modul, action, req, request); + parse(moasession, target, oaURL, bkuURL, templateURL, useMandate, ccc, req, request); } 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 new file mode 100644 index 000000000..26e24f5b4 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -0,0 +1,238 @@ +/* + * 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 javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.ExceptionHandler; + +import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; +import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.moduls.IRequestStorage; +import at.gv.egovernment.moa.id.process.ProcessExecutionException; +import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController; +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.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 StatisticLogger statisticLogger; + @Autowired protected IRequestStorage requestStorage; + @Autowired protected ITransactionStorage transactionStorage; + @Autowired protected MOAReversionLogger revisionsLogger; + @Autowired protected AuthConfiguration authConfig; + + + protected void handleError(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) throws IOException { + + Throwable loggedException = null; + + if (exceptionThrown != null + && exceptionThrown instanceof ProcessExecutionException) { + ProcessExecutionException procExc = + (ProcessExecutionException) exceptionThrown; + if (procExc.getCause() != null && + procExc.getCause() instanceof TaskExecutionException) { + TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); + loggedException = taskExc.getOriginalException(); + + } + } + + if (loggedException == null) + loggedException = exceptionThrown; + + + if (!(loggedException instanceof MOAIDException)) { + Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); + + } else { + if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { + Logger.error(loggedException.getMessage(), loggedException); + + } else { + Logger.error(loggedException.getMessage()); + + } + } + + //store error into transaction store + try { + String key = Random.nextRandom(); + transactionStorage.put(key, exceptionThrown); + + if (key != null && MiscUtil.isNotEmpty(pendingRequestID)) { + String redirectURL = null; + + redirectURL = ServletUtils.getBaseUrl(req); + redirectURL += AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT + + "?" + ERROR_CODE_PARAM + "=" + key + + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; + + resp.setContentType("text/html"); + resp.setStatus(302); + + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); + + return; + + } else { + //Exception can not be stored in database + handleErrorNoRedirect(loggedException, req, resp); + + } + + } catch (MOADatabaseException e) { + Logger.warn("Exception can not be stored to Database.", e); + handleErrorNoRedirect(loggedException, req, resp); + + } + + + } + + + /** + * 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) throws IOException { + + //log Exception into statistic database + statisticLogger.logErrorOperation(throwable); + + //write errror to console + Logger.error(throwable.getMessage(), throwable); + + //return error to Web browser + if (throwable instanceof MOAIDException) + MOAIDExceptionHandler(req, resp, (MOAIDException)throwable); + + else + GenericExceptionHandler(req, resp, (Exception)throwable); + } + + @ExceptionHandler({MOAIDException.class}) + public void MOAIDExceptionHandler(HttpServletRequest req, HttpServletResponse resp, MOAIDException e) throws IOException { + if (e instanceof ProtocolNotActiveException) { + resp.getWriter().write(e.getMessage()); + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); + return; + + } else if (e instanceof AuthnRequestValidatorException) { + AuthnRequestValidatorException ex = (AuthnRequestValidatorException)e; + //log Error Message + statisticLogger.logErrorOperation(ex, ex.getErrorRequest()); + return; + + } else if (e instanceof InvalidProtocolRequestException) { + //write log entry + String samlRequest = req.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + + //send error response + ErrorResponseUtils utils = ErrorResponseUtils.getInstance(); + String code = utils.mapInternalErrorToExternalError(e.getMessageId()); + String descr = e.getMessage(); + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Protocol validation FAILED!" + + "(Errorcode=" + code + + " | Description=" + descr + ")"); + return; + } else if (e instanceof ConfigurationException) { + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + + "(Errorcode=9199" + +" | Description="+ e.getMessage() + ")"); + return; + + //TODO: check exception type + } else if (e instanceof MOAIDException) { + String samlRequest = req.getParameter("SAMLRequest"); + if (MiscUtil.isNotEmpty(samlRequest)) + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + else + Logger.error("Failed to generate a valid protocol request!"); + + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + + "(Errorcode=6000" + +" | Description=Das Authentifizierungsprotokoll wurde nicht erkannt oder wird nicht unterst\u00FCzt" + ")"); + return; + + } + + } + + @ExceptionHandler({Exception.class}) + public void GenericExceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception exception) throws IOException { + Logger.error("Internel Server Error." , exception); + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + + "(Errorcode=9199" + +" | Description="+ exception.getMessage() + ")"); + return; + + } + + @ExceptionHandler({IOException.class}) + public void IOExceptionHandler(HttpServletRequest req, HttpServletResponse resp, IOException exception) { + Logger.error("Internel Server Error." , exception); + resp.setContentType("text/html;charset=UTF-8"); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + + } +} 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 new file mode 100644 index 000000000..375afca4d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractProcessEngineSignalController.java @@ -0,0 +1,84 @@ +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.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.moduls.IRequest; +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 ProcessEngine processEngine; + + protected void signalProcessManagement(HttpServletRequest req, HttpServletResponse resp) throws IOException { + String pendingRequestID = StringEscapeUtils.escapeHtml(getPendingRequestId(req)); + + try { + if (pendingRequestID == null) { + throw new IllegalStateException("Unable to determine MOA pending-request id."); + } + + IRequest 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}); + + } + + //add transactionID and unique sessionID to Logger + TransactionIDUtils.setSessionId(pendingReq.getUniqueSessionIdentifier()); + TransactionIDUtils.setTransactionId(pendingReq.getUniqueTransactionIdentifier()); + + // process instance is mandatory + if (pendingReq.getProcessInstanceId() == null) { + throw new IllegalStateException("MOA session does not provide process instance id."); + } + + // wake up next task + processEngine.signal(pendingReq.getProcessInstanceId()); + + } catch (Exception ex) { + handleError(null, ex, req, resp, pendingRequestID); + + } finally { + //MOASessionDBUtils.closeSession(); + TransactionIDUtils.removeTransactionId(); + TransactionIDUtils.removeSessionId(); + + } + + + } + + /** + * Retrieves the current pending-request id from the HttpServletRequest parameter + * {@link MOAIDAuthConstants#PARAM_TARGET_PENDINGREQUESTID}. + *

+ * 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/AuthServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java index fe24d45dd..fb6c71846 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java @@ -1,507 +1,378 @@ -/******************************************************************************* - * 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.servlet; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -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.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.advancedlogging.StatisticLogger; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; -import at.gv.egovernment.moa.id.process.ProcessEngine; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -import at.gv.egovernment.moa.id.storage.IExceptionStore; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.egovernment.moa.util.URLDecoder; - -/** - * Base class for MOA-ID Auth Servlets, providing standard error handling and - * constant names. - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class AuthServlet extends HttpServlet { - - /** - * - */ - private static final long serialVersionUID = -6929905344382283738L; - - protected static final String ERROR_CODE_PARAM = "errorid"; - - /** - * The process engine. - */ - private ProcessEngine processEngine; - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - Logger.debug("GET " + this.getServletName()); - - this.setNoCachingHeadersInHttpRespone(req, resp); - } - - protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp) { - - if (null != errorMessage) { - Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage); - } - - if (null != exceptionThrown) { - if (null == errorMessage) - errorMessage = exceptionThrown.getMessage(); - Logger.error(errorMessage, exceptionThrown); - req.setAttribute("ExceptionThrown", exceptionThrown); - } - - if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); - } - - - StatisticLogger logger = StatisticLogger.getInstance(); - logger.logErrorOperation(exceptionThrown); - - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, - MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, - MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Handles an error.
> - *

    - *
  • Logs the error
  • - *
  • Places error message and exception thrown into the request as request - * attributes (to be used by "/errorpage-auth.jsp")
  • - *
  • Sets HTTP status 500 (internal server error)
  • - *
- * - * @param errorMessage - * error message - * @param exceptionThrown - * exception thrown - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleError(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { - - Throwable loggedException = null; - - if (exceptionThrown != null - && exceptionThrown instanceof ProcessExecutionException) { - ProcessExecutionException procExc = - (ProcessExecutionException) exceptionThrown; - if (procExc.getCause() != null && - procExc.getCause() instanceof TaskExecutionException) { - TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); - loggedException = taskExc.getOriginalException(); - - } - } - - if (loggedException == null) - loggedException = exceptionThrown; - - - if (!(loggedException instanceof MOAIDException)) { - Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); - - } else { - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { - Logger.error(loggedException.getMessage(), loggedException); - - } else { - Logger.error(loggedException.getMessage()); - - } - } - - IExceptionStore store = DBExceptionStoreImpl.getStore(); - String id = store.storeException(loggedException); - - if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { - - String redirectURL = null; - - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id - + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - return; - - } else { - - //Exception can not be stored in database - handleErrorNoRedirect(errorMessage, loggedException, req, resp); - } - } - - /** - * Handles a WrongParametersException. - * - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleWrongParameters(WrongParametersException ex, - HttpServletRequest req, HttpServletResponse resp) { - Logger.error(ex.toString()); - req.setAttribute("WrongParameters", ex.getMessage()); - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, - MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, - MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Logs all servlet parameters for debugging purposes. - */ - protected void logParameters(HttpServletRequest req) { - for (Enumeration params = req.getParameterNames(); params - .hasMoreElements();) { - String parname = (String) params.nextElement(); - Logger.debug("Parameter " + parname + req.getParameter(parname)); - } - } - - /** - * 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 getParameters(HttpServletRequest req) throws IOException, - FileUploadException { - - Map parameters = new HashMap(); - - 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 = ""; - String endS = "urn:publicid:gv.at:baseid"; - 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 { - // request is encoded as application/x-www-urlencoded - InputStream in = req.getInputStream(); - - String paramName; - String paramValueURLEncoded; - do { - paramName = new String(readBytesUpTo(in, '=')); - if (paramName.length() > 0) { - paramValueURLEncoded = readBytesUpTo(in, '&'); - String paramValue = URLDecoder.decode(paramValueURLEncoded, - "UTF-8"); - parameters.put(paramName, paramValue); - } - } while (paramName.length() > 0); - in.close(); - } - - 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(); - } - - /** - * Calls the web application initializer. - * - * @see javax.servlet.Servlet#init(ServletConfig) - */ - public void init(ServletConfig servletConfig) throws ServletException { - super.init(servletConfig); - } - - -// public void contextDestroyed(ServletContextEvent arg0) { -// Security.removeProvider((new IAIK()).getName()); -// Security.removeProvider((new ECCProvider()).getName()); +///******************************************************************************* +// * 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.servlet; +// +//import java.io.IOException; +// +//import javax.servlet.RequestDispatcher; +//import javax.servlet.ServletConfig; +//import javax.servlet.ServletContext; +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServlet; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//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.advancedlogging.StatisticLogger; +//import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +//import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +//import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +//import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +//import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +//import at.gv.egovernment.moa.id.config.ConfigurationException; +//import at.gv.egovernment.moa.id.process.ProcessEngine; +//import at.gv.egovernment.moa.id.process.ProcessExecutionException; +//import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; +//import at.gv.egovernment.moa.id.storage.IExceptionStore; +//import at.gv.egovernment.moa.id.util.ServletUtils; +//import at.gv.egovernment.moa.logging.Logger; +//import at.gv.egovernment.moa.util.MiscUtil; +// +///** +// * Base class for MOA-ID Auth Servlets, providing standard error handling and +// * constant names. +// * +// * @author Paul Ivancsics +// * @version $Id$ +// */ +//public class AuthServlet extends HttpServlet { +// +// /** +// * +// */ +// private static final long serialVersionUID = -6929905344382283738L; +// +// protected static final String ERROR_CODE_PARAM = "errorid"; +// +// /** +// * The process engine. +// */ +// private ProcessEngine processEngine; +// +// @Override +// protected void doGet(HttpServletRequest req, HttpServletResponse resp) +// throws ServletException, IOException { +// Logger.debug("GET " + this.getServletName()); +// +// this.setNoCachingHeadersInHttpRespone(req, resp); // } - - /** - * Set response headers to avoid caching - * - * @param request - * HttpServletRequest - * @param response - * HttpServletResponse - */ - protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, - HttpServletResponse response) { - response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, - MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, - MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, - MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - - } - - /** - * 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; - } - - /** - * Checks if HTTP requests are allowed - * - * @param authURL - * requestURL - * @throws AuthenticationException - * if HTTP requests are not allowed - * @throws ConfigurationException - */ - protected void checkIfHTTPisAllowed(String authURL) - throws AuthenticationException, ConfigurationException { - // check if HTTP Connection may be allowed (through - // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) - - //Removed from MOA-ID 2.0 config -// String boolStr = AuthConfigurationProvider -// .getInstance() -// .getGenericConfigurationParameter( -// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); - if ((!authURL.startsWith("https:")) - //&& (false == BoolUtils.valueOf(boolStr)) - ) - throw new AuthenticationException("auth.07", new Object[] { authURL - + "*" }); - - } - - - /** - * 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; - } - -} +// +// protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, +// HttpServletRequest req, HttpServletResponse resp) { +// +// if (null != errorMessage) { +// Logger.error(errorMessage); +// req.setAttribute("ErrorMessage", errorMessage); +// } +// +// if (null != exceptionThrown) { +// if (null == errorMessage) +// errorMessage = exceptionThrown.getMessage(); +// Logger.error(errorMessage, exceptionThrown); +// req.setAttribute("ExceptionThrown", exceptionThrown); +// } +// +// if (Logger.isDebugEnabled()) { +// req.setAttribute("LogLevel", "debug"); +// } +// +// +// StatisticLogger logger = StatisticLogger.getInstance(); +// logger.logErrorOperation(exceptionThrown); +// +// +// // forward this to errorpage-auth.jsp where the HTML error page is +// // generated +// ServletContext context = getServletContext(); +// RequestDispatcher dispatcher = context +// .getRequestDispatcher("/errorpage-auth.jsp"); +// try { +// +// resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, +// MOAIDAuthConstants.HEADER_VALUE_EXPIRES); +// resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, +// MOAIDAuthConstants.HEADER_VALUE_PRAGMA); +// resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); +// resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); +// +// dispatcher.forward(req, resp); +// } catch (ServletException e) { +// Logger.error(e); +// } catch (IOException e) { +// Logger.error(e); +// } +// } +// +// /** +// * Handles an error.
> +// *
    +// *
  • Logs the error
  • +// *
  • Places error message and exception thrown into the request as request +// * attributes (to be used by "/errorpage-auth.jsp")
  • +// *
  • Sets HTTP status 500 (internal server error)
  • +// *
+// * +// * @param errorMessage +// * error message +// * @param exceptionThrown +// * exception thrown +// * @param req +// * servlet request +// * @param resp +// * servlet response +// */ +// protected void handleError(String errorMessage, Throwable exceptionThrown, +// HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { +// +// Throwable loggedException = null; +// +// if (exceptionThrown != null +// && exceptionThrown instanceof ProcessExecutionException) { +// ProcessExecutionException procExc = +// (ProcessExecutionException) exceptionThrown; +// if (procExc.getCause() != null && +// procExc.getCause() instanceof TaskExecutionException) { +// TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); +// loggedException = taskExc.getOriginalException(); +// +// } +// } +// +// if (loggedException == null) +// loggedException = exceptionThrown; +// +// +// if (!(loggedException instanceof MOAIDException)) { +// Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); +// +// } else { +// if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { +// Logger.error(loggedException.getMessage(), loggedException); +// +// } else { +// Logger.error(loggedException.getMessage()); +// +// } +// } +// +// IExceptionStore store = DBExceptionStoreImpl.getStore(); +// String id = store.storeException(loggedException); +// +// if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { +// +// String redirectURL = null; +// +// redirectURL = ServletUtils.getBaseUrl(req); +// +// //TODO: DEVELOPMENT +//// redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id +//// + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; +// +// resp.setContentType("text/html"); +// resp.setStatus(302); +// +// resp.addHeader("Location", redirectURL); +// Logger.debug("REDIRECT TO: " + redirectURL); +// +// return; +// +// } else { +// +// //Exception can not be stored in database +// handleErrorNoRedirect(errorMessage, loggedException, req, resp); +// } +// } +// +// /** +// * Handles a WrongParametersException. +// * +// * @param req +// * servlet request +// * @param resp +// * servlet response +// */ +// protected void handleWrongParameters(WrongParametersException ex, +// HttpServletRequest req, HttpServletResponse resp) { +// Logger.error(ex.toString()); +// req.setAttribute("WrongParameters", ex.getMessage()); +// +// // forward this to errorpage-auth.jsp where the HTML error page is +// // generated +// ServletContext context = getServletContext(); +// RequestDispatcher dispatcher = context +// .getRequestDispatcher("/errorpage-auth.jsp"); +// try { +// resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, +// MOAIDAuthConstants.HEADER_VALUE_EXPIRES); +// resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, +// MOAIDAuthConstants.HEADER_VALUE_PRAGMA); +// resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); +// resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); +// +// dispatcher.forward(req, resp); +// } catch (ServletException e) { +// Logger.error(e); +// } catch (IOException e) { +// Logger.error(e); +// } +// } +// +// +// /** +// * Calls the web application initializer. +// * +// * @see javax.servlet.Servlet#init(ServletConfig) +// */ +// public void init(ServletConfig servletConfig) throws ServletException { +// super.init(servletConfig); +// } +// +// +// /** +// * Set response headers to avoid caching +// * +// * @param request +// * HttpServletRequest +// * @param response +// * HttpServletResponse +// */ +// protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, +// HttpServletResponse response) { +// response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, +// MOAIDAuthConstants.HEADER_VALUE_EXPIRES); +// response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, +// MOAIDAuthConstants.HEADER_VALUE_PRAGMA); +// response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); +// response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, +// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); +// +// } +// +// /** +// * 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; +// } +// +// /** +// * Checks if HTTP requests are allowed +// * +// * @param authURL +// * requestURL +// * @throws AuthenticationException +// * if HTTP requests are not allowed +// * @throws ConfigurationException +// */ +// protected void checkIfHTTPisAllowed(String authURL) +// throws AuthenticationException, ConfigurationException { +// // check if HTTP Connection may be allowed (through +// // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) +// +// //Removed from MOA-ID 2.0 config +//// String boolStr = AuthConfigurationProvider +//// .getInstance() +//// .getGenericConfigurationParameter( +//// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); +// if ((!authURL.startsWith("https:")) +// //&& (false == BoolUtils.valueOf(boolStr)) +// ) +// throw new AuthenticationException("auth.07", new Object[] { authURL +// + "*" }); +// +// } +// +// +// /** +// * 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; +// } +// +//} 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 new file mode 100644 index 000000000..6bccd5b88 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GeneralProcessEngineSignalController.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.servlet; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * @author tlenz + * + */ +@Controller +public class GeneralProcessEngineSignalController extends AbstractProcessEngineSignalController { + + + @RequestMapping(value = {"/GenerateIframeTemplate", + "/SSOSendAssertionServlet", + "/signalProcess" + }, + method = {RequestMethod.POST, RequestMethod.GET}) + public void performGenericAuthenticationProcess(HttpServletRequest req, HttpServletResponse resp) throws IOException { + signalProcessManagement(req, resp); + + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java index 15d596049..663a14881 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java @@ -1,168 +1,168 @@ -/******************************************************************************* - * 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.util.Enumeration; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.process.ExecutionContextImpl; -import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public class GenerateIFrameTemplateServlet extends AuthServlet { - - private static final long serialVersionUID = 1L; - - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - Logger.debug("Receive " + GenerateIFrameTemplateServlet.class + " Request"); - - String pendingRequestID = null; - - try { - String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); - moasessionid = StringEscapeUtils.escapeHtml(moasessionid); - AuthenticationSession moasession = null; - try { - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); - moasession = AuthenticationSessionStoreage.getSession(moasessionid); - - } catch (MOADatabaseException e) { - Logger.info("MOASession with SessionID="+ moasessionid + " is not found in Database"); - throw new MOAIDException("init.04", new Object[] { - moasessionid}); - - } catch (Throwable e) { - Logger.info("No HTTP Session found!"); - throw new MOAIDException("auth.18", new Object[] {}); - } - - - - ExecutionContext ec = new ExecutionContextImpl(); - // set execution context - Enumeration reqParamNames = req.getParameterNames(); - while(reqParamNames.hasMoreElements()) { - String paramName = reqParamNames.nextElement(); - if (MiscUtil.isNotEmpty(paramName)) - ec.put(paramName, req.getParameter(paramName)); - - } - - ec.put("pendingRequestID", pendingRequestID); - ec.put(MOAIDAuthConstants.PARAM_SESSIONID, moasessionid); - -// String bkuid = req.getParameter(MOAIDAuthConstants.PARAM_BKU); -// String useMandate = req.getParameter(MOAIDAuthConstants.PARAM_USEMANDATE); -// String ccc = req.getParameter(MOAIDAuthConstants.PARAM_CCC); -// ec.put("ccc", moasession.getCcc()); -// ec.put("useMandate", moasession.getUseMandate()); -// ec.put("bkuURL", moasession.getBkuURL()); - - // select and create process instance - String processDefinitionId = ModuleRegistration.getInstance().selectProcess(ec); - if (processDefinitionId == null) { - Logger.warn("No suitable process found for SessionID " + moasession.getSessionID()); - throw new MOAIDException("process.02", new Object[] { moasession.getSessionID() }); - } - - String processInstanceId = getProcessEngine().createProcessInstance(processDefinitionId, ec); - - // keep process instance id in moa session - moasession.setProcessInstanceId(processInstanceId); - - // make sure moa session has been persisted before running the process - try { - AuthenticationSessionStoreage.storeSession(moasession); - } catch (MOADatabaseException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { moasession.getSessionID() }); - } - - Logger.info("BKU is selected -> Start BKU communication ..."); - - // start process - getProcessEngine().start(processInstanceId); - - } - catch (WrongParametersException ex) { - handleWrongParameters(ex, req, resp); - } - - catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (ProcessExecutionException e) { - Throwable cause = e.getCause(); - if (cause != null && cause instanceof TaskExecutionException) { - Throwable taskCause = cause.getCause(); - if (taskCause != null && taskCause instanceof WrongParametersException) { - WrongParametersException internalEx = (WrongParametersException) taskCause; - handleWrongParameters(internalEx, req, resp); - return; - - } else if (taskCause != null && taskCause instanceof MOAIDException) { - MOAIDException moaTaskCause = (MOAIDException) taskCause; - handleError(null, moaTaskCause, req, resp, pendingRequestID); - return; - - } - } - - Logger.error("BKUSelectionServlet has an interal Error.", e); - - } catch (Exception e) { - Logger.error("BKUSelectionServlet has an interal Error.", e); - - } - - finally { - - } - } - - - - - - - - - -} +///******************************************************************************* +// * 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.util.Enumeration; +// +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import org.apache.commons.lang.StringEscapeUtils; +// +//import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +//import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +//import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +//import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +//import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +//import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; +//import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +//import at.gv.egovernment.moa.id.process.ExecutionContextImpl; +//import at.gv.egovernment.moa.id.process.ProcessExecutionException; +//import at.gv.egovernment.moa.id.process.api.ExecutionContext; +//import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +//import at.gv.egovernment.moa.logging.Logger; +//import at.gv.egovernment.moa.util.MiscUtil; +// +//public class GenerateIFrameTemplateServlet extends AuthServlet { +// +// private static final long serialVersionUID = 1L; +// +// protected void doGet(HttpServletRequest req, HttpServletResponse resp) +// throws ServletException, IOException { +// Logger.debug("Receive " + GenerateIFrameTemplateServlet.class + " Request"); +// +// String pendingRequestID = null; +// +// try { +// String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); +// moasessionid = StringEscapeUtils.escapeHtml(moasessionid); +// AuthenticationSession moasession = null; +// try { +// pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); +// moasession = AuthenticationSessionStoreage.getSession(moasessionid); +// +// } catch (MOADatabaseException e) { +// Logger.info("MOASession with SessionID="+ moasessionid + " is not found in Database"); +// throw new MOAIDException("init.04", new Object[] { +// moasessionid}); +// +// } catch (Throwable e) { +// Logger.info("No HTTP Session found!"); +// throw new MOAIDException("auth.18", new Object[] {}); +// } +// +// +// +// ExecutionContext ec = new ExecutionContextImpl(); +// // set execution context +// Enumeration reqParamNames = req.getParameterNames(); +// while(reqParamNames.hasMoreElements()) { +// String paramName = reqParamNames.nextElement(); +// if (MiscUtil.isNotEmpty(paramName)) +// ec.put(paramName, req.getParameter(paramName)); +// +// } +// +// ec.put("pendingRequestID", pendingRequestID); +// ec.put(MOAIDAuthConstants.PARAM_SESSIONID, moasessionid); +// +//// String bkuid = req.getParameter(MOAIDAuthConstants.PARAM_BKU); +//// String useMandate = req.getParameter(MOAIDAuthConstants.PARAM_USEMANDATE); +//// String ccc = req.getParameter(MOAIDAuthConstants.PARAM_CCC); +//// ec.put("ccc", moasession.getCcc()); +//// ec.put("useMandate", moasession.getUseMandate()); +//// ec.put("bkuURL", moasession.getBkuURL()); +// +// // select and create process instance +// String processDefinitionId = ModuleRegistration.getInstance().selectProcess(ec); +// if (processDefinitionId == null) { +// Logger.warn("No suitable process found for SessionID " + moasession.getSessionID()); +// throw new MOAIDException("process.02", new Object[] { moasession.getSessionID() }); +// } +// +// String processInstanceId = getProcessEngine().createProcessInstance(processDefinitionId, ec); +// +// // keep process instance id in moa session +// moasession.setProcessInstanceId(processInstanceId); +// +// // make sure moa session has been persisted before running the process +// try { +// AuthenticationSessionStoreage.storeSession(moasession); +// } catch (MOADatabaseException e) { +// Logger.error("Database Error! MOASession is not stored!"); +// throw new MOAIDException("init.04", new Object[] { moasession.getSessionID() }); +// } +// +// Logger.info("BKU is selected -> Start BKU communication ..."); +// +// // start process +// getProcessEngine().start(processInstanceId); +// +// } +// catch (WrongParametersException ex) { +// handleWrongParameters(ex, req, resp); +// } +// +// catch (MOAIDException ex) { +// handleError(null, ex, req, resp, pendingRequestID); +// +// } catch (ProcessExecutionException e) { +// Throwable cause = e.getCause(); +// if (cause != null && cause instanceof TaskExecutionException) { +// Throwable taskCause = cause.getCause(); +// if (taskCause != null && taskCause instanceof WrongParametersException) { +// WrongParametersException internalEx = (WrongParametersException) taskCause; +// handleWrongParameters(internalEx, req, resp); +// return; +// +// } else if (taskCause != null && taskCause instanceof MOAIDException) { +// MOAIDException moaTaskCause = (MOAIDException) taskCause; +// handleError(null, moaTaskCause, req, resp, pendingRequestID); +// return; +// +// } +// } +// +// Logger.error("BKUSelectionServlet has an interal Error.", e); +// +// } catch (Exception e) { +// Logger.error("BKUSelectionServlet has an interal Error.", e); +// +// } +// +// finally { +// +// } +// } +// +// +// +// +// +// +// +// +// +//} 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 fe5cd1ac0..48292cee1 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 @@ -31,6 +31,8 @@ import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; import org.opensaml.saml2.core.LogoutResponse; import org.opensaml.saml2.metadata.SingleLogoutService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -43,8 +45,7 @@ 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.AssertionStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.Random; @@ -56,10 +57,13 @@ import at.gv.egovernment.moa.util.URLEncoder; * @author tlenz * */ -public class IDPSingleLogOutServlet extends AuthServlet { +@Controller +public class IDPSingleLogOutServlet extends AbstractController { - private static final long serialVersionUID = -1301786072691577221L; - + @Autowired SSOManager ssoManager; + @Autowired AuthenticationManager authManager; + @Autowired IAuthenticationSessionStoreage authenicationStorage; + protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Logger.debug("receive IDP SingleLogOut Request"); @@ -79,9 +83,8 @@ public class IDPSingleLogOutServlet extends AuthServlet { return; } - - SSOManager ssomanager = SSOManager.getInstance(); - String ssoid = ssomanager.getSSOSessionID(req); + + String ssoid = ssoManager.getSSOSessionID(req); Object restartProcessObj = req.getParameter(MOAIDAuthConstants.PARAM_SLORESTART); @@ -91,9 +94,9 @@ public class IDPSingleLogOutServlet extends AuthServlet { if (tokkenObj != null && tokkenObj instanceof String) { tokken = (String) tokkenObj; try { - status = AssertionStorage.getInstance().get(tokken, String.class); + status = transactionStorage.get(tokken, String.class); if (MiscUtil.isNotEmpty(status)) { - AssertionStorage.getInstance().remove(tokken); + transactionStorage.remove(tokken); } VelocityContext context = new VelocityContext(); @@ -104,13 +107,13 @@ public class IDPSingleLogOutServlet extends AuthServlet { context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssomanager.printSingleLogOutInfo(context, resp); + ssoManager.printSingleLogOutInfo(context, resp); } catch (MOAIDException e) { - handleErrorNoRedirect(e.getMessage(), e, req, resp); + handleErrorNoRedirect(e, req, resp); } catch (MOADatabaseException e) { - handleErrorNoRedirect(e.getMessage(), e, req, resp); + handleErrorNoRedirect(e, req, resp); } @@ -118,16 +121,14 @@ public class IDPSingleLogOutServlet extends AuthServlet { } else if (MiscUtil.isNotEmpty(ssoid)) { try { - if (ssomanager.isValidSSOSession(ssoid, null)) { + if (ssoManager.isValidSSOSession(ssoid, null)) { - AuthenticationManager authmanager = AuthenticationManager.getInstance(); - String moaSessionID = AuthenticationSessionStoreage.getMOASessionSSOID(ssoid); + String moaSessionID = authenicationStorage.getMOASessionSSOID(ssoid); if (MiscUtil.isNotEmpty(moaSessionID)) { - AuthenticationSession authSession = AuthenticationSessionStoreage - .getSession(moaSessionID); + AuthenticationSession authSession = authenicationStorage.getSession(moaSessionID); if(authSession != null) { - authmanager.performSingleLogOut(req, resp, authSession, authURL); + authManager.performSingleLogOut(req, resp, authSession, authURL); return; } @@ -147,7 +148,7 @@ public class IDPSingleLogOutServlet extends AuthServlet { if (MiscUtil.isNotEmpty(restartProcess)) { Logger.info("Restart Single LogOut process after timeout ... "); try { - SLOInformationContainer sloContainer = AssertionStorage.getInstance().get(restartProcess, SLOInformationContainer.class); + SLOInformationContainer sloContainer = transactionStorage.get(restartProcess, SLOInformationContainer.class); if (sloContainer.hasFrontChannelOA()) sloContainer.putFailedOA("differntent OAs"); @@ -171,13 +172,13 @@ public class IDPSingleLogOutServlet extends AuthServlet { else statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; - AssertionStorage.getInstance().put(artifact, statusCode); - redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); + transactionStorage.put(artifact, statusCode); + redirectURL = HTTPUtils.addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); } - //redirect to Redirect Servlet - String url = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix() + "/RedirectServlet"; - url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(redirectURL, "UTF-8")); + //redirect to Redirect Servlet + String url = authURL + "/RedirectServlet"; + url = HTTPUtils.addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(redirectURL, "UTF-8")); url = resp.encodeRedirectURL(url); resp.setContentType("text/html"); @@ -205,10 +206,11 @@ public class IDPSingleLogOutServlet extends AuthServlet { MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); try { - ssomanager.printSingleLogOutInfo(context, resp); + ssoManager.printSingleLogOutInfo(context, resp); } catch (MOAIDException e) { e.printStackTrace(); + } return; } @@ -218,10 +220,11 @@ public class IDPSingleLogOutServlet extends AuthServlet { context.put("successMsg", MOAIDMessageProvider.getInstance().getMessage("slo.02", null)); try { - ssomanager.printSingleLogOutInfo(context, resp); + ssoManager.printSingleLogOutInfo(context, resp); } catch (MOAIDException e) { e.printStackTrace(); + } } 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 a5504ec4c..4ed276814 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 @@ -51,6 +51,7 @@ import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +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; @@ -58,9 +59,8 @@ import org.springframework.web.bind.annotation.RequestMethod; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.AuthenticationManager; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +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; @@ -70,14 +70,16 @@ 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; + @RequestMapping(value = "/LogOut", method = {RequestMethod.POST, RequestMethod.GET}) public void performLogOut(HttpServletRequest req, HttpServletResponse resp) throws IOException { Logger.debug("receive LogOut Request"); String redirectUrl = (String) req.getParameter(REDIRECT_URL); - - SSOManager ssomanager = SSOManager.getInstance(); - + try { //get SSO token from request String ssoid = ssomanager.getSSOSessionID(req); @@ -103,15 +105,13 @@ public class LogOutServlet { //TODO: Single LogOut Implementation //delete SSO session and MOA session - AuthenticationManager authmanager = AuthenticationManager.getInstance(); - String moasessionid = AuthenticationSessionStoreage.getMOASessionSSOID(ssoid); - - RequestStorage.removePendingRequest(AuthenticationSessionStoreage.getPendingRequestID(moasessionid)); - + String moasessionid = authenticatedSessionStorage.getMOASessionSSOID(ssoid); authmanager.performOnlyIDPLogOut(req, resp, moasessionid); + Logger.info("User with SSO Id " + ssoid + " 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 diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java deleted file mode 100644 index f3e3ae8a4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/ProcessEngineSignalServlet.java +++ /dev/null @@ -1,122 +0,0 @@ -package at.gv.egovernment.moa.id.auth.servlet; - -import java.io.IOException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -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.MOAIDException; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.logging.Logger; - -/** - * Servlet that resumes a suspended process (in case of asynchronous tasks). - * - * @author tknall - * - */ -public class ProcessEngineSignalServlet extends AuthServlet { - - private static final long serialVersionUID = 1L; - - /** - * Sets response headers that prevent caching (code taken from {@link AuthServlet}). - * - * @param resp - * The HttpServletResponse. - */ - private void setNoCachingHeaders(HttpServletResponse resp) { - resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - } - - /** - * Processes a GET request, delegating the call to {@link #doPost(HttpServletRequest, HttpServletResponse)}. - */ - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - this.doPost(req, resp); - } - - /** - * Resumes the current process instance that has been suspended due to an asynchronous task. The process instance is - * retrieved from the MOA session referred to by the request parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}. - */ - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - String sessionID = StringEscapeUtils.escapeHtml(getMoaSessionId(req)); - - setNoCachingHeaders(resp); - String pendingRequestID = null; - try { - - if (sessionID == null) { - throw new IllegalStateException("Unable to determine MOA session id."); - } - - // retrieve moa session - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - IRequest 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}); - - } - - AuthenticationSessionExtensions extendedSessionInformation = AuthenticationSessionStoreage.getAuthenticationSessionExtensions(sessionID); - AuthenticationSession session = BaseAuthenticationServer.getSession(sessionID); - - //add transactionID and unique sessionID to Logger - if (extendedSessionInformation != null) - TransactionIDUtils.setSessionId(extendedSessionInformation.getUniqueSessionId()); - TransactionIDUtils.setTransactionId(pendingRequestID); - - // process instance is mandatory - if (session.getProcessInstanceId() == null) { - throw new IllegalStateException("MOA session does not provide process instance id."); - } - - // wake up next task - getProcessEngine().signal(session.getProcessInstanceId()); - - } catch (Exception ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } finally { - //MOASessionDBUtils.closeSession(); - TransactionIDUtils.removeTransactionId(); - TransactionIDUtils.removeSessionId(); - - } - - } - - /** - * Retrieves the current MOA session id from the HttpServletRequest parameter - * {@link MOAIDAuthConstants#PARAM_SESSIONID}. - *

- * Note that this class/method can be overwritten by modules providing their own strategy of retrieving the - * respective MOA session id. - * - * @param request - * The unterlying HttpServletRequest. - * @return The current MOA session id. - */ - public String getMoaSessionId(HttpServletRequest request) { - return StringEscapeUtils.escapeHtml(request.getParameter(MOAIDAuthConstants.PARAM_SESSIONID)); - } - -} 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 a914659b0..ba8ace6c9 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 @@ -25,13 +25,16 @@ package at.gv.egovernment.moa.id.auth.servlet; import java.io.IOException; import java.io.PrintWriter; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +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.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.RedirectFormBuilder; - import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.SSOManager; @@ -42,18 +45,16 @@ import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLEncoder; - -public class RedirectServlet extends AuthServlet{ - - private static final long serialVersionUID = 1L; +@Controller +public class RedirectServlet { public static final String REDIRCT_PARAM_URL = "redirecturl"; - private static final String DEFAULT_REDIRECTTARGET = "_parent"; + @Autowired SSOManager ssoManager; - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { + @RequestMapping(value = "/RedirectServlet", method = RequestMethod.GET) + public void performLogOut(HttpServletRequest req, HttpServletResponse resp) throws IOException { Logger.debug("Receive " + RedirectServlet.class + " Request"); String url = req.getParameter(REDIRCT_PARAM_URL); @@ -89,12 +90,12 @@ public class RedirectServlet extends AuthServlet{ if (MiscUtil.isNotEmpty(target)) { // redirectURL = addURLParameter(redirectURL, PARAM_TARGET, // URLEncoder.encode(session.getTarget(), "UTF-8")); - url = addURLParameter(url, MOAIDAuthConstants.PARAM_TARGET, + url = HTTPUtils.addURLParameter(url, MOAIDAuthConstants.PARAM_TARGET, URLEncoder.encode(target, "UTF-8")); } - url = addURLParameter(url, MOAIDAuthConstants.PARAM_SAMLARTIFACT, + url = HTTPUtils.addURLParameter(url, MOAIDAuthConstants.PARAM_SAMLARTIFACT, URLEncoder.encode(artifact, "UTF-8")); url = resp.encodeRedirectURL(url); @@ -109,8 +110,7 @@ public class RedirectServlet extends AuthServlet{ } else if (MiscUtil.isNotEmpty(interIDP)) { //store IDP identifier and redirect to generate AuthRequst service Logger.info("Receive an interfederation redirect request for IDP " + interIDP); - SSOManager sso = SSOManager.getInstance(); - sso.setInterfederationIDPCookie(req, resp, interIDP); + ssoManager.setInterfederationIDPCookie(req, resp, interIDP); Logger.debug("Redirect to " + url); url = resp.encodeRedirectURL(url); @@ -141,7 +141,7 @@ public class RedirectServlet extends AuthServlet{ } + } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java index 62ee1ed85..1d18ccb2c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java @@ -28,9 +28,7 @@ package at.gv.egovernment.moa.id.auth.servlet; */ public class SAML2InterfederationSignalServlet extends - ProcessEngineSignalServlet { - - private static final long serialVersionUID = 8208970012249149156L; + AbstractProcessEngineSignalController { //TODO: getMOASessionID from SAML2 relayState diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java index 064431a6b..4c895e387 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java @@ -1,176 +1,177 @@ -/******************************************************************************* - * 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 javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -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.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.moduls.RequestStorage; -import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public class SSOSendAssertionServlet extends AuthServlet{ - - private static final long serialVersionUID = 1L; - - private static final String PARAM = "value"; - private static final String MODULE = "mod"; - private static final String ACTION = "action"; - private static final String ID = "identifier"; - - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - String id = null; - Logger.debug("Receive " + SSOSendAssertionServlet.class + " Request"); - try { - - Object idObject = req.getParameter(ID); - - if (idObject != null && (idObject instanceof String)) { - id = (String) idObject; - } - - String value = req.getParameter(PARAM); - value = StringEscapeUtils.escapeHtml(value); - if (!ParamValidatorUtils.isValidUseMandate(value)) - throw new WrongParametersException("SSOSendAssertionServlet", PARAM, null); - - //get module and action - Object moduleObject = req.getParameter(MODULE); - String module = null; - if (moduleObject != null && (moduleObject instanceof String)) { - module = (String) moduleObject; - } - - - Object actionObject = req.getParameter(ACTION); - String action = null; - if (actionObject != null && (actionObject instanceof String)) { - action = (String) actionObject; - } - - if (MiscUtil.isEmpty(module) || MiscUtil.isEmpty(action) || MiscUtil.isEmpty(id)) { - Logger.warn("No Moduel or Action parameter received!"); - throw new WrongParametersException("Module or Action is empty", "", "auth.10"); - } - - - SSOManager ssomanager = SSOManager.getInstance(); - //get SSO Cookie for Request - String ssoId = ssomanager.getSSOSessionID(req); - - //check SSO session - 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); - - - AuthenticationSessionStoreage.destroySession(correspondingMOASession); - - ssomanager.deleteSSOSessionID(req, resp); - } - } - - boolean isValidSSOSession = ssomanager.isValidSSOSession(ssoId, null); - - String moaSessionID = null; - - if (isValidSSOSession) { - - - //check UseMandate flag - String valueString = null;; - if ((value != null) && (value.compareTo("") != 0)) { - valueString = value; - } else { - valueString = "false"; - } - - if (valueString.compareToIgnoreCase("true") == 0) { - moaSessionID = AuthenticationSessionStoreage.getMOASessionSSOID(ssoId); - AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moaSessionID); - AuthenticationSessionStoreage.setAuthenticated(moaSessionID, true); - - //log event - //String pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); - IRequest pendingReq = RequestStorage.getPendingRequest(id); - MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_FINISHED); - - String redirectURL = new DataURLBuilder().buildDataURL(moasession.getAuthURL(), - ModulUtils.buildAuthURL(module, action, id), ""); - - resp.setContentType("text/html"); - resp.setStatus(302); - - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - } - - else { - throw new AuthenticationException("auth.21", new Object[] {}); - } - - } else { - handleError("SSO Session is not valid", null, req, resp, id); - } - - - } catch (MOADatabaseException e) { - handleError("SSO Session is not found", e, req, resp, id); - - } catch (WrongParametersException e) { - handleError("Parameter is not valid", e, req, resp, id); - - } catch (AuthenticationException e) { - handleError(e.getMessage(), e, req, resp, id); - - } catch (Exception e) { - Logger.error("SSOSendAssertion has an interal Error.", e); - } - - } - -} +///******************************************************************************* +// * 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 javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import org.apache.commons.lang.StringEscapeUtils; +// +//import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +//import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; +//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.commons.db.ex.MOADatabaseException; +//import at.gv.egovernment.moa.id.moduls.IRequest; +//import at.gv.egovernment.moa.id.moduls.RequestStorage; +//import at.gv.egovernment.moa.id.moduls.SSOManager; +//import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +//import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +//import at.gv.egovernment.moa.logging.Logger; +//import at.gv.egovernment.moa.util.MiscUtil; +// +//public class SSOSendAssertionServlet extends AuthServlet{ +// +// private static final long serialVersionUID = 1L; +// +// private static final String PARAM = "value"; +// private static final String MODULE = "mod"; +// private static final String ACTION = "action"; +// private static final String ID = "identifier"; +// +// protected void doPost(HttpServletRequest req, HttpServletResponse resp) +// throws ServletException, IOException { +// +// String id = null; +// Logger.debug("Receive " + SSOSendAssertionServlet.class + " Request"); +// try { +// +// Object idObject = req.getParameter(ID); +// +// if (idObject != null && (idObject instanceof String)) { +// id = (String) idObject; +// } +// +// String value = req.getParameter(PARAM); +// value = StringEscapeUtils.escapeHtml(value); +// if (!ParamValidatorUtils.isValidUseMandate(value)) +// throw new WrongParametersException("SSOSendAssertionServlet", PARAM, null); +// +// //get module and action +// Object moduleObject = req.getParameter(MODULE); +// String module = null; +// if (moduleObject != null && (moduleObject instanceof String)) { +// module = (String) moduleObject; +// } +// +// +// Object actionObject = req.getParameter(ACTION); +// String action = null; +// if (actionObject != null && (actionObject instanceof String)) { +// action = (String) actionObject; +// } +// +// if (MiscUtil.isEmpty(module) || MiscUtil.isEmpty(action) || MiscUtil.isEmpty(id)) { +// Logger.warn("No Moduel or Action parameter received!"); +// throw new WrongParametersException("Module or Action is empty", "", "auth.10"); +// } +// +// +// SSOManager ssomanager = SSOManager.getInstance(); +// //get SSO Cookie for Request +// String ssoId = ssomanager.getSSOSessionID(req); +// +// //check SSO session +// 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); +// +// +// AuthenticationSessionStoreage.destroySession(correspondingMOASession); +// +// ssomanager.deleteSSOSessionID(req, resp); +// } +// } +// +// boolean isValidSSOSession = ssomanager.isValidSSOSession(ssoId, null); +// +// String moaSessionID = null; +// +// if (isValidSSOSession) { +// +// +// //check UseMandate flag +// String valueString = null;; +// if ((value != null) && (value.compareTo("") != 0)) { +// valueString = value; +// } else { +// valueString = "false"; +// } +// +// if (valueString.compareToIgnoreCase("true") == 0) { +// moaSessionID = AuthenticationSessionStoreage.getMOASessionSSOID(ssoId); +// AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moaSessionID); +// AuthenticationSessionStoreage.setAuthenticated(moaSessionID, true); +// +// //log event +// //String pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); +// IRequest pendingReq = RequestStorage.getPendingRequest(id); +// MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_FINISHED); +// +// //TODO: only for development!!!!!!! +//// String redirectURL = new DataURLBuilder().buildDataURL(moasession.getAuthURL(), +//// ModulUtils.buildAuthURL(module, action, id), ""); +// +// String redirectURL = "Remove commants in Class:SSOSendAssertionServlet Line:141"; +// +// resp.setContentType("text/html"); +// resp.setStatus(302); +// +// +// resp.addHeader("Location", redirectURL); +// Logger.debug("REDIRECT TO: " + redirectURL); +// +// } +// +// else { +// throw new AuthenticationException("auth.21", new Object[] {}); +// } +// +// } else { +// handleError("SSO Session is not valid", null, req, resp, id); +// } +// +// +// } catch (MOADatabaseException e) { +// handleError("SSO Session is not found", e, req, resp, id); +// +// } catch (WrongParametersException e) { +// handleError("Parameter is not valid", e, req, resp, id); +// +// } catch (AuthenticationException e) { +// handleError(e.getMessage(), e, req, resp, id); +// +// } catch (Exception e) { +// Logger.error("SSOSendAssertion has an interal Error.", e); +// } +// +// } +// +//} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java index b68f42086..7f0a1c157 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java @@ -74,6 +74,8 @@ public interface IOAAuthParameters { public boolean isSTORKPVPGateway(); + public boolean isRemovePBKFromAuthBlock(); + /** * @return the identityLinkDomainIdentifier */ 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 386e04f45..171940063 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 @@ -486,4 +486,13 @@ public class DynamicOAAuthParameters implements IOAAuthParameters, Serializable{ // TODO Auto-generated method stub return false; } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isRemovePBKFromAuthBlock() + */ + @Override + public boolean isRemovePBKFromAuthBlock() { + // TODO Auto-generated method stub + return false; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java index d1c3401a1..c7f86c167 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java @@ -1,624 +1,624 @@ -/******************************************************************************* - * 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.entrypoints; - -import java.io.IOException; -import java.util.Iterator; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; -import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -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.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.IRequest; -import at.gv.egovernment.moa.id.moduls.ModulStorage; -import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; -import at.gv.egovernment.moa.id.moduls.RequestStorage; -import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -import at.gv.egovernment.moa.id.util.ErrorResponseUtils; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -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; - -public class DispatcherServlet extends AuthServlet{ - - /** - * - */ - private static final long serialVersionUID = 1L; - - public static final String PARAM_TARGET_MODULE = "mod"; - public static final String PARAM_TARGET_ACTION = "action"; - public static final String PARAM_TARGET_PENDINGREQUESTID = "pendingid"; - -// @Override -// public void init(ServletConfig config) throws ServletException { -// try { -// super.init(config); -// MOAIDAuthInitializer.initialize(); -// Logger.info(MOAIDMessageProvider.getInstance().getMessage( -// "init.00", 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.entrypoints; +// +//import java.io.IOException; +//import java.util.Iterator; +// +//import javax.servlet.ServletException; +//import javax.servlet.http.HttpServletRequest; +//import javax.servlet.http.HttpServletResponse; +// +//import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +//import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; +//import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; +//import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; +//import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +//import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; +//import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +//import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +//import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; +//import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +//import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; +//import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +//import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; +//import at.gv.egovernment.moa.id.config.ConfigurationException; +//import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +//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.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.IRequest; +//import at.gv.egovernment.moa.id.moduls.ModulStorage; +//import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; +//import at.gv.egovernment.moa.id.moduls.RequestStorage; +//import at.gv.egovernment.moa.id.moduls.SSOManager; +//import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; +//import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +//import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; +//import at.gv.egovernment.moa.id.util.ErrorResponseUtils; +//import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +//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; +// +//public class DispatcherServlet extends AuthServlet{ +// +// /** +// * +// */ +// private static final long serialVersionUID = 1L; +// +// public static final String PARAM_TARGET_MODULE = "mod"; +// public static final String PARAM_TARGET_ACTION = "action"; +// public static final String PARAM_TARGET_PENDINGREQUESTID = "pendingid"; +// +//// @Override +//// public void init(ServletConfig config) throws ServletException { +//// try { +//// super.init(config); +//// MOAIDAuthInitializer.initialize(); +//// Logger.info(MOAIDMessageProvider.getInstance().getMessage( +//// "init.00", null)); +//// +//// Logger.info("Dispatcher Servlet initialization finished."); +//// +//// } catch (Exception ex) { +//// Logger.fatal( +//// MOAIDMessageProvider.getInstance().getMessage("init.02", +//// null), ex); +//// +//// //throw new ServletException(ex); +//// +//// } +//// +//// } +// +// protected void processRequest(HttpServletRequest req, +// HttpServletResponse resp) throws ServletException, IOException { +// boolean isValidSSOSession = false; +// boolean useSSOOA = false; +// String protocolRequestID = null; // -// Logger.info("Dispatcher Servlet initialization finished."); +// try { +// Logger.debug("REQUEST: " + req.getRequestURI()); +// Logger.debug("QUERY : " + req.getQueryString()); +// +// +//// *** start of error handling *** +// +// String errorid = req.getParameter(ERROR_CODE_PARAM); +// if (errorid != null) { +// +// Throwable throwable = DBExceptionStoreImpl.getStore() +// .fetchException(errorid); +// DBExceptionStoreImpl.getStore().removeException(errorid); +// +// Object idObject = req.getParameter(PARAM_TARGET_PENDINGREQUESTID); +// +// //Map errorRequests = RequestStorage.getPendingRequest(req.getSession()); +// +// String pendingRequestID = null; +// if (idObject != null && (idObject instanceof String)) { +// pendingRequestID = (String) idObject; +// } +// +// if (throwable != null) { +// +// IRequest errorRequest = null; +// if (pendingRequestID != null) { +// errorRequest = RequestStorage.getPendingRequest(pendingRequestID); +// +// } +// +// if (errorRequest != null) { +// RequestStorage.removePendingRequest(pendingRequestID); +// MOAReversionLogger.getInstance().logEvent(errorRequest, MOAIDEventConstants.TRANSACTION_ERROR); +// +// try { +// IModulInfo handlingModule = ModulStorage +// .getModuleByPath(errorRequest +// .requestedModule()); +// if (handlingModule != null) { +// +// if (handlingModule.generateErrorMessage( +// throwable, req, resp, errorRequest)) { +// +// //log Error Message +// StatisticLogger logger = StatisticLogger.getInstance(); +// logger.logErrorOperation(throwable, errorRequest); +// +// //remove MOASession +// AuthenticationSession moaSession = AuthenticationSessionStoreage.getSessionWithPendingRequestID(pendingRequestID); +// if (moaSession != null) +// AuthenticationManager.getInstance().performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); +// +// return; +// +// } else { +// handleErrorNoRedirect(throwable.getMessage(), throwable, +// req, resp); +// +// } +// } +// +// } catch (Throwable e) { +// Logger.error(e); +// handleErrorNoRedirect(throwable.getMessage(), +// throwable, req, resp); +// } +// +// } else { +// handleErrorNoRedirect(throwable.getMessage(), throwable, +// req, resp); +// } +// +// } else +// handleErrorNoRedirect(MOAIDMessageProvider.getInstance().getMessage("auth.26", null), +// null, req, resp); +// +// return; +// } +// +//// *** end of error handling *** +// +// +//// *** start of protocol specific stuff *** +// +// Object moduleObject = req.getParameter(PARAM_TARGET_MODULE); +// String module = null; +// if (moduleObject != null && (moduleObject instanceof String)) { +// module = (String) moduleObject; +// } +// +// if (module == null) { +// module = (String) req.getAttribute(PARAM_TARGET_MODULE); +// } +// +// Object actionObject = req.getParameter(PARAM_TARGET_ACTION); +// String action = null; +// if (actionObject != null && (actionObject instanceof String)) { +// action = (String) actionObject; +// } +// +// if (action == null) { +// action = req.getParameter(PARAM_TARGET_ACTION); +// } +// +// Logger.debug("dispatching to " + module + " protocol " + action); +// +// IModulInfo info = ModulStorage.getModuleByPath(module); +// +// IAction moduleAction = null; +// +// if (info == null) { +// +// Iterator modules = ModulStorage.getAllModules() +// .iterator(); +// while (modules.hasNext()) { +// info = modules.next(); +// moduleAction = info.canHandleRequest(req, resp); +// if (moduleAction != null) { +// action = moduleAction.getDefaultActionName(); +// module = info.getPath(); +// break; +// } +// info = null; +// } +// +// if (moduleAction == null) { +// resp.sendError(HttpServletResponse.SC_NOT_FOUND); +// Logger.error("Protocol " + module +// + " has no module registered"); +// return; +// } +// } +// +// if (moduleAction == null) { +// moduleAction = info.getAction(action); +// +// if (moduleAction == null) { +// resp.sendError(HttpServletResponse.SC_NOT_FOUND); +// Logger.error("Action " + action + " is not available!"); +// return; +// } +// } +// +// //get SSO Cookie for Request +// SSOManager ssomanager = SSOManager.getInstance(); +// String ssoId = ssomanager.getSSOSessionID(req); // -// } catch (Exception ex) { -// Logger.fatal( -// MOAIDMessageProvider.getInstance().getMessage("init.02", -// null), ex); +// IRequest protocolRequest = null; +// String uniqueSessionIdentifier = null; // -// //throw new ServletException(ex); +// try { +// Object idObject = req.getParameter(PARAM_TARGET_PENDINGREQUESTID); +// +// if (idObject != null && (idObject instanceof String)) { +// +// protocolRequestID = (String) idObject; +// protocolRequest = RequestStorage.getPendingRequest(protocolRequestID); +// +// //get IRequest if it exits +// if (protocolRequest != null) { +// Logger.debug(DispatcherServlet.class.getName()+": Found PendingRequest with ID " + protocolRequestID); +// +// } else { +// Logger.error("No PendingRequest with ID " + protocolRequestID + " found.!"); +// handleErrorNoRedirect("Während des Anmeldevorgangs ist ein Fehler aufgetreten. Bitte versuchen Sie es noch einmal.", +// null, req, resp); +// return; +// } +// } else { +// try { +// +// //load unique session identifier with SSO-sessionID +// uniqueSessionIdentifier = ssomanager.getUniqueSessionIdentifier(ssoId); +// if (MiscUtil.isEmpty(uniqueSessionIdentifier)) +// uniqueSessionIdentifier = Random.nextRandom(); +// TransactionIDUtils.setSessionId(uniqueSessionIdentifier); +// +// //set transactionID to Logger +// protocolRequestID = Random.nextRandom(); +// TransactionIDUtils.setTransactionId(protocolRequestID); +// +// //log information for security and process reversion +// MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.SESSION_CREATED, uniqueSessionIdentifier); +// MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.TRANSACTION_CREATED, protocolRequestID); +// MOAReversionLogger.getInstance().logEvent(uniqueSessionIdentifier, protocolRequestID, MOAIDEventConstants.TRANSACTION_IP, req.getRemoteAddr()); +// +// protocolRequest = info.preProcess(req, resp, action, uniqueSessionIdentifier, protocolRequestID); +// +// //request is a valid interfederation response +// if (protocolRequest != null && +// protocolRequest.getInterfederationResponse() != null ) { +// Logger.debug("Create new interfederated MOA-Session and add to HTTPRequest"); +// +// //reload SP protocol implementation +// info = ModulStorage.getModuleByPath(protocolRequest.requestedModule()); +// moduleAction = info.getAction(protocolRequest.requestedAction()); +// +// //create interfederated MOASession +// String sessionID = +// AuthenticationSessionStoreage.createInterfederatedSession(protocolRequest, true, ssoId); +// req.getParameterMap().put(MOAIDAuthConstants.PARAM_SESSIONID, new String[]{ sessionID }); +// +// Logger.info("PreProcessing of SSO interfederation response complete. "); +// +// //request is a not valid interfederation response +// } else if (protocolRequest != null && +// MiscUtil.isNotEmpty(protocolRequest.getRequestID())) { +// +// OAAuthParameter oaParams = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(protocolRequest.getOAURL()); +// if (!oaParams.isPerformLocalAuthenticationOnInterfederationError()) { +// // -> send end error to service provider +// Logger.info("Federated authentication for entity " + protocolRequest.getOAURL() +// + " FAILED. Sending error message to service provider."); +// MOAIDException e = new MOAIDException("auth.27", new Object[]{}); +// IModulInfo requestedModul = ModulStorage.getModuleByPath(protocolRequest.requestedModule()); +// if (!requestedModul.generateErrorMessage(e, req, resp, protocolRequest)) +// handleErrorNoRedirect(e.getMessage(), e, req, +// resp); +// +// return; +// +// } else +// //-> Restart local authentication +// Logger.info("Restart authentication with stored " + protocolRequest.requestedModule() +// + " AuthnRequest for OnlineApplication " + protocolRequest.getOAURL()); +// +// //request is a new authentication request +// } else if (protocolRequest != null && +// MiscUtil.isEmpty(protocolRequest.getRequestID())) { +// //Start new Authentication +// protocolRequest.setModule(module); +// +// //if preProcessing has not set a specific action from decoded request +// // then set the default action +// if (MiscUtil.isEmpty(protocolRequest.requestedAction())) +// protocolRequest.setAction(action); +// else +// moduleAction = info.getAction(protocolRequest.requestedAction()); +// +// protocolRequest.setRequestID(protocolRequestID); +// protocolRequest.setSessionIdentifier(uniqueSessionIdentifier); +// RequestStorage.setPendingRequest(protocolRequest); +// Logger.debug(DispatcherServlet.class.getName()+": Create PendingRequest with ID " + protocolRequestID + "."); +// +// +// } else { +// Logger.error("Failed to generate a valid protocol request!"); +// resp.setContentType("text/html;charset=UTF-8"); +// resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!"); +// return; +// +// } +// +// } catch (ProtocolNotActiveException e) { +// resp.getWriter().write(e.getMessage()); +// resp.setContentType("text/html;charset=UTF-8"); +// resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); +// return; +// +// } catch (AuthnRequestValidatorException e) { +// //log Error Message +// StatisticLogger logger = StatisticLogger.getInstance(); +// logger.logErrorOperation(e, e.getErrorRequest()); +// +// //TODO: maybe add some error message handling??? +// +// return; +// +// }catch (InvalidProtocolRequestException e) { +// ErrorResponseUtils utils = ErrorResponseUtils.getInstance(); +// String code = utils.mapInternalErrorToExternalError(e.getMessageId()); +// String descr = e.getMessage(); +// Logger.error("Protocol validation FAILED!"); +// resp.setContentType("text/html;charset=UTF-8"); +// resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Protocol validation FAILED!" + +// "(Errorcode=" + code + +// " | Description=" + descr + ")"); +// return; +// } catch (ConfigurationException e) { +// resp.setContentType("text/html;charset=UTF-8"); +// resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + +// "(Errorcode=9199" +// +" | Description="+ e.getMessage() + ")"); +// return; +// +// } catch (MOAIDException e) { +// Logger.error("Failed to generate a valid protocol request!"); +// resp.setContentType("text/html;charset=UTF-8"); +// resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + +// "(Errorcode=6000" +// +" | Description=Das Authentifizierungsprotokoll wurde nicht erkannt oder wird nicht unterst\u00FCzt" + ")"); +// return; +// +// } +// } +// +//// *** end of protocol specific stuff *** +// +// if (protocolRequest != null) +// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), +// protocolRequest, MOAIDEventConstants.AUTHPROTOCOL_TYPE, protocolRequest.requestedModule()); +// +//// *** start handling authentication *** +// +// AuthenticationManager authmanager = AuthenticationManager.getInstance(); +// +// String moasessionID = null; +// String newSSOSessionId = null; +// AuthenticationSession moasession = null; +// IAuthData authData = null; +// +// boolean needAuthentication = moduleAction.needAuthentication(protocolRequest, req, resp); +// +// if (needAuthentication) { +// +// //check if interfederation IDP is requested +// ssomanager.checkInterfederationIsRequested(req, resp, protocolRequest); +// +// //check SSO session +// 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); +// +// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), +// protocolRequest, MOAIDEventConstants.AUTHPROCESS_SSO_INVALID); +// +// AuthenticationSessionStoreage.destroySession(correspondingMOASession); +// ssomanager.deleteSSOSessionID(req, resp); +// } +// } +// +// //load Parameters from OnlineApplicationConfiguration +// OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() +// .getOnlineApplicationParameter(protocolRequest.getOAURL()); +// +// if (oaParam == null) { +// throw new AuthenticationException("auth.00", new Object[] { protocolRequest.getOAURL() }); +// } +// +// +// isValidSSOSession = ssomanager.isValidSSOSession(ssoId, protocolRequest); +// useSSOOA = oaParam.useSSO() || oaParam.isInderfederationIDP(); +// +// +// //if a legacy request is used SSO should not be allowed, actually +// boolean isUseMandateRequested = LegacyHelper.isUseMandateRequested(req); +// +// if (protocolRequest.isPassiv() +// && protocolRequest.forceAuth()) { +// // conflict! +// throw new NoPassivAuthenticationException(); +// } +// +// boolean tryperform = authmanager.tryPerformAuthentication( +// req, resp); +// +// if (tryperform) +// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), +// protocolRequest, MOAIDEventConstants.AUTHPROCESS_FINISHED); +// else +// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), +// protocolRequest, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, protocolRequest.getOAURL()); +// +// if (protocolRequest.forceAuth()) { +// if (!tryperform) { +// authmanager.doAuthentication(req, resp, +// protocolRequest); +// return; +// } +// } else if (protocolRequest.isPassiv()) { +// if (tryperform || (isValidSSOSession && useSSOOA && !isUseMandateRequested) ) { +// // Passive authentication ok! +// } else { +// throw new NoPassivAuthenticationException(); +// } +// } else { +// if (tryperform || (isValidSSOSession && useSSOOA && !isUseMandateRequested) ) { +// // Is authenticated .. proceed +// } else { +// // Start authentication! +// authmanager.doAuthentication(req, resp, +// protocolRequest); +// return; +// } +// } +// +// if ((useSSOOA || isValidSSOSession)) //TODO: SSO with mandates requires an OVS extension +// { +// +// if (useSSOOA && isValidSSOSession) { +// +// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), +// protocolRequest, MOAIDEventConstants.AUTHPROCESS_SSO); +// +// moasessionID = ssomanager.getMOASession(ssoId); +// moasession = AuthenticationSessionStoreage.getSession(moasessionID); +// +// //use new OAParameter +// if (oaParam.useSSOQuestion() && !AuthenticationSessionStoreage.isAuthenticated(moasessionID)) { +// authmanager.sendTransmitAssertionQuestion(req, resp, protocolRequest, oaParam); +// return; +// } +// +// } else { +// moasessionID = (String) req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); +// moasession = AuthenticationSessionStoreage.getSession(moasessionID); +// +// } +// //save SSO session usage in Database +// if (useSSOOA) { +// newSSOSessionId = ssomanager.createSSOSessionInformations(moasessionID, protocolRequest.getOAURL()); +// +// if (MiscUtil.isNotEmpty(newSSOSessionId)) { +// ssomanager.setSSOSessionID(req, resp, newSSOSessionId); +// +// } else { +// ssomanager.deleteSSOSessionID(req, resp); +// +// } +// } +// +// } else { +// moasessionID = (String) req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); +// moasession = AuthenticationSessionStoreage.getSession(moasessionID); +// moasessionID = AuthenticationSessionStoreage.changeSessionID(moasession); +// +// } +// +// //build authenticationdata from session information and OA configuration +// authData = AuthenticationDataBuilder.buildAuthenticationData(protocolRequest, moasession); +// } +// +//// *** end handling authentication *** +// +//// *** start finalizing authentication (SSO, final redirects, statistic logging etc) *** +// +// SLOInformationInterface assertionID = moduleAction.processRequest(protocolRequest, req, resp, authData); +// +// RequestStorage.removePendingRequest(protocolRequestID); +// +// if (needAuthentication) { +// boolean isSSOSession = MiscUtil.isNotEmpty(newSSOSessionId) && useSSOOA; +// +// if ((useSSOOA || isSSOSession) //TODO: SSO with mandates requires an OVS extension +// && !moasession.getUseMandate()) { +// +// try { +// //Store OA specific SSO session information +// AuthenticationSessionStoreage.addSSOInformation(moasessionID, +// newSSOSessionId, assertionID, protocolRequest); +// +// } catch (AuthenticationException e) { +// Logger.warn("SSO Session information can not be stored -> SSO is not enabled!"); +// +// authmanager.performOnlyIDPLogOut(req, resp, moasessionID); +// isSSOSession = false; +// } +// +// } else { +// authmanager.performOnlyIDPLogOut(req, resp, moasessionID); +// } +// +// //Advanced statistic logging +// StatisticLogger logger = StatisticLogger.getInstance(); +// logger.logSuccessOperation(protocolRequest, authData, isSSOSession); +// +// } +// +//// *** end finalizing authentication *** +// +// } catch (Throwable e) { +// Logger.warn("An authentication error occured: ", e);; +// // Try handle module specific, if not possible rethrow +// if (!info.generateErrorMessage(e, req, resp, protocolRequest)) +// handleErrorNoRedirect(e.getMessage(), e, req, +// resp); +// +// } // +// //log transaction_destroy to reversionslog +// MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.TRANSACTION_DESTROYED, protocolRequestID); +// +// } catch (WrongParametersException ex) { +// handleWrongParameters(ex, req, resp); +// +// } catch (MOAIDException ex) { +// handleError(null, ex, req, resp, protocolRequestID); +// +// } catch (Throwable e) { +// handleErrorNoRedirect(e.getMessage(), e, req, +// resp); // } // +// finally { +// +// +// TransactionIDUtils.removeTransactionId(); +// TransactionIDUtils.removeSessionId(); +// } +// +// Logger.debug("Clossing Dispatcher processing loop"); +// } +// +// @Override +// protected void doGet(HttpServletRequest req, HttpServletResponse resp) +// throws ServletException, IOException { +// processRequest(req, resp); +// } +// +// @Override +// protected void doPost(HttpServletRequest req, HttpServletResponse resp) +// throws ServletException, IOException { +// processRequest(req, resp); // } - - protected void processRequest(HttpServletRequest req, - HttpServletResponse resp) throws ServletException, IOException { - boolean isValidSSOSession = false; - boolean useSSOOA = false; - String protocolRequestID = null; - - try { - Logger.debug("REQUEST: " + req.getRequestURI()); - Logger.debug("QUERY : " + req.getQueryString()); - - -// *** start of error handling *** - - String errorid = req.getParameter(ERROR_CODE_PARAM); - if (errorid != null) { - - Throwable throwable = DBExceptionStoreImpl.getStore() - .fetchException(errorid); - DBExceptionStoreImpl.getStore().removeException(errorid); - - Object idObject = req.getParameter(PARAM_TARGET_PENDINGREQUESTID); - - //Map errorRequests = RequestStorage.getPendingRequest(req.getSession()); - - String pendingRequestID = null; - if (idObject != null && (idObject instanceof String)) { - pendingRequestID = (String) idObject; - } - - if (throwable != null) { - - IRequest errorRequest = null; - if (pendingRequestID != null) { - errorRequest = RequestStorage.getPendingRequest(pendingRequestID); - - } - - if (errorRequest != null) { - RequestStorage.removePendingRequest(pendingRequestID); - MOAReversionLogger.getInstance().logEvent(errorRequest, MOAIDEventConstants.TRANSACTION_ERROR); - - try { - IModulInfo handlingModule = ModulStorage - .getModuleByPath(errorRequest - .requestedModule()); - if (handlingModule != null) { - - if (handlingModule.generateErrorMessage( - throwable, req, resp, errorRequest)) { - - //log Error Message - StatisticLogger logger = StatisticLogger.getInstance(); - logger.logErrorOperation(throwable, errorRequest); - - //remove MOASession - AuthenticationSession moaSession = AuthenticationSessionStoreage.getSessionWithPendingRequestID(pendingRequestID); - if (moaSession != null) - AuthenticationManager.getInstance().performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); - - return; - - } else { - handleErrorNoRedirect(throwable.getMessage(), throwable, - req, resp); - - } - } - - } catch (Throwable e) { - Logger.error(e); - handleErrorNoRedirect(throwable.getMessage(), - throwable, req, resp); - } - - } else { - handleErrorNoRedirect(throwable.getMessage(), throwable, - req, resp); - } - - } else - handleErrorNoRedirect(MOAIDMessageProvider.getInstance().getMessage("auth.26", null), - null, req, resp); - - return; - } - -// *** end of error handling *** - - -// *** start of protocol specific stuff *** - - Object moduleObject = req.getParameter(PARAM_TARGET_MODULE); - String module = null; - if (moduleObject != null && (moduleObject instanceof String)) { - module = (String) moduleObject; - } - - if (module == null) { - module = (String) req.getAttribute(PARAM_TARGET_MODULE); - } - - Object actionObject = req.getParameter(PARAM_TARGET_ACTION); - String action = null; - if (actionObject != null && (actionObject instanceof String)) { - action = (String) actionObject; - } - - if (action == null) { - action = req.getParameter(PARAM_TARGET_ACTION); - } - - Logger.debug("dispatching to " + module + " protocol " + action); - - IModulInfo info = ModulStorage.getModuleByPath(module); - - IAction moduleAction = null; - - if (info == null) { - - Iterator modules = ModulStorage.getAllModules() - .iterator(); - while (modules.hasNext()) { - info = modules.next(); - moduleAction = info.canHandleRequest(req, resp); - if (moduleAction != null) { - action = moduleAction.getDefaultActionName(); - module = info.getPath(); - break; - } - info = null; - } - - if (moduleAction == null) { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - Logger.error("Protocol " + module - + " has no module registered"); - return; - } - } - - if (moduleAction == null) { - moduleAction = info.getAction(action); - - if (moduleAction == null) { - resp.sendError(HttpServletResponse.SC_NOT_FOUND); - Logger.error("Action " + action + " is not available!"); - return; - } - } - - //get SSO Cookie for Request - SSOManager ssomanager = SSOManager.getInstance(); - String ssoId = ssomanager.getSSOSessionID(req); - - IRequest protocolRequest = null; - String uniqueSessionIdentifier = null; - - try { - Object idObject = req.getParameter(PARAM_TARGET_PENDINGREQUESTID); - - if (idObject != null && (idObject instanceof String)) { - - protocolRequestID = (String) idObject; - protocolRequest = RequestStorage.getPendingRequest(protocolRequestID); - - //get IRequest if it exits - if (protocolRequest != null) { - Logger.debug(DispatcherServlet.class.getName()+": Found PendingRequest with ID " + protocolRequestID); - - } else { - Logger.error("No PendingRequest with ID " + protocolRequestID + " found.!"); - handleErrorNoRedirect("Während des Anmeldevorgangs ist ein Fehler aufgetreten. Bitte versuchen Sie es noch einmal.", - null, req, resp); - return; - } - } else { - try { - - //load unique session identifier with SSO-sessionID - uniqueSessionIdentifier = ssomanager.getUniqueSessionIdentifier(ssoId); - if (MiscUtil.isEmpty(uniqueSessionIdentifier)) - uniqueSessionIdentifier = Random.nextRandom(); - TransactionIDUtils.setSessionId(uniqueSessionIdentifier); - - //set transactionID to Logger - protocolRequestID = Random.nextRandom(); - TransactionIDUtils.setTransactionId(protocolRequestID); - - //log information for security and process reversion - MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.SESSION_CREATED, uniqueSessionIdentifier); - MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.TRANSACTION_CREATED, protocolRequestID); - MOAReversionLogger.getInstance().logEvent(uniqueSessionIdentifier, protocolRequestID, MOAIDEventConstants.TRANSACTION_IP, req.getRemoteAddr()); - - protocolRequest = info.preProcess(req, resp, action, uniqueSessionIdentifier, protocolRequestID); - - //request is a valid interfederation response - if (protocolRequest != null && - protocolRequest.getInterfederationResponse() != null ) { - Logger.debug("Create new interfederated MOA-Session and add to HTTPRequest"); - - //reload SP protocol implementation - info = ModulStorage.getModuleByPath(protocolRequest.requestedModule()); - moduleAction = info.getAction(protocolRequest.requestedAction()); - - //create interfederated MOASession - String sessionID = - AuthenticationSessionStoreage.createInterfederatedSession(protocolRequest, true, ssoId); - req.getParameterMap().put(MOAIDAuthConstants.PARAM_SESSIONID, new String[]{ sessionID }); - - Logger.info("PreProcessing of SSO interfederation response complete. "); - - //request is a not valid interfederation response - } else if (protocolRequest != null && - MiscUtil.isNotEmpty(protocolRequest.getRequestID())) { - - OAAuthParameter oaParams = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(protocolRequest.getOAURL()); - if (!oaParams.isPerformLocalAuthenticationOnInterfederationError()) { - // -> send end error to service provider - Logger.info("Federated authentication for entity " + protocolRequest.getOAURL() - + " FAILED. Sending error message to service provider."); - MOAIDException e = new MOAIDException("auth.27", new Object[]{}); - IModulInfo requestedModul = ModulStorage.getModuleByPath(protocolRequest.requestedModule()); - if (!requestedModul.generateErrorMessage(e, req, resp, protocolRequest)) - handleErrorNoRedirect(e.getMessage(), e, req, - resp); - - return; - - } else - //-> Restart local authentication - Logger.info("Restart authentication with stored " + protocolRequest.requestedModule() - + " AuthnRequest for OnlineApplication " + protocolRequest.getOAURL()); - - //request is a new authentication request - } else if (protocolRequest != null && - MiscUtil.isEmpty(protocolRequest.getRequestID())) { - //Start new Authentication - protocolRequest.setModule(module); - - //if preProcessing has not set a specific action from decoded request - // then set the default action - if (MiscUtil.isEmpty(protocolRequest.requestedAction())) - protocolRequest.setAction(action); - else - moduleAction = info.getAction(protocolRequest.requestedAction()); - - protocolRequest.setRequestID(protocolRequestID); - protocolRequest.setSessionIdentifier(uniqueSessionIdentifier); - RequestStorage.setPendingRequest(protocolRequest); - Logger.debug(DispatcherServlet.class.getName()+": Create PendingRequest with ID " + protocolRequestID + "."); - - - } else { - Logger.error("Failed to generate a valid protocol request!"); - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!"); - return; - - } - - } catch (ProtocolNotActiveException e) { - resp.getWriter().write(e.getMessage()); - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); - return; - - } catch (AuthnRequestValidatorException e) { - //log Error Message - StatisticLogger logger = StatisticLogger.getInstance(); - logger.logErrorOperation(e, e.getErrorRequest()); - - //TODO: maybe add some error message handling??? - - return; - - }catch (InvalidProtocolRequestException e) { - ErrorResponseUtils utils = ErrorResponseUtils.getInstance(); - String code = utils.mapInternalErrorToExternalError(e.getMessageId()); - String descr = e.getMessage(); - Logger.error("Protocol validation FAILED!"); - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Protocol validation FAILED!" + - "(Errorcode=" + code + - " | Description=" + descr + ")"); - return; - } catch (ConfigurationException e) { - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + - "(Errorcode=9199" - +" | Description="+ e.getMessage() + ")"); - return; - - } catch (MOAIDException e) { - Logger.error("Failed to generate a valid protocol request!"); - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + - "(Errorcode=6000" - +" | Description=Das Authentifizierungsprotokoll wurde nicht erkannt oder wird nicht unterst\u00FCzt" + ")"); - return; - - } - } - -// *** end of protocol specific stuff *** - - if (protocolRequest != null) - MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), - protocolRequest, MOAIDEventConstants.AUTHPROTOCOL_TYPE, protocolRequest.requestedModule()); - -// *** start handling authentication *** - - AuthenticationManager authmanager = AuthenticationManager.getInstance(); - - String moasessionID = null; - String newSSOSessionId = null; - AuthenticationSession moasession = null; - IAuthData authData = null; - - boolean needAuthentication = moduleAction.needAuthentication(protocolRequest, req, resp); - - if (needAuthentication) { - - //check if interfederation IDP is requested - ssomanager.checkInterfederationIsRequested(req, resp, protocolRequest); - - //check SSO session - 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); - - MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), - protocolRequest, MOAIDEventConstants.AUTHPROCESS_SSO_INVALID); - - AuthenticationSessionStoreage.destroySession(correspondingMOASession); - ssomanager.deleteSSOSessionID(req, resp); - } - } - - //load Parameters from OnlineApplicationConfiguration - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(protocolRequest.getOAURL()); - - if (oaParam == null) { - throw new AuthenticationException("auth.00", new Object[] { protocolRequest.getOAURL() }); - } - - - isValidSSOSession = ssomanager.isValidSSOSession(ssoId, protocolRequest); - useSSOOA = oaParam.useSSO() || oaParam.isInderfederationIDP(); - - - //if a legacy request is used SSO should not be allowed, actually - boolean isUseMandateRequested = LegacyHelper.isUseMandateRequested(req); - - if (protocolRequest.isPassiv() - && protocolRequest.forceAuth()) { - // conflict! - throw new NoPassivAuthenticationException(); - } - - boolean tryperform = authmanager.tryPerformAuthentication( - req, resp); - - if (tryperform) - MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), - protocolRequest, MOAIDEventConstants.AUTHPROCESS_FINISHED); - else - MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), - protocolRequest, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, protocolRequest.getOAURL()); - - if (protocolRequest.forceAuth()) { - if (!tryperform) { - authmanager.doAuthentication(req, resp, - protocolRequest); - return; - } - } else if (protocolRequest.isPassiv()) { - if (tryperform || (isValidSSOSession && useSSOOA && !isUseMandateRequested) ) { - // Passive authentication ok! - } else { - throw new NoPassivAuthenticationException(); - } - } else { - if (tryperform || (isValidSSOSession && useSSOOA && !isUseMandateRequested) ) { - // Is authenticated .. proceed - } else { - // Start authentication! - authmanager.doAuthentication(req, resp, - protocolRequest); - return; - } - } - - if ((useSSOOA || isValidSSOSession)) //TODO: SSO with mandates requires an OVS extension - { - - if (useSSOOA && isValidSSOSession) { - - MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), - protocolRequest, MOAIDEventConstants.AUTHPROCESS_SSO); - - moasessionID = ssomanager.getMOASession(ssoId); - moasession = AuthenticationSessionStoreage.getSession(moasessionID); - - //use new OAParameter - if (oaParam.useSSOQuestion() && !AuthenticationSessionStoreage.isAuthenticated(moasessionID)) { - authmanager.sendTransmitAssertionQuestion(req, resp, protocolRequest, oaParam); - return; - } - - } else { - moasessionID = (String) req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); - moasession = AuthenticationSessionStoreage.getSession(moasessionID); - - } - //save SSO session usage in Database - if (useSSOOA) { - newSSOSessionId = ssomanager.createSSOSessionInformations(moasessionID, protocolRequest.getOAURL()); - - if (MiscUtil.isNotEmpty(newSSOSessionId)) { - ssomanager.setSSOSessionID(req, resp, newSSOSessionId); - - } else { - ssomanager.deleteSSOSessionID(req, resp); - - } - } - - } else { - moasessionID = (String) req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); - moasession = AuthenticationSessionStoreage.getSession(moasessionID); - moasessionID = AuthenticationSessionStoreage.changeSessionID(moasession); - - } - - //build authenticationdata from session information and OA configuration - authData = AuthenticationDataBuilder.buildAuthenticationData(protocolRequest, moasession); - } - -// *** end handling authentication *** - -// *** start finalizing authentication (SSO, final redirects, statistic logging etc) *** - - SLOInformationInterface assertionID = moduleAction.processRequest(protocolRequest, req, resp, authData); - - RequestStorage.removePendingRequest(protocolRequestID); - - if (needAuthentication) { - boolean isSSOSession = MiscUtil.isNotEmpty(newSSOSessionId) && useSSOOA; - - if ((useSSOOA || isSSOSession) //TODO: SSO with mandates requires an OVS extension - && !moasession.getUseMandate()) { - - try { - //Store OA specific SSO session information - AuthenticationSessionStoreage.addSSOInformation(moasessionID, - newSSOSessionId, assertionID, protocolRequest); - - } catch (AuthenticationException e) { - Logger.warn("SSO Session information can not be stored -> SSO is not enabled!"); - - authmanager.performOnlyIDPLogOut(req, resp, moasessionID); - isSSOSession = false; - } - - } else { - authmanager.performOnlyIDPLogOut(req, resp, moasessionID); - } - - //Advanced statistic logging - StatisticLogger logger = StatisticLogger.getInstance(); - logger.logSuccessOperation(protocolRequest, authData, isSSOSession); - - } - -// *** end finalizing authentication *** - - } catch (Throwable e) { - Logger.warn("An authentication error occured: ", e);; - // Try handle module specific, if not possible rethrow - if (!info.generateErrorMessage(e, req, resp, protocolRequest)) - handleErrorNoRedirect(e.getMessage(), e, req, - resp); - - } - - //log transaction_destroy to reversionslog - MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.TRANSACTION_DESTROYED, protocolRequestID); - - } catch (WrongParametersException ex) { - handleWrongParameters(ex, req, resp); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, protocolRequestID); - - } catch (Throwable e) { - handleErrorNoRedirect(e.getMessage(), e, req, - resp); - } - - finally { - - - TransactionIDUtils.removeTransactionId(); - TransactionIDUtils.removeSessionId(); - } - - Logger.debug("Clossing Dispatcher processing loop"); - } - - @Override - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - processRequest(req, resp); - } - - @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - processRequest(req, resp); - } -} +//} 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 c38bbc68f..b6df5e5c6 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 @@ -24,8 +24,6 @@ package at.gv.egovernment.moa.id.moduls; import java.io.IOException; import java.io.PrintWriter; -import java.lang.reflect.InvocationTargetException; -import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; @@ -38,39 +36,21 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; -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.LogoutRequest; import org.opensaml.saml2.core.LogoutResponse; -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.StatusCode; -import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.SingleLogoutService; -import org.opensaml.saml2.metadata.SingleSignOnService; -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.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.LoginFormBuilder; -import at.gv.egovernment.moa.id.auth.builder.SendAssertionFormBuilder; 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.InvalidProtocolRequestException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; @@ -78,93 +58,93 @@ import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.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.PVPConstants; 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.builder.SingleLogOutBuilder; -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.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; 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 { - private static final AuthenticationManager INSTANCE = new AuthenticationManager(); 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 ProcessEngine processEngine; + @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; - private AuthenticationManager() { - } - - public static AuthenticationManager getInstance() { - return INSTANCE; + public AuthenticationManager() { + } - + /** - * Checks if this request can authenticate a MOA Session + * 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 MOASession exists * - * @param request - * @param response - * @return + * @return true if session is already authenticated, otherwise false + * @throws MOAIDException */ - public boolean tryPerformAuthentication(HttpServletRequest request, - HttpServletResponse response) { - - String sessionID = (String) request.getParameter(PARAM_SESSIONID); - if (sessionID != null) { - Logger.debug("Find MOASession: " + sessionID); - AuthenticationSession authSession; - try { - authSession = AuthenticationSessionStoreage.getSession(sessionID); - - if (authSession != null) { - Logger.info("MOASession found! A: " - + authSession.isAuthenticated() + ", AU " - + authSession.isAuthenticatedUsed()); - if (authSession.isAuthenticated() - && !authSession.isAuthenticatedUsed()) { - authSession.setAuthenticatedUsed(true); - - AuthenticationSessionStoreage.storeSession(authSession); - - return true; // got authenticated - } - } + private boolean tryPerformAuthentication(RequestImpl protocolRequest, AuthenticationSession moaSession) { + + //if no MOASession exist -> authentication is required + if (moaSession == null) { + return false; - } catch (MOADatabaseException e) { - return false; - } catch (BuildException e) { + } else { + //if MOASession is Found but not authenticated --> authentication is required + if (!moaSession.isAuthenticated()) { return false; } + + //if MOASession is already authenticated and protocol-request is authenticated + // --> no authentication is required any more + else if (moaSession.isAuthenticated() && protocolRequest.isAuthenticated()) { + return true; + + // if MOASession is authenticated and SSO is allowed --> authenticate pendingRequest + } else if (!protocolRequest.isAuthenticated() + && moaSession.isAuthenticated() && protocolRequest.needSingleSignOnFunctionality()) { + Logger.debug("Found active MOASession and SSO is allowed --> pendingRequest is authenticted"); + protocolRequest.setAuthenticated(true); + protocolRequest.setMOASessionIdentifier(moaSession.getSessionID()); + return true; + + } + + // force authentication as backup solution + else { + Logger.warn("Authentication-required check find an unsuspected state --> force authentication"); + return false; + + } } - return false; } public void performSingleLogOut(HttpServletRequest httpReq, @@ -193,11 +173,9 @@ public class AuthenticationManager extends MOAIDAuthConstants { } - SSOManager ssomanager = SSOManager.getInstance(); - //store active OAs to SLOContaine - List dbOAs = AuthenticationSessionStoreage.getAllActiveOAFromMOASession(session); - List dbIDPs = AuthenticationSessionStoreage.getAllActiveIDPsFromMOASession(session); + List dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(session); + List dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(session); SLOInformationContainer sloContainer = new SLOInformationContainer(); sloContainer.setSloRequest(pvpReq); sloContainer.parseActiveIDPs(dbIDPs, pvpSLOIssuer); @@ -205,8 +183,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { //terminate MOASession try { - AuthenticationSessionStoreage.destroySession(session.getSessionID()); - ssomanager.deleteSSOSessionID(httpReq, httpResp); + authenticatedSessionStore.destroySession(session.getSessionID()); + ssoManager.deleteSSOSessionID(httpReq, httpResp); } catch (MOADatabaseException e) { Logger.warn("Delete MOASession FAILED."); @@ -276,7 +254,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { } } - AssertionStorage.getInstance().put(relayState, sloContainer); + //put SLO process-information into transaction storage + transactionStorage.put(relayState, sloContainer); if (MiscUtil.isEmpty(authURL)) authURL = pvpReq.getAuthURL(); @@ -289,7 +268,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { context.put("redirectURLs", sloReqList); context.put("timeoutURL", timeOutURL); context.put("timeout", SLOTIMEOUT); - ssomanager.printSingleLogOutInfo(context, httpResp); + ssoManager.printSingleLogOutInfo(context, httpResp); } else { @@ -309,7 +288,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { else context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssomanager.printSingleLogOutInfo(context, httpResp); + ssoManager.printSingleLogOutInfo(context, httpResp); } @@ -327,7 +306,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { VelocityContext context = new VelocityContext(); context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssomanager.printSingleLogOutInfo(context, httpResp); + ssoManager.printSingleLogOutInfo(context, httpResp); } @@ -352,8 +331,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { AuthenticationSession authSession; try { - authSession = AuthenticationSessionStoreage - .getSession(moaSessionID); + authSession = authenticatedSessionStore.getSession(moaSessionID); if(authSession == null) { Logger.info("NO MOA Authentication data for ID " + moaSessionID); @@ -364,10 +342,10 @@ public class AuthenticationManager extends MOAIDAuthConstants { //HTTPSessionUtils.setHTTPSessionString(session, MOA_SESSION, null); // remove moa session from HTTP Session //log Session_Destroy to reversionslog - AuthenticationSessionExtensions sessionExtensions = AuthenticationSessionStoreage.getAuthenticationSessionExtensions(moaSessionID); - MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.SESSION_DESTROYED, sessionExtensions.getUniqueSessionId()); + AuthenticationSessionExtensions sessionExtensions = authenticatedSessionStore.getAuthenticationSessionExtensions(moaSessionID); + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, sessionExtensions.getUniqueSessionId()); - AuthenticationSessionStoreage.destroySession(moaSessionID); + authenticatedSessionStore.destroySession(moaSessionID); //session.invalidate(); @@ -378,366 +356,209 @@ public class AuthenticationManager extends MOAIDAuthConstants { } - public void doAuthentication(HttpServletRequest request, - HttpServletResponse response, IRequest target) - throws ServletException, IOException, MOAIDException { - - Logger.info("Starting authentication ..."); - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_START); - - if (MiscUtil.isEmpty(target.getRequestedIDP())) { - perfomLocalAuthentication(request, response, target); - - } else { - Logger.info("Use IDP " + target.getRequestedIDP() + " for authentication ..."); - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION); - buildPVP21AuthenticationRequest(request, response, target); - - } - } - - public void sendTransmitAssertionQuestion(HttpServletRequest request, - HttpServletResponse response, IRequest target, OAAuthParameter oaParam) - throws ServletException, IOException, MOAIDException { - - String form = SendAssertionFormBuilder.buildForm(target.requestedModule(), - target.requestedAction(), target.getRequestID(), oaParam, - target.getAuthURL()); - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_START); - - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(form); - out.flush(); - } + /** + * 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 { - private void buildPVP21AuthenticationRequest(HttpServletRequest request, - HttpServletResponse response, IRequest target) - throws ServletException, IOException, MOAIDException { - - boolean requiredLocalAuthentication = true; + //generic authentication request validation + if (pendingReq.isPassiv() + && pendingReq.forceAuth()) { + // conflict! + throw new NoPassivAuthenticationException(); + } + + //get SSO cookie from http request + String ssoId = ssoManager.getSSOSessionID(httpReq); - Logger.debug("Build PVP 2.1 authentication request"); - - //get IDP metadata + //check if interfederation IDP is requested + ssoManager.checkInterfederationIsRequested(httpReq, httpResp, pendingReq); - OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(target.getRequestedIDP()); - OAAuthParameter sp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(target.getOAURL()); - - if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) { - Logger.info("Requested interfederation IDP " + target.getRequestedIDP() + " is not valid for interfederation."); - Logger.debug("isInderfederationIDP:" + String.valueOf(idp.isInderfederationIDP()) - + " isInboundSSOAllowed:" + String.valueOf(idp.isInboundSSOInterfederationAllowed())); - Logger.info("Switch to local authentication on this IDP ... "); - - perfomLocalAuthentication(request, response, target); - return; - - } + //check SSO session + if (ssoId != null) { + String correspondingMOASession = ssoManager.existsOldSSOSession(ssoId); - try { - EntityDescriptor idpEntity = MOAMetadataProvider.getInstance(). - getEntityDescriptor(target.getRequestedIDP()); - - if (idpEntity != null ) { + if (correspondingMOASession != null) { + Logger.warn("Request sends an old SSO Session ID("+ssoId+")! " + + "Invalidate the corresponding MOASession with ID="+ correspondingMOASession); - //fetch endpoint from IDP metadata - SingleSignOnService redirectEndpoint = null; - for (SingleSignOnService sss : - idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS).getSingleSignOnServices()) { - - // use POST binding as default if it exists - //TODO: maybe use RedirectBinding as default - if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { - redirectEndpoint = sss; - - } else if ( sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) && - redirectEndpoint == null ) - redirectEndpoint = sss; - } - - if (redirectEndpoint != null) { - - AuthnRequest authReq = SAML2Utils - .createSAMLObject(AuthnRequest.class); - SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); - authReq.setID(gen.generateIdentifier()); - - //send passive AuthnRequest - authReq.setIsPassive(idp.isPassivRequestUsedForInterfederation()); - - authReq.setAssertionConsumerServiceIndex(0); - authReq.setIssueInstant(new DateTime()); - Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - String serviceURL = PVPConfiguration.getInstance().getIDPPublicPath().get(0); - issuer.setValue(serviceURL); - - issuer.setFormat(NameIDType.ENTITY); - authReq.setIssuer(issuer); - NameIDPolicy policy = SAML2Utils - .createSAMLObject(NameIDPolicy.class); - policy.setAllowCreate(true); - policy.setFormat(NameID.TRANSIENT); - authReq.setNameIDPolicy(policy); - - authReq.setDestination(redirectEndpoint.getLocation()); - - RequestedAuthnContext reqAuthContext = - SAML2Utils.createSAMLObject(RequestedAuthnContext.class); - - AuthnContextClassRef authnClassRef = - SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - - //check if STORK protocol module is in ClassPath - Class storkRequstTemplate = null; - Integer storkSecClass = null; - try { - storkRequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest"); - if (storkRequstTemplate != null && - storkRequstTemplate.isInstance(target)) { - Object storkAuthnRequest = target.getClass().getMethod("getStorkAuthnRequest", null).invoke(target, null); - storkSecClass = (Integer) storkAuthnRequest.getClass().getMethod("getQaa", null).invoke(storkAuthnRequest, null); - - } - - } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { - - - } - - if (sp != null && sp.isSTORKPVPGateway()) { - //use PVP SecClass instead of STORK QAA level - String secClass = null; - if (storkRequstTemplate != null && - storkRequstTemplate.isInstance(target)) { - - try { - secClass = PVPtoSTORKMapper.getInstance().mapToSecClass( - PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); - - } catch (Exception e) { - Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); - - } - } - - if (MiscUtil.isNotEmpty(secClass)) - authnClassRef.setAuthnContextClassRef(secClass); - else - authnClassRef.setAuthnContextClassRef("http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3"); - - } else { - if (storkRequstTemplate != null && - storkRequstTemplate.isInstance(target)) { - //use requested QAA level from STORK request - try { - authnClassRef.setAuthnContextClassRef( - PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); - Logger.debug("Use STORK-QAA level " + authnClassRef.getAuthnContextClassRef() - + " from STORK request"); - - } catch (Exception e) { - Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); - - } - - } - - if (MiscUtil.isEmpty(authnClassRef.getAuthnContextClassRef())) - //TODO: switch to eIDAS QAA-levels - authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4"); - - } - - reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); - reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); - authReq.setRequestedAuthnContext(reqAuthContext); - - IEncoder binding = null; - if (redirectEndpoint.getBinding().equals( - SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = new RedirectBinding(); - - } else if (redirectEndpoint.getBinding().equals( - SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = new PostBinding(); - - } - - binding.encodeRequest(request, response, authReq, - redirectEndpoint.getLocation(), target.getRequestID()); - - //build and send request without an error - requiredLocalAuthentication = false; - - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_IDP, idpEntity.getEntityID()); - - - } else { - Logger.warn("Requested IDP " + target.getRequestedIDP() - + " does not support POST or Redirect Binding."); - - } - - } else { - Logger.warn("Requested IDP " + target.getRequestedIDP() - + " is not found in InterFederation configuration"); + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_INVALID); + authenticatedSessionStore.destroySession(correspondingMOASession); + ssoManager.deleteSSOSessionID(httpReq, httpResp); } + } + + // check if Service-Provider allows SSO sessions + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + boolean useSSOOA = oaParam.useSSO() || oaParam.isInderfederationIDP(); + + revisionsLogger.logEvent(oaParam, + pendingReq, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, pendingReq.getOAURL()); + + //if a legacy request is used SSO should not be allowed in case of mandate authentication + boolean isUseMandateRequested = LegacyHelper.isUseMandateRequested(httpReq); + + //check if SSO Session is valid + boolean isValidSSOSession = ssoManager.isValidSSOSession(ssoId, pendingReq); + + //check if SSO is allowed for the actually executed request + boolean isSSOAllowed = (useSSOOA && !isUseMandateRequested); + pendingReq.setNeedSingleSignOnFunctionality(isSSOAllowed); - } catch (MetadataProviderException e) { - Logger.error("IDP metadata error." , e); - - } catch (NoSuchAlgorithmException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (MessageEncodingException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (SecurityException e) { - Logger.error("Build IDP authentication request FAILED.", e); + //get MOASession from SSO-Cookie if SSO is allowed + AuthenticationSession moaSession = null; + if (isValidSSOSession && isSSOAllowed) { + String moasessionID = ssoManager.getMOASession(ssoId); + moaSession = authenticatedSessionStore.getSession(moasessionID); + if (moaSession == 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 tryperform = tryPerformAuthentication((RequestImpl) pendingReq, moaSession); - if (requiredLocalAuthentication) { - Logger.info("Switch to local authentication on this IDP ... "); - if (idp.isPerformLocalAuthenticationOnInterfederationError()) - perfomLocalAuthentication(request, response, target); + //perfom SSO-Consents question if it it required + if (tryperform && isSSOAllowed && oaParam.useSSOQuestion()) { + sendTransmitAssertionQuestion(httpReq, httpResp, pendingReq, oaParam); + return null; - else - throw new AuthenticationException("auth.29", new String[]{target.getRequestedIDP()}); } + + //force new authentication authentication process + if (pendingReq.forceAuth()) { + startAuthenticationProcess(httpReq, httpResp, pendingReq); + return null; + + } else if (pendingReq.isPassiv()) { + if (tryperform) { + // Passive authentication ok! + revisionsLogger.logEvent(oaParam, + pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); + return moaSession; + + } else { + throw new NoPassivAuthenticationException(); + + } + } else { + if (tryperform) { + // Is authenticated .. proceed + revisionsLogger.logEvent(oaParam, + pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); + return moaSession; + + } else { + // Start authentication! + startAuthenticationProcess(httpReq, httpResp, pendingReq); + return null; + } + } } - private void perfomLocalAuthentication(HttpServletRequest request, - HttpServletResponse response, IRequest target) + private void startAuthenticationProcess(HttpServletRequest httpReq, + HttpServletResponse httpResp, RequestImpl pendingReq) throws ServletException, IOException, MOAIDException { - Logger.debug("Starting authentication on this IDP ..."); - - response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + Logger.info("Starting authentication ..."); + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_START); - List legacyallowed_prot = AuthConfigurationProviderFactory.getInstance().getLegacyAllowedProtocols(); - - //is legacy allowed - boolean legacyallowed = legacyallowed_prot.contains(target.requestedModule()); + //is legacy allowed + List legacyallowed_prot = authConfig.getLegacyAllowedProtocols(); + boolean legacyallowed = legacyallowed_prot.contains(pendingReq.requestedModule()); //check legacy request parameter - boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(request); + boolean legacyparamavail = ParamValidatorUtils.areAllLegacyParametersAvailable(httpReq); + //create MOASession object AuthenticationSession moasession; try { - //check if an MOASession exists and if not create an new MOASession - //moasession = getORCreateMOASession(request); - moasession = AuthenticationSessionStoreage.createSession(target); + moasession = authenticatedSessionStore.createSession(pendingReq); } catch (MOADatabaseException e1) { Logger.error("Database Error! MOASession can not be created!"); throw new MOAIDException("init.04", new Object[] {}); + } + //create authentication process execution context try { + // create execution context + ExecutionContext executionContext = new ExecutionContextImpl(); + executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, pendingReq.getRequestID()); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID, + MiscUtil.isNotEmpty( + pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); - if (legacyallowed && legacyparamavail) { - - // create execution context - ExecutionContext executionContext = new ExecutionContextImpl(); - executionContext.put(MOAIDAuthConstants.PARAM_SESSIONID, moasession.getSessionID()); - executionContext.put("pendingRequestID", target.getRequestID()); - - executionContext.put("isLegacyRequest", true); - - Enumeration reqParamNames = request.getParameterNames(); + boolean leagacyMode = (legacyallowed && legacyparamavail); + executionContext.put("isLegacyRequest", leagacyMode); + executionContext.put("performBKUSelection", leagacyMode + && MiscUtil.isEmpty(pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); + + //add leagcy parameters to context + if (leagacyMode) { + Enumeration reqParamNames = httpReq.getParameterNames(); while(reqParamNames.hasMoreElements()) { String paramName = reqParamNames.nextElement(); - if (MiscUtil.isNotEmpty(paramName)) - executionContext.put(paramName, request.getParameter(paramName)); + if (MiscUtil.isNotEmpty(paramName) && + MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName)) + executionContext.put(paramName, httpReq.getParameter(paramName)); } - - // create process instance - String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext); + } + // create process instance + String processDefinitionId = ModuleRegistration.getInstance().selectProcess(executionContext); - if (processDefinitionId == null) { - Logger.warn("No suitable process found for SessionID " + moasession.getSessionID() ); - throw new MOAIDException("process.02",new Object[] { - moasession.getSessionID()}); - } + if (processDefinitionId == null) { + Logger.warn("No suitable process found for SessionID " + moasession.getSessionID() ); + throw new MOAIDException("process.02",new Object[] { + moasession.getSessionID()}); + } - String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); + String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); - // keep process instance id in moa session - moasession.setProcessInstanceId(processInstanceId); + // keep process instance id in protocol pending-request + pendingReq.setProcessInstanceId(processInstanceId); - // make sure moa session has been persisted before running the process - try { - AuthenticationSessionStoreage.storeSession(moasession); - } catch (MOADatabaseException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { - moasession.getSessionID()}); - } - - // start process - processEngine.start(processInstanceId); - - } else { - MOAReversionLogger.getInstance().logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_BKUSELECTION_INIT); - - //load Parameters from OnlineApplicationConfiguration - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(target.getOAURL()); - - if (oaParam == null) { - throw new AuthenticationException("auth.00", new Object[] { target.getOAURL() }); - } - - else { - - //check if an MOASession exists and if not create an new MOASession - //moasession = getORCreateMOASession(request); - - //set OnlineApplication configuration in Session - moasession.setOAURLRequested(target.getOAURL()); - moasession.setAction(target.requestedAction()); - moasession.setModul(target.requestedModule()); - } - - //Build authentication form - - - String publicURLPreFix = target.getAuthURL(); - if (publicURLPreFix.endsWith("/")) - publicURLPreFix = publicURLPreFix.substring(0, publicURLPreFix.length() - 1); - String loginForm = LoginFormBuilder.buildLoginForm(target.requestedModule(), - target.requestedAction(), oaParam, publicURLPreFix, moasession.getSessionID()); - - //store MOASession - try { - AuthenticationSessionStoreage.storeSession(moasession, target.getRequestID()); - } catch (MOADatabaseException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { - moasession.getSessionID()}); - } - - //set MOAIDSession - //request.getSession().setAttribute(MOA_SESSION, moasession.getSessionID()); + //store pending-request + requestStoreage.storePendingRequest(pendingReq); + + + // make sure moa session has been persisted before running the process + try { + authenticatedSessionStore.storeSession(moasession); - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(loginForm); - out.flush(); + } catch (MOADatabaseException e) { + Logger.error("Database Error! MOASession is not stored!"); + throw new MOAIDException("init.04", new Object[] { + moasession.getSessionID()}); } + + // start process + processEngine.start(processInstanceId); + } catch (ProcessExecutionException e) { Throwable cause = e.getCause(); if (cause != null && cause instanceof TaskExecutionException) { @@ -746,11 +567,36 @@ public class AuthenticationManager extends MOAIDAuthConstants { MOAIDException moaTaskCause = (MOAIDException) taskCause; Logger.warn(taskCause); throw moaTaskCause; - + } - } - - throw new MOAIDException("process.01", new Object[] { moasession.getProcessInstanceId(), moasession }, e); - } + } + + throw new MOAIDException("process.01", new Object[] { pendingReq.getProcessInstanceId(), moasession }, e); + } + } + + private void sendTransmitAssertionQuestion(HttpServletRequest request, + HttpServletResponse response, IRequest target, IOAAuthParameters oaParam) + throws ServletException, IOException, MOAIDException { + + //TODO: change to process management version!!!! + + //set authenticated flag to false, because user consents is required + target.setAuthenticated(false); + + +// String form = SendAssertionFormBuilder.buildForm(target.requestedModule(), +// target.requestedAction(), target.getRequestID(), oaParam, +// target.getAuthURL()); + + String form =null; + + revisionsLogger.logEvent(target.getOnlineApplicationConfiguration(), + target, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_START); + + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.print(form); + out.flush(); } } 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 index fda92d71a..7833e795e 100644 --- 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 @@ -25,9 +25,7 @@ package at.gv.egovernment.moa.id.moduls; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; 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 index bdbb1b458..79e52f6e1 100644 --- 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 @@ -25,22 +25,12 @@ package at.gv.egovernment.moa.id.moduls; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; public interface IModulInfo { //public List getServlets(); public String getName(); public String getPath(); - - public IAction getAction(String action); - - public IRequest preProcess(HttpServletRequest request, - HttpServletResponse response, String action, String sessionID, String transactionID) - throws MOAIDException; - - public IAction canHandleRequest(HttpServletRequest request, - HttpServletResponse response); - + public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) throws Throwable; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java index 4ae271bbc..f5d381e42 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java @@ -22,32 +22,121 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; -import java.util.Date; -import java.util.List; - -import org.opensaml.saml2.core.Attribute; - +import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; public interface IRequest { + + /** + * Indicates the module, which implements this authentication protocol. + * The class, which is referenced, had to implement the 'IModulInfo' interface. + * + * @return Full-qualified name of the class which implements this protocol + */ + public String requestedModule(); + + /** + * Indicates the protocol specific action, which should executed if the request is processed. + * The class, which is referenced, had to implement the 'IAction' interface. + * + * @return Full-qualified name of the class which implements the action + */ + public String requestedAction(); + + /** + * Unique identifier, which indicates the service provider. + * In case of SAML1 protocol, it is the OA http-GET parameter + * + * @return Unique identifier for the service provider + */ public String getOAURL(); + + /** + * Indicates the passive flag in authentication requests. + * If the passive flag is set, the identification and authentication process + * failed if no active SSO session is found. + * + * @return true, if the is passive flag is set in authentication request, otherwise false + */ public boolean isPassiv(); + + /** + * Indicates the force authentication flag in authentication request + * If this flag is set, a new identification and authentication process + * is carried out in any case. + * + * @return true, if the force authentication flag is set, otherwise false + */ public boolean forceAuth(); - public boolean isSSOSupported(); - public String requestedModule(); - public String requestedAction(); - public void setModule(String module); - public void setAction(String action); - public String getTarget(); - public void setRequestID(String id); - public String getRequestID(); - public String getSessionIdentifier(); - public void setSessionIdentifier(String sessionIdentifier); - public String getRequestedIDP(); - public MOAResponse getInterfederationResponse(); - public List getRequestedAttributes(); - public IOAAuthParameters getOnlineApplicationConfiguration(); + + + /** + * Returns a generic request-data object with is stored with a specific identifier + * + * @param key The specific identifier of the request-data object + * @return The request-data object or null if no data is found with this key + */ + public Object getGenericData(String key); + + /** + * Returns a generic request-data object with is stored with a specific identifier + * + * @param key The specific identifier of the request-data object + * @param clazz The class type which is stored with this key + * @return The request-data object or null if no data is found with this key + */ + public T getGenericData(String key, final Class clazz); + + /** + * Store a generic data-object to request 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 request-data storage + */ + public void setGenericDataToSession(String key, Object object) throws SessionDataStorageException; + + /** + * Hold the identifier of this request object. + * This identifier can be used to load the request from request storage + * + * @return Request identifier + */ + public String getRequestID(); + + + /** + * Hold the identifier of the MOASession which is associated with this request + * + * @return MOASession identifier if a associated session exists, otherwise null + */ + public String getMOASessionIdentifier(); + + + /** + * Holds a unique transaction identifier, which could be used for looging + * This transaction identifier is unique for a single identification and authentication process + * + * @return Unique transaction identifier. + */ + public String getUniqueTransactionIdentifier(); + + /** + * Holds a unique session identifier, which could be used for logging + * This session identifier is unique for the full Single Sign-On session time + * + * @return Unique session identifier + */ + public String getUniqueSessionIdentifier(); + + + /** + * Hold the identifier if the process instance, which is associated with this request + * + * @return ProcessInstanceID if this request is associated with a authentication process, otherwise null + */ + public String getProcessInstanceId(); + /** * get the IDP URL PreFix, which was used for authentication request @@ -57,5 +146,33 @@ public interface IRequest { public String getAuthURL(); public String getAuthURLWithOutSlash(); - //public void setTarget(); + /** + * Indicates if this pending request needs authentication + * + * @return true if this request needs authentication, otherwise false + */ + public boolean isNeedAuthentication(); + + /** + * Indicates, if this pending request needs Single Sign-On (SSO) functionality + * + * @return true if this request needs SSO, otherwise false + */ + public boolean needSingleSignOnFunctionality(); + public void setNeedSingleSignOnFunctionality(boolean needSSO); + + /** + * Indicates, if this pending request is already authenticated + * + * @return true if this request is already authenticated, otherwise false + */ + public boolean isAuthenticated(); + public void setAuthenticated(boolean isAuthenticated); + + /** + * Get get Service-Provider configuration which is associated with this request. + * + * @return Service-Provider configuration + */ + public IOAAuthParameters getOnlineApplicationConfiguration(); } 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 new file mode 100644 index 000000000..6f46edce3 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequestStorage.java @@ -0,0 +1,41 @@ +/* + * 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.auth.exception.MOAIDException; + +/** + * @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; + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java index 99b7f4217..13768a343 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java @@ -1,46 +1,46 @@ -/******************************************************************************* - * 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.entrypoints.DispatcherServlet; - - -public class ModulUtils { - - public static final String UNAUTHDISPATCHER = "dispatcher"; - public static final String AUTHDISPATCHER = "dispatcher"; - - public static String buildUnauthURL(String modul, String action, String pendingRequestID) { - return UNAUTHDISPATCHER + "?" + - DispatcherServlet.PARAM_TARGET_MODULE + "=" + modul + "&" + - DispatcherServlet.PARAM_TARGET_ACTION + "=" + action + "&" + - DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - } - - public static String buildAuthURL(String modul, String action, String pendingRequestID) { - return AUTHDISPATCHER + - "?" + DispatcherServlet.PARAM_TARGET_MODULE + "=" + modul + "&" + - DispatcherServlet.PARAM_TARGET_ACTION + "=" + action + "&" + - DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - } -} +///******************************************************************************* +// * 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.entrypoints.DispatcherServlet; +// +// +//public class ModulUtils { +// +// public static final String UNAUTHDISPATCHER = "dispatcher"; +// public static final String AUTHDISPATCHER = "dispatcher"; +// +// public static String buildUnauthURL(String modul, String action, String pendingRequestID) { +// return UNAUTHDISPATCHER + "?" + +// DispatcherServlet.PARAM_TARGET_MODULE + "=" + modul + "&" + +// DispatcherServlet.PARAM_TARGET_ACTION + "=" + action + "&" + +// DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; +// } +// +// public static String buildAuthURL(String modul, String action, String pendingRequestID) { +// return AUTHDISPATCHER + +// "?" + DispatcherServlet.PARAM_TARGET_MODULE + "=" + modul + "&" + +// DispatcherServlet.PARAM_TARGET_ACTION + "=" + action + "&" + +// DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; +// } +//} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index cdaade1bb..bba9f66ae 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -25,45 +25,73 @@ package at.gv.egovernment.moa.id.moduls; import java.io.Serializable; import java.net.MalformedURLException; import java.net.URL; +import java.util.HashMap; import java.util.List; +import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.opensaml.saml2.core.Attribute; +import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; +import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; +import at.gv.egovernment.moa.id.commons.MOAIDConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; 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{ - private static final long serialVersionUID = 1L; + public static final String DATAID_INTERFEDERATIOIDP_URL = "interIDPURL"; + public static final String DATAID_INTERFEDERATIOIDP_RESPONSE = "interIDPResponse"; + public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; - private String oaURL; - private boolean passiv = false; - private boolean force = false; - private boolean ssosupport = false; + private static final long serialVersionUID = 1L; + private String module = null; private String action = null; - private String target = null; + private String requestID; - private String sessionIdentifier; - private IOAAuthParameters OAConfiguration = null; + private String moaSessionIdentifier; + private String processInstanceId; + + 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; - //MOA-ID interfederation - private String requestedIDP = null; - private MOAResponse response = null; + private boolean needAuthentication = true; + private boolean isAuthenticated = false; + private boolean needSSO = false; + + + private Map genericDataStorage = new HashMap(); /** * @throws ConfigurationException * */ - public RequestImpl(HttpServletRequest req) throws ConfigurationException { + public RequestImpl(HttpServletRequest req) throws ConfigurationException { + //set requestID + requestID = Random.nextRandom(); + + //set unique transaction identifier for logging + uniqueTransactionIdentifer = Random.nextRandom(); + TransactionIDUtils.setTransactionId(uniqueTransactionIdentifer); + + + //check if End-Point is valid String authURLString = HTTPUtils.extractAuthURLFromRequest(req); URL authURL; try { @@ -122,7 +150,16 @@ public abstract class RequestImpl implements IRequest, Serializable{ 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!?!"); + } /** @@ -156,83 +193,44 @@ public abstract class RequestImpl implements IRequest, Serializable{ this.force = force; } - public boolean isSSOSupported() { - return ssosupport; - } - - public String requestedModule() { - return module; - } - public String requestedAction() { return action; } - public void setSsosupport(boolean ssosupport) { - this.ssosupport = ssosupport; - } - - public void setModule(String module) { - this.module = module; - } - public void setAction(String action) { this.action = action; } - - public String getTarget() { - return target; - } - public void setTarget(String target) { - this.target = target; - } - - public void setRequestID(String id) { - this.requestID = id; - - } - - public String getRequestID() { - return requestID; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getRequestedIDP() + /** + * @return the module */ - @Override - public String getRequestedIDP() { - return requestedIDP; + public String requestedModule() { + return module; } /** - * @param requestedIDP the requestedIDP to set + * @param module the module to set */ - public void setRequestedIDP(String requestedIDP) { - this.requestedIDP = requestedIDP; + public void setModule(String module) { + this.module = module; } - /** - * @return the response - */ - public MOAResponse getInterfederationResponse() { - return response; + public void setRequestID(String id) { + this.requestID = id; + } - /** - * @param response the response to set - */ - public void setInterfederationResponse(MOAResponse response) { - this.response = response; + public String getRequestID() { + return requestID; } - public String getSessionIdentifier() { - return this.sessionIdentifier; + public String getMOASessionIdentifier() { + return this.moaSessionIdentifier; } - public void setSessionIdentifier(String sessionIdentifier) { - this.sessionIdentifier = sessionIdentifier; + public void setMOASessionIdentifier(String moaSessionIdentifier) { + this.moaSessionIdentifier = moaSessionIdentifier; } @@ -246,6 +244,36 @@ public abstract class RequestImpl implements IRequest, Serializable{ } + 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 */ @@ -261,11 +289,99 @@ public abstract class RequestImpl implements IRequest, Serializable{ } -// /** -// * @param authURL the authURL to set -// */ -// public void setAuthURL(String authURL) { -// this.authURL = 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 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 getGenericData(String key, final Class 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 index f0b12431a..66ca42398 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java @@ -22,23 +22,32 @@ *******************************************************************************/ 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.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.storage.AssertionStorage; +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; -public class RequestStorage { +@Service("RequestStorage") +public class RequestStorage implements IRequestStorage{ - public static IRequest getPendingRequest(String pendingReqID) { + @Autowired ITransactionStorage transactionStorage; + @Autowired ProcessInstanceStoreDAO processInstanceStore; + + @Override + public IRequest getPendingRequest(String pendingReqID) { try { - AssertionStorage storage = AssertionStorage.getInstance(); - IRequest pendingRequest = storage.get(pendingReqID, IRequest.class); + IRequest pendingRequest = transactionStorage.get(pendingReqID, IRequest.class); //set transactionID and sessionID to Logger - TransactionIDUtils.setTransactionId(((IRequest)pendingRequest).getRequestID()); - TransactionIDUtils.setSessionId(((IRequest)pendingRequest).getSessionIdentifier()); + TransactionIDUtils.setTransactionId(pendingRequest.getUniqueTransactionIdentifier()); + TransactionIDUtils.setSessionId(pendingRequest.getUniqueSessionIdentifier()); return pendingRequest; @@ -49,12 +58,11 @@ public class RequestStorage { } } - public static void setPendingRequest(Object pendingRequest) throws MOAIDException { - try { - AssertionStorage storage = AssertionStorage.getInstance(); - + @Override + public void storePendingRequest(IRequest pendingRequest) throws MOAIDException { + try { if (pendingRequest instanceof IRequest) { - storage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest); + transactionStorage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest); } else { throw new MOAIDException("auth.20", null); @@ -69,12 +77,52 @@ public class RequestStorage { } - public static void removePendingRequest(String requestID) { + @Override + public void removePendingRequest(String requestID) { if (requestID != null) { - AssertionStorage storage = AssertionStorage.getInstance(); - storage.remove(requestID); + + //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 { + + if (pendingRequest instanceof RequestImpl) { + String newRequestID = Random.nextRandom(); + + Logger.debug("Change pendingRequestID from " + pendingRequest.getRequestID() + + " to " + newRequestID); + + ((RequestImpl)pendingRequest).setRequestID(newRequestID); + storePendingRequest(pendingRequest); + + 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 2a618272f..89d50425b 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 @@ -40,23 +40,27 @@ import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.hibernate.Query; import org.hibernate.Session; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; 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.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@Service("MOAID_SSOManager") public class SSOManager { private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; @@ -65,27 +69,29 @@ public class SSOManager { private static final String SSOCOOKIE = "MOA_ID_SSO"; private static final String SSOINTERFEDERATION = "MOA_INTERFEDERATION_SSO"; - private static final int DEFAULTSSOTIMEOUT = 15 * 60; // sec - private static final int INTERFEDERATIONCOOKIEMAXAGE = 5 * 60;// sec + + @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; + @Autowired protected AuthConfiguration authConfig; - private static SSOManager instance = null; - - public static SSOManager getInstance() { - if (instance == null) { - instance = new SSOManager(); - - } - - return instance; - } - + /** + * 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} + * + * @param httpReq HttpServletRequest + * @param httpResp HttpServletResponse + * @param protocolRequest Authentication request which is actually in process + * @throws SessionDataStorageException + * + **/ public void checkInterfederationIsRequested(HttpServletRequest httpReq, HttpServletResponse httpResp, - IRequest protocolRequest) { + IRequest protocolRequest) throws SessionDataStorageException { String interIDP = httpReq.getParameter(MOAIDAuthConstants.INTERFEDERATION_IDP); - if (MiscUtil.isNotEmpty(protocolRequest.getRequestedIDP())) { - Logger.debug("Protocolspecific preprocessing already set interfederation IDP " + protocolRequest.getRequestedIDP()); + String interfederationIDP = + protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + if (MiscUtil.isNotEmpty(interfederationIDP)) { + Logger.debug("Protocolspecific preprocessing already set interfederation IDP " + interfederationIDP); return; } @@ -95,14 +101,14 @@ public class SSOManager { RequestImpl moaReq = (RequestImpl) protocolRequest; if (MiscUtil.isNotEmpty(interIDP)) { Logger.info("Receive SSO request for interfederation IDP " + interIDP); - moaReq.setRequestedIDP(interIDP); + moaReq.setGenericDataToSession(RequestImpl.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.setRequestedIDP(cookie); + moaReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, cookie); deleteCookie(httpReq, httpResp, SSOINTERFEDERATION); } @@ -120,7 +126,7 @@ public class SSOManager { } - public boolean isValidSSOSession(String ssoSessionID, IRequest protocolRequest) throws ConfigurationException { + public boolean isValidSSOSession(String ssoSessionID, IRequest protocolRequest) throws ConfigurationException, SessionDataStorageException { // search SSO Session if (ssoSessionID == null) { @@ -128,7 +134,7 @@ public class SSOManager { return false; } - AuthenticatedSessionStore storedSession = AuthenticationSessionStoreage.isValidSessionWithSSOID(ssoSessionID, null); + AuthenticatedSessionStore storedSession = authenticatedSessionStore.isValidSessionWithSSOID(ssoSessionID); if (storedSession == null) return false; @@ -137,7 +143,7 @@ public class SSOManager { //check if session is out of lifetime Date now = new Date(); - long maxSSOSessionTime = AuthConfigurationProviderFactory.getInstance().getSSOCreatedTimeOut() * 1000; + long maxSSOSessionTime = authConfig.getSSOCreatedTimeOut() * 1000; Date ssoSessionValidTo = new Date(storedSession.getCreated().getTime() + maxSSOSessionTime); if (now.after(ssoSessionValidTo)) { Logger.info("Found outdated SSO session information. Start reauthentication process ... "); @@ -150,12 +156,16 @@ public class SSOManager { storedSession.isInterfederatedSSOSession() && !storedSession.isAuthenticated()) { - if (MiscUtil.isEmpty(((RequestImpl) protocolRequest).getRequestedIDP())) { - InterfederationSessionStore selectedIDP = AuthenticationSessionStoreage.searchInterfederatedIDPFORSSOWithMOASession(storedSession.getSessionid()); + String interfederationIDP = + protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + + if (MiscUtil.isEmpty(interfederationIDP)) { + InterfederationSessionStore selectedIDP = authenticatedSessionStore.searchInterfederatedIDPFORSSOWithMOASession(storedSession.getSessionid()); if (selectedIDP != null) { //no local SSO session exist -> request interfederated IDP - ((RequestImpl) protocolRequest).setRequestedIDP(selectedIDP.getIdpurlprefix()); + protocolRequest.setGenericDataToSession( + RequestImpl.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 ..."); @@ -174,16 +184,17 @@ public class SSOManager { } public String getMOASession(String ssoSessionID) { - return AuthenticationSessionStoreage.getMOASessionSSOID(ssoSessionID); + return authenticatedSessionStore.getMOASessionSSOID(ssoSessionID); } + //TODO: refactor for faster DB access public String getUniqueSessionIdentifier(String ssoSessionID) { try { if (MiscUtil.isNotEmpty(ssoSessionID)) { - String moaSessionID = AuthenticationSessionStoreage.getMOASessionSSOID(ssoSessionID); + String moaSessionID = authenticatedSessionStore.getMOASessionSSOID(ssoSessionID); if (MiscUtil.isNotEmpty(moaSessionID)) { - AuthenticationSessionExtensions extSessionInformation = AuthenticationSessionStoreage.getAuthenticationSessionExtensions(moaSessionID); + AuthenticationSessionExtensions extSessionInformation = authenticatedSessionStore.getAuthenticationSessionExtensions(moaSessionID); return extSessionInformation.getUniqueSessionId(); } @@ -253,14 +264,6 @@ public class SSOManager { } public void setSSOSessionID(HttpServletRequest httpReq, HttpServletResponse httpResp, String ssoId) { - int ssoTimeOut; - try { - ssoTimeOut = (int) AuthConfigurationProviderFactory.getInstance().getSSOCreatedTimeOut(); - - } catch (ConfigurationException e) { - Logger.info("SSO Timeout can not be loaded from MOA-ID configuration. Use default Timeout with " + DEFAULTSSOTIMEOUT); - ssoTimeOut = DEFAULTSSOTIMEOUT; - } setCookie(httpReq, httpResp, SSOCOOKIE, ssoId, -1); } @@ -285,12 +288,12 @@ public class SSOManager { if (MiscUtil.isNotEmpty(ssoSessionID)) { - AuthenticatedSessionStore storedSession = AuthenticationSessionStoreage.isValidSessionWithSSOID(ssoSessionID, null); + AuthenticatedSessionStore storedSession = authenticatedSessionStore.isValidSessionWithSSOID(ssoSessionID); if (storedSession == null) return false; - InterfederationSessionStore selectedIDP = AuthenticationSessionStoreage.searchInterfederatedIDPFORSSOWithMOASessionIDPID(storedSession.getSessionid(), entityID); + InterfederationSessionStore selectedIDP = authenticatedSessionStore.searchInterfederatedIDPFORSSOWithMOASessionIDPID(storedSession.getSessionid(), entityID); if (selectedIDP != null) { //no local SSO session exist -> request interfederated IDP @@ -317,7 +320,7 @@ public class SSOManager { InputStream is = null; String pathLocation = null; try { - String rootconfigdir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); + String rootconfigdir = authConfig.getRootConfigFileDir(); pathLocation = rootconfigdir + HTMLTEMPLATESDIR + HTMLTEMPLATEFULL; File file = new File(new URI(pathLocation)); is = new FileInputStream(file); @@ -359,7 +362,7 @@ public class SSOManager { BufferedReader reader = new BufferedReader(new InputStreamReader(is )); //set default elements to velocity context - context.put("contextpath", AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix()); + context.put("contextpath", authConfig.getPublicURLPrefix()); StringWriter writer = new StringWriter(); //velocityEngine.evaluate(context, writer, "SLO_Template", reader); 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 index 5cf84abed..26301d664 100644 --- 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 @@ -61,6 +61,17 @@ public interface ProcessEngine { */ 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}. * 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 index 096e5ee9e..6da695d75 100644 --- 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 @@ -12,8 +12,9 @@ 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.auth.modules.TaskExecutionException; 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; @@ -21,13 +22,13 @@ 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.dao.ProcessInstanceStoreDAOImpl; 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. @@ -36,10 +37,11 @@ public class ProcessEngineImpl implements ProcessEngine { private Logger log = LoggerFactory.getLogger(getClass()); + @Autowired ProcessInstanceStoreDAO piStoreDao; + @Autowired ApplicationContext context; + private ProcessDefinitionParser pdp = new ProcessDefinitionParser(); - ProcessInstanceStoreDAO piStoreDao = ProcessInstanceStoreDAOImpl.getInstance(); - private Map processDefinitions = new ConcurrentHashMap(); private final static String MDC_CTX_PI_NAME = "processInstanceId"; @@ -176,17 +178,21 @@ public class ProcessEngineImpl implements ProcessEngine { if (clazz != null) { log.debug("Instantiating task implementing class '{}'.", clazz); - Class instanceClass = null; + Object instanceClass = null; try { - instanceClass = Class.forName(clazz, true, Thread.currentThread().getContextClassLoader()); + instanceClass = context.getBean(clazz); + } catch (Exception e) { throw new ProcessExecutionException("Unable to get class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); + } - if (!Task.class.isAssignableFrom(instanceClass)) { + 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.newInstance(); + task = (Task) instanceClass; + } catch (Exception e) { throw new ProcessExecutionException("Unable to instantiate class '" + clazz + "' associated with task '" + ti.getId() + "' .", e); } @@ -352,5 +358,25 @@ public class ProcessEngineImpl implements ProcessEngine { 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/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index a75a5de8c..577e971db 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -6,6 +6,7 @@ import org.hibernate.Transaction; import org.hibernate.criterion.Restrictions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; @@ -14,16 +15,11 @@ import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; * Database backed implementation of the {@link ProcessInstanceStoreDAO} * interface. */ +@Service("ProcessInstanceStoreage") public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { private Logger log = LoggerFactory.getLogger(getClass()); - private static ProcessInstanceStoreDAO instance = new ProcessInstanceStoreDAOImpl(); - - public static ProcessInstanceStoreDAO getInstance() { - return instance; - } - @Override public void saveOrUpdate(ProcessInstanceStore pIStore) throws MOADatabaseException { try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java new file mode 100644 index 000000000..cc1886324 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java @@ -0,0 +1,268 @@ +/* + * 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.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.config.auth.IOAAuthParameters; +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.IRequest; +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 AbstractProtocolModulController 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 moaSession = authmanager.doAuthentication(req, resp, pendingReq); + if (moaSession != null) { + //authenticated MOASession already exists --> protocol-specific postProcessing can start directly + finalizeAuthenticationProcess(req, resp, pendingReq, moaSession); + + } + + } else { + executeProtocolSpecificAction(req, resp, pendingReq, null); + + } + + } catch (Exception e) { + buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); + + } + } + + /** + * 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, AuthenticationSession moaSession) throws Exception { + + String newSSOSessionId = null; + + //if Single Sign-On functionality is enabled for this request + if (pendingReq.needSingleSignOnFunctionality()) { + + //Store SSO information into database + 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); + + } + + } + + //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 { + authenticatedSessionStorage.addSSOInformation(moaSession.getSessionID(), + newSSOSessionId, sloInformation, pendingReq); + + } 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 || + !clazz.isInstance(IAction.class)) { + 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 buildProtocolSpecificErrorResponse(Throwable throwable, HttpServletRequest req, + HttpServletResponse resp, IRequest protocolRequest) throws IOException { + try { + + Class clazz = Class.forName(protocolRequest.requestedModule()); + if (clazz == null || + !clazz.isInstance(IModulInfo.class)) { + 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 Message + statisticLogger.logErrorOperation(throwable, protocolRequest); + + //remove MOASession + AuthenticationSession moaSession = authenticatedSessionStorage.getSession( + protocolRequest.getMOASessionIdentifier()); + if (moaSession != null) + authmanager.performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); + + return; + + } else { + handleErrorNoRedirect(throwable, req, resp); + + } + + } catch (Throwable e) { + Logger.error(e); + handleErrorNoRedirect(throwable, req, resp); + } + + } + + /* (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 new file mode 100644 index 000000000..ed53d1a20 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/ProtocolFinalizationController.java @@ -0,0 +1,199 @@ +/* + * 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.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.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +import at.gv.egovernment.moa.id.util.ParamValidatorUtils; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +@Controller +public class ProtocolFinalizationController extends AbstractProtocolModulController { + + @RequestMapping(value = "/finalizeAuthProtocol", method = {RequestMethod.GET}) + public void finalizeAuthProtocol(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException, IOException { + + //read pendingRequest from http request + Object idObject = 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 = req.getParameter(ERROR_CODE_PARAM); + if (errorid != null) { + try { + //load stored exception from database + Throwable throwable = transactionStorage.get(errorid, Throwable.class); + transactionStorage.remove(errorid); + + if (throwable != null) { + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR); + + //build protocol-specific error message if possible + buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); + + //log Error Message + statisticLogger.logErrorOperation(throwable, pendingReq); + + //get MOASession for this pendingRequest + AuthenticationSession moaSession = + authenticatedSessionStorage.getSession( + pendingReq.getMOASessionIdentifier()); + + //remove MOASession if someone is found + if (moaSession != null) + authmanager.performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); + + return; + + } else { + handleErrorNoRedirect(throwable, req, resp); + + } + } else { + handleErrorNoRedirect(new Exception( + MOAIDMessageProvider.getInstance().getMessage("auth.26", null)), + req, resp); + + } + + } catch (Throwable e) { + Logger.error(e); + handleErrorNoRedirect(e, req, resp); + + } + + // 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); + return; + + } + try { + Logger.debug("Finalize PendingRequest with ID " + pendingRequestID); + + //get MOASession from database + String sessionID = pendingReq.getMOASessionIdentifier(); + + // check parameter + if (!ParamValidatorUtils.isValidSessionID(sessionID)) { + throw new WrongParametersException("FinalizeAuthProtocol", PARAM_SESSIONID, "auth.12"); + + } + + //load MOASession from database + AuthenticationSession moaSession = authenticatedSessionStorage.getSession(sessionID); + if (moaSession == null) { + Logger.error("No MOASession with ID " + sessionID + " found.!"); + handleErrorNoRedirect(new MOAIDException("auth.02", new Object[]{sessionID}), req, resp); + return; + + } + + //check if MOASession and pending-request are authenticated + if (moaSession.isAuthenticated() && pendingReq.isAuthenticated()) { + finalizeAuthenticationProcess(req, resp, pendingReq, moaSession); + + } else { + Logger.error("MOASession oder Pending-Request are not authenticated --> Abort authentication process!"); + handleErrorNoRedirect(new MOAIDException("auth.20", null), req, resp); + return; + + } + + } catch (Exception e) { + Logger.error("Finalize authentication protocol FAILED." , e); + buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); + + } + } + + //remove pending-request + requestStorage.removePendingRequest(pendingRequestID); + + } + + /* (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/UniqueSessionIdentifierInterceptor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/UniqueSessionIdentifierInterceptor.java new file mode 100644 index 000000000..e8b8022c4 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/UniqueSessionIdentifierInterceptor.java @@ -0,0 +1,93 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +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.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.MOAIDConstants; +import at.gv.egovernment.moa.id.moduls.SSOManager; +import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +public class UniqueSessionIdentifierInterceptor implements HandlerInterceptor { + + @Autowired private SSOManager ssomanager; + + /* (non-Javadoc) + * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) + */ + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + + //get SSO Cookie for Request + String ssoId = ssomanager.getSSOSessionID(request); + + //search for unique session identifier + String uniqueSessionIdentifier = ssomanager.getUniqueSessionIdentifier(ssoId); + if (MiscUtil.isEmpty(uniqueSessionIdentifier)) + uniqueSessionIdentifier = Random.nextRandom(); + TransactionIDUtils.setSessionId(uniqueSessionIdentifier); + + request.setAttribute(MOAIDConstants.UNIQUESESSIONIDENTIFIER, uniqueSessionIdentifier); + + return true; + } + + /* (non-Javadoc) + * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) + */ + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) throws Exception { + + //set security headers + response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + } + + /* (non-Javadoc) + * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) + */ + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) + throws Exception { + // TODO Auto-generated method stub + + } + +} 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 9327cabd7..c9a34496a 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 @@ -24,6 +24,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; @@ -36,8 +37,8 @@ import org.opensaml.saml2.core.AttributeQuery; import org.opensaml.saml2.core.Response; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; - -import java.util.Arrays; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -51,15 +52,19 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; /** * @author tlenz * */ +@Service("AttributQueryAction") public class AttributQueryAction implements IAction { + @Autowired IAuthenticationSessionStoreage authenticationSessionStorage; + @Autowired private AuthenticationDataBuilder authDataBuilder; + private final static List DEFAULTSTORKATTRIBUTES = Arrays.asList( new String[]{PVPConstants.EID_STORK_TOKEN_NAME}); @@ -86,7 +91,7 @@ public class AttributQueryAction implements IAction { //load moaSession String nameID = attrQuery.getSubject().getNameID().getValue(); - AuthenticationSession session = AuthenticationSessionStoreage.getSessionWithUserNameID(nameID); + AuthenticationSession session = authenticationSessionStorage.getSessionWithUserNameID(nameID); if (session == null) { Logger.warn("AttributeQuery nameID does not match to an active single sign-on session."); throw new AttributQueryException("AttributeQuery nameID does not match to an active single sign-on session.", null); @@ -96,7 +101,7 @@ public class AttributQueryAction implements IAction { DateTime date = new DateTime(); //generate authData - authData = AuthenticationDataBuilder.buildAuthenticationData(req, session, attrQuery.getAttributes()); + authData = authDataBuilder.buildAuthenticationData(req, session, attrQuery.getAttributes()); //add default attributes in case of mandates or STORK is in use List attrList = addDefaultAttributes(attrQuery, authData); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java index 04b7854b1..eb4cb8a18 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java @@ -25,6 +25,8 @@ package at.gv.egovernment.moa.id.protocols.pvp2x; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Service; + import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationImpl; @@ -33,6 +35,7 @@ import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.requestHandler.RequestManager; +@Service("PVPAuthenticationRequestAction") public class AuthenticationAction implements IAction { public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, @@ -54,7 +57,8 @@ public class AuthenticationAction implements IAction { } public String getDefaultActionName() { - return (PVP2XProtocol.REDIRECT); + 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 index 50f91df44..5c1c60dc8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java @@ -62,6 +62,8 @@ import org.opensaml.xml.security.x509.X509Credential; import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.signature.Signer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.w3c.dom.Document; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; @@ -79,15 +81,18 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableEx import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; +@Service("pvpMetadataService") public class MetadataAction implements IAction { private static final int VALIDUNTIL_IN_HOURS = 24; - + + @Autowired private MOAReversionLogger revisionsLogger; + public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { try { - MOAReversionLogger.getInstance().logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_PVP_METADATA); + revisionsLogger.logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_PVP_METADATA); EntitiesDescriptor idpEntitiesDescriptor = SAML2Utils.createSAMLObject(EntitiesDescriptor.class); 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 c0ec086ed..fc4928366 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 @@ -23,10 +23,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; import java.util.List; import javax.servlet.http.HttpServletRequest; @@ -55,10 +52,11 @@ import org.opensaml.ws.security.SecurityPolicyException; import org.opensaml.xml.io.MarshallingException; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.signature.SignableXMLObject; +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.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -66,14 +64,9 @@ import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IModulInfo; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; -import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.id.moduls.RequestStorage; -import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IDecoder; +import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController; 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; @@ -103,7 +96,8 @@ import at.gv.egovernment.moa.id.util.VelocityLogAdapter; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { +@Controller +public class PVP2XProtocol extends AbstractProtocolModulController { public static final String NAME = PVP2XProtocol.class.getName(); public static final String PATH = "id_pvp2x"; @@ -119,41 +113,15 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { public static final String ENDPOINT_SP = "sp"; public static final String PARAMETER_ENDPOINT = "endpointtype"; - - private static List decoder = new ArrayList(); - - private static HashMap actions = new HashMap(); - + public static final List DEFAULTREQUESTEDATTRFORINTERFEDERATION = Arrays.asList( new String[] { PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME }); - static { - decoder.add(new PostBinding()); - decoder.add(new RedirectBinding()); - decoder.add(new SoapBinding()); - - actions.put(REDIRECT, new AuthenticationAction()); - actions.put(POST, new AuthenticationAction()); - actions.put(METADATA, new MetadataAction()); - actions.put(ATTRIBUTEQUERY, new AttributQueryAction()); - actions.put(SINGLELOGOUT, new SingleLogOutAction()); - - //TODO: insert getArtifact action - - instance = new PVP2XProtocol(); - + static { new VelocityLogAdapter(); - } - - private static PVP2XProtocol instance = null; - - public static PVP2XProtocol getInstance() { - if (instance == null) { - instance = new PVP2XProtocol(); - } - return instance; + } public String getName() { @@ -163,65 +131,139 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { public String getPath() { return PATH; } - - private IDecoder findDecoder(String action, HttpServletRequest req) { - Iterator decoderIT = decoder.iterator(); - while (decoderIT.hasNext()) { - IDecoder decoder = decoderIT.next(); - if (decoder.handleDecode(action, req)) { - return decoder; - } - } - - return null; - } - - private boolean isServiceProviderEndPointUsed(HttpServletRequest req) throws InvalidProtocolRequestException { - Object obj = req.getParameter(PARAMETER_ENDPOINT); - if (obj instanceof String) { - String param = (String) obj; - if (MiscUtil.isNotEmpty(param)) { - if (ENDPOINT_IDP.equals(param)) - return false; - - else if (ENDPOINT_SP.equals(param)) - return true; - } - } - - Logger.error("No valid PVP 2.1 entpoint descriptor"); - throw new InvalidProtocolRequestException("pvp2.20", new Object[] {}); - } public PVP2XProtocol() { super(); } - - public IRequest preProcess(HttpServletRequest request, - HttpServletResponse response, String action, - String sessionId, String transactionId) throws MOAIDException { - - if (!AuthConfigurationProviderFactory.getInstance().getAllowedProtocols().isPVP21Active()) { + //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()) { Logger.info("PVP2.1 is deaktivated!"); throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }); } + //create pendingRequest object + PVPTargetConfiguration pendingReq = new PVPTargetConfiguration(req); + pendingReq.setModule(NAME); + + revisionsLogger.logEvent( + pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), + MOAIDEventConstants.TRANSACTION_IP, + req.getRemoteAddr()); + + MetadataAction metadataAction = applicationContext.getBean(MetadataAction.class); + metadataAction.processRequest(new PVPTargetConfiguration(req), + req, resp, null); - - if(METADATA.equals(action)) { - return new PVPTargetConfiguration(request); + } + + //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()) { + Logger.info("PVP2.1 is deaktivated!"); + throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }); } - IDecoder decoder = findDecoder(action, request); - if (decoder == null) { - return null; + try { + //create pendingRequest object + PVPTargetConfiguration pendingReq = new PVPTargetConfiguration(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 + PostBinding coder = applicationContext.getBean(PostBinding.class); + InboundMessage msg = (InboundMessage) coder.decode(req, resp, false); + 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); + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + + } catch (SecurityException e) { + String samlRequest = req.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + + } catch (Throwable e) { + String samlRequest = req.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + + throw new MOAIDException(e.getMessage(), new Object[] {}); + } + } + + //PVP2.x IDP Redirect-Binding end-point + @RequestMapping(value = "/pvp2/redirect", method = {RequestMethod.GET}) + public void PVPIDPRedirecttRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException { + if (!AuthConfigurationProviderFactory.getInstance().getAllowedProtocols().isPVP21Active()) { + Logger.info("PVP2.1 is deaktivated!"); + throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }); + } + try { + //create pendingRequest object + PVPTargetConfiguration pendingReq = new PVPTargetConfiguration(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 + RedirectBinding coder = applicationContext.getBean(RedirectBinding.class); + InboundMessage msg = (InboundMessage) coder.decode(req, resp, false); + 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); + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + + } catch (SecurityException e) { + String samlRequest = req.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + + } catch (Throwable e) { + String samlRequest = req.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - InboundMessage msg = (InboundMessage) decoder.decode(request, response, isServiceProviderEndPointUsed(request)); + throw new MOAIDException(e.getMessage(), new Object[] {}); + } + } + + + + + public 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[] {}); @@ -236,91 +278,76 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { if (msg instanceof MOARequest && ((MOARequest)msg).getSamlRequest() instanceof AuthnRequest) - return preProcessAuthRequest(request, response, (MOARequest) msg, sessionId, transactionId); + preProcessAuthRequest(request, response, pendingReq); else if (msg instanceof MOARequest && ((MOARequest)msg).getSamlRequest() instanceof AttributeQuery) - return preProcessAttributQueryRequest(request, response, (MOARequest) msg, sessionId, transactionId); + preProcessAttributQueryRequest(request, response, pendingReq); else if (msg instanceof MOARequest && ((MOARequest)msg).getSamlRequest() instanceof LogoutRequest) - return preProcessLogOut(request, response, msg, sessionId, transactionId); + preProcessLogOut(request, response, pendingReq); else if (msg instanceof MOAResponse && ((MOAResponse)msg).getResponse() instanceof LogoutResponse) - return preProcessLogOut(request, response, msg, sessionId, transactionId); - - else if (msg instanceof MOAResponse && - ((MOAResponse)msg).getResponse() instanceof Response) { - //load service provider AuthRequest from session - - IRequest obj = RequestStorage.getPendingRequest(msg.getRelayState()); - if (obj instanceof RequestImpl) { - RequestImpl iReqSP = (RequestImpl) obj; - - MOAReversionLogger.getInstance().logEvent(iReqSP, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHRESPONSE); - - MOAResponse processedMsg = preProcessAuthResponse((MOAResponse) msg); - - if ( processedMsg != null ) { - iReqSP.setInterfederationResponse(processedMsg); - - MOAReversionLogger.getInstance().logEvent(iReqSP, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_REVEIVED); - - Logger.info("Receive a valid assertion from IDP " + msg.getEntityID() - + ". Switch to original transaction with ID " + iReqSP.getRequestID()); - TransactionIDUtils.setTransactionId(iReqSP.getRequestID()); - TransactionIDUtils.setSessionId(iReqSP.getSessionIdentifier()); - - } else { - Logger.info("Interfederated IDP " + msg.getEntityID() + " has NO valid SSO session." - +". Switch back local authentication process ..."); - - SSOManager ssomanager = SSOManager.getInstance(); - ssomanager.removeInterfederatedSSOIDP(msg.getEntityID(), request); - - iReqSP.setRequestedIDP(null); - - } - - return iReqSP; - - } - - Logger.error("Stored PVP21 authrequest from service provider has an unsuppored type."); - return null; - - } else { + preProcessLogOut(request, response, pendingReq); + + else { Logger.error("Receive unsupported PVP21 message"); throw new MOAIDException("Unsupported PVP21 message", new Object[] {}); } - } catch (PVP2Exception e) { - String samlRequest = request.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - throw e; - - } catch (SecurityPolicyException e) { - String samlRequest = request.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROTOCOL_TYPE, PATH); - } catch (SecurityException e) { - String samlRequest = request.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + //switch to session authentication + performAuthentication(request, response, pendingReq); + +// else if (msg instanceof MOAResponse && +// ((MOAResponse)msg).getResponse() instanceof Response) { +// //load service provider AuthRequest from session +// +// IRequest obj = RequestStorage.getPendingRequest(msg.getRelayState()); +// if (obj instanceof RequestImpl) { +// RequestImpl iReqSP = (RequestImpl) obj; +// +// MOAReversionLogger.getInstance().logEvent(iReqSP, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHRESPONSE); +// +// MOAResponse processedMsg = preProcessAuthResponse((MOAResponse) msg); +// +// if ( processedMsg != null ) { +// iReqSP.setInterfederationResponse(processedMsg); +// +// MOAReversionLogger.getInstance().logEvent(iReqSP, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_REVEIVED); +// +// Logger.info("Receive a valid assertion from IDP " + msg.getEntityID() +// + ". Switch to original transaction with ID " + iReqSP.getRequestID()); +// TransactionIDUtils.setTransactionId(iReqSP.getRequestID()); +// TransactionIDUtils.setSessionId(iReqSP.getSessionIdentifier()); +// +// } else { +// Logger.info("Interfederated IDP " + msg.getEntityID() + " has NO valid SSO session." +// +". Switch back local authentication process ..."); +// +// SSOManager ssomanager = SSOManager.getInstance(); +// ssomanager.removeInterfederatedSSOIDP(msg.getEntityID(), request); +// +// iReqSP.setRequestedIDP(null); +// +// } +// +// return iReqSP; +// +// } +// +// Logger.error("Stored PVP21 authrequest from service provider has an unsuppored type."); +// return null; + +// } - } catch (InvalidProtocolRequestException e) { - String samlRequest = request.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - throw e; - } catch (Throwable e) { - String samlRequest = request.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - - throw new MOAIDException(e.getMessage(), new Object[] {}); - } + + } public boolean generateErrorMessage(Throwable e, @@ -423,26 +450,6 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { return true; } - public IAction getAction(String action) { - return actions.get(action); - } - - public IAction canHandleRequest(HttpServletRequest request, - HttpServletResponse response) { - if(request.getParameter("SAMLRequest") != null && request.getMethod().equals("GET")) { - return getAction(REDIRECT); - - } else if(request.getParameter("SAMLRequest") != null && request.getMethod().equals("POST")) { - return getAction(POST); - - } - - if(METADATA.equals(request.getParameter("action"))) { - return getAction(METADATA); - } - return null; - } - public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) { @@ -458,12 +465,10 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { * @return * @throws MOAIDException */ - private IRequest preProcessLogOut(HttpServletRequest request, - HttpServletResponse response, InboundMessage inMsg, - String sessionId, String transactionId) throws MOAIDException { + private void preProcessLogOut(HttpServletRequest request, + HttpServletResponse response, PVPTargetConfiguration pendingReq) throws MOAIDException { - PVPTargetConfiguration config = new PVPTargetConfiguration(request); - + InboundMessage inMsg = pendingReq.getRequest(); MOARequest msg; if (inMsg instanceof MOARequest && ((MOARequest)inMsg).getSamlRequest() instanceof LogoutRequest) { @@ -482,11 +487,11 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { Logger.info("Dispatch PVP2 SingleLogOut: OAURL=" + oaURL + " Binding=" + msg.getRequestBinding()); - config.setOAURL(oaURL); - config.setOnlineApplicationConfiguration(oa); - config.setBinding(msg.getRequestBinding()); + pendingReq.setOAURL(oaURL); + pendingReq.setOnlineApplicationConfiguration(oa); + pendingReq.setBinding(msg.getRequestBinding()); - MOAReversionLogger.getInstance().logEvent(sessionId, transactionId, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_SLO); + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_SLO); @@ -524,23 +529,26 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { throw new MOAIDException("Unsupported request", new Object[] {}); - config.setRequest(inMsg); - config.setAction(SINGLELOGOUT); - return config; + pendingReq.setRequest(inMsg); + pendingReq.setAction(SINGLELOGOUT); + + //Single LogOut Request needs no authentication + pendingReq.setNeedAuthentication(false); + + //set protocol action, which should be executed + pendingReq.setAction(SingleLogOutAction.class.getName()); } /** * PreProcess AttributeQuery request * @param request * @param response - * @param moaRequest - * @return + * @param pendingReq * @throws Throwable */ - private IRequest preProcessAttributQueryRequest(HttpServletRequest request, - HttpServletResponse response, MOARequest moaRequest, - String sessionId, String transactionId) throws Throwable { - + private void preProcessAttributQueryRequest(HttpServletRequest request, + HttpServletResponse response, PVPTargetConfiguration pendingReq) throws Throwable { + MOARequest moaRequest = ((MOARequest)pendingReq.getRequest()); AttributeQuery attrQuery = (AttributeQuery) moaRequest.getSamlRequest(); moaRequest.setEntityID(attrQuery.getIssuer().getValue()); @@ -571,29 +579,34 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { } - PVPTargetConfiguration config = new PVPTargetConfiguration(request); - config.setRequest(moaRequest); - config.setOAURL(moaRequest.getEntityID()); - config.setOnlineApplicationConfiguration(oa); - config.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); + pendingReq.setRequest(moaRequest); + pendingReq.setOAURL(moaRequest.getEntityID()); + pendingReq.setOnlineApplicationConfiguration(oa); + pendingReq.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); + + //Attribute-Query Request needs authentication + pendingReq.setNeedAuthentication(true); + + //set protocol action, which should be executed after authentication + pendingReq.setAction(AttributQueryAction.class.getName()); + + //write revisionslog entry + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_ATTRIBUTQUERY); - MOAReversionLogger.getInstance().logEvent(sessionId, transactionId, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_ATTRIBUTQUERY); - return config; } /** * PreProcess Authn request * @param request * @param response - * @param moaRequest - * @return + * @param pendingReq * @throws Throwable */ - private IRequest preProcessAuthRequest(HttpServletRequest request, - HttpServletResponse response, MOARequest moaRequest, - String sessionId, String transactionId) 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)) { @@ -620,7 +633,6 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { } - //parse AssertionConsumerService AssertionConsumerService consumerService = null; if (MiscUtil.isNotEmpty(authnRequest.getAssertionConsumerServiceURL()) && @@ -699,21 +711,25 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { Logger.info("Dispatch PVP2 AuthnRequest: OAURL=" + oaURL + " Binding=" + consumerService.getBinding()); - PVPTargetConfiguration config = new PVPTargetConfiguration(request); - config.setOAURL(oaURL); - config.setOnlineApplicationConfiguration(oa); - config.setBinding(consumerService.getBinding()); - config.setRequest(moaRequest); - config.setConsumerURL(consumerService.getLocation()); + pendingReq.setOAURL(oaURL); + pendingReq.setOnlineApplicationConfiguration(oa); + pendingReq.setBinding(consumerService.getBinding()); + pendingReq.setRequest(moaRequest); + pendingReq.setConsumerURL(consumerService.getLocation()); //parse AuthRequest - config.setPassiv(authReq.isPassive()); - config.setForce(authReq.isForceAuthn()); + pendingReq.setPassiv(authReq.isPassive()); + pendingReq.setForce(authReq.isForceAuthn()); + //AuthnRequest needs authentication + pendingReq.setNeedAuthentication(true); - MOAReversionLogger.getInstance().logEvent(sessionId, transactionId, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHREQUEST); + //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); - return config; } /** @@ -753,5 +769,5 @@ public class PVP2XProtocol extends MOAIDAuthConstants implements IModulInfo { } return null; - } + } } 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 5062646b6..0dd309154 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 @@ -25,27 +25,20 @@ package at.gv.egovernment.moa.id.protocols.pvp2x; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.artifact.SAMLArtifactMap; 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.egovernment.moa.id.protocols.pvp2x.utils.StoredAssertion; -import at.gv.egovernment.moa.id.storage.AssertionStorage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; +@Service("PVPAssertionStorage") public class PVPAssertionStorage implements SAMLArtifactMap { - - private static PVPAssertionStorage instance = null; - - public static PVPAssertionStorage getInstance() { - if(instance == null) { - instance = new PVPAssertionStorage(); - } - return instance; - } - - //private Map assertions = new HashMap(); - private AssertionStorage assertions = AssertionStorage.getInstance(); + @Autowired private ITransactionStorage transactionStorage; + public boolean contains(String artifact) { - return assertions.containsKey(artifact); + return transactionStorage.containsKey(artifact); } public void put(String artifact, String relyingPartyId, String issuerId, @@ -56,7 +49,7 @@ public class PVPAssertionStorage implements SAMLArtifactMap { samlMessage); try { - assertions.put(artifact, assertion); + transactionStorage.put(artifact, assertion); } catch (MOADatabaseException e) { // TODO Insert Error Handling, if Assertion could not be stored @@ -66,7 +59,7 @@ public class PVPAssertionStorage implements SAMLArtifactMap { public SAMLArtifactMapEntry get(String artifact) { try { - return assertions.get(artifact, SAMLArtifactMapEntry.class); + return transactionStorage.get(artifact, SAMLArtifactMapEntry.class); } catch (MOADatabaseException e) { // TODO Insert Error Handling, if Assertion could not be read @@ -76,7 +69,7 @@ public class PVPAssertionStorage implements SAMLArtifactMap { } public void remove(String artifact) { - assertions.remove(artifact); + transactionStorage.remove(artifact); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index 0b402a0fd..07367e1d0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -43,7 +43,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; 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.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.logging.Logger; public class PVPTargetConfiguration extends RequestImpl { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SingleLogOutAction.java index 582f5939d..8928aaeca 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 @@ -37,6 +37,8 @@ import org.hibernate.Transaction; import org.opensaml.saml2.core.LogoutRequest; import org.opensaml.saml2.core.LogoutResponse; import org.opensaml.saml2.metadata.SingleLogoutService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -57,8 +59,8 @@ 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.AssertionStorage; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; +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; @@ -68,8 +70,14 @@ import at.gv.egovernment.moa.util.URLEncoder; * @author tlenz * */ +@Service("pvpSingleLogOutService") public class SingleLogOutAction implements IAction { + @Autowired private SSOManager ssomanager; + @Autowired private AuthenticationManager authManager; + @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; + @Autowired private ITransactionStorage transactionStorage; + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.data.IAuthData) */ @@ -87,7 +95,7 @@ public class SingleLogOutAction implements IAction { LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); AuthenticationSession session = - AuthenticationSessionStoreage.searchMOASessionWithNameIDandOAID( + authenticationSessionStorage.searchMOASessionWithNameIDandOAID( logOutReq.getIssuer().getValue(), logOutReq.getNameID().getValue()); @@ -96,7 +104,6 @@ public class SingleLogOutAction implements IAction { + logOutReq.getNameID().getValue() + " and OA " + logOutReq.getIssuer().getValue()); Logger.info("Search active SSO session with SSO session cookie"); - SSOManager ssomanager = SSOManager.getInstance(); String ssoID = ssomanager.getSSOSessionID(httpReq); if (MiscUtil.isEmpty(ssoID)) { Logger.info("Can not find active Session. Single LogOut not possible!"); @@ -110,7 +117,7 @@ public class SingleLogOutAction implements IAction { } else { String moasession = ssomanager.getMOASession(ssoID); try { - session = AuthenticationSessionStoreage.getSession(moasession); + session = authenticationSessionStorage.getSession(moasession); } catch (MOADatabaseException e) { Logger.info("Can not find active Session. Single LogOut not possible!"); @@ -124,8 +131,7 @@ public class SingleLogOutAction implements IAction { } } } - - AuthenticationManager authManager = AuthenticationManager.getInstance(); + authManager.performSingleLogOut(httpReq, httpResp, session, pvpReq); } else if (pvpReq.getRequest() instanceof MOAResponse && @@ -235,7 +241,7 @@ public class SingleLogOutAction implements IAction { else statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; - AssertionStorage.getInstance().put(artifact, statusCode); + transactionStorage.put(artifact, statusCode); redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java deleted file mode 100644 index 4d353ffcd..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java +++ /dev/null @@ -1,121 +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.apache.velocity.app.VelocityEngine; -import org.apache.velocity.runtime.RuntimeConstants; -import org.opensaml.common.SAMLObject; -import org.opensaml.common.binding.BasicSAMLMessageContext; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.binding.encoding.HTTPArtifactEncoder; -import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.saml2.metadata.impl.SingleSignOnServiceBuilder; -import org.opensaml.ws.message.decoder.MessageDecodingException; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.ws.transport.http.HttpServletResponseAdapter; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.credential.Credential; -import org.opensaml.xml.signature.Signature; - -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPAssertionStorage; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; - -public class ArtifactBinding implements IDecoder, IEncoder { - - public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState) - throws MessageEncodingException, SecurityException { - - } - - public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState) - throws MessageEncodingException, SecurityException { - try { - Credential credentials = CredentialProvider - .getIDPAssertionSigningCredential(); - - Signature signer = CredentialProvider.getIDPSignature(credentials); - response.setSignature(signer); - - VelocityEngine engine = new VelocityEngine(); - engine.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8"); - engine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); - engine.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8"); - engine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); - engine.setProperty("classpath.resource.loader.class", - "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - engine.init(); - - HTTPArtifactEncoder encoder = new HTTPArtifactEncoder(engine, - "resources/templates/pvp_postbinding_template.html", - PVPAssertionStorage.getInstance()); - - encoder.setPostEncoding(false); - HttpServletResponseAdapter responseAdapter = new HttpServletResponseAdapter( - resp, true); - BasicSAMLMessageContext context = new BasicSAMLMessageContext(); - SingleSignOnService service = new SingleSignOnServiceBuilder() - .buildObject(); - service.setBinding(SAMLConstants.SAML2_ARTIFACT_BINDING_URI); - service.setLocation(targetLocation); - context.setOutboundSAMLMessageSigningCredential(credentials); - context.setPeerEntityEndpoint(service); - context.setOutboundSAMLMessage(response); - context.setOutboundMessageTransport(responseAdapter); - - encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); - - } catch (Exception e) { - throw new SecurityException(e); - } - } - - public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, boolean isSPEndPoint) throws MessageDecodingException, - SecurityException { - - return null; - } - - - public boolean handleDecode(String action, HttpServletRequest req) { - - return false; - } - - public String getSAML2BindingName() { - return SAMLConstants.SAML2_ARTIFACT_BINDING_URI; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index b8f7e6d80..9e176f724 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -28,7 +28,6 @@ import javax.servlet.http.HttpServletResponse; import org.apache.velocity.app.VelocityEngine; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; -import org.opensaml.common.binding.SAMLMessageContext; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.decoding.HTTPPostDecoder; import org.opensaml.saml2.binding.encoding.HTTPPostEncoder; @@ -48,6 +47,7 @@ import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.x509.X509Credential; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; @@ -67,6 +67,7 @@ import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@Service("PVPPostBindingCoder") public class PostBinding implements IDecoder, IEncoder { public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java deleted file mode 100644 index 7f6054f2d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java +++ /dev/null @@ -1,82 +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.requestHandler; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.joda.time.DateTime; -import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry; -import org.opensaml.saml2.core.ArtifactResolve; -import org.opensaml.saml2.core.ArtifactResponse; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPAssertionStorage; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; -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.binding.SoapBinding; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.RequestDeniedException; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.logging.Logger; - -public class ArtifactResolution implements IRequestHandler { - - public boolean handleObject(InboundMessage obj) { - return (obj instanceof MOARequest && - ((MOARequest)obj).getSamlRequest() instanceof ArtifactResolve); - } - - public SLOInformationInterface process(PVPTargetConfiguration obj, HttpServletRequest req, - HttpServletResponse resp, IAuthData authData) throws MOAIDException { - if (!handleObject(obj.getRequest())) { - throw new MOAIDException("pvp2.13", null); - } - - ArtifactResolve artifactResolve = (ArtifactResolve) ((MOARequest)obj.getRequest()).getSamlRequest(); - String artifactID = artifactResolve.getArtifact().getArtifact(); - - PVPAssertionStorage pvpAssertion = PVPAssertionStorage.getInstance(); - - if (!pvpAssertion.contains(artifactID)) { - throw new RequestDeniedException(); - } else { - try { - SAMLArtifactMapEntry assertion = pvpAssertion.get(artifactID); - ArtifactResponse response = SAML2Utils - .createSAMLObject(ArtifactResponse.class); - response.setMessage(assertion.getSamlMessage()); - response.setIssueInstant(new DateTime()); - SoapBinding encoder = new SoapBinding(); - encoder.encodeRespone(req, resp, response, null, null); - } catch (Exception e) { - Logger.error("Failed to resolve artifact", e); - } - } - - return null; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index 059e68865..974d90e11 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java @@ -41,15 +41,14 @@ import at.gv.egovernment.moa.id.data.SLOInformationImpl; import at.gv.egovernment.moa.id.data.SLOInformationInterface; 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.binding.ArtifactBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; -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.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.exceptions.BindingNotSupportedException; +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.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; @@ -92,12 +91,7 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { if (consumerService.getBinding().equals( SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { binding = new RedirectBinding(); - - } else if (consumerService.getBinding().equals( - SAMLConstants.SAML2_ARTIFACT_BINDING_URI)) { - // TODO: not supported YET!! - binding = new ArtifactBinding(); - + } else if (consumerService.getBinding().equals( SAMLConstants.SAML2_POST_BINDING_URI)) { binding = new PostBinding(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java index b58b09f12..f26b2a735 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java @@ -30,12 +30,9 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; -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.exceptions.SAMLRequestNotSupported; public class RequestManager { @@ -54,7 +51,7 @@ public class RequestManager { private RequestManager() { handler = new ArrayList(); handler.add(new AuthnRequestHandler()); - handler.add(new ArtifactResolution()); + } public SLOInformationInterface handle(PVPTargetConfiguration pvpRequest, HttpServletRequest req, HttpServletResponse resp, IAuthData authData) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java deleted file mode 100644 index 3b97f3b08..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java +++ /dev/null @@ -1,227 +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.io.Serializable; -import java.util.Date; -import java.util.List; - -import org.apache.commons.lang.SerializationUtils; -import org.hibernate.HibernateException; -import org.hibernate.Query; -import org.hibernate.Session; - -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.data.AuthenticationData; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public class AssertionStorage { - - private static AssertionStorage instance = null; - - public static AssertionStorage getInstance() { - if(instance == null) { - instance = new AssertionStorage(); - } - return instance; - } - - public boolean containsKey(String artifact) { - try { - searchInDatabase(artifact); - return true; - - } catch (MOADatabaseException e) { - return false; - } - - } - - public void put(String artifact, Object assertion) throws MOADatabaseException { - //setup AssertionStore element - AssertionStore element = new AssertionStore(); - element.setArtifact(artifact); - element.setType(assertion.getClass().getName()); - element.setDatatime(new Date()); - - //serialize the Assertion for Database storage - byte[] data = SerializationUtils.serialize((Serializable) assertion); - element.setAssertion(data); - - //store AssertionStore element to Database - try { - MOASessionDBUtils.saveOrUpdate(element); - Logger.info(assertion.getClass().getName() + " with ID: " + artifact + " is stored in Database"); - } catch (MOADatabaseException e) { - Logger.warn("Sessioninformation could not be stored."); - throw new MOADatabaseException(e); - } - - } - - - /** - * @param samlArtifact - * @param class1 - * @param authdatatimeout - * @return - * @throws MOADatabaseException - * @throws AuthenticationException - */ - public T get(String samlArtifact, - final Class clazz) throws MOADatabaseException { - - try { - return get(samlArtifact, clazz, -1); - - } catch (AuthenticationException e) { - //this execption only occurs if an additional timeOut is used - Logger.error("This exeption should not occur!!!!", e); - return null; - } - } - - public T get(String artifact, final Class clazz, long authdatatimeout) throws MOADatabaseException, AuthenticationException { - - AssertionStore element = searchInDatabase(artifact); - - if (authdatatimeout > -1) { - //check timeout - long now = new Date().getTime(); - - if (now - element.getDatatime().getTime() > authdatatimeout) - throw new AuthenticationException("1207", new Object[] { artifact }); - } - - - //Deserialize Assertion - Object data = SerializationUtils.deserialize(element.getAssertion()); - - //check if assertion has the correct class type - try { - @SuppressWarnings("unchecked") - T test = (T) Class.forName(element.getType()).cast(data); - return test; - - } catch (Exception e) { - Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + artifact); - throw new MOADatabaseException("Sessioninformation Cast-Exception"); - } - } - - public void clean(long now, long authDataTimeOut) { - Date expioredate = new Date(now - authDataTimeOut); - - List results; - Session session = MOASessionDBUtils.getCurrentSession(); - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getAssertionWithTimeOut"); - query.setTimestamp("timeout", expioredate); - results = query.list(); - session.getTransaction().commit(); - - if (results.size() != 0) { - for(AssertionStore result : results) { - try { - cleanDelete(result); - Logger.info("Remove stored information with ID: " + result.getArtifact() - + " after timeout."); - - } catch (HibernateException e){ - Logger.warn("Sessioninformation with ID=" + result.getArtifact() - + " not removed after timeout! (Error during Database communication)", e); - } - - } - } - } - } - - public void remove(String artifact) { - - try { - AssertionStore element = searchInDatabase(artifact); - cleanDelete(element); - Logger.info("Remove stored information with ID: " + artifact); - - - } catch (MOADatabaseException e) { - Logger.info("Sessioninformation not removed! (Sessioninformation with ID=" + artifact - + "not found)"); - - } catch (HibernateException e) { - Logger.warn("Sessioninformation not removed! (Error during Database communication)", e); - } - } - - private void cleanDelete(AssertionStore element) { - try { - element.setAssertion("blank".getBytes()); - MOASessionDBUtils.saveOrUpdate(element); - - } catch (MOADatabaseException e) { - Logger.warn("Blank shortTime session with artifact=" + element.getArtifact() + " FAILED.", e); - - } finally { - if (!MOASessionDBUtils.delete(element)) - Logger.error("ShortTime session with artifact=" + element.getArtifact() - + " not removed! (Error during Database communication)"); - - } - - } - - @SuppressWarnings("rawtypes") - private AssertionStore searchInDatabase(String artifact) throws MOADatabaseException { - MiscUtil.assertNotNull(artifact, "artifact"); - Logger.trace("Getting sessioninformation with ID " + artifact + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - List result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getAssertionWithArtifact"); - query.setParameter("artifact", artifact); - result = query.list(); - - //send transaction - session.getTransaction().commit(); - } - - 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"); - } - - return (AssertionStore) result.get(0); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java deleted file mode 100644 index 9dee39fe8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AuthenticationSessionStoreage.java +++ /dev/null @@ -1,1130 +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.ArrayList; -import java.util.Date; -import java.util.List; - -import org.apache.commons.lang.SerializationUtils; -import org.apache.commons.lang.StringEscapeUtils; -import org.hibernate.HibernateException; -import org.hibernate.Query; -import org.hibernate.Session; -import org.hibernate.Transaction; - -import com.fasterxml.jackson.core.JsonProcessingException; - -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.db.MOASessionDBUtils; -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.commons.utils.JsonMapper; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.EncryptedData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStoreDAOImpl; -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; - -public class AuthenticationSessionStoreage { - - //private static HashMap sessionStore = new HashMap(); - - private static JsonMapper mapper = new JsonMapper(); - - public static boolean isAuthenticated(String moaSessionID) { - - AuthenticatedSessionStore session; - - try { - session = searchInDatabase(moaSessionID, true); - return session.isAuthenticated(); - - } catch (MOADatabaseException e) { - return false; - } - } - - public static AuthenticationSession createSession(IRequest target) throws MOADatabaseException, BuildException { - String id = Random.nextRandom(); - 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(); - dbsession.setCreated(now); - dbsession.setUpdated(now); - - dbsession.setPendingRequestID(target.getRequestID()); - - //set additional session informations - AuthenticationSessionExtensions sessionExt = new AuthenticationSessionExtensions(); - sessionExt.setUniqueSessionId(target.getSessionIdentifier()); - dbsession.setAdditionalInformation(mapper.serialize(sessionExt)); - - AuthenticationSession session = new AuthenticationSession(id, now); - encryptSession(session, dbsession); - - //store AssertionStore element to Database - MOASessionDBUtils.saveOrUpdate(dbsession); - Logger.info("Create MOASession with sessionID: " + id); - - return session; - - } catch (MOADatabaseException e) { - Logger.warn("MOASession could not be created."); - throw new MOADatabaseException(e); - - } catch (JsonProcessingException e) { - Logger.warn("Extended session information can not be stored.", e); - throw new MOADatabaseException(e); - - } - - } - - public static AuthenticationSession getSession(String sessionID) throws MOADatabaseException { - - try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); - return decryptSession(dbsession); - - } catch (MOADatabaseException e) { - Logger.info("No MOA Session with id: " + sessionID); - throw new MOADatabaseException("No MOA Session with id: " + sessionID); - - } catch (Throwable e) { - Logger.warn("MOASession deserialization-exception by using MOASessionID=" + sessionID, e); - throw new MOADatabaseException("MOASession deserialization-exception"); - } - } - - public static AuthenticationSessionExtensions getAuthenticationSessionExtensions(String sessionID) throws MOADatabaseException { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); - - if (MiscUtil.isNotEmpty(dbsession.getAdditionalInformation())) { - try { - return (AuthenticationSessionExtensions)mapper.deserialize(dbsession.getAdditionalInformation(), - AuthenticationSessionExtensions.class); - - } catch (Exception e) { - Logger.warn("Extended session information extraction FAILED!", e); - } - } - return null; - - } - - public static void setAuthenticationSessionExtensions(String sessionID, AuthenticationSessionExtensions sessionExtensions) throws MOADatabaseException { - try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); - - dbsession.setAdditionalInformation( - mapper.serialize(sessionExtensions)); - - MOASessionDBUtils.saveOrUpdate(dbsession); - Logger.debug("MOASession with sessionID=" + sessionID + " is stored in Database"); - - - } catch (MOADatabaseException e) { - Logger.warn("MOASession could not be stored."); - throw new MOADatabaseException(e); - - } catch (JsonProcessingException e) { - Logger.warn("Extended session information can not be stored.", e); - throw new MOADatabaseException("Extended session information can not be stored.", e); - - } - - } - - public static void storeSession(AuthenticationSession session) throws MOADatabaseException, BuildException { - storeSession(session, null); - } - - public static void storeSession(AuthenticationSession session, String pendingRequestID) throws MOADatabaseException, BuildException { - - try { - AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true); - - if (MiscUtil.isNotEmpty(pendingRequestID)) - dbsession.setPendingRequestID(pendingRequestID); - - encryptSession(session, dbsession); - - //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1 - dbsession.setAuthenticated(session.isAuthenticated()); - dbsession.setUpdated(new Date()); - - MOASessionDBUtils.saveOrUpdate(dbsession); - Logger.debug("MOASession with sessionID=" + session.getSessionID() + " is stored in Database"); - - } catch (MOADatabaseException e) { - Logger.warn("MOASession could not be stored."); - throw new MOADatabaseException(e); - } - } - - public static void destroySession(String moaSessionID) throws MOADatabaseException { - - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - Transaction tx = null; - try { - synchronized (session) { - - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithID"); - query.setParameter("sessionid", moaSessionID); - 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 session found with this sessionID"); - } - - AuthenticatedSessionStore dbsession = (AuthenticatedSessionStore) result.get(0); - tx.commit(); - cleanDelete(dbsession); - } - - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - - } - - } - - public static String changeSessionID(AuthenticationSession session, String newSessionID) throws BuildException, AuthenticationException { - try { - AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true); - - - - Logger.debug("Change SessionID from " + session.getSessionID() - + "to " + newSessionID); - - session.setSessionID(newSessionID); - encryptSession(session, dbsession); - - dbsession.setSessionid(newSessionID); - dbsession.setAuthenticated(session.isAuthenticated()); - - //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1 - dbsession.setUpdated(new Date()); - - MOASessionDBUtils.saveOrUpdate(dbsession); - - Logger.trace("Change SessionID complete."); - - return newSessionID; - - } catch (MOADatabaseException e) { - throw new AuthenticationException("TODO!", null); - } - - - - } - - public static String changeSessionID(AuthenticationSession session) - throws AuthenticationException, BuildException { - String id = Random.nextRandom(); - return changeSessionID(session, id); - - } - - public static void setAuthenticated(String moaSessionID, boolean value) { - - AuthenticatedSessionStore session; - - try { - session = searchInDatabase(moaSessionID, true); - session.setAuthenticated(value); - MOASessionDBUtils.saveOrUpdate(session); - - - } catch (MOADatabaseException e) { - Logger.warn("isAuthenticated can not be stored in MOASession " + moaSessionID, e); - } - } - - public static String getMOASessionSSOID(String SSOSessionID) { - MiscUtil.assertNotNull(SSOSessionID, "SSOsessionID"); - Logger.trace("Get authenticated session with SSOID " + SSOSessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - Transaction tx = null; - try { - synchronized (session) { - - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithSSOID"); - query.setParameter("sessionid", SSOSessionID); - result = query.list(); - - //send transaction - tx.commit(); - - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - return null; - - } else { - return result.get(0).getSessionid(); - - } - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - } - } - - public static boolean isSSOSession(String sessionID) throws MOADatabaseException { - try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); - return dbsession.isSSOSession(); - - } catch (MOADatabaseException e) { - Logger.info("No MOA Session with id: " + sessionID); - throw new MOADatabaseException("No MOA Session with id: " + sessionID); - } - } - - public static AuthenticatedSessionStore isValidSessionWithSSOID(String SSOId, String moaSessionId) { - MiscUtil.assertNotNull(SSOId, "SSOSessionID"); - Logger.trace("Get authenticated session with SSOID " + SSOId + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - Transaction tx = null; - try { - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithSSOID"); - query.setParameter("sessionid", SSOId); - result = query.list(); - - //send transaction - tx.commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - return null; - - } else { - return result.get(0); - } - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - } - } - - public static void addSSOInformation(String moaSessionID, String SSOSessionID, - SLOInformationInterface SLOInfo, IRequest protocolRequest) throws AuthenticationException { - - AuthenticatedSessionStore dbsession; - Transaction tx = null; - - try { - - Session session = MOASessionDBUtils.getCurrentSession(); - List result; - - Logger.trace("Add SSO information to session " + moaSessionID); - - synchronized (session) { - - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithID"); - query.setParameter("sessionid", moaSessionID); - result = query.list(); - - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - tx.rollback(); - throw new MOADatabaseException("No session found with this sessionID"); - } - - dbsession = (AuthenticatedSessionStore) result.get(0); - - OASessionStore activeOA = null; - //check if OA already has an active OA session - if (dbsession.getActiveOAsessions() != null) { - for (OASessionStore el : dbsession.getActiveOAsessions()) { - if (el.getOaurlprefix().equals(protocolRequest.getOAURL())) - activeOA = el; - } - } - - if (activeOA == null) - activeOA = new OASessionStore(); - - //set active OA applications - activeOA.setOaurlprefix(protocolRequest.getOAURL()); - activeOA.setMoasession(dbsession); - activeOA.setCreated(new Date()); - - //set additional information for SLO - if (SLOInfo != null) { - activeOA.setAssertionSessionID(SLOInfo.getSessionIndex()); - activeOA.setUserNameID(SLOInfo.getUserNameIdentifier()); - activeOA.setUserNameIDFormat(SLOInfo.getUserNameIDFormat()); - activeOA.setProtocolType(SLOInfo.getProtocolType()); - activeOA.setAttributeQueryUsed(false); - activeOA.setAuthURL(protocolRequest.getAuthURL()); - - - } - - List activeOAs = dbsession.getActiveOAsessions(); - activeOAs.add(activeOA); - dbsession.setActiveOAsessions(activeOAs); - - - //Store used SSOId - if (dbsession.getSSOsessionid() != null) { - OldSSOSessionIDStore oldSSOId = new OldSSOSessionIDStore(); - oldSSOId.setOldsessionid(dbsession.getSSOsessionid()); - oldSSOId.setMoasession(dbsession); - - List oldSSOIds = dbsession.getOldssosessionids(); - oldSSOIds.add(oldSSOId); - } - - dbsession.setSSOSession(true); - dbsession.setSSOsessionid(SSOSessionID); - dbsession.setAuthenticated(false); - dbsession.setPendingRequestID("empty"); - - //Store MOASession - session.saveOrUpdate(dbsession); - - //send transaction - tx.commit(); - - if (SLOInfo != null) - Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getOAURL() - + " and AssertionID: " + SLOInfo.getSessionIndex()); - else - Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getOAURL()); - - } - - } catch (MOADatabaseException e) { - throw new AuthenticationException("No MOASession found with Id="+moaSessionID, null); - - } catch(HibernateException e) { - Logger.warn("Error during database saveOrUpdate. Rollback.", e); - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw new AuthenticationException("SSO Session information can not be stored! --> SSO is deactivated", null); - } - } - - public static List getAllActiveOAFromMOASession(AuthenticationSession moaSession) { - MiscUtil.assertNotNull(moaSession, "MOASession"); - Session session = null; - - try { - List oas = new ArrayList(); - - AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); - oas.addAll(dbsession.getActiveOAsessions()); - - session = MOASessionDBUtils.getCurrentSession(); - session.getTransaction().commit(); - - return oas; - - } catch (MOADatabaseException e) { - Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e); - - } catch (Exception e) { - if (session != null && session.getTransaction() != null - && !session.getTransaction().wasCommitted()) { - session.getTransaction().rollback(); - throw e; - - } - - } - - return null; - } - - public static List getAllActiveIDPsFromMOASession(AuthenticationSession moaSession) { - MiscUtil.assertNotNull(moaSession, "MOASession"); - Session session = null; - try { - List idps = new ArrayList(); - AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); - idps.addAll(dbsession.getInderfederation()); - - session = MOASessionDBUtils.getCurrentSession(); - session.getTransaction().commit(); - - return idps; - - } catch (MOADatabaseException e) { - Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e); - - } catch (Exception e) { - if (session != null && session.getTransaction() != null - && !session.getTransaction().wasCommitted()) { - session.getTransaction().rollback(); - throw e; - - } - - } - - return null; - } - - public static AuthenticationSession searchMOASessionWithNameIDandOAID(String oaID, String userNameID) { - MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier"); - MiscUtil.assertNotNull(userNameID, "userNameID"); - Logger.trace("Get moaSession for userNameID " + userNameID + " and OA " - + oaID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - Transaction tx = null; - - List result = null;; - try { - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getMOASessionWithNameIDandOAID"); - query.setParameter("oaID", oaID); - query.setParameter("nameID", userNameID); - result = query.list(); - - //send transaction - tx.commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No unique entry found."); - return null; - - } - - return decryptSession(result.get(0)); - - } catch (BuildException e) { - Logger.warn("MOASession deserialization-exception by using MOASessionID=" + result.get(0).getSessionid(), e); - return null; - - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - } - - } - - public static OASessionStore searchActiveOASSOSession(AuthenticationSession moaSession, String oaID, String protocolType) { - MiscUtil.assertNotNull(moaSession, "MOASession"); - MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier"); - MiscUtil.assertNotNull(protocolType, "usedProtocol"); - Logger.trace("Get active OnlineApplication for sessionID " + moaSession.getSessionID() + " with OAID " - + oaID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - Transaction tx = null; - try { - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getActiveOAWithSessionIDandOAIDandProtocol"); - query.setParameter("sessionID", moaSession.getSessionID()); - query.setParameter("oaID", oaID); - query.setParameter("protocol", protocolType); - result = query.list(); - - //send transaction - tx.commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - - } - - return result.get(0).getActiveOAsessions().get(0); - - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - } - } - - public static String getPendingRequestID(String sessionID) { - try { - AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); - return dbsession.getPendingRequestID(); - - } catch (MOADatabaseException e) { - Logger.warn("MOASession with ID " + sessionID + " not found"); - return ""; - } - } - - public static AuthenticationSession getSessionWithPendingRequestID(String pedingRequestID) { - Transaction tx = null; - try { - MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID"); - Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithPendingRequestID"); - query.setParameter("sessionid", pedingRequestID); - result = query.list(); - - //send transaction - tx.commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - return null; - } - - return decryptSession(result.get(0)); - - } catch (Throwable e) { - Logger.warn("MOASession deserialization-exception by using MOASessionID=" + pedingRequestID); - - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - - return null; - - } - } - - public static boolean deleteSessionWithPendingRequestID(String id) { - MiscUtil.assertNotNull(id, "PendingRequestID"); - Logger.trace("Delete MOAsession with PendingRequestID " + id + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - Transaction tx = null; - try { - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithPendingRequestID"); - query.setParameter("sessionid", id); - result = query.list(); - - //send transaction - tx.commit(); - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - return false; - - } else { - cleanDelete(result.get(0)); - return true; - } - } - - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - } - } - - public static AuthenticationSession getSessionWithUserNameID(String nameID) { - - Transaction tx = null; - try { - MiscUtil.assertNotNull(nameID, "nameID"); - Logger.trace("Get authenticated session with pedingRequestID " + nameID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getMOAISessionWithUserNameID"); - query.setParameter("usernameid", StringEscapeUtils.escapeHtml(nameID)); - result = query.list(); - - //send transaction - tx.commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - } - - return decryptSession(result.get(0)); - - } catch (Throwable e) { - Logger.warn("MOASession deserialization-exception by using MOASessionID=" + nameID); - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - return null; - } - - } - - public static InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASession(String sessionID) { - MiscUtil.assertNotNull(sessionID, "MOASession"); - Logger.trace("Get interfederated IDP for SSO with sessionID " + sessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - Transaction tx = null; - try { - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionID"); - query.setParameter("sessionID", sessionID); - result = query.list(); - - //send transaction - tx.commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - - } - - return result.get(0).getInderfederation().get(0); - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - } - } - - public static InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASessionIDPID(String sessionID, String idpID) { - MiscUtil.assertNotNull(sessionID, "MOASession"); - MiscUtil.assertNotNull(idpID, "Interfederated IDP ID"); - Logger.trace("Get interfederated IDP "+ idpID + " for SSO with sessionID " + sessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - Transaction tx = null; - try { - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionIDIDPID"); - query.setParameter("sessionID", sessionID); - query.setParameter("idpID", idpID); - result = query.list(); - - //send transaction - tx.commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - - } - - return result.get(0).getInderfederation().get(0); - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - } - } - - public static String createInterfederatedSession(IRequest req, boolean isAuthenticated, String ssoID) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException { - AuthenticatedSessionStore dbsession = null; - - //search for active SSO session - if (MiscUtil.isNotEmpty(ssoID)) { - String moaSession = getMOASessionSSOID(ssoID); - if (MiscUtil.isNotEmpty(moaSession)) { - try { - dbsession = searchInDatabase(moaSession, true); - - }catch (MOADatabaseException e) { - - } - } - } - - String id = null; - Date now = new Date(); - //create new MOASession if any exists - AuthenticationSession session = null; - if (dbsession == null) { - id = Random.nextRandom(); - dbsession = new AuthenticatedSessionStore(); - dbsession.setSessionid(id); - dbsession.setCreated(now); - dbsession.setPendingRequestID(req.getRequestID()); - session = new AuthenticationSession(id, now); - - } else { - id = dbsession.getSessionid(); - session = decryptSession(dbsession); - - } - - dbsession.setInterfederatedSSOSession(true); - dbsession.setAuthenticated(isAuthenticated); - dbsession.setUpdated(now); - session.setAuthenticated(true); - session.setAuthenticatedUsed(false); - encryptSession(session, dbsession); - - //add interfederation information - List idpList = dbsession.getInderfederation(); - InterfederationSessionStore idp = null; - if (idpList == null) { - idpList = new ArrayList(); - dbsession.setInderfederation(idpList); - - } else { - for (InterfederationSessionStore el : idpList) { - //resue old entry if interfederation IDP is reused for authentication - if (el.getIdpurlprefix().equals(req.getInterfederationResponse().getEntityID())) - idp = el; - - } - } - - //create new interfederation IDP entry - if (idp == null) { - idp = new InterfederationSessionStore(); - idp.setCreated(now); - idp.setIdpurlprefix(req.getInterfederationResponse().getEntityID()); - idp.setAuthURL(req.getAuthURL()); - - try { - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance(). - getOnlineApplicationParameter(idp.getIdpurlprefix()); - idp.setStoreSSOInformation(oa.isInterfederationSSOStorageAllowed()); - - } catch (ConfigurationException e) { - Logger.warn("MOASession could not be created."); - throw new MOADatabaseException(e); - - } - idp.setMoasession(dbsession); - idpList.add(idp); - - } - AssertionAttributeExtractor extract = new AssertionAttributeExtractor(req.getInterfederationResponse().getResponse()); - idp.setSessionIndex(extract.getSessionIndex()); - idp.setUserNameID(extract.getNameID()); - idp.setAttributesRequested(false); - idp.setQAALevel(extract.getQAALevel()); - - //store AssertionStore element to Database - try { - MOASessionDBUtils.saveOrUpdate(dbsession); - Logger.debug("MOASession with sessionID=" + id + " is stored in Database"); - - } catch (MOADatabaseException e) { - Logger.warn("MOASession could not be created."); - throw new MOADatabaseException(e); - } - - return id; - } - - public static InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(AuthenticationSession moaSession) { - MiscUtil.assertNotNull(moaSession, "MOASession"); - Logger.trace("Get interfederated IDP for AttributeQuery with sessionID " + moaSession.getSessionID() + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - Transaction tx = null; - try { - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getInterfederatedIDPForAttributeQueryWithSessionID"); - query.setParameter("sessionID", moaSession.getSessionID()); - result = query.list(); - - //send transaction - tx.commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - - } - - return result.get(0).getInderfederation().get(0); - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - } - } - - /** - * @param entityID - * @param requestID - */ - public static boolean removeInterfederetedSession(String entityID, - String pedingRequestID) { - - try { - Logger.debug("Remove interfederated IDP from local SSO session ..."); - - MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID"); - Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithPendingRequestID"); - query.setParameter("sessionid", pedingRequestID); - result = query.list(); - - //send transaction - session.getTransaction().commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - return false; - } - - AuthenticatedSessionStore authsession = result.get(0); - - List idpSessions = authsession.getInderfederation(); - if (idpSessions != null) { - for (InterfederationSessionStore idp : idpSessions) { - if (idp.getIdpurlprefix().equals(entityID)) - idpSessions.remove(idp); - - } - } - - MOASessionDBUtils.saveOrUpdate(authsession); - return true; - - } catch (Throwable e) { - Logger.warn("MOASession deserialization-exception by using MOASessionID=" + pedingRequestID); - return false; - } - } - - public static void clean(long now, long authDataTimeOutCreated, long authDataTimeOutUpdated) { - Date expioredatecreate = new Date(now - authDataTimeOutCreated); - Date expioredateupdate = new Date(now - authDataTimeOutUpdated); - - List results; - Session session = MOASessionDBUtils.getCurrentSession(); - Transaction tx = null; - try { - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getMOAISessionsWithTimeOut"); - query.setTimestamp("timeoutcreate", expioredatecreate); - query.setTimestamp("timeoutupdate", expioredateupdate); - results = query.list(); - tx.commit(); - - if (results.size() != 0) { - for(AuthenticatedSessionStore result : results) { - try { - cleanDelete(result); - Logger.info("Authenticated session with sessionID=" + result.getSessionid() - + " after session timeout."); - - } catch (HibernateException e){ - Logger.warn("Authenticated session with sessionID=" + result.getSessionid() - + " not removed after timeout! (Error during Database communication)", e); - } - } - } - } - - } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) - tx.rollback(); - throw e; - } - } - - private static void encryptSession(AuthenticationSession session, AuthenticatedSessionStore dbsession) throws BuildException { - byte[] serialized = SerializationUtils.serialize(session); - - EncryptedData encdata = SessionEncrytionUtil.getInstance().encrypt(serialized); - dbsession.setSession(encdata.getEncData()); - dbsession.setIv(encdata.getIv()); - } - - private static AuthenticationSession decryptSession(AuthenticatedSessionStore dbsession) throws BuildException { - EncryptedData encdata = new EncryptedData(dbsession.getSession(), - dbsession.getIv()); - byte[] decrypted = SessionEncrytionUtil.getInstance().decrypt(encdata); - - return (AuthenticationSession) SerializationUtils.deserialize(decrypted); - - } - - private static void cleanDelete(AuthenticatedSessionStore result) { - - try { - AuthenticationSession session = getSession(result.getSessionid()); - if (session.getProcessInstanceId() != null) { - ProcessInstanceStoreDAOImpl.getInstance().remove(session.getProcessInstanceId()); - } - - } catch (MOADatabaseException e) { - Logger.warn("Removing process associated with moa session " + result.getSessionid() + " FAILED.", e); - } - - try { - result.setSession("blank".getBytes()); - MOASessionDBUtils.saveOrUpdate(result); - - } catch (MOADatabaseException e) { - Logger.warn("Blank authenticated session with sessionID=" + result.getSessionid() + " FAILED.", e); - - } finally { - if (!MOASessionDBUtils.delete(result)) - Logger.error("Authenticated session with sessionID=" + result.getSessionid() + " not removed! (Error during Database communication)"); - } - } - - @SuppressWarnings("rawtypes") - private static AuthenticatedSessionStore searchInDatabase(String sessionID, boolean commit) throws MOADatabaseException { - MiscUtil.assertNotNull(sessionID, "moasessionID"); - Logger.trace("Get authenticated session with sessionID " + sessionID + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - - List result; - Transaction tx = null; - try { - synchronized (session) { - tx = session.beginTransaction(); - Query query = session.getNamedQuery("getSessionWithID"); - query.setParameter("sessionid", sessionID); - result = query.list(); - - //send transaction - if (commit) - tx.commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - throw new MOADatabaseException("No session found with this sessionID"); - } - - return (AuthenticatedSessionStore) result.get(0); - } catch (Exception e) { - if (tx != null && !tx.wasCommitted() && commit) - tx.rollback(); - throw e; - } - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java new file mode 100644 index 000000000..743caec55 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java @@ -0,0 +1,1049 @@ +/******************************************************************************* + * 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.ArrayList; +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang.SerializationUtils; +import org.apache.commons.lang.StringEscapeUtils; +import org.hibernate.HibernateException; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.springframework.stereotype.Service; + +import com.fasterxml.jackson.core.JsonProcessingException; + +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.db.MOASessionDBUtils; +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.commons.utils.JsonMapper; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.data.EncryptedData; +import at.gv.egovernment.moa.id.data.SLOInformationInterface; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; +import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; +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; + +@Service("AuthenticationSessionStoreage") +public class DBAuthenticationSessionStoreage implements IAuthenticationSessionStoreage{ + + private static JsonMapper mapper = new JsonMapper(); + + @Override + public boolean isAuthenticated(String moaSessionID) { + + AuthenticatedSessionStore session; + + try { + session = searchInDatabase(moaSessionID, true); + return session.isAuthenticated(); + + } catch (MOADatabaseException e) { + return false; + } + } + + @Override + public AuthenticationSession createSession(IRequest target) throws MOADatabaseException, BuildException { + String id = Random.nextRandom(); + 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(); + dbsession.setCreated(now); + dbsession.setUpdated(now); + + dbsession.setPendingRequestID(target.getRequestID()); + + //set additional session informations + AuthenticationSessionExtensions sessionExt = new AuthenticationSessionExtensions(); + sessionExt.setUniqueSessionId(target.getUniqueSessionIdentifier()); + dbsession.setAdditionalInformation(mapper.serialize(sessionExt)); + + AuthenticationSession session = new AuthenticationSession(id, now); + encryptSession(session, dbsession); + + //store AssertionStore element to Database + MOASessionDBUtils.saveOrUpdate(dbsession); + Logger.info("Create MOASession with sessionID: " + id); + + return session; + + } catch (MOADatabaseException e) { + Logger.warn("MOASession could not be created."); + throw new MOADatabaseException(e); + + } catch (JsonProcessingException e) { + Logger.warn("Extended session information can not be stored.", e); + throw new MOADatabaseException(e); + + } + + } + + @Override + public AuthenticationSession getSession(String sessionID) throws MOADatabaseException { + + if (MiscUtil.isEmpty(sessionID)) + return null; + + try { + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + return decryptSession(dbsession); + + } catch (MOADatabaseException e) { + Logger.info("No MOA Session with id: " + sessionID); + return null; + + } catch (Throwable e) { + Logger.warn("MOASession deserialization-exception by using MOASessionID=" + sessionID, e); + throw new MOADatabaseException("MOASession deserialization-exception"); + } + } + + @Override + public AuthenticationSessionExtensions getAuthenticationSessionExtensions(String sessionID) throws MOADatabaseException { + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + + if (MiscUtil.isNotEmpty(dbsession.getAdditionalInformation())) { + try { + return (AuthenticationSessionExtensions)mapper.deserialize(dbsession.getAdditionalInformation(), + AuthenticationSessionExtensions.class); + + } catch (Exception e) { + Logger.warn("Extended session information extraction FAILED!", e); + } + } + return null; + + } + + @Override + public void setAuthenticationSessionExtensions(String sessionID, AuthenticationSessionExtensions sessionExtensions) throws MOADatabaseException { + try { + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + + dbsession.setAdditionalInformation( + mapper.serialize(sessionExtensions)); + + MOASessionDBUtils.saveOrUpdate(dbsession); + Logger.debug("MOASession with sessionID=" + sessionID + " is stored in Database"); + + + } catch (MOADatabaseException e) { + Logger.warn("MOASession could not be stored."); + throw new MOADatabaseException(e); + + } catch (JsonProcessingException e) { + Logger.warn("Extended session information can not be stored.", e); + throw new MOADatabaseException("Extended session information can not be stored.", e); + + } + + } + + @Override + public void storeSession(AuthenticationSession session) throws MOADatabaseException, BuildException { + try { + AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true); + + encryptSession(session, dbsession); + + //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1 + dbsession.setAuthenticated(session.isAuthenticated()); + dbsession.setUpdated(new Date()); + + MOASessionDBUtils.saveOrUpdate(dbsession); + Logger.debug("MOASession with sessionID=" + session.getSessionID() + " is stored in Database"); + + } catch (MOADatabaseException e) { + Logger.warn("MOASession could not be stored."); + throw new MOADatabaseException(e); + } + } + + @Override + public void destroySession(String moaSessionID) throws MOADatabaseException { + + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithID"); + query.setParameter("sessionid", moaSessionID); + 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 session found with this sessionID"); + } + + AuthenticatedSessionStore dbsession = (AuthenticatedSessionStore) result.get(0); + tx.commit(); + cleanDelete(dbsession); + } + + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + + } + + } + + @Override + public String changeSessionID(AuthenticationSession session, String newSessionID) throws BuildException, MOADatabaseException { + + AuthenticatedSessionStore dbsession = searchInDatabase(session.getSessionID(), true); + + Logger.debug("Change SessionID from " + session.getSessionID() + + "to " + newSessionID); + + session.setSessionID(newSessionID); + encryptSession(session, dbsession); + + dbsession.setSessionid(newSessionID); + dbsession.setAuthenticated(session.isAuthenticated()); + + //set Timestamp in this state, because automated timestamp generation is buggy in Hibernate 4.2.1 + dbsession.setUpdated(new Date()); + + MOASessionDBUtils.saveOrUpdate(dbsession); + + Logger.trace("Change SessionID complete."); + + return newSessionID; + + } + + @Override + public String changeSessionID(AuthenticationSession session) + throws BuildException, MOADatabaseException { + String id = Random.nextRandom(); + return changeSessionID(session, id); + + } + + @Override + public void setAuthenticated(String moaSessionID, boolean isAuthenticated) { + + AuthenticatedSessionStore session; + + try { + session = searchInDatabase(moaSessionID, true); + session.setAuthenticated(isAuthenticated); + MOASessionDBUtils.saveOrUpdate(session); + + + } catch (MOADatabaseException e) { + Logger.warn("isAuthenticated can not be stored in MOASession " + moaSessionID, e); + } + } + + @Override + public String getMOASessionSSOID(String SSOSessionID) { + MiscUtil.assertNotNull(SSOSessionID, "SSOsessionID"); + Logger.trace("Get authenticated session with SSOID " + SSOSessionID + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithSSOID"); + query.setParameter("sessionid", SSOSessionID); + result = query.list(); + + //send transaction + tx.commit(); + + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + return null; + + } else { + return result.get(0).getSessionid(); + + } + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } + } + + @Override + public boolean isSSOSession(String sessionID) throws MOADatabaseException { + try { + AuthenticatedSessionStore dbsession = searchInDatabase(sessionID, true); + return dbsession.isSSOSession(); + + } catch (MOADatabaseException e) { + Logger.info("No MOA Session with id: " + sessionID); + throw new MOADatabaseException("No MOA Session with id: " + sessionID); + } + } + + @Override + public AuthenticatedSessionStore isValidSessionWithSSOID(String SSOId) { + + //TODO: is this method really needed?? + MiscUtil.assertNotNull(SSOId, "SSOSessionID"); + Logger.trace("Get authenticated session with SSOID " + SSOId + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithSSOID"); + query.setParameter("sessionid", SSOId); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + return null; + + } else { + return result.get(0); + } + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } + } + + @Override + public void addSSOInformation(String moaSessionID, String SSOSessionID, + SLOInformationInterface SLOInfo, IRequest protocolRequest) throws AuthenticationException { + + AuthenticatedSessionStore dbsession; + Transaction tx = null; + + try { + + Session session = MOASessionDBUtils.getCurrentSession(); + List result; + + Logger.trace("Add SSO information to session " + moaSessionID); + + synchronized (session) { + + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithID"); + query.setParameter("sessionid", moaSessionID); + result = query.list(); + + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + tx.rollback(); + throw new MOADatabaseException("No session found with this sessionID"); + } + + dbsession = (AuthenticatedSessionStore) result.get(0); + + OASessionStore activeOA = null; + //check if OA already has an active OA session + if (dbsession.getActiveOAsessions() != null) { + for (OASessionStore el : dbsession.getActiveOAsessions()) { + if (el.getOaurlprefix().equals(protocolRequest.getOAURL())) + activeOA = el; + } + } + + if (activeOA == null) + activeOA = new OASessionStore(); + + //set active OA applications + activeOA.setOaurlprefix(protocolRequest.getOAURL()); + activeOA.setMoasession(dbsession); + activeOA.setCreated(new Date()); + + //set additional information for SLO + if (SLOInfo != null) { + activeOA.setAssertionSessionID(SLOInfo.getSessionIndex()); + activeOA.setUserNameID(SLOInfo.getUserNameIdentifier()); + activeOA.setUserNameIDFormat(SLOInfo.getUserNameIDFormat()); + activeOA.setProtocolType(SLOInfo.getProtocolType()); + activeOA.setAttributeQueryUsed(false); + activeOA.setAuthURL(protocolRequest.getAuthURL()); + + + } + + List activeOAs = dbsession.getActiveOAsessions(); + activeOAs.add(activeOA); + dbsession.setActiveOAsessions(activeOAs); + + + //Store used SSOId + if (dbsession.getSSOsessionid() != null) { + OldSSOSessionIDStore oldSSOId = new OldSSOSessionIDStore(); + oldSSOId.setOldsessionid(dbsession.getSSOsessionid()); + oldSSOId.setMoasession(dbsession); + + List oldSSOIds = dbsession.getOldssosessionids(); + oldSSOIds.add(oldSSOId); + } + + dbsession.setSSOSession(true); + dbsession.setSSOsessionid(SSOSessionID); + dbsession.setAuthenticated(false); + dbsession.setPendingRequestID("empty"); + + //Store MOASession + session.saveOrUpdate(dbsession); + + //send transaction + tx.commit(); + + if (SLOInfo != null) + Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getOAURL() + + " and AssertionID: " + SLOInfo.getSessionIndex()); + else + Logger.info("Add SSO-Session login information for OA: " + protocolRequest.getOAURL()); + + } + + } catch (MOADatabaseException e) { + throw new AuthenticationException("No MOASession found with Id="+moaSessionID, null); + + } catch(HibernateException e) { + Logger.warn("Error during database saveOrUpdate. Rollback.", e); + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw new AuthenticationException("SSO Session information can not be stored! --> SSO is deactivated", null); + } + } + + @Override + public List getAllActiveOAFromMOASession(AuthenticationSession moaSession) { + MiscUtil.assertNotNull(moaSession, "MOASession"); + Session session = null; + + try { + List oas = new ArrayList(); + + AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); + oas.addAll(dbsession.getActiveOAsessions()); + + session = MOASessionDBUtils.getCurrentSession(); + session.getTransaction().commit(); + + return oas; + + } catch (MOADatabaseException e) { + Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e); + + } catch (Exception e) { + if (session != null && session.getTransaction() != null + && !session.getTransaction().wasCommitted()) { + session.getTransaction().rollback(); + throw e; + + } + + } + + return null; + } + + @Override + public List getAllActiveIDPsFromMOASession(AuthenticationSession moaSession) { + MiscUtil.assertNotNull(moaSession, "MOASession"); + Session session = null; + try { + List idps = new ArrayList(); + AuthenticatedSessionStore dbsession = searchInDatabase(moaSession.getSessionID(), false); + idps.addAll(dbsession.getInderfederation()); + + session = MOASessionDBUtils.getCurrentSession(); + session.getTransaction().commit(); + + return idps; + + } catch (MOADatabaseException e) { + Logger.warn("NO session information found for sessionID " + moaSession.getSessionID(), e); + + } catch (Exception e) { + if (session != null && session.getTransaction() != null + && !session.getTransaction().wasCommitted()) { + session.getTransaction().rollback(); + throw e; + + } + + } + + return null; + } + + @Override + public AuthenticationSession searchMOASessionWithNameIDandOAID(String oaID, String userNameID) { + MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier"); + MiscUtil.assertNotNull(userNameID, "userNameID"); + Logger.trace("Get moaSession for userNameID " + userNameID + " and OA " + + oaID + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + Transaction tx = null; + + List result = null;; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getMOASessionWithNameIDandOAID"); + query.setParameter("oaID", oaID); + query.setParameter("nameID", userNameID); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No unique entry found."); + return null; + + } + + return decryptSession(result.get(0)); + + } catch (BuildException e) { + Logger.warn("MOASession deserialization-exception by using MOASessionID=" + result.get(0).getSessionid(), e); + return null; + + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } + + } + + @Override + public OASessionStore searchActiveOASSOSession(AuthenticationSession moaSession, String oaID, String protocolType) { + MiscUtil.assertNotNull(moaSession, "MOASession"); + MiscUtil.assertNotNull(oaID, "OnlineApplicationIdentifier"); + MiscUtil.assertNotNull(protocolType, "usedProtocol"); + Logger.trace("Get active OnlineApplication for sessionID " + moaSession.getSessionID() + " with OAID " + + oaID + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getActiveOAWithSessionIDandOAIDandProtocol"); + query.setParameter("sessionID", moaSession.getSessionID()); + query.setParameter("oaID", oaID); + query.setParameter("protocol", protocolType); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() == 0) { + Logger.trace("No entries found."); + return null; + + } + + return result.get(0).getActiveOAsessions().get(0); + + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } + } + + @Override + public AuthenticationSession getSessionWithUserNameID(String nameID) { + + Transaction tx = null; + try { + MiscUtil.assertNotNull(nameID, "nameID"); + Logger.trace("Get authenticated session with pedingRequestID " + nameID + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getMOAISessionWithUserNameID"); + query.setParameter("usernameid", StringEscapeUtils.escapeHtml(nameID)); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() == 0) { + Logger.trace("No entries found."); + return null; + } + + return decryptSession(result.get(0)); + + } catch (Throwable e) { + Logger.warn("MOASession deserialization-exception by using MOASessionID=" + nameID); + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + return null; + } + + } + + @Override + public InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASession(String sessionID) { + MiscUtil.assertNotNull(sessionID, "MOASession"); + Logger.trace("Get interfederated IDP for SSO with sessionID " + sessionID + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionID"); + query.setParameter("sessionID", sessionID); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() == 0) { + Logger.trace("No entries found."); + return null; + + } + + return result.get(0).getInderfederation().get(0); + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } + } + + @Override + public InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASessionIDPID(String sessionID, String idpID) { + MiscUtil.assertNotNull(sessionID, "MOASession"); + MiscUtil.assertNotNull(idpID, "Interfederated IDP ID"); + Logger.trace("Get interfederated IDP "+ idpID + " for SSO with sessionID " + sessionID + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getInterfederatedIDPForSSOWithSessionIDIDPID"); + query.setParameter("sessionID", sessionID); + query.setParameter("idpID", idpID); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() == 0) { + Logger.trace("No entries found."); + return null; + + } + + return result.get(0).getInderfederation().get(0); + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } + } + + public String createInterfederatedSession(IRequest req, boolean isAuthenticated, String ssoID) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException { + AuthenticatedSessionStore dbsession = null; + + //search for active SSO session + if (MiscUtil.isNotEmpty(ssoID)) { + String moaSession = getMOASessionSSOID(ssoID); + if (MiscUtil.isNotEmpty(moaSession)) { + try { + dbsession = searchInDatabase(moaSession, true); + + }catch (MOADatabaseException e) { + + } + } + } + + String id = null; + Date now = new Date(); + //create new MOASession if any exists + AuthenticationSession session = null; + if (dbsession == null) { + id = Random.nextRandom(); + dbsession = new AuthenticatedSessionStore(); + dbsession.setSessionid(id); + dbsession.setCreated(now); + dbsession.setPendingRequestID(req.getRequestID()); + session = new AuthenticationSession(id, now); + + } else { + id = dbsession.getSessionid(); + session = decryptSession(dbsession); + + } + + dbsession.setInterfederatedSSOSession(true); + dbsession.setAuthenticated(isAuthenticated); + dbsession.setUpdated(now); + session.setAuthenticated(true); + encryptSession(session, dbsession); + + //add interfederation information + List idpList = dbsession.getInderfederation(); + + MOAResponse interfederationResp = req.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, MOAResponse.class); + String interFedEntityID = interfederationResp.getEntityID(); + + InterfederationSessionStore idp = null; + if (idpList == null) { + idpList = new ArrayList(); + dbsession.setInderfederation(idpList); + + } else { + for (InterfederationSessionStore el : idpList) { + //resue old entry if interfederation IDP is reused for authentication + if (el.getIdpurlprefix().equals(interFedEntityID)) + idp = el; + + } + } + + //create new interfederation IDP entry + if (idp == null) { + idp = new InterfederationSessionStore(); + idp.setCreated(now); + idp.setIdpurlprefix(interFedEntityID); + idp.setAuthURL(req.getAuthURL()); + + try { + OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance(). + getOnlineApplicationParameter(idp.getIdpurlprefix()); + idp.setStoreSSOInformation(oa.isInterfederationSSOStorageAllowed()); + + } catch (ConfigurationException e) { + Logger.warn("MOASession could not be created."); + throw new MOADatabaseException(e); + + } + idp.setMoasession(dbsession); + idpList.add(idp); + + } + AssertionAttributeExtractor extract = new AssertionAttributeExtractor(interfederationResp.getResponse()); + idp.setSessionIndex(extract.getSessionIndex()); + idp.setUserNameID(extract.getNameID()); + idp.setAttributesRequested(false); + idp.setQAALevel(extract.getQAALevel()); + + //store AssertionStore element to Database + try { + MOASessionDBUtils.saveOrUpdate(dbsession); + Logger.debug("MOASession with sessionID=" + id + " is stored in Database"); + + } catch (MOADatabaseException e) { + Logger.warn("MOASession could not be created."); + throw new MOADatabaseException(e); + } + + return id; + } + + @Override + public InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(AuthenticationSession moaSession) { + MiscUtil.assertNotNull(moaSession, "MOASession"); + Logger.trace("Get interfederated IDP for AttributeQuery with sessionID " + moaSession.getSessionID() + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getInterfederatedIDPForAttributeQueryWithSessionID"); + query.setParameter("sessionID", moaSession.getSessionID()); + result = query.list(); + + //send transaction + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() == 0) { + Logger.trace("No entries found."); + return null; + + } + + return result.get(0).getInderfederation().get(0); + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } + } + + @Override + public boolean removeInterfederetedSession(String entityID, + String pedingRequestID) { + + try { + Logger.debug("Remove interfederated IDP from local SSO session ..."); + + MiscUtil.assertNotNull(pedingRequestID, "pedingRequestID"); + Logger.trace("Get authenticated session with pedingRequestID " + pedingRequestID + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + + //TODO: !!!!!!!!!!! PendingRequestID does not work + + synchronized (session) { + session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithPendingRequestID"); + query.setParameter("sessionid", pedingRequestID); + result = query.list(); + + //send transaction + session.getTransaction().commit(); + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + return false; + } + + AuthenticatedSessionStore authsession = result.get(0); + + List idpSessions = authsession.getInderfederation(); + if (idpSessions != null) { + for (InterfederationSessionStore idp : idpSessions) { + if (idp.getIdpurlprefix().equals(entityID)) + idpSessions.remove(idp); + + } + } + + MOASessionDBUtils.saveOrUpdate(authsession); + return true; + + } catch (Throwable e) { + Logger.warn("MOASession deserialization-exception by using MOASessionID=" + pedingRequestID); + return false; + } + } + + @Override + public void clean(Date now, long authDataTimeOutCreated, long authDataTimeOutUpdated) { + Date expioredatecreate = new Date(now.getTime() - authDataTimeOutCreated); + Date expioredateupdate = new Date(now.getTime() - authDataTimeOutUpdated); + + List results; + Session session = MOASessionDBUtils.getCurrentSession(); + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getMOAISessionsWithTimeOut"); + query.setTimestamp("timeoutcreate", expioredatecreate); + query.setTimestamp("timeoutupdate", expioredateupdate); + results = query.list(); + tx.commit(); + + if (results.size() != 0) { + for(AuthenticatedSessionStore result : results) { + try { + cleanDelete(result); + Logger.info("Authenticated session with sessionID=" + result.getSessionid() + + " after session timeout."); + + } catch (HibernateException e){ + Logger.warn("Authenticated session with sessionID=" + result.getSessionid() + + " not removed after timeout! (Error during Database communication)", e); + } + } + } + } + + } catch (Exception e) { + if (tx != null && !tx.wasCommitted()) + tx.rollback(); + throw e; + } + } + + private static void encryptSession(AuthenticationSession session, AuthenticatedSessionStore dbsession) throws BuildException { + byte[] serialized = SerializationUtils.serialize(session); + + EncryptedData encdata = SessionEncrytionUtil.getInstance().encrypt(serialized); + dbsession.setSession(encdata.getEncData()); + dbsession.setIv(encdata.getIv()); + } + + private static AuthenticationSession decryptSession(AuthenticatedSessionStore dbsession) throws BuildException { + EncryptedData encdata = new EncryptedData(dbsession.getSession(), + dbsession.getIv()); + byte[] decrypted = SessionEncrytionUtil.getInstance().decrypt(encdata); + + return (AuthenticationSession) SerializationUtils.deserialize(decrypted); + + } + + private static void cleanDelete(AuthenticatedSessionStore result) { + + try { + result.setSession("blank".getBytes()); + MOASessionDBUtils.saveOrUpdate(result); + + } catch (MOADatabaseException e) { + Logger.warn("Blank authenticated session with sessionID=" + result.getSessionid() + " FAILED.", e); + + } finally { + if (!MOASessionDBUtils.delete(result)) + Logger.error("Authenticated session with sessionID=" + result.getSessionid() + " not removed! (Error during Database communication)"); + } + } + + @SuppressWarnings("rawtypes") + private static AuthenticatedSessionStore searchInDatabase(String sessionID, boolean commit) throws MOADatabaseException { + MiscUtil.assertNotNull(sessionID, "moasessionID"); + Logger.trace("Get authenticated session with sessionID " + sessionID + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + + List result; + Transaction tx = null; + try { + synchronized (session) { + tx = session.beginTransaction(); + Query query = session.getNamedQuery("getSessionWithID"); + query.setParameter("sessionid", sessionID); + result = query.list(); + + //send transaction + if (commit) + tx.commit(); + } + + Logger.trace("Found entries: " + result.size()); + + //Assertion requires an unique artifact + if (result.size() != 1) { + Logger.trace("No entries found."); + throw new MOADatabaseException("No session found with this sessionID"); + + } + + return (AuthenticatedSessionStore) result.get(0); + + } catch (Exception e) { + if (tx != null && !tx.wasCommitted() && commit) + tx.rollback(); + throw e; + } + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBExceptionStoreImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBExceptionStoreImpl.java deleted file mode 100644 index 4cddd141b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBExceptionStoreImpl.java +++ /dev/null @@ -1,175 +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 org.apache.commons.lang.SerializationUtils; -import org.hibernate.HibernateException; -import org.hibernate.Query; -import org.hibernate.Session; - -import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.session.ExceptionStore; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public class DBExceptionStoreImpl implements IExceptionStore { - - private static DBExceptionStoreImpl store; - - public static DBExceptionStoreImpl getStore() { - if(store == null) { - store = new DBExceptionStoreImpl(); - } - return store; - } - - public String storeException(Throwable e) { - String id = Random.nextRandom(); - - Logger.debug("Store Exception with ID " + id); - - ExceptionStore dbexception = new ExceptionStore(); - dbexception.setExid(id); - - byte[] data = SerializationUtils.serialize(e); - dbexception.setException(data); - - dbexception.setTimestamp(new Date()); - - try { - MOASessionDBUtils.saveOrUpdate(dbexception); - - } catch (MOADatabaseException e1) { - Logger.warn("Exception can not be stored in Database.", e); - return null; - } - - return id; - } - - public Throwable fetchException(String id) { - - try { - Logger.debug("Fetch Exception with ID " + id); - - ExceptionStore ex = searchInDatabase(id); - - Object data = SerializationUtils.deserialize(ex.getException()); - if (data instanceof Throwable) - return (Throwable) data; - - else { - Logger.warn("Exeption is not of classtype Throwable"); - return null; - } - - - } catch (MOADatabaseException e) { - Logger.info("No Exception found with ID=" + id); - return null; - - } catch (Exception e) { - Logger.warn("Exception can not deserialized from Database.",e); - return null; - } - - } - - public void removeException(String id) { - try { - ExceptionStore ex = searchInDatabase(id); - MOASessionDBUtils.delete(ex); - - Logger.debug("Delete Execption with ID " + id); - - } catch (MOADatabaseException e) { - Logger.info("No Exception found with ID=" + id); - } - - - } - - public void clean(long now, long exceptionTimeOut) { - Date expioredate = new Date(now - exceptionTimeOut); - - List results; - Session session = MOASessionDBUtils.getCurrentSession(); - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getExceptionWithTimeOut"); - query.setTimestamp("timeout", expioredate); - results = query.list(); - session.getTransaction().commit(); - - if (results.size() != 0) { - for(ExceptionStore result : results) { - try { - MOASessionDBUtils.delete(result); - Logger.info("Remove Exception with ID=" + result.getExid() - + " after timeout."); - - } catch (HibernateException e){ - Logger.warn("Exception with ID=" + result.getExid() - + " not removed after timeout! (Error during Database communication)", e); - } - - } - } - } - } - - @SuppressWarnings("rawtypes") - private ExceptionStore searchInDatabase(String id) throws MOADatabaseException { - MiscUtil.assertNotNull(id, "exceptionID"); - Logger.trace("Getting Exception with ID " + id + " from database."); - Session session = MOASessionDBUtils.getCurrentSession(); - List result; - - synchronized (session) { - session.beginTransaction(); - Query query = session.getNamedQuery("getExceptionWithID"); - query.setParameter("id", id); - result = query.list(); - - //send transaction - session.getTransaction().commit(); - } - - Logger.trace("Found entries: " + result.size()); - - //Assertion requires an unique artifact - if (result.size() != 1) { - Logger.trace("No entries found."); - throw new MOADatabaseException("No Exception found with ID " + id); - } - - return (ExceptionStore) result.get(0); - } - -} 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 new file mode 100644 index 000000000..f33a7549c --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java @@ -0,0 +1,215 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.storage; + +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +import org.apache.commons.lang.SerializationUtils; +import org.hibernate.HibernateException; +import org.hibernate.Query; +import org.hibernate.Session; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; +import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +@Service("TransactionStorage") +public class DBTransactionStorage implements ITransactionStorage { + + public boolean containsKey(String key) { + try { + searchInDatabase(key); + return true; + + } catch (MOADatabaseException e) { + return false; + } + + } + + public void put(String key, Object value) throws MOADatabaseException { + //setup AssertionStore element + AssertionStore element = new AssertionStore(); + element.setArtifact(key); + element.setType(value.getClass().getName()); + element.setDatatime(new Date()); + + //serialize the Assertion for Database storage + byte[] data = SerializationUtils.serialize((Serializable) value); + element.setAssertion(data); + + //store AssertionStore element to Database + try { + MOASessionDBUtils.saveOrUpdate(element); + Logger.info(value.getClass().getName() + " with ID: " + key + " is stored in Database"); + } catch (MOADatabaseException e) { + Logger.warn("Sessioninformation could not be stored."); + throw new MOADatabaseException(e); + } + + } + + public T get(String key, + final Class clazz) throws MOADatabaseException { + + try { + return get(key, clazz, -1); + + } catch (AuthenticationException e) { + //this execption only occurs if an additional timeOut is used + Logger.error("This exeption should not occur!!!!", e); + return null; + + } + } + + public T get(String key, final Class clazz, long dataTimeOut) throws MOADatabaseException, AuthenticationException { + + AssertionStore element = searchInDatabase(key); + + if (dataTimeOut > -1) { + //check timeout + long now = new Date().getTime(); + + if (now - element.getDatatime().getTime() > dataTimeOut) { + Logger.info("Transaction-Data with key: " + key + " is out of time."); + throw new AuthenticationException("1207", new Object[] { key }); + + } + } + + + //Deserialize Assertion + Object data = SerializationUtils.deserialize(element.getAssertion()); + + //check if assertion has the correct class type + try { + @SuppressWarnings("unchecked") + T test = (T) Class.forName(element.getType()).cast(data); + return test; + + } catch (Exception e) { + Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + key); + throw new MOADatabaseException("Sessioninformation Cast-Exception"); + + } + } + + public void clean(Date now, long dataTimeOut) { + Date expioredate = new Date(now.getTime() - dataTimeOut); + + List results; + Session session = MOASessionDBUtils.getCurrentSession(); + + synchronized (session) { + session.beginTransaction(); + Query query = session.getNamedQuery("getAssertionWithTimeOut"); + query.setTimestamp("timeout", expioredate); + results = query.list(); + session.getTransaction().commit(); + + if (results.size() != 0) { + for(AssertionStore result : results) { + try { + cleanDelete(result); + Logger.info("Remove stored information with ID: " + result.getArtifact() + + " after timeout."); + + } catch (HibernateException e){ + Logger.warn("Sessioninformation with ID=" + result.getArtifact() + + " not removed after timeout! (Error during Database communication)", e); + } + + } + } + } + } + + public void remove(String key) { + + try { + AssertionStore element = searchInDatabase(key); + cleanDelete(element); + Logger.info("Remove stored information with ID: " + key); + + + } catch (MOADatabaseException e) { + Logger.info("Sessioninformation not removed! (Sessioninformation with ID=" + key + + "not found)"); + + } catch (HibernateException e) { + Logger.warn("Sessioninformation not removed! (Error during Database communication)", e); + } + } + + private void cleanDelete(AssertionStore element) { + try { + element.setAssertion("blank".getBytes()); + MOASessionDBUtils.saveOrUpdate(element); + + } catch (MOADatabaseException e) { + Logger.warn("Blank shortTime session with artifact=" + element.getArtifact() + " FAILED.", e); + + } finally { + if (!MOASessionDBUtils.delete(element)) + Logger.error("ShortTime session with artifact=" + element.getArtifact() + + " not removed! (Error during Database communication)"); + + } + + } + + @SuppressWarnings("rawtypes") + private AssertionStore searchInDatabase(String artifact) throws MOADatabaseException { + MiscUtil.assertNotNull(artifact, "artifact"); + Logger.trace("Getting sessioninformation with ID " + artifact + " from database."); + Session session = MOASessionDBUtils.getCurrentSession(); + List result; + + synchronized (session) { + session.beginTransaction(); + Query query = session.getNamedQuery("getAssertionWithArtifact"); + query.setParameter("artifact", artifact); + result = query.list(); + + //send transaction + session.getTransaction().commit(); + } + + 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"); + } + + return (AssertionStore) result.get(0); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ExceptionStoreImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ExceptionStoreImpl.java deleted file mode 100644 index ce974c531..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ExceptionStoreImpl.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.storage; - -import java.util.HashMap; -import java.util.Map; - -import at.gv.egovernment.moa.id.util.Random; - -public class ExceptionStoreImpl implements IExceptionStore { - - // Just a quick implementation - private static IExceptionStore store; - - public static IExceptionStore getStore() { - if(store == null) { - store = new ExceptionStoreImpl(); - } - return store; - } - - private Map exceptionStore = new HashMap(); - - public String storeException(Throwable e) { - String id = Random.nextRandom(); - exceptionStore.put(id, e); - return id; - } - - public Throwable fetchException(String id) { - return exceptionStore.get(id); - } - - public void removeException(String id) { - exceptionStore.remove(id); - } - -} 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 new file mode 100644 index 000000000..e89713b2e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IAuthenticationSessionStoreage.java @@ -0,0 +1,281 @@ +/* + * 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.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.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.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.data.SLOInformationInterface; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; + +/** + * @author tlenz + * + */ +public interface IAuthenticationSessionStoreage { + + /** + * Check if the stored MOASession is already authenticated + * + * @param moaSessionID MOASession identifier + * @return true if the MOASession is authenticated, otherwise false + */ + public boolean isAuthenticated(String moaSessionID); + + /** + * Create a new MOASession + * + * @param target Pending Request which is associated with this MOASession + * @return MOASession object + * @throws MOADatabaseException MOASession storage operation FAILED + * @throws BuildException MOASession encryption FAILED + */ + public AuthenticationSession createSession(IRequest target) throws MOADatabaseException, BuildException; + + /** + * Get a MOASession with sessionID + * + * @param sessionID SessionID which corresponds to a MOASession + * @return MOASession, or null if no session exists with this ID + * @throws MOADatabaseException MOASession load operation FAILED + */ + public AuthenticationSession getSession(String sessionID) throws MOADatabaseException; + + /** + * Get the session-data extension-object for a MOASession + * + * @param sessionID SessionID which corresponds to a MOASession + * @return AuthenticationSessionExtensions, or null if no session exists with this ID or extensionobject is null + * @throws MOADatabaseException MOASession load operation FAILED + */ + public AuthenticationSessionExtensions getAuthenticationSessionExtensions(String sessionID) throws MOADatabaseException; + + /** + * Store a session-data extension-object to MOASession + * + * @param sessionID SessionID which corresponds to a MOASession + * @param sessionExtensions AuthenticationSessionExtensions object + * @throws MOADatabaseException MOASession storage operation FAILED + */ + public void setAuthenticationSessionExtensions(String sessionID, AuthenticationSessionExtensions sessionExtensions) throws MOADatabaseException; + + + /** + * Store a MOASession + * + * @param session MOASession which should be stored + * @throws MOADatabaseException MOASession storage operation FAILED + * @throws BuildException MOASession encryption FAILED + */ + public void storeSession(AuthenticationSession session) throws MOADatabaseException, BuildException; + + /** + * Delete a MOASession + * + * @param moaSessionID SessionID which corresponds to a MOASession + * @throws MOADatabaseException MOASession delete operation FAILED + */ + public void destroySession(String moaSessionID) throws MOADatabaseException; + + + /** + * Change the sessionID of a MOASession + * + * @param session MOASession for which the sessionID should be changed + * @param newSessionID new MOASessionID which should be used + * @return new MOASessionID + * @throws MOADatabaseException MOASession storage operation FAILED + * @throws BuildException MOASession encryption/decryption FAILED + */ + public String changeSessionID(AuthenticationSession session, String newSessionID) throws BuildException, MOADatabaseException; + + /** + * Change the sessionID of a MOASession + * + * @param session MOASession for which the sessionID should be changed + * @return new MOASessionID + * @throws MOADatabaseException MOASession storage operation FAILED + * @throws BuildException MOASession encryption/decryption FAILED + */ + public String changeSessionID(AuthenticationSession session) throws BuildException, MOADatabaseException; + + /** + * Set the isAuthenticated flag to MOASession + * + * @param moaSessionID SessionID which corresponds to a MOASession + * @param isAuthenticated Is authenticated flag (true/false) + */ + public void setAuthenticated(String moaSessionID, boolean isAuthenticated); + + /** + * Find the MOASessionId of an active Single Sign-On session + * + * @param SSOSessionID Single Sign-On sessionID + * @return MOASessionID of the associated MOASession + */ + public String getMOASessionSSOID(String SSOSessionID); + + /** + * Check if a MOASession is an active Single Sign-On session + * + * @param sessionID SessionID which corresponds to a MOASession + * @return true, if the MOASession is a SSO session, otherwise false + * @throws MOADatabaseException MOASession load operation FAILED + */ + public boolean isSSOSession(String sessionID) throws MOADatabaseException; + + + /** + * @param SSOId + * @return + */ + public AuthenticatedSessionStore isValidSessionWithSSOID(String SSOId); + + /** + * Add Single Sign-On processing information to a MOASession. + * This processing information is required to execute a Single Log-Out process + * + * @param moaSessionID SessionID which corresponds to a MOASession + * @param SSOSessionID Single Sign-On sessionID + * @param SLOInfo Data object with Single LogOut information + * @param protocolRequest Protocol-request object of the authentication request + * @throws AuthenticationException Single Sign-On information store operation FAILED + */ + public void addSSOInformation(String moaSessionID, String SSOSessionID, + SLOInformationInterface SLOInfo, IRequest protocolRequest) throws AuthenticationException; + + + /** + * Get all Single Sign-On authenticated Service-Provider of a MOASession + * + * @param moaSession MOASession data object + * @return List of Service-Provider information + */ + public List getAllActiveOAFromMOASession(AuthenticationSession moaSession); + + + /** + * Get all active interfederation connections for a MOASession + * + * @param moaSession MOASession data object + * @return List of Interfederation-IDP information + */ + public List getAllActiveIDPsFromMOASession(AuthenticationSession moaSession); + + /** + * Search a MOASession 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 + */ + public AuthenticationSession searchMOASessionWithNameIDandOAID(String oaID, String userNameID); + + /** + * Search a active Single Sign-On session for a specific Service-Provider + * + * @param moaSession MOASession data object + * @param oaID Service-Provider identifier, which has received the authentication information + * @param protocolType Authentication protocol, which was used for SSO from this Service-Provider + * @return Internal Single Sign-On information for this Service-Provider + */ + public OASessionStore searchActiveOASSOSession(AuthenticationSession moaSession, String oaID, String protocolType); + + + /** + * Search a active MOASession with a userID + * + * @param nameID UserID (bPK) + * @return MOASession, or null if no corresponding MOASession is found + */ + public AuthenticationSession getSessionWithUserNameID(String nameID); + + /** + * Search an active federation IDP which could be used for federated Single Sign-On + * + * @param sessionID SessionID which corresponds to a MOASession + * @return Information of the federated IDP, or null if no active federated IDP is found + */ + public InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASession(String sessionID); + + /** + * Get information to an active federated IDP of MOASession + * + * @param sessionID SessionID which corresponds to a MOASession + * @param idpID Unique identifier of the federated IDP + * @return Information of the federated IDP, or null if no active federated IDP is found + */ + public InterfederationSessionStore searchInterfederatedIDPFORSSOWithMOASessionIDPID(String sessionID, String idpID); + + + /** + * Create a MOASession from interfederation information + * + * @param req Pending request + * @param isAuthenticated true if the session should be marked as authenticated, otherwise false + * @param ssoID Single Sign-On session identifer + * @return MOASessionID of new created MOASession + * @throws MOADatabaseException + * @throws AssertionAttributeExtractorExeption + * @throws BuildException + */ + @Deprecated + public String createInterfederatedSession(IRequest req, boolean isAuthenticated, String ssoID) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException; + + /** + * Search an active federation IDP which could be used for federated Single Sign-On by using an AttributeQuery + * + * @param moaSession MOASession data object + * @return Information of the federated IDP, or null if no active federated IDP is found + */ + public InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(AuthenticationSession moaSession); + + /** + * Remove an active federation IDP from MOASession + * + * @param entityID Unique identifier of the federated IDP + * @param pedingRequestID + * @return true if the federated IDP could be remove, otherwise false + */ + @Deprecated + public boolean removeInterfederetedSession(String entityID, String pedingRequestID); + + /** + * Clean all MOASessions which has a timeOut + * + * @param now Current Time + * @param authDataTimeOutCreated timeOut after MOASession is created [ms] + * @param authDataTimeOutUpdated timeOut after MOASession is updated last time [ms] + */ + public void clean(Date now, long authDataTimeOutCreated, long authDataTimeOutUpdated); +} + diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IExceptionStore.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IExceptionStore.java deleted file mode 100644 index 4c76a49a4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/IExceptionStore.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.storage; - -public interface IExceptionStore { - public String storeException(Throwable e); - public Throwable fetchException(String id); - public void removeException(String id); -} 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 new file mode 100644 index 000000000..d05689e68 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java @@ -0,0 +1,90 @@ +/* + * 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 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 + * @throws MOADatabaseException In case of store operation failed + */ + public void put(String key, Object value) 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 + * @throws MOADatabaseException In case of load operation failed + */ + public T get(String key, final Class 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 + * @throws MOADatabaseException In case of load operation failed + * @throws AuthenticationException In case of data-object timeout occurs + */ + public T get(String key, final Class clazz, long dataTimeOut) throws MOADatabaseException, AuthenticationException; + + /** + * Remove a data object from transaction storage + * + * @param key Id which identifiers the data object + */ + public void remove(String key); + + /** + * Clean-up the transaction storage + * + * @param now Current time + * @param dataTimeOut Data-object timeout in [ms] + */ + public void clean(Date now, long dataTimeOut); + +} 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 index 2aceb833c..d2499af9d 100644 --- 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 @@ -172,5 +172,14 @@ public class HTTPUtils { return authURL; } + + 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; + } } -- cgit v1.2.3 From 89dc33e5d6053af56a6d2cb11271ab092ced7dc3 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 18 Feb 2016 10:58:10 +0100 Subject: add WebFrontEnd security interceptor --- .../UniqueSessionIdentifierInterceptor.java | 86 ++++++++++++++++++++ .../WebFrontEndSecurityInterceptor.java | 95 ++++++++++++++++++++++ .../UniqueSessionIdentifierInterceptor.java | 93 --------------------- 3 files changed, 181 insertions(+), 93 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/UniqueSessionIdentifierInterceptor.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/WebFrontEndSecurityInterceptor.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/UniqueSessionIdentifierInterceptor.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/UniqueSessionIdentifierInterceptor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/UniqueSessionIdentifierInterceptor.java new file mode 100644 index 000000000..bedc67513 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/UniqueSessionIdentifierInterceptor.java @@ -0,0 +1,86 @@ +/* + * 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.interceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +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.egovernment.moa.id.moduls.SSOManager; +import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +public class UniqueSessionIdentifierInterceptor implements HandlerInterceptor { + + @Autowired private SSOManager ssomanager; + + /* (non-Javadoc) + * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) + */ + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + + //get SSO Cookie for Request + String ssoId = ssomanager.getSSOSessionID(request); + + //search for unique session identifier + String uniqueSessionIdentifier = ssomanager.getUniqueSessionIdentifier(ssoId); + if (MiscUtil.isEmpty(uniqueSessionIdentifier)) + uniqueSessionIdentifier = Random.nextRandom(); + TransactionIDUtils.setSessionId(uniqueSessionIdentifier); + + request.setAttribute(MOAIDConstants.UNIQUESESSIONIDENTIFIER, uniqueSessionIdentifier); + + return true; + } + + /* (non-Javadoc) + * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) + */ + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) throws Exception { + + } + + /* (non-Javadoc) + * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) + */ + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) + throws Exception { + // TODO Auto-generated method stub + + } + +} 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 new file mode 100644 index 000000000..7835687e8 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/WebFrontEndSecurityInterceptor.java @@ -0,0 +1,95 @@ +/* + * 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.interceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +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.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +public class WebFrontEndSecurityInterceptor implements HandlerInterceptor { + + @Autowired AuthConfiguration authConfig; + + /* (non-Javadoc) + * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) + */ + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) + throws Exception { + + //check AuthURL + String authURL = HTTPUtils.extractAuthURLFromRequest(request); + if (!authURL.startsWith("https:") && !authConfig.isHTTPAuthAllowed()) { + String errorMsg = MOAIDMessageProvider.getInstance().getMessage("auth.07", new Object[] { authURL + "*" }); + Logger.info(errorMsg); + response.sendError( + HttpServletResponse.SC_FORBIDDEN, + errorMsg); + + return false; + } else { + return true; + + } + } + + /* (non-Javadoc) + * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) + */ + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, + ModelAndView modelAndView) throws Exception { + + //TODO: add additional headers or checks + + //set security headers + response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); + response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); + response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); + response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); + + } + + /* (non-Javadoc) + * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) + */ + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) + throws Exception { + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/UniqueSessionIdentifierInterceptor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/UniqueSessionIdentifierInterceptor.java deleted file mode 100644 index e8b8022c4..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/UniqueSessionIdentifierInterceptor.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; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -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.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.commons.MOAIDConstants; -import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ -public class UniqueSessionIdentifierInterceptor implements HandlerInterceptor { - - @Autowired private SSOManager ssomanager; - - /* (non-Javadoc) - * @see org.springframework.web.servlet.HandlerInterceptor#preHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object) - */ - @Override - public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) - throws Exception { - - //get SSO Cookie for Request - String ssoId = ssomanager.getSSOSessionID(request); - - //search for unique session identifier - String uniqueSessionIdentifier = ssomanager.getUniqueSessionIdentifier(ssoId); - if (MiscUtil.isEmpty(uniqueSessionIdentifier)) - uniqueSessionIdentifier = Random.nextRandom(); - TransactionIDUtils.setSessionId(uniqueSessionIdentifier); - - request.setAttribute(MOAIDConstants.UNIQUESESSIONIDENTIFIER, uniqueSessionIdentifier); - - return true; - } - - /* (non-Javadoc) - * @see org.springframework.web.servlet.HandlerInterceptor#postHandle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, org.springframework.web.servlet.ModelAndView) - */ - @Override - public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, - ModelAndView modelAndView) throws Exception { - - //set security headers - response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES); - response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA); - response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); - response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); - - } - - /* (non-Javadoc) - * @see org.springframework.web.servlet.HandlerInterceptor#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception) - */ - @Override - public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) - throws Exception { - // TODO Auto-generated method stub - - } - -} -- cgit v1.2.3 From 98cdf5c84739362a2d41702f538c370fa3d2c86e Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 18 Feb 2016 11:01:55 +0100 Subject: update error handling and Web based error messages --- .../moa/id/auth/exception/MOAIDException.java | 13 ++ .../moa/id/auth/servlet/AbstractController.java | 211 ++++++++++++++------- .../protocols/AbstractProtocolModulController.java | 5 +- .../protocols/ProtocolFinalizationController.java | 20 +- .../moa/id/util/ErrorResponseUtils.java | 6 +- 5 files changed, 176 insertions(+), 79 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIDException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIDException.java index 165fee599..ef6aaa75c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIDException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIDException.java @@ -79,6 +79,8 @@ public class MOAIDException extends Exception { /** wrapped exception */ private Throwable wrapped; + private Object[] parameters; + /** * Create a new MOAIDException. * @@ -89,6 +91,7 @@ public class MOAIDException extends Exception { public MOAIDException(String messageId, Object[] parameters) { super(MOAIDMessageProvider.getInstance().getMessage(messageId, parameters)); this.messageId = messageId; + this.parameters = parameters; } /** @@ -108,6 +111,7 @@ public class MOAIDException extends Exception { super(MOAIDMessageProvider.getInstance().getMessage(messageId, parameters)); this.messageId = messageId; this.wrapped = wrapped; + this.parameters = parameters; } /** @@ -163,7 +167,16 @@ public class MOAIDException extends Exception { return wrapped; } + + /** + * @return the parameters + */ +public Object[] getParameters() { + return parameters; +} + +/** * Convert this MOAIDException to an ErrorResponse * element from the MOA namespace. * diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index 26e24f5b4..887692477 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -22,11 +22,21 @@ */ package at.gv.egovernment.moa.id.auth.servlet; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.net.URI; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ExceptionHandler; @@ -48,6 +58,7 @@ import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.ErrorResponseUtils; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.id.util.ServletUtils; +import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -59,34 +70,20 @@ public abstract class AbstractController extends MOAIDAuthConstants { public static final String ERROR_CODE_PARAM = "errorid"; + private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; + private static final String HTMLTEMPLATEFULL = "error_message.html"; + @Autowired protected StatisticLogger statisticLogger; @Autowired protected IRequestStorage requestStorage; @Autowired protected ITransactionStorage transactionStorage; @Autowired protected MOAReversionLogger revisionsLogger; @Autowired protected AuthConfiguration authConfig; - - + protected void handleError(String errorMessage, Throwable exceptionThrown, HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) throws IOException { - Throwable loggedException = null; - - if (exceptionThrown != null - && exceptionThrown instanceof ProcessExecutionException) { - ProcessExecutionException procExc = - (ProcessExecutionException) exceptionThrown; - if (procExc.getCause() != null && - procExc.getCause() instanceof TaskExecutionException) { - TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); - loggedException = taskExc.getOriginalException(); - - } - } - - if (loggedException == null) - loggedException = exceptionThrown; - - + Throwable loggedException = extractOriginalExceptionFromProcessException(exceptionThrown); + if (!(loggedException instanceof MOAIDException)) { Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); @@ -103,13 +100,13 @@ public abstract class AbstractController extends MOAIDAuthConstants { //store error into transaction store try { String key = Random.nextRandom(); - transactionStorage.put(key, exceptionThrown); + transactionStorage.put(key, loggedException); if (key != null && MiscUtil.isNotEmpty(pendingRequestID)) { String redirectURL = null; redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT + redirectURL += "/"+AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT + "?" + ERROR_CODE_PARAM + "=" + key + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; @@ -123,13 +120,13 @@ public abstract class AbstractController extends MOAIDAuthConstants { } else { //Exception can not be stored in database - handleErrorNoRedirect(loggedException, req, resp); + handleErrorNoRedirect(loggedException, req, resp, true); } } catch (MOADatabaseException e) { Logger.warn("Exception can not be stored to Database.", e); - handleErrorNoRedirect(loggedException, req, resp); + handleErrorNoRedirect(loggedException, req, resp, true); } @@ -147,77 +144,60 @@ public abstract class AbstractController extends MOAIDAuthConstants { * @throws IOException */ protected void handleErrorNoRedirect(Throwable throwable, HttpServletRequest req, - HttpServletResponse resp) throws IOException { + HttpServletResponse resp, boolean writeExceptionToStatisticLog) throws IOException { //log Exception into statistic database - statisticLogger.logErrorOperation(throwable); + if (writeExceptionToStatisticLog) + statisticLogger.logErrorOperation(throwable); //write errror to console Logger.error(throwable.getMessage(), throwable); //return error to Web browser - if (throwable instanceof MOAIDException) - MOAIDExceptionHandler(req, resp, (MOAIDException)throwable); + if (throwable instanceof MOAIDException || throwable instanceof ProcessExecutionException) + MOAIDExceptionHandler(req, resp, (Exception)throwable); else - GenericExceptionHandler(req, resp, (Exception)throwable); + GenericExceptionHandler(resp, (Exception)throwable); } @ExceptionHandler({MOAIDException.class}) - public void MOAIDExceptionHandler(HttpServletRequest req, HttpServletResponse resp, MOAIDException e) throws IOException { + public void MOAIDExceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws IOException { if (e instanceof ProtocolNotActiveException) { resp.getWriter().write(e.getMessage()); resp.setContentType("text/html;charset=UTF-8"); resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); - return; } else if (e instanceof AuthnRequestValidatorException) { AuthnRequestValidatorException ex = (AuthnRequestValidatorException)e; //log Error Message - statisticLogger.logErrorOperation(ex, ex.getErrorRequest()); - return; - - } else if (e instanceof InvalidProtocolRequestException) { - //write log entry - String samlRequest = req.getParameter("SAMLRequest"); - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + statisticLogger.logErrorOperation(ex, ex.getErrorRequest()); - //send error response - ErrorResponseUtils utils = ErrorResponseUtils.getInstance(); - String code = utils.mapInternalErrorToExternalError(e.getMessageId()); - String descr = e.getMessage(); - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Protocol validation FAILED!" + - "(Errorcode=" + code + - " | Description=" + descr + ")"); - return; - } else if (e instanceof ConfigurationException) { - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + - "(Errorcode=9199" - +" | Description="+ e.getMessage() + ")"); - return; + //write error message + writeBadRequestErrorResponse(req, resp, (MOAIDException) e); - //TODO: check exception type - } else if (e instanceof MOAIDException) { - String samlRequest = req.getParameter("SAMLRequest"); - if (MiscUtil.isNotEmpty(samlRequest)) - Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - else - Logger.error("Failed to generate a valid protocol request!"); + } else if (e instanceof InvalidProtocolRequestException) { + //send error response + writeBadRequestErrorResponse(req, resp, (MOAIDException) e); - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + - "(Errorcode=6000" - +" | Description=Das Authentifizierungsprotokoll wurde nicht erkannt oder wird nicht unterst\u00FCzt" + ")"); - return; + } else if (e instanceof ConfigurationException) { + //send HTML formated error message + writeHTMLErrorResponse(resp, (MOAIDException) e); + } else if (e instanceof MOAIDException) { + //send HTML formated error message + writeHTMLErrorResponse(resp, e); + + } else if (e instanceof ProcessExecutionException) { + //send HTML formated error message + writeHTMLErrorResponse(resp, e); + } } @ExceptionHandler({Exception.class}) - public void GenericExceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception exception) throws IOException { + public void GenericExceptionHandler(HttpServletResponse resp, Exception exception) throws IOException { Logger.error("Internel Server Error." , exception); resp.setContentType("text/html;charset=UTF-8"); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + @@ -228,11 +208,108 @@ public abstract class AbstractController extends MOAIDAuthConstants { } @ExceptionHandler({IOException.class}) - public void IOExceptionHandler(HttpServletRequest req, HttpServletResponse resp, IOException exception) { + public void IOExceptionHandler(HttpServletResponse resp, IOException exception) { Logger.error("Internel Server Error." , exception); resp.setContentType("text/html;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } + + private void writeBadRequestErrorResponse(HttpServletRequest req, HttpServletResponse resp, MOAIDException e) throws IOException { + ErrorResponseUtils utils = ErrorResponseUtils.getInstance(); + String code = utils.mapInternalErrorToExternalError( + ((InvalidProtocolRequestException)e).getMessageId()); + String descr = e.getMessage(); + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Protocol validation FAILED!" + + "(Errorcode=" + code + + " | Description=" + descr + ")"); + + } + + private void writeHTMLErrorResponse(HttpServletResponse httpResp, Exception error) throws IOException { + VelocityContext context = new VelocityContext(); + + //add errorcode and errormessage + context.put("errorMsg", error.getMessage()); + context.put("errorCode", ErrorResponseUtils.getInstance().getResponseErrorCode(error)); + + //add stacktrace if debug is enabled + if (Logger.isDebugEnabled()) { + context.put("stacktrace", getStacktraceFromException(error)); + + } + + try { + InputStream is = null; + String pathLocation = null; + try { + String rootconfigdir = authConfig.getRootConfigFileDir(); + pathLocation = rootconfigdir + HTMLTEMPLATESDIR + HTMLTEMPLATEFULL; + File file = new File(new URI(pathLocation)); + is = new FileInputStream(file); + evaluateErrorTemplate(context, httpResp, is); + + } catch (Exception e) { + Logger.warn("SLO Template is not found in configuration directory (" + + pathLocation + "). Load template from project library ... "); + + try { + pathLocation = "resources/templates/" + HTMLTEMPLATEFULL; + is = Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream(pathLocation); + evaluateErrorTemplate(context, httpResp, is); + + } catch (Exception e1) { + Logger.error("Single LogOut form can not created.", e); + throw new MOAIDException("Create Single LogOut information FAILED.", null, e); + } + + } finally { + if (is != null) + is.close(); + + } + } catch (Exception e) { + Logger.error("Error-message form can not created.", e); + GenericExceptionHandler(httpResp, error); + + } + } + + private void evaluateErrorTemplate(VelocityContext context, HttpServletResponse httpResp, InputStream is) throws Exception { + VelocityEngine engine = VelocityProvider.getClassPathVelocityEngine(); + BufferedReader reader = new BufferedReader(new InputStreamReader(is )); + StringWriter writer = new StringWriter(); + engine.evaluate(context, writer, "Error Template", reader); + httpResp.setContentType("text/html;charset=UTF-8"); + httpResp.getOutputStream().write(writer.toString().getBytes("UTF-8")); + + } + + private String getStacktraceFromException(Exception ex) { + StringWriter errors = new StringWriter(); + ex.printStackTrace(new PrintWriter(errors)); + return errors.toString(); + + } + + private Throwable extractOriginalExceptionFromProcessException(Throwable exception) { + Throwable returnexception = exception; + + while(returnexception != null + && returnexception instanceof ProcessExecutionException) { + ProcessExecutionException procExc = (ProcessExecutionException) returnexception; + if (procExc.getCause() != null && + procExc.getCause() instanceof TaskExecutionException) { + TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); + returnexception = taskExc.getOriginalException(); + + } + } + + return returnexception; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java index cc1886324..de64ec98e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java @@ -229,13 +229,14 @@ public abstract class AbstractProtocolModulController extends AbstractController return; } else { - handleErrorNoRedirect(throwable, req, resp); + handleErrorNoRedirect(throwable, req, resp, true); } } catch (Throwable e) { Logger.error(e); - handleErrorNoRedirect(throwable, req, resp); + handleErrorNoRedirect(throwable, req, resp, true); + } } 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 index ed53d1a20..107212c38 100644 --- 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 @@ -90,27 +90,28 @@ public class ProtocolFinalizationController extends AbstractProtocolModulControl return; } else { - handleErrorNoRedirect(throwable, req, resp); + handleErrorNoRedirect(throwable, req, resp, true); } } else { handleErrorNoRedirect(new Exception( MOAIDMessageProvider.getInstance().getMessage("auth.26", null)), - req, resp); + req, resp, false); } } catch (Throwable e) { - Logger.error(e); - handleErrorNoRedirect(e, req, resp); + 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); + handleErrorNoRedirect(new MOAIDException("auth.28", new Object[]{pendingRequestID}), req, resp, false); return; } @@ -130,7 +131,7 @@ public class ProtocolFinalizationController extends AbstractProtocolModulControl AuthenticationSession moaSession = authenticatedSessionStorage.getSession(sessionID); if (moaSession == null) { Logger.error("No MOASession with ID " + sessionID + " found.!"); - handleErrorNoRedirect(new MOAIDException("auth.02", new Object[]{sessionID}), req, resp); + handleErrorNoRedirect(new MOAIDException("auth.02", new Object[]{sessionID}), req, resp, true); return; } @@ -141,7 +142,7 @@ public class ProtocolFinalizationController extends AbstractProtocolModulControl } else { Logger.error("MOASession oder Pending-Request are not authenticated --> Abort authentication process!"); - handleErrorNoRedirect(new MOAIDException("auth.20", null), req, resp); + handleErrorNoRedirect(new MOAIDException("auth.20", null), req, resp, true); return; } @@ -154,7 +155,8 @@ public class ProtocolFinalizationController extends AbstractProtocolModulControl } //remove pending-request - requestStorage.removePendingRequest(pendingRequestID); + if (pendingReq != null) + requestStorage.removePendingRequest(pendingReq.getRequestID()); } 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 index 99ac6ba4c..8bd682421 100644 --- 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 @@ -27,6 +27,7 @@ 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.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.process.ProcessExecutionException; import at.gv.egovernment.moa.util.Messages; import at.gv.egovernment.moa.util.MiscUtil; @@ -78,7 +79,10 @@ public class ErrorResponseUtils { } else if (throwable instanceof MOAIDException) { MOAIDException error = (MOAIDException) throwable; errorCode = mapInternalErrorToExternalError(error.getMessageId()); - + + } else if (throwable instanceof ProcessExecutionException) { + errorCode = "1100"; + } else { errorCode = INTERNALERRORCODE; -- cgit v1.2.3 From c9370266c7553db65e9d18f7fe2a0230ab94d912 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 18 Feb 2016 11:02:55 +0100 Subject: refactor authentication process to use service-provider configuration from pending-request --- .../moa/id/auth/MOAIDAuthConstants.java | 6 + .../id/auth/builder/AuthenticationDataBuilder.java | 4 +- .../builder/CreateXMLSignatureRequestBuilder.java | 16 +- .../moa/id/auth/data/AuthenticationSession.java | 352 +-------------------- .../id/auth/modules/AbstractAuthServletTask.java | 51 +++ .../tasks/CreateInterfedeartionRequestTask.java | 3 +- .../internal/tasks/EvaluateBKUSelectionTask.java | 5 +- .../tasks/GenerateBKUSelectionFrameTask.java | 2 +- .../StartAuthentificationParameterParser.java | 239 ++++++-------- .../id/auth/servlet/IDPSingleLogOutServlet.java | 4 +- .../moa/id/config/auth/IOAAuthParameters.java | 7 + .../moa/id/moduls/AuthenticationManager.java | 3 +- .../egovernment/moa/id/moduls/IRequestStorage.java | 3 +- .../egovernment/moa/id/moduls/RequestStorage.java | 14 +- .../id/protocols/pvp2x/AttributQueryAction.java | 2 +- .../id/protocols/pvp2x/PVPTargetConfiguration.java | 11 +- .../builder/assertion/PVP2AssertionBuilder.java | 27 +- .../pvp2x/requestHandler/AuthnRequestHandler.java | 2 +- .../moa/id/storage/DBTransactionStorage.java | 88 ++++-- .../moa/id/storage/ITransactionStorage.java | 15 +- 20 files changed, 296 insertions(+), 558 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index 082ebcdcd..d76021bbd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -177,4 +177,10 @@ public class MOAIDAuthConstants extends MOAIDConstants{ public static final String PROCESSCONTEXT_INTERFEDERATION_ENTITYID = "interfederationIDPEntityID"; public static final String PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION = "requireLocalAuthentication"; + //General protocol-request data-store keys + public static final String AUTHPROCESS_DATA_TARGET = "authProces_Target"; + public static final String AUTHPROCESS_DATA_TARGETFRIENDLYNAME = "authProces_TargetFriendlyName"; + public static final String AUTHPROCESS_DATA_SECURITYLAYERTEMPLATE = "authProces_SecurityLayerTemplate"; + + } 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 5bde82899..2f882f41e 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 @@ -198,7 +198,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { IOAAuthParameters oaParam = null; if (reqAttributes == null) { //get OnlineApplication from MOA-ID-Auth configuration - oaParam = authConfig.getOnlineApplicationParameter(oaID); + oaParam = protocolRequest.getOnlineApplicationConfiguration(); //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway if (oaParam.isSTORKPVPGateway()) @@ -879,7 +879,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); - authData.setIssuer(session.getAuthURL()); + authData.setIssuer(protocolRequest.getAuthURL()); //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO authData.setIdentificationValue(identityLink.getIdentificationValue()); 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 bbbfacbd1..e763c5355 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,9 +50,10 @@ import java.text.MessageFormat; import java.util.Calendar; import java.util.List; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DateTimeUtils; import at.gv.egovernment.moa.util.StringUtils; @@ -156,7 +157,7 @@ public class CreateXMLSignatureRequestBuilder implements Constants { * @param session current session * @return String representation of <CreateXMLSignatureRequest> */ - public String buildForeignID(String subject, OAAuthParameter oaParam, AuthenticationSession session) { + public String buildForeignID(String subject, IRequest pendingReq) { String request = ""; request += ""; @@ -165,7 +166,7 @@ public class CreateXMLSignatureRequestBuilder implements Constants { request += ""; request += ""; - request += buildForeignIDTextToBeSigned(subject, oaParam, session); + request += buildForeignIDTextToBeSigned(subject,pendingReq); request += ""; request += ""; @@ -180,9 +181,10 @@ public class CreateXMLSignatureRequestBuilder implements Constants { return request; } - public static String buildForeignIDTextToBeSigned(String subject, OAAuthParameter oaParam, AuthenticationSession session) { - - String target = session.getTarget(); + public static String buildForeignIDTextToBeSigned(String subject, IRequest pendingReq) { + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + String target = pendingReq.getGenericData( + MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, String.class); String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(target); Calendar cal = Calendar.getInstance(); 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 3849eb8a2..196415ddc 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 @@ -75,53 +75,12 @@ public class AuthenticationSession implements Serializable { private String sessionID; private Date sessionCreated = null; - - /** - * "Geschäftsbereich" the online application belongs to; maybe null if the - * online application is a business application - */ - private String target; - /** - * Friendly name for the target, if target is configured via MOA-ID configuration - */ - private String targetFriendlyName; - - /** - * SourceID - */ - private String sourceID; - - /** - * public online application URL requested - */ - private String oaURLRequested; - /** - * public online application URL prefix - */ - private String oaPublicURLPrefix; - /** - * URL of MOA ID authentication component - */ - private String authURL; - /** - * HTML template URL - */ - private String templateURL; - + /** * URL of the BKU */ private String bkuURL; - /** - * Indicates whether the corresponding online application is a business service or not - */ - private boolean businessService; - - /** - * Indicates whether the corresponding online application is a stork service or not - */ - private boolean storkService; // Store Mandate /** @@ -131,11 +90,6 @@ public class AuthenticationSession implements Serializable { private boolean isOW = false; - /** - * STORK - */ - private String ccc; - /** * * Mandate element @@ -158,12 +112,6 @@ public class AuthenticationSession implements Serializable { */ private IdentityLink identityLink; - // /** - // * timestamp logging when identity link has been received - // */ - // private Date timestampIdentityLink; - - // store Authblock /** * authentication block to be signed by the user */ @@ -176,11 +124,9 @@ public class AuthenticationSession implements Serializable { */ private String issueInstant; - // Signer certificate /** * Signer certificate of the foreign citizen or for mandate mode */ - // private X509Certificate signerCertificate; private byte[] signerCertificate; /** @@ -200,26 +146,8 @@ public class AuthenticationSession implements Serializable { * the AUTHBlock. */ private List extendedSAMLAttributesAUTH; - -// /** -// * If infobox validators are needed after signing, they can be stored in this list. -// */ -// private List infoboxValidators; - - /** - * The register and number in the register parameter in case of a business service application. - */ - private String domainIdentifier; - - /** - * This string contains all identifiers of infoboxes, the online application is configured to - * accept. The infobox identifiers are comma separated. - */ - private String pushInfobox; - + private boolean authenticated; - - private boolean ssoRequested = false; private String QAALevel = null; @@ -228,15 +156,8 @@ public class AuthenticationSession implements Serializable { private boolean isForeigner; private Map genericSessionDataStorate = new HashedMap(); - - public boolean isAuthenticated() { - return authenticated; - } - - public void setAuthenticated(boolean authenticated) { - this.authenticated = authenticated; - } - + + /** * Constructor for AuthenticationSession. * @@ -249,6 +170,14 @@ public class AuthenticationSession implements Serializable { } + public boolean isAuthenticated() { + return authenticated; + } + + public void setAuthenticated(boolean authenticated) { + this.authenticated = authenticated; + } + public X509Certificate getSignerCertificate() { try { return new X509Certificate(signerCertificate); @@ -310,24 +239,6 @@ public class AuthenticationSession implements Serializable { this.sessionID = sessionId; } - /** - * Returns the oaURLRequested. - * - * @return String - */ - public String getOAURLRequested() { - return oaURLRequested; - } - - /** - * Returns the oaURLRequested. - * - * @return String - */ - public String getPublicOAURLPrefix() { - return oaPublicURLPrefix; - } - /** * Returns the BKU URL. * @@ -336,54 +247,7 @@ public class AuthenticationSession implements Serializable { public String getBkuURL() { return bkuURL; } - - /** - * Returns the target. - * - * @return String - */ - public String getTarget() { - return target; - } - - /** - * Returns the sourceID. - * - * @return String - */ - public String getSourceID() { - return sourceID; - } - - /** - * Returns the target friendly name. - * - * @return String - */ - public String getTargetFriendlyName() { - return targetFriendlyName; - } - - /** - * Sets the oaURLRequested. - * - * @param oaURLRequested - * The oaURLRequested to set - */ - public void setOAURLRequested(String oaURLRequested) { - this.oaURLRequested = oaURLRequested; - } - - /** - * Sets the oaPublicURLPrefix - * - * @param oaPublicURLPrefix - * The oaPublicURLPrefix to set - */ - public void setPublicOAURLPrefix(String oaPublicURLPrefix) { - this.oaPublicURLPrefix = oaPublicURLPrefix; - } - + /** * Sets the bkuURL * @@ -393,63 +257,7 @@ public class AuthenticationSession implements Serializable { public void setBkuURL(String bkuURL) { this.bkuURL = bkuURL; } - - /** - * Sets the target. If the target includes the target prefix, the prefix will be stripped off. - * - * @param target - * The target to set - */ - public void setTarget(String target) { - if (target != null && target.startsWith(TARGET_PREFIX_)) { - // If target starts with prefix "urn:publicid:gv.at:cdid+"; remove - // prefix - this.target = target.substring(TARGET_PREFIX_.length()); - Logger.debug("Target prefix stripped off; resulting target: " + this.target); - } else { - this.target = target; - } - } - - /** - * Sets the sourceID - * - * @param sourceID - * The sourceID to set - */ - public void setSourceID(String sourceID) { - this.sourceID = sourceID; - } - - /** - * Sets the target. If the target includes the target prefix, the prefix will be stripped off. - * - * @param target - * The target to set - */ - public void setTargetFriendlyName(String targetFriendlyName) { - this.targetFriendlyName = targetFriendlyName; - } - - /** - * Returns the authURL. - * - * @return String - */ - public String getAuthURL() { - return authURL; - } - - /** - * Sets the authURL. - * - * @param authURL - * The authURL to set - */ - public void setAuthURL(String authURL) { - this.authURL = authURL; - } - + /** * Returns the authBlock. * @@ -469,61 +277,6 @@ public class AuthenticationSession implements Serializable { this.authBlock = authBlock; } - /** - * Returns the businessService. - * - * @return true if the corresponding online application is a business application, - * otherwise false - */ - public boolean getBusinessService() { - return businessService; - } - - /** - * Sets the businessService variable. - * - * @param businessService - * the value for setting the businessService variable. - */ - public void setBusinessService(boolean businessService) { - this.businessService = businessService; - } - - - /** - * Returns the storkService. - * - * @return true if the corresponding online application is a stork application, - * otherwise false - */ - public boolean getStorkService() { - return storkService; - } - - /** - * Sets the storkService variable. - * - * @param storkService - * the value for setting the storkService variable. - */ - public void setStorkService(boolean storkService) { - this.storkService = storkService; - } - - /** - * @return template URL - */ - public String getTemplateURL() { - return templateURL; - } - - /** - * @param string - * the template URL - */ - public void setTemplateURL(String string) { - templateURL = string; - } /** * Returns the SAML Attributes to be appended to the AUTHBlock. Maybe null. @@ -610,54 +363,6 @@ public class AuthenticationSession implements Serializable { public void setIssueInstant(String issueInstant) { this.issueInstant = issueInstant; } - - /** - * Returns domain identifier (the register and number in the register parameter). - * null in the case of not a business service. - * - * @return the domainIdentifier - */ - public String getDomainIdentifier() { - return domainIdentifier; - } - - /** - * Sets the register and number in the register parameter if the application is a business - * service. If the domain identifier includes the registerAndOrdNr prefix, the prefix will be - * stripped off. - * - * @param domainIdentifier - * the domain identifier to set - */ - public void setDomainIdentifier(String domainIdentifier) { - if (domainIdentifier != null && domainIdentifier.startsWith(REGISTERANDORDNR_PREFIX_)) { - // If domainIdentifier starts with prefix - // "urn:publicid:gv.at:wbpk+"; remove this prefix - this.domainIdentifier = domainIdentifier.substring(REGISTERANDORDNR_PREFIX_.length()); - Logger.debug("Register and ordernumber prefix stripped off; resulting register string: " + this.domainIdentifier); - } else { - this.domainIdentifier = domainIdentifier; - } - } - - /** - * Gets all identifiers of infoboxes, the online application is configured to accept. The - * infobox identifiers are comma separated. - * - * @return the string containing infobox identifiers - */ - public String getPushInfobox() { - if (pushInfobox == null) return ""; - return pushInfobox; - } - - /** - * @param pushInfobox - * the infobox identifiers to set (comma separated) - */ - public void setPushInfobox(String pushInfobox) { - this.pushInfobox = pushInfobox; - } /** * @@ -713,15 +418,7 @@ public class AuthenticationSession implements Serializable { public void setMandateReferenceValue(String mandateReferenceValue) { this.mandateReferenceValue = mandateReferenceValue; } - - public String getCcc() { - return ccc; - } - - public void setCcc(String ccc) { - this.ccc = ccc; - } - + public boolean isForeigner() { return isForeigner; } @@ -745,24 +442,7 @@ public class AuthenticationSession implements Serializable { public void setMISMandate(MISMandate mandate) { this.mandate = mandate; } - - /** - * @return the ssoRequested - */ - - // TODO: SSO only allowed without mandates, actually!!!!!! - public boolean isSsoRequested() { - return ssoRequested && !useMandate; - } - - /** - * @param ssoRequested - * the ssoRequested to set - */ - public void setSsoRequested(boolean ssoRequested) { - this.ssoRequested = ssoRequested; - } - + /** * @return the isOW */ 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 index a73fd6858..66f91266f 100644 --- 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 @@ -7,6 +7,7 @@ import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACH import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE; import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_EXPIRES; import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_PRAGMA; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -29,19 +30,24 @@ 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.lang.StringEscapeUtils; import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.ObjectUtils; import org.springframework.beans.factory.annotation.Autowired; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +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.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.moduls.IRequest; 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.AbstractProtocolModulController; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; @@ -66,6 +72,51 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { protected static final String ERROR_CODE_PARAM = "errorid"; + protected IRequest pendingReq = null; + protected AuthenticationSession moasession = null; + + protected void defaultTaskInitialization(HttpServletRequest req, ExecutionContext executionContext) throws MOAIDException, MOADatabaseException { + String pendingRequestID = StringEscapeUtils.escapeHtml( + ObjectUtils.defaultIfNull( + (String) executionContext.get(PARAM_TARGET_PENDINGREQUESTID), + req.getParameter(PARAM_TARGET_PENDINGREQUESTID))); + + if (MiscUtil.isEmpty(pendingRequestID)) { + Logger.info("No PendingRequestID received"); + throw new MOAIDException("auth.10", new Object[]{"VerifyIdentityLink", "pendingRequestID"}); + } + + pendingReq = requestStoreage.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 + String newPendingRequestID = requestStoreage.changePendingRequestID(pendingReq); + executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, newPendingRequestID); + + try { + moasession = authenticatedSessionStorage.getSession(pendingReq.getMOASessionIdentifier()); + + if (moasession == null) { + Logger.warn("MOASessionID is empty."); + throw new MOAIDException("auth.18", new Object[] {}); + } + + } catch (MOADatabaseException e) { + Logger.info("MOASession with SessionID=" + pendingReq.getMOASessionIdentifier() + " is not found in Database"); + throw new MOAIDException("init.04", new Object[] { pendingReq.getMOASessionIdentifier() }); + + } catch (Throwable e) { + Logger.info("No HTTP Session found!"); + throw new MOAIDException("auth.18", new Object[] {}); + } + + } + protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, HttpServletRequest req, HttpServletResponse resp) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java index f1ab58ee0..053f5d7ff 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java @@ -53,6 +53,7 @@ import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; @@ -103,7 +104,7 @@ public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { try { OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(idpEntityID); - OAAuthParameter sp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(pendingReq.getOAURL()); + IOAAuthParameters sp = pendingReq.getOnlineApplicationConfiguration(); String requestedIDP = pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); 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 fe3e8680c..9db5baeab 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 @@ -56,7 +56,7 @@ public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { throws TaskExecutionException { try { //load pending request - String pendingReqID = request.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); + String pendingReqID = request.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID); pendingReqID = StringEscapeUtils.escapeHtml(pendingReqID); IRequest pendingReq = requestStoreage.getPendingRequest(pendingReqID); @@ -86,7 +86,8 @@ public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { Enumeration reqParamNames = request.getParameterNames(); while(reqParamNames.hasMoreElements()) { String paramName = reqParamNames.nextElement(); - if (MiscUtil.isNotEmpty(paramName)) + if (MiscUtil.isNotEmpty(paramName) && + !MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID.equalsIgnoreCase(paramName)) executionContext.put(paramName, request.getParameter(paramName)); } 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 1bdc132d9..cb0b63276 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 @@ -80,7 +80,7 @@ public class GenerateBKUSelectionFrameTask extends AbstractAuthServletTask { if (publicURLPreFix.endsWith("/")) publicURLPreFix = publicURLPreFix.substring(0, publicURLPreFix.length() - 1); String loginForm = LoginFormBuilder.buildLoginForm(pendingReq.requestedModule(), - pendingReq.requestedAction(), oaParam, publicURLPreFix, MOAIDAuthConstants.PARAM_SESSIONID); + pendingReq.requestedAction(), oaParam, publicURLPreFix, pendingReq.getRequestID()); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = new PrintWriter(response.getOutputStream()); 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 8af8ed238..3699633bd 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 @@ -27,6 +27,8 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -34,8 +36,8 @@ import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; @@ -44,9 +46,12 @@ import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.StringUtils; +@Service("StartAuthentificationParameterParser") public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ - public static void parse(AuthenticationSession moasession, + @Autowired AuthConfiguration authConfig; + + public void parse(AuthenticationSession moasession, String target, String oaURL, String bkuURL, @@ -57,30 +62,20 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ IRequest protocolReq) throws WrongParametersException, MOAIDException { String targetFriendlyName = null; - -// String sso = req.getParameter(PARAM_SSO); - + // escape parameter strings target = StringEscapeUtils.escapeHtml(target); - //oaURL = StringEscapeUtils.escapeHtml(oaURL); bkuURL = StringEscapeUtils.escapeHtml(bkuURL); templateURL = StringEscapeUtils.escapeHtml(templateURL); useMandate = StringEscapeUtils.escapeHtml(useMandate); ccc = StringEscapeUtils.escapeHtml(ccc); - // sso = StringEscapeUtils.escapeHtml(sso); - - // check parameter - - //pvp2.x can use general identifier (equals oaURL in SAML1) -// if (!ParamValidatorUtils.isValidOA(oaURL)) -// throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12"); + //validate parameters if (!ParamValidatorUtils.isValidUseMandate(useMandate)) throw new WrongParametersException("StartAuthentication", PARAM_USEMANDATE, "auth.12"); if (!ParamValidatorUtils.isValidCCC(ccc)) throw new WrongParametersException("StartAuthentication", PARAM_CCC, "auth.12"); -// if (!ParamValidatorUtils.isValidUseMandate(sso)) -// throw new WrongParametersException("StartAuthentication", PARAM_SSO, "auth.12"); + //check UseMandate flag String useMandateString = null; @@ -100,161 +95,98 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ //load OnlineApplication configuration - OAAuthParameter oaParam; - if (moasession.getPublicOAURLPrefix() != null) { - Logger.debug("Loading OA parameters for PublicURLPrefix: " + moasession.getPublicOAURLPrefix()); - oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter( - moasession.getPublicOAURLPrefix()); - - if (oaParam == null) - throw new AuthenticationException("auth.00", - new Object[] { moasession.getPublicOAURLPrefix() }); - - } else { - oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(oaURL); - - if (oaParam == null) + IOAAuthParameters oaParam = protocolReq.getOnlineApplicationConfiguration(); + if (oaParam == null) throw new AuthenticationException("auth.00", - new Object[] { oaURL }); + new Object[] { protocolReq.getOAURL() }); - // get target and target friendly name from config - String targetConfig = oaParam.getTarget(); - String targetFriendlyNameConfig = oaParam.getTargetFriendlyName(); + // get target and target friendly name from config + String targetConfig = oaParam.getTarget(); + String targetFriendlyNameConfig = oaParam.getTargetFriendlyName(); - if (!oaParam.getBusinessService()) { - if (StringUtils.isEmpty(targetConfig) - || (protocolReq.requestedModule().equals("at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol") && - !StringUtils.isEmpty(target)) - ) { - //INFO: ONLY SAML1 legacy mode - // if SAML1 is used and target attribute is given in request - // use requested target - // check target parameter - if (!ParamValidatorUtils.isValidTarget(target)) { - Logger.error("Selected target is invalid. Using target: " + target); - throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12"); - } - if (MiscUtil.isNotEmpty(targetConfig)) - targetFriendlyName = targetFriendlyNameConfig; + if (!oaParam.getBusinessService()) { + if (StringUtils.isEmpty(targetConfig) + || (protocolReq.requestedModule().equals("at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol") && + !StringUtils.isEmpty(target)) + ) { + //INFO: ONLY SAML1 legacy mode + // if SAML1 is used and target attribute is given in request + // use requested target + // check target parameter + if (!ParamValidatorUtils.isValidTarget(target)) { + Logger.error("Selected target is invalid. Using target: " + target); + throw new WrongParametersException("StartAuthentication", PARAM_TARGET, "auth.12"); + } + if (MiscUtil.isNotEmpty(targetConfig)) + targetFriendlyName = targetFriendlyNameConfig; + + else { + String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(target); + if (MiscUtil.isNotEmpty(sectorName)) + targetFriendlyName = sectorName; else { - String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(target); - if (MiscUtil.isNotEmpty(sectorName)) - targetFriendlyName = sectorName; - - else { - //check target contains subSector - int delimiter = target.indexOf("-"); - if (delimiter > 0) { - targetFriendlyName = - TargetToSectorNameMapper.getSectorNameViaTarget(target.substring(0, delimiter)); - - } - } - } - - } else { - // use target from config - target = targetConfig; - targetFriendlyName = targetFriendlyNameConfig; + //check target contains subSector + int delimiter = target.indexOf("-"); + if (delimiter > 0) { + targetFriendlyName = + TargetToSectorNameMapper.getSectorNameViaTarget(target.substring(0, delimiter)); + + } + } } - moasession.setTarget(target); - moasession.setTargetFriendlyName(targetFriendlyName); - + } else { - Logger.debug("Business: " + moasession.getBusinessService() + " stork: " + moasession.getStorkService()); - moasession.setDomainIdentifier(oaParam.getIdentityLinkDomainIdentifier()); - + // use target from config + target = targetConfig; + targetFriendlyName = targetFriendlyNameConfig; } + if (isEmpty(target)) + throw new WrongParametersException("StartAuthentication", + PARAM_TARGET, "auth.05"); -// //check useSSO flag -// String useSSOString = null; -// boolean useSSOBoolean = false; -// if ((sso != null) && (sso.compareTo("") != 0)) { -// useSSOString = sso; -// } else { -// useSSOString = "false"; -// } - // -// if (useSSOString.compareToIgnoreCase("true") == 0) -// useSSOBoolean = true; -// else -// useSSOBoolean = false; - - //moasession.setSsoRequested(useSSOBoolean); - moasession.setSsoRequested(true && oaParam.useSSO()); //make always SSO if OA requested it!!!! + protocolReq.setGenericDataToSession(MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, target); + protocolReq.setGenericDataToSession( + MOAIDAuthConstants.AUTHPROCESS_DATA_TARGETFRIENDLYNAME, targetFriendlyName); + Logger.debug("Service-Provider is of type 'PublicService' with DomainIdentifier:" + target); + + } else { + Logger.debug("Service-Provider is of type 'PrivateService' with DomainIdentifier:" + oaParam.getIdentityLinkDomainIdentifier()); - //Validate BKU URI - List allowedbkus = oaParam.getBKUURL(); - allowedbkus.addAll(AuthConfigurationProviderFactory.getInstance().getDefaultBKUURLs()); - if (!ParamValidatorUtils.isValidBKUURI(bkuURL, allowedbkus)) - throw new WrongParametersException("StartAuthentication", PARAM_BKU, "auth.12"); - - moasession.setBkuURL(bkuURL); - - if ((!oaParam.getBusinessService())) { - if (isEmpty(target)) - throw new WrongParametersException("StartAuthentication", - PARAM_TARGET, "auth.05"); - - } else { - if (useMandateBoolean) { - Logger.error("Online-Mandate Mode for business application not supported."); - throw new AuthenticationException("auth.17", null); - } - target = null; - targetFriendlyName = null; + if (useMandateBoolean) { + Logger.error("Online-Mandate Mode for business application not supported."); + throw new AuthenticationException("auth.17", null); } - moasession.setPublicOAURLPrefix(oaParam.getPublicURLPrefix()); - moasession.setBusinessService(oaParam.getBusinessService()); - - //moasession.setStorkService(oaParam.getStorkService()); - } - - //check OnlineApplicationURL - if (isEmpty(oaURL)) - throw new WrongParametersException("StartAuthentication", - PARAM_OA, "auth.05"); - moasession.setOAURLRequested(oaURL); - - //check AuthURL - String authURL = protocolReq.getAuthURL(); - if (!authURL.startsWith("https:") && !AuthConfigurationProviderFactory.getInstance().isHTTPAuthAllowed()) - throw new AuthenticationException("auth.07", - new Object[] { authURL + "*" }); - - //set Auth URL from configuration - moasession.setAuthURL(authURL); - - //check and set SourceID - if (oaParam.getSAML1Parameter() != null) { - String sourceID = oaParam.getSAML1Parameter().getSourceID(); - if (MiscUtil.isNotEmpty(sourceID)) - moasession.setSourceID(sourceID); } - + + //Validate BKU URI + List allowedbkus = oaParam.getBKUURL(); + allowedbkus.addAll(authConfig.getDefaultBKUURLs()); + if (!ParamValidatorUtils.isValidBKUURI(bkuURL, allowedbkus)) + throw new WrongParametersException("StartAuthentication", PARAM_BKU, "auth.12"); + moasession.setBkuURL(bkuURL); + + //validate securityLayer-template if (MiscUtil.isEmpty(templateURL)) { List templateURLList = oaParam.getTemplateURL(); List defaulTemplateURLList = - AuthConfigurationProviderFactory.getInstance().getSLRequestTemplates(); + authConfig.getSLRequestTemplates(); if ( templateURLList != null && templateURLList.size() > 0 && MiscUtil.isNotEmpty(templateURLList.get(0)) ) { templateURL = FileUtils.makeAbsoluteURL( oaParam.getTemplateURL().get(0), - AuthConfigurationProviderFactory.getInstance().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))) { templateURL = FileUtils.makeAbsoluteURL( defaulTemplateURLList.get(0), - AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir()); + authConfig.getRootConfigFileDir()); Logger.info("No SL-Template in request, load SL-Template from general configuration (URL: " + templateURL + ")"); } else { @@ -267,13 +199,22 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ if (!ParamValidatorUtils.isValidTemplate(req, templateURL, oaParam.getTemplateURL())) throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12"); - moasession.setTemplateURL(templateURL); - - moasession.setCcc(ccc); - + protocolReq.setGenericDataToSession( + MOAIDAuthConstants.AUTHPROCESS_DATA_SECURITYLAYERTEMPLATE, + templateURL); + + + //validate SSO functionality + String domainIdentifier = authConfig.getSSOTagetIdentifier().trim(); + if (MiscUtil.isEmpty(domainIdentifier) && protocolReq.needSingleSignOnFunctionality()) { + //do not use SSO if no Target is set + Logger.warn("NO SSO-Target found in configuration. Single Sign-On is deaktivated!"); + protocolReq.setNeedSingleSignOnFunctionality(false); + + } } - public static void parse(ExecutionContext ec, HttpServletRequest req, + public void parse(ExecutionContext ec, HttpServletRequest req, AuthenticationSession moasession, IRequest request) throws WrongParametersException, MOAIDException { //get Parameters from request @@ -294,7 +235,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ oaURL = request.getOAURL(); //only needed for SAML1 - String target = request.getGenericData("target", String.class); + String target = request.getGenericData("saml1_target", String.class); parse(moasession, target, oaURL, bkuURL, templateURL, useMandate, ccc, req, request); @@ -307,7 +248,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ * parameter * @return true if the parameter is null or empty */ - private static boolean isEmpty(String param) { + private boolean isEmpty(String param) { return param == null || param.length() == 0; } 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 48292cee1..87d41dbf1 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 @@ -110,10 +110,10 @@ public class IDPSingleLogOutServlet extends AbstractController { ssoManager.printSingleLogOutInfo(context, resp); } catch (MOAIDException e) { - handleErrorNoRedirect(e, req, resp); + handleErrorNoRedirect(e, req, resp, false); } catch (MOADatabaseException e) { - handleErrorNoRedirect(e, req, resp); + handleErrorNoRedirect(e, req, resp, false); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java index 7f0a1c157..58034cc7b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java @@ -66,6 +66,11 @@ public interface IOAAuthParameters { public boolean getBusinessService(); + /** + * Get target of a public service-provider + * + * @return target identifier without prefix + */ public String getTarget(); public String getTargetFriendlyName(); @@ -77,6 +82,8 @@ public interface IOAAuthParameters { public boolean isRemovePBKFromAuthBlock(); /** + * Return the private-service domain-identifier with PreFix + * * @return the identityLinkDomainIdentifier */ public String getIdentityLinkDomainIdentifier(); 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 b6df5e5c6..4131e49fc 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 @@ -496,6 +496,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { AuthenticationSession moasession; try { moasession = authenticatedSessionStore.createSession(pendingReq); + pendingReq.setMOASessionIdentifier(moasession.getSessionID()); } catch (MOADatabaseException e1) { Logger.error("Database Error! MOASession can not be created!"); @@ -514,7 +515,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { boolean leagacyMode = (legacyallowed && legacyparamavail); executionContext.put("isLegacyRequest", leagacyMode); - executionContext.put("performBKUSelection", leagacyMode + executionContext.put("performBKUSelection", !leagacyMode && MiscUtil.isEmpty(pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); //add leagcy parameters to context 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 index 6f46edce3..d26af89a2 100644 --- 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 @@ -23,6 +23,7 @@ package at.gv.egovernment.moa.id.moduls; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; /** * @author tlenz @@ -36,6 +37,6 @@ public interface IRequestStorage { public void removePendingRequest(String requestID); - public String changePendingRequestID(IRequest pendingRequest) throws MOAIDException; + public String changePendingRequestID(IRequest pendingRequest) throws MOAIDException, MOADatabaseException; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java index 66ca42398..c49df43fa 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java @@ -44,14 +44,19 @@ public class RequestStorage implements IRequestStorage{ 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.setTransactionId(pendingRequest.getUniqueTransactionIdentifier()); TransactionIDUtils.setSessionId(pendingRequest.getUniqueSessionIdentifier()); return pendingRequest; - } catch (MOADatabaseException e) { + } catch (MOADatabaseException | NullPointerException e) { Logger.info("No PendingRequst found with pendingRequestID " + pendingReqID); return null; @@ -106,16 +111,17 @@ public class RequestStorage implements IRequestStorage{ * @see at.gv.egovernment.moa.id.storage.IRequestStorage#changePendingRequestID(at.gv.egovernment.moa.id.moduls.IRequest) */ @Override - public String changePendingRequestID(IRequest pendingRequest) throws MOAIDException { + 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); - storePendingRequest(pendingRequest); + transactionStorage.changeKey(oldRequestID, newRequestID, pendingRequest); return newRequestID; 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 c9a34496a..36145375b 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 @@ -107,7 +107,7 @@ public class AttributQueryAction implements IAction { List attrList = addDefaultAttributes(attrQuery, authData); //build PVP 2.1 assertion - Assertion assertion = PVP2AssertionBuilder.buildAssertion(req.getAuthURL(), attrQuery, attrList, authData, date, authData.getSessionIndex()); + Assertion assertion = PVP2AssertionBuilder.buildAssertion(req, attrQuery, attrList, authData, date, authData.getSessionIndex()); //build PVP 2.1 response Response authResponse = AuthResponseBuilder.buildResponse(req.getAuthURL(), attrQuery, date, assertion); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index 07367e1d0..181e89806 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -36,8 +36,6 @@ import org.opensaml.saml2.metadata.RequestedAttribute; import org.opensaml.saml2.metadata.SPSSODescriptor; import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMetadataInformationException; @@ -98,9 +96,7 @@ public class PVPTargetConfiguration extends RequestImpl { for (String el : PVP2XProtocol.DEFAULTREQUESTEDATTRFORINTERFEDERATION) reqAttr.put(el, ""); - try { - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(getOAURL()); - + try { SPSSODescriptor spSSODescriptor = getRequest().getEntityMetadata().getSPSSODescriptor(SAMLConstants.SAML20P_NS); if (spSSODescriptor.getAttributeConsumingServices() != null && spSSODescriptor.getAttributeConsumingServices().size() > 0) { @@ -136,15 +132,12 @@ public class PVPTargetConfiguration extends RequestImpl { reqAttr.put(attr.getName(), ""); } - return AttributQueryBuilder.buildSAML2AttributeList(oa, reqAttr.keySet().iterator()); + return AttributQueryBuilder.buildSAML2AttributeList(this.getOnlineApplicationConfiguration(), reqAttr.keySet().iterator()); } catch (NoMetadataInformationException e) { Logger.warn("NO metadata found for Entity " + getRequest().getEntityID()); return null; - } catch (ConfigurationException e) { - Logger.error("Load configuration for OA " + getOAURL() + " FAILED", e); - return null; } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index 065118e2b..208cd67f2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -55,7 +55,6 @@ 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; @@ -64,21 +63,18 @@ import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationImpl; +import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; -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.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.MandateAttributesNotHandleAbleException; 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.CheckMandateAttributes; 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; @@ -90,7 +86,7 @@ import at.gv.egovernment.moa.util.MiscUtil; public class PVP2AssertionBuilder implements PVPConstants { - public static Assertion buildAssertion(String authURL, AttributeQuery attrQuery, + public static Assertion buildAssertion(IRequest pendingReq, AttributeQuery attrQuery, List reqAttributes, IAuthData authData, DateTime date, String sessionIndex) throws ConfigurationException { @@ -136,12 +132,12 @@ public class PVP2AssertionBuilder implements PVPConstants { SubjectConfirmationData subjectConfirmationData = null; - return buildGenericAssertion(authURL, attrQuery.getIssuer().getValue(), date, + return buildGenericAssertion(pendingReq, attrQuery.getIssuer().getValue(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, new DateTime(authData.getSsoSessionValidTo().getTime())); } - public static Assertion buildAssertion(String authURL, AuthnRequest authnRequest, + public static Assertion buildAssertion(PVPTargetConfiguration pendingReq, AuthnRequest authnRequest, IAuthData authData, EntityDescriptor peerEntity, DateTime date, AssertionConsumerService assertionConsumerService, SLOInformationImpl sloInformation) throws MOAIDException { @@ -153,9 +149,7 @@ public class PVP2AssertionBuilder implements PVPConstants { AuthnContextClassRef authnContextClassRef = SAML2Utils .createSAMLObject(AuthnContextClassRef.class); - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter( - peerEntity.getEntityID()); + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); if (reqAuthnContext == null) { authnContextClassRef.setAuthnContextClassRef(authData.getQAALevel()); @@ -416,12 +410,12 @@ public class PVP2AssertionBuilder implements PVPConstants { sloInformation.setNameIDFormat(subjectNameID.getFormat()); sloInformation.setSessionIndex(sessionIndex); - return buildGenericAssertion(authURL, peerEntity.getEntityID(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, subjectConfirmationData.getNotOnOrAfter()); + return buildGenericAssertion(pendingReq, peerEntity.getEntityID(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, subjectConfirmationData.getNotOnOrAfter()); } /** * - * @param authURL IDP PublicURL PreFix + * @param pendingReq IDP PublicURL PreFix * @param entityID Service Provider EntityID * @param date * @param authnContextClassRef @@ -434,7 +428,7 @@ public class PVP2AssertionBuilder implements PVPConstants { * @throws ConfigurationException */ - private static Assertion buildGenericAssertion(String authURL, String entityID, DateTime date, + private static Assertion buildGenericAssertion(IRequest pendingReq, String entityID, DateTime date, AuthnContextClassRef authnContextClassRef, List attrList, NameID subjectNameID, SubjectConfirmationData subjectConfirmationData, String sessionIndex, DateTime isValidTo) throws ConfigurationException { @@ -486,6 +480,7 @@ public class PVP2AssertionBuilder implements PVPConstants { Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); + String authURL = pendingReq.getAuthURL(); if (authURL.endsWith("/")) authURL = authURL.substring(0, authURL.length()-1); issuer.setValue(authURL); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index 974d90e11..4fbca5b13 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java @@ -81,7 +81,7 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { SLOInformationImpl sloInformation = new SLOInformationImpl(); //build Assertion - Assertion assertion = PVP2AssertionBuilder.buildAssertion(obj.getAuthURL(), authnRequest, authData, + Assertion assertion = PVP2AssertionBuilder.buildAssertion(obj, authnRequest, authData, peerEntity, date, consumerService, sloInformation); Response authResponse = AuthResponseBuilder.buildResponse(obj.getAuthURL(), authnRequest, date, assertion); 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 f33a7549c..ff631a720 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 @@ -53,28 +53,38 @@ public class DBTransactionStorage implements ITransactionStorage { } - public void put(String key, Object value) throws MOADatabaseException { - //setup AssertionStore element - AssertionStore element = new AssertionStore(); - element.setArtifact(key); - element.setType(value.getClass().getName()); - element.setDatatime(new Date()); - - //serialize the Assertion for Database storage - byte[] data = SerializationUtils.serialize((Serializable) value); - element.setAssertion(data); + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.storage.ITransactionStorage#changeKey(java.lang.String, java.lang.String, java.lang.Object) + */ + @Override + public void changeKey(String oldKey, String newKey, Object value) throws MOADatabaseException { + //search if key already exists + AssertionStore element = searchInDatabase(oldKey); + if (element == null) { + Logger.info("No transaction-data with oldKey:" + oldKey + + " found. Process gets stopped."); + throw new MOADatabaseException("No transaction-data with oldKey:" + oldKey + + " found. Process gets stopped."); + + } - //store AssertionStore element to Database - try { - MOASessionDBUtils.saveOrUpdate(element); - Logger.info(value.getClass().getName() + " with ID: " + key + " is stored in Database"); - } catch (MOADatabaseException e) { - Logger.warn("Sessioninformation could not be stored."); - throw new MOADatabaseException(e); + put(element, newKey, value); + + } + + public void put(String key, Object value) throws MOADatabaseException { + //search if key already exists + AssertionStore element = searchInDatabase(key); + + //create a new entry if key does not exists already + if (element == null) { + element = new AssertionStore(); + } + put(element, key, value); } - + public T get(String key, final Class clazz) throws MOADatabaseException { @@ -93,6 +103,9 @@ public class DBTransactionStorage implements ITransactionStorage { AssertionStore element = searchInDatabase(key); + if (element == null) + return null; + if (dataTimeOut > -1) { //check timeout long now = new Date().getTime(); @@ -155,13 +168,18 @@ public class DBTransactionStorage implements ITransactionStorage { try { AssertionStore element = searchInDatabase(key); + if (element == null) { + Logger.debug("Sessioninformation not removed! (Sessioninformation with ID=" + key + + "not found)"); + return; + } + cleanDelete(element); - Logger.info("Remove stored information with ID: " + key); + Logger.debug("Remove stored information with ID: " + key); } catch (MOADatabaseException e) { - Logger.info("Sessioninformation not removed! (Sessioninformation with ID=" + key - + "not found)"); + Logger.info("Sessioninformation not removed! (Message:"+ e.getMessage() + ")"); } catch (HibernateException e) { Logger.warn("Sessioninformation not removed! (Error during Database communication)", e); @@ -206,10 +224,34 @@ public class DBTransactionStorage implements ITransactionStorage { //Assertion requires an unique artifact if (result.size() != 1) { - Logger.trace("No entries found."); - throw new MOADatabaseException("No sessioninformation found with this ID"); + Logger.debug("No transaction information with ID:" + artifact + " found."); + return null; + } return (AssertionStore) result.get(0); } + + private void put(AssertionStore element, String key, Object value) throws MOADatabaseException { + element.setArtifact(key); + element.setType(value.getClass().getName()); + element.setDatatime(new Date()); + + //serialize the Assertion for Database storage + byte[] data = SerializationUtils.serialize((Serializable) value); + element.setAssertion(data); + + //store AssertionStore element to Database + try { + MOASessionDBUtils.saveOrUpdate(element); + Logger.debug(value.getClass().getName() + " with ID: " + key + " is stored in Database"); + + } catch (MOADatabaseException e) { + Logger.warn("Sessioninformation could not be stored."); + throw new MOADatabaseException(e); + + } + + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java index d05689e68..48283d2b6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java @@ -55,7 +55,7 @@ public interface ITransactionStorage { * * @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 + * @return The transaction-data object from type class, or null * @throws MOADatabaseException In case of load operation failed */ public T get(String key, final Class clazz) throws MOADatabaseException; @@ -66,12 +66,23 @@ public interface ITransactionStorage { * @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 + * @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 get(String key, final Class 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 * -- cgit v1.2.3 From 3cec20ee2161cb1a8c8c4516e47a8402d950957e Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 18 Feb 2016 12:22:57 +0100 Subject: fix problem with pending-requests and protocol specific error messages --- .../id/auth/modules/TaskExecutionException.java | 22 +- .../tasks/CreateInterfedeartionRequestTask.java | 2 +- .../internal/tasks/EvaluateBKUSelectionTask.java | 13 +- .../internal/tasks/FinalizeAuthenticationTask.java | 23 +- .../tasks/GenerateBKUSelectionFrameTask.java | 7 +- .../tasks/RestartAuthProzessManagement.java | 7 +- .../moa/id/auth/servlet/AbstractController.java | 214 +++++++++------- .../AbstractProcessEngineSignalController.java | 2 + .../AbstractAuthProtocolModulController.java | 272 +++++++++++++++++++++ .../protocols/AbstractProtocolModulController.java | 269 -------------------- .../protocols/ProtocolFinalizationController.java | 2 +- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 4 +- 12 files changed, 448 insertions(+), 389 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractAuthProtocolModulController.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/TaskExecutionException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/TaskExecutionException.java index 3e9f4cf14..932019d2c 100644 --- 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 @@ -22,7 +22,9 @@ */ package at.gv.egovernment.moa.id.auth.modules; +import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.process.ProcessExecutionException; +import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -32,14 +34,18 @@ public class TaskExecutionException extends ProcessExecutionException { private static final long serialVersionUID = 1L; Throwable originalException = null; + String pendingRequestID = null; /** * @param message * @param cause */ - public TaskExecutionException(String message, Throwable cause) { + public TaskExecutionException(IRequest pendingReq, String message, Throwable cause) { super(message, cause); - originalException = cause; + this.originalException = cause; + + if (MiscUtil.isNotEmpty(pendingReq.getRequestID())) + this.pendingRequestID = pendingReq.getRequestID(); } @@ -50,7 +56,19 @@ public class TaskExecutionException extends ProcessExecutionException { */ 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/CreateInterfedeartionRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java index 053f5d7ff..d0c12a6f3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java @@ -93,7 +93,7 @@ public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { if (MiscUtil.isEmpty(idpEntityID)) { Logger.info("Interfederation not possible -> not inderfederation IDP EntityID found!"); - throw new TaskExecutionException("Interfederation not possible", new MOAIDException("No inderfederation-IDP EntityID found.", null)); + throw new TaskExecutionException(pendingReq, "Interfederation not possible", new MOAIDException("No inderfederation-IDP EntityID found.", null)); } 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 9db5baeab..3b18959a5 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 @@ -31,12 +31,10 @@ import org.apache.commons.lang.StringEscapeUtils; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; 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.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -58,7 +56,7 @@ public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { //load pending request String pendingReqID = request.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID); pendingReqID = StringEscapeUtils.escapeHtml(pendingReqID); - IRequest pendingReq = requestStoreage.getPendingRequest(pendingReqID); + pendingReq = requestStoreage.getPendingRequest(pendingReqID); if (pendingReq == null) { Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); @@ -70,12 +68,11 @@ public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { String newPendingRequestID = requestStoreage.changePendingRequestID(pendingReq); executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, newPendingRequestID); - AuthenticationSession moaSession = null; String moaSessionID = pendingReq.getMOASessionIdentifier(); try { - moaSession = authenticatedSessionStorage.getSession(moaSessionID); + moasession = authenticatedSessionStorage.getSession(moaSessionID); - if (moaSession == null) { + if (moasession == null) { Logger.info("MOASession with SessionID="+ moaSessionID + " is not found in Database"); throw new MOAIDException("init.04", new Object[] { moaSessionID}); @@ -108,11 +105,11 @@ public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { } catch (MOAIDException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } catch (Exception e) { Logger.warn("EvaluateBKUSelectionTask has an internal error", e); - throw new TaskExecutionException(e.getMessage(), 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/FinalizeAuthenticationTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java index ed309d85a..4fd43b6ba 100644 --- 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 @@ -29,15 +29,13 @@ import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; 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.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController; +import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -57,7 +55,7 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { throws TaskExecutionException { try { - IRequest pendingReq = requestStoreage.getPendingRequest( + pendingReq = requestStoreage.getPendingRequest( (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); if (pendingReq == null) { @@ -67,16 +65,15 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { } //get Session from context - String moasessionid = pendingReq.getMOASessionIdentifier(); - AuthenticationSession session = null; + String moasessionid = pendingReq.getMOASessionIdentifier(); if (MiscUtil.isEmpty(moasessionid)) { Logger.warn("MOASessionID is empty."); throw new MOAIDException("auth.18", new Object[] {}); } try { - session = authenticatedSessionStorage.getSession(moasessionid); - if (session == null) { + moasession = authenticatedSessionStorage.getSession(moasessionid); + if (moasession == null) { Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); throw new MOAIDException("init.04", new Object[] { moasessionid }); @@ -98,8 +95,8 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { //set MOASession to authenticated and store MOASession - session.setAuthenticated(true); - String newMOASessionID = authenticatedSessionStorage.changeSessionID(session); + moasession.setAuthenticated(true); + String newMOASessionID = authenticatedSessionStorage.changeSessionID(moasession); //set pendingRequest to authenticated and set new MOASessionID ((RequestImpl)pendingReq).setMOASessionIdentifier(newMOASessionID); @@ -109,7 +106,7 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { Logger.info("AuthProcess finished. Redirect to Protocol Dispatcher."); String redirectURL = new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), - AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT, pendingReq.getRequestID()); + AbstractAuthProtocolModulController.FINALIZEPROTOCOL_ENDPOINT, pendingReq.getRequestID()); response.setContentType("text/html"); response.setStatus(302); @@ -117,11 +114,11 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { Logger.debug("REDIRECT TO: " + redirectURL); } catch (MOAIDException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } catch (Exception e) { Logger.warn("FinalizeAuthenticationTask has an internal error", e); - throw new TaskExecutionException(e.getMessage(), 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/GenerateBKUSelectionFrameTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java index cb0b63276..47b68bc51 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 @@ -37,7 +37,6 @@ import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.logging.Logger; @@ -55,7 +54,7 @@ public class GenerateBKUSelectionFrameTask extends AbstractAuthServletTask { public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { try { - IRequest pendingReq = requestStoreage.getPendingRequest( + pendingReq = requestStoreage.getPendingRequest( (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); if (pendingReq == null) { @@ -89,11 +88,11 @@ public class GenerateBKUSelectionFrameTask extends AbstractAuthServletTask { } catch (MOAIDException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } catch (Exception e) { Logger.warn("FinalizeAuthenticationTask has an internal error", e); - throw new TaskExecutionException(e.getMessage(), 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/RestartAuthProzessManagement.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java index d8b558846..d7859dd8b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java @@ -57,8 +57,9 @@ public class RestartAuthProzessManagement extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { + IRequest pendingReq = null; try { - IRequest pendingReq = requestStoreage.getPendingRequest( + pendingReq = requestStoreage.getPendingRequest( (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); if (pendingReq == null) { @@ -110,11 +111,11 @@ public class RestartAuthProzessManagement extends AbstractAuthServletTask { } catch (MOAIDException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } catch (Exception e) { Logger.warn("RestartAuthProzessManagement has an internal error", e); - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index 887692477..acff2e40e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -52,7 +52,7 @@ import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.moduls.IRequestStorage; import at.gv.egovernment.moa.id.process.ProcessExecutionException; -import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController; +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; @@ -78,35 +78,65 @@ public abstract class AbstractController extends MOAIDAuthConstants { @Autowired protected ITransactionStorage transactionStorage; @Autowired protected MOAReversionLogger revisionsLogger; @Autowired protected AuthConfiguration authConfig; - - protected void handleError(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) throws IOException { - Throwable loggedException = extractOriginalExceptionFromProcessException(exceptionThrown); + @ExceptionHandler({MOAIDException.class}) + public void MOAIDExceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws IOException { + Logger.error(e.getMessage() , e); + internalMOAIDExceptionHandler(req, resp, e, true); - if (!(loggedException instanceof MOAIDException)) { - Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); + } - } else { - if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { - Logger.error(loggedException.getMessage(), loggedException); + @ExceptionHandler({Exception.class}) + public void GenericExceptionHandler(HttpServletResponse resp, Exception exception) throws IOException { + Logger.error("Internel Server Error." , exception); + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + + "(Errorcode=9199" + +" | Description="+ exception.getMessage() + ")"); + return; + + } - } else { - Logger.error(loggedException.getMessage()); + @ExceptionHandler({IOException.class}) + public void IOExceptionHandler(HttpServletResponse resp, IOException exception) { + Logger.error("Internel Server Error." , exception); + resp.setContentType("text/html;charset=UTF-8"); + resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); + return; + + } - } - } + protected void handleError(String errorMessage, Throwable exceptionThrown, + HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) throws IOException { - //store error into transaction store - try { - String key = Random.nextRandom(); - transactionStorage.put(key, loggedException); + 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(); - if (key != null && MiscUtil.isNotEmpty(pendingRequestID)) { + //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 + if (MiscUtil.isNotEmpty(pendingRequestID)) { + + //put exception into transaction store for redirect + String key = Random.nextRandom(); + transactionStorage.put(key, loggedException); + + //build up redirect URL String redirectURL = null; - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/"+AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT + redirectURL += "/"+AbstractAuthProtocolModulController.FINALIZEPROTOCOL_ENDPOINT + "?" + ERROR_CODE_PARAM + "=" + key + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; @@ -119,7 +149,8 @@ public abstract class AbstractController extends MOAIDAuthConstants { return; } else { - //Exception can not be stored in database + //write exception into browser window, because protocol-specific error message + // is not possible without pendingRequest handleErrorNoRedirect(loggedException, req, resp, true); } @@ -132,8 +163,7 @@ public abstract class AbstractController extends MOAIDAuthConstants { } - - + /** * Handles all exceptions with no pending request. * Therefore, the error is written to the users browser @@ -151,71 +181,36 @@ public abstract class AbstractController extends MOAIDAuthConstants { statisticLogger.logErrorOperation(throwable); //write errror to console - Logger.error(throwable.getMessage(), throwable); + logExceptionToTechnicalLog(throwable); //return error to Web browser if (throwable instanceof MOAIDException || throwable instanceof ProcessExecutionException) - MOAIDExceptionHandler(req, resp, (Exception)throwable); + internalMOAIDExceptionHandler(req, resp, (Exception)throwable, false); else GenericExceptionHandler(resp, (Exception)throwable); } - @ExceptionHandler({MOAIDException.class}) - public void MOAIDExceptionHandler(HttpServletRequest req, HttpServletResponse resp, Exception e) throws IOException { - if (e instanceof ProtocolNotActiveException) { - resp.getWriter().write(e.getMessage()); - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); - - } else if (e instanceof AuthnRequestValidatorException) { - AuthnRequestValidatorException ex = (AuthnRequestValidatorException)e; - //log Error Message - 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(resp, (MOAIDException) e); - - } else if (e instanceof MOAIDException) { - //send HTML formated error message - writeHTMLErrorResponse(resp, e); - - } else if (e instanceof ProcessExecutionException) { - //send HTML formated error message - writeHTMLErrorResponse(resp, e); - - } - - } + /** + * 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)) { + Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); - @ExceptionHandler({Exception.class}) - public void GenericExceptionHandler(HttpServletResponse resp, Exception exception) throws IOException { - Logger.error("Internel Server Error." , exception); - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error!" + - "(Errorcode=9199" - +" | Description="+ exception.getMessage() + ")"); - return; - - } + } else { + if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { + Logger.error(loggedException.getMessage(), loggedException); - @ExceptionHandler({IOException.class}) - public void IOExceptionHandler(HttpServletResponse resp, IOException exception) { - Logger.error("Internel Server Error." , exception); - resp.setContentType("text/html;charset=UTF-8"); - resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); - return; - - } + } else { + Logger.error(loggedException.getMessage()); + } + } + } + private void writeBadRequestErrorResponse(HttpServletRequest req, HttpServletResponse resp, MOAIDException e) throws IOException { ErrorResponseUtils utils = ErrorResponseUtils.getInstance(); String code = utils.mapInternalErrorToExternalError( @@ -295,21 +290,68 @@ public abstract class AbstractController extends MOAIDAuthConstants { 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 returnexception = exception; + Throwable exholder = exception; + TaskExecutionException taskExc = null; - while(returnexception != null - && returnexception instanceof ProcessExecutionException) { - ProcessExecutionException procExc = (ProcessExecutionException) returnexception; + while(exholder != null + && exholder instanceof ProcessExecutionException) { + ProcessExecutionException procExc = (ProcessExecutionException) exholder; if (procExc.getCause() != null && procExc.getCause() instanceof TaskExecutionException) { - TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); - returnexception = taskExc.getOriginalException(); + taskExc = (TaskExecutionException) procExc.getCause(); + exholder = taskExc.getOriginalException(); } } - return returnexception; + 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("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_FORBIDDEN, 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(resp, (MOAIDException) e); + + } else if (e instanceof MOAIDException) { + //send HTML formated error message + writeHTMLErrorResponse(resp, e); + + } else if (e instanceof ProcessExecutionException) { + //send HTML formated error message + writeHTMLErrorResponse(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 index 375afca4d..2abe1582d 100644 --- 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 @@ -52,6 +52,8 @@ public abstract class AbstractProcessEngineSignalController extends AbstractCont // wake up next task processEngine.signal(pendingReq.getProcessInstanceId()); + //TODO: + } catch (Exception ex) { handleError(null, ex, req, resp, pendingRequestID); 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 new file mode 100644 index 000000000..5341951d2 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractAuthProtocolModulController.java @@ -0,0 +1,272 @@ +/* + * 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.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.config.auth.IOAAuthParameters; +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.IRequest; +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 moaSession = authmanager.doAuthentication(req, resp, pendingReq); + if (moaSession != null) { + //authenticated MOASession already exists --> protocol-specific postProcessing can start directly + finalizeAuthenticationProcess(req, resp, pendingReq, moaSession); + + } + + } else { + executeProtocolSpecificAction(req, resp, pendingReq, null); + + } + + } catch (Exception e) { + buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); + + } + } + + /** + * 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, AuthenticationSession moaSession) throws Exception { + + String newSSOSessionId = null; + + //if Single Sign-On functionality is enabled for this request + if (pendingReq.needSingleSignOnFunctionality()) { + + //Store SSO information into database + 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); + + } + + } + + //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 { + authenticatedSessionStorage.addSSOInformation(moaSession.getSessionID(), + newSSOSessionId, sloInformation, pendingReq); + + } 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 || + !clazz.isInstance(IAction.class)) { + 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 buildProtocolSpecificErrorResponse(Throwable throwable, HttpServletRequest req, + HttpServletResponse resp, IRequest protocolRequest) throws IOException { + try { + + Class clazz = Class.forName(protocolRequest.requestedModule()); + if (clazz == null || + !clazz.isInstance(IModulInfo.class)) { + 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); + + //remove MOASession + AuthenticationSession moaSession = authenticatedSessionStorage.getSession( + protocolRequest.getMOASessionIdentifier()); + if (moaSession != null) + authmanager.performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); + + return; + + } else { + handleErrorNoRedirect(throwable, req, resp, true); + + } + + } catch (Throwable e) { + Logger.error(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/AbstractProtocolModulController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java deleted file mode 100644 index de64ec98e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/AbstractProtocolModulController.java +++ /dev/null @@ -1,269 +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.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.config.auth.IOAAuthParameters; -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.IRequest; -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 AbstractProtocolModulController 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 moaSession = authmanager.doAuthentication(req, resp, pendingReq); - if (moaSession != null) { - //authenticated MOASession already exists --> protocol-specific postProcessing can start directly - finalizeAuthenticationProcess(req, resp, pendingReq, moaSession); - - } - - } else { - executeProtocolSpecificAction(req, resp, pendingReq, null); - - } - - } catch (Exception e) { - buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); - - } - } - - /** - * 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, AuthenticationSession moaSession) throws Exception { - - String newSSOSessionId = null; - - //if Single Sign-On functionality is enabled for this request - if (pendingReq.needSingleSignOnFunctionality()) { - - //Store SSO information into database - 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); - - } - - } - - //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 { - authenticatedSessionStorage.addSSOInformation(moaSession.getSessionID(), - newSSOSessionId, sloInformation, pendingReq); - - } 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 || - !clazz.isInstance(IAction.class)) { - 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 buildProtocolSpecificErrorResponse(Throwable throwable, HttpServletRequest req, - HttpServletResponse resp, IRequest protocolRequest) throws IOException { - try { - - Class clazz = Class.forName(protocolRequest.requestedModule()); - if (clazz == null || - !clazz.isInstance(IModulInfo.class)) { - 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 Message - statisticLogger.logErrorOperation(throwable, protocolRequest); - - //remove MOASession - AuthenticationSession moaSession = authenticatedSessionStorage.getSession( - protocolRequest.getMOASessionIdentifier()); - if (moaSession != null) - authmanager.performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); - - return; - - } else { - handleErrorNoRedirect(throwable, req, resp, true); - - } - - } catch (Throwable e) { - Logger.error(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 index 107212c38..8c3f2c946 100644 --- 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 @@ -45,7 +45,7 @@ import at.gv.egovernment.moa.logging.Logger; * */ @Controller -public class ProtocolFinalizationController extends AbstractProtocolModulController { +public class ProtocolFinalizationController extends AbstractAuthProtocolModulController { @RequestMapping(value = "/finalizeAuthProtocol", method = {RequestMethod.GET}) public void finalizeAuthProtocol(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException, IOException { 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 fc4928366..6fb03a37d 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 @@ -66,7 +66,7 @@ import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; -import at.gv.egovernment.moa.id.protocols.AbstractProtocolModulController; +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.PostBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; @@ -97,7 +97,7 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Controller -public class PVP2XProtocol extends AbstractProtocolModulController { +public class PVP2XProtocol extends AbstractAuthProtocolModulController { public static final String NAME = PVP2XProtocol.class.getName(); public static final String PATH = "id_pvp2x"; -- cgit v1.2.3 From 81fdd532bfd5e1ec778b6dcd57516e5c3778cf94 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 18 Feb 2016 12:23:24 +0100 Subject: remove unused code --- .../id/auth/modules/AbstractAuthServletTask.java | 244 +------------ .../moa/id/auth/servlet/AuthServlet.java | 378 --------------------- .../servlet/GenerateIFrameTemplateServlet.java | 168 --------- 3 files changed, 1 insertion(+), 789 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/AbstractAuthServletTask.java index 66f91266f..68d5ae299 100644 --- 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 @@ -1,29 +1,17 @@ package at.gv.egovernment.moa.id.auth.modules; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_CACHE_CONTROL; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_EXPIRES; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_PRAGMA; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_EXPIRES; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.HEADER_VALUE_PRAGMA; import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import javax.servlet.RequestDispatcher; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; @@ -36,24 +24,16 @@ import org.apache.commons.lang3.ObjectUtils; import org.springframework.beans.factory.annotation.Autowired; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; 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.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.moduls.IRequest; 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.AbstractProtocolModulController; 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.id.util.ServletUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -63,8 +43,6 @@ import at.gv.egovernment.moa.util.MiscUtil; */ public abstract class AbstractAuthServletTask extends MoaIdTask { - @Autowired private StatisticLogger statisticLogger; - @Autowired private ITransactionStorage transactionStorage; @Autowired protected IRequestStorage requestStoreage; @Autowired protected IAuthenticationSessionStoreage authenticatedSessionStorage; @Autowired protected MOAReversionLogger revisionsLogger; @@ -116,165 +94,6 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { } } - - protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp) { - - if (null != errorMessage) { - Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage); - } - - if (null != exceptionThrown) { - if (null == errorMessage) - errorMessage = exceptionThrown.getMessage(); - Logger.error(errorMessage, exceptionThrown); - req.setAttribute("ExceptionThrown", exceptionThrown); - } - - if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); - } - - statisticLogger.logErrorOperation(exceptionThrown); - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = req.getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - - resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); - resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); - resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); - - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Handles an error.
> - *

    - *
  • Logs the error
  • - *
  • Places error message and exception thrown into the request as request - * attributes (to be used by "/errorpage-auth.jsp")
  • - *
  • Sets HTTP status 500 (internal server error)
  • - *
- * - * @param errorMessage - * error message - * @param exceptionThrown - * exception thrown - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleError(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { - - if (null != errorMessage) { - Logger.error(errorMessage); - req.setAttribute("ErrorMessage", errorMessage); - } - - if (null != exceptionThrown) { - if (null == errorMessage) - errorMessage = exceptionThrown.getMessage(); - Logger.error(errorMessage, exceptionThrown); - req.setAttribute("ExceptionThrown", exceptionThrown); - } - - if (Logger.isDebugEnabled()) { - req.setAttribute("LogLevel", "debug"); - } - - if (!(exceptionThrown instanceof MOAIDException)) { - Logger.error("Receive an internal error: Message=" + exceptionThrown.getMessage(), exceptionThrown); - - } - - - try { - String key = Random.nextRandom(); - transactionStorage.put(key, exceptionThrown); - - if (key != null && MiscUtil.isNotEmpty(pendingRequestID)) { - String redirectURL = null; - - redirectURL = ServletUtils.getBaseUrl(req) + "/"; - redirectURL += AbstractProtocolModulController.FINALIZEPROTOCOL_ENDPOINT - + "?" + ERROR_CODE_PARAM + "=" + key - + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - return; - - } else { - //Exception can not be stored in database - handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); - } - - } catch (MOADatabaseException e) { - Logger.warn("Exception can not be stored to Database.", e); - handleErrorNoRedirect(errorMessage, exceptionThrown, req, resp); - - } - - - - - } - - /** - * Handles a WrongParametersException. - * - * @param req - * servlet request - * @param resp - * servlet response - */ - protected void handleWrongParameters(WrongParametersException ex, - HttpServletRequest req, HttpServletResponse resp) { - Logger.error(ex.toString()); - req.setAttribute("WrongParameters", ex.getMessage()); - - // forward this to errorpage-auth.jsp where the HTML error page is - // generated - ServletContext context = req.getServletContext(); - RequestDispatcher dispatcher = context - .getRequestDispatcher("/errorpage-auth.jsp"); - try { - setNoCachingHeaders(resp); - dispatcher.forward(req, resp); - } catch (ServletException e) { - Logger.error(e); - } catch (IOException e) { - Logger.error(e); - } - } - - /** - * Logs all servlet parameters for debugging purposes. - */ - protected void logParameters(HttpServletRequest req) { - for (Enumeration params = req.getParameterNames(); params - .hasMoreElements();) { - String parname = (String) params.nextElement(); - Logger.debug("Parameter " + parname + req.getParameter(parname)); - } - } /** * Parses the request input stream for parameters, assuming parameters are @@ -334,27 +153,7 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { } } - else { - // request is encoded as application/x-www-urlencoded - // [tknall]: we must not consume request body input stream once servlet-api request parameters have been accessed - - /* - InputStream in = req.getInputStream(); - - String paramName; - String paramValueURLEncoded; - do { - paramName = new String(readBytesUpTo(in, '=')); - if (paramName.length() > 0) { - paramValueURLEncoded = readBytesUpTo(in, '&'); - String paramValue = URLDecoder.decode(paramValueURLEncoded, - "UTF-8"); - parameters.put(paramName, paramValue); - } - } while (paramName.length() > 0); - in.close(); - */ - + else { Iterator> requestParamIt = req.getParameterMap().entrySet().iterator(); while (requestParamIt.hasNext()) { Entry entry = requestParamIt.next(); @@ -393,19 +192,6 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { return bout.toString(); } - /** - * Sets response headers that prevent caching (code taken from {@link AuthServlet}). - * - * @param resp - * The HttpServletResponse. - */ - public void setNoCachingHeaders(HttpServletResponse resp) { - resp.setHeader(HEADER_EXPIRES, HEADER_VALUE_EXPIRES); - resp.setHeader(HEADER_PRAGMA, HEADER_VALUE_PRAGMA); - resp.setHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL); - resp.addHeader(HEADER_CACHE_CONTROL, HEADER_VALUE_CACHE_CONTROL_IE); - } - /** * Adds a parameter to a URL. * @@ -425,32 +211,4 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { else return url + "&" + param; } - - /** - * Checks if HTTP requests are allowed - * - * @param authURL - * requestURL - * @throws AuthenticationException - * if HTTP requests are not allowed - * @throws ConfigurationException - */ - protected void checkIfHTTPisAllowed(String authURL) - throws AuthenticationException, ConfigurationException { - // check if HTTP Connection may be allowed (through - // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) - - //Removed from MOA-ID 2.0 config -// String boolStr = AuthConfigurationProvider -// .getInstance() -// .getGenericConfigurationParameter( -// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); - if ((!authURL.startsWith("https:")) - //&& (false == BoolUtils.valueOf(boolStr)) - ) - throw new AuthenticationException("auth.07", new Object[] { authURL - + "*" }); - - } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java deleted file mode 100644 index fb6c71846..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AuthServlet.java +++ /dev/null @@ -1,378 +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.servlet; -// -//import java.io.IOException; -// -//import javax.servlet.RequestDispatcher; -//import javax.servlet.ServletConfig; -//import javax.servlet.ServletContext; -//import javax.servlet.ServletException; -//import javax.servlet.http.HttpServlet; -//import javax.servlet.http.HttpServletRequest; -//import javax.servlet.http.HttpServletResponse; -// -//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.advancedlogging.StatisticLogger; -//import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -//import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -//import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -//import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -//import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -//import at.gv.egovernment.moa.id.config.ConfigurationException; -//import at.gv.egovernment.moa.id.process.ProcessEngine; -//import at.gv.egovernment.moa.id.process.ProcessExecutionException; -//import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -//import at.gv.egovernment.moa.id.storage.IExceptionStore; -//import at.gv.egovernment.moa.id.util.ServletUtils; -//import at.gv.egovernment.moa.logging.Logger; -//import at.gv.egovernment.moa.util.MiscUtil; -// -///** -// * Base class for MOA-ID Auth Servlets, providing standard error handling and -// * constant names. -// * -// * @author Paul Ivancsics -// * @version $Id$ -// */ -//public class AuthServlet extends HttpServlet { -// -// /** -// * -// */ -// private static final long serialVersionUID = -6929905344382283738L; -// -// protected static final String ERROR_CODE_PARAM = "errorid"; -// -// /** -// * The process engine. -// */ -// private ProcessEngine processEngine; -// -// @Override -// protected void doGet(HttpServletRequest req, HttpServletResponse resp) -// throws ServletException, IOException { -// Logger.debug("GET " + this.getServletName()); -// -// this.setNoCachingHeadersInHttpRespone(req, resp); -// } -// -// protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, -// HttpServletRequest req, HttpServletResponse resp) { -// -// if (null != errorMessage) { -// Logger.error(errorMessage); -// req.setAttribute("ErrorMessage", errorMessage); -// } -// -// if (null != exceptionThrown) { -// if (null == errorMessage) -// errorMessage = exceptionThrown.getMessage(); -// Logger.error(errorMessage, exceptionThrown); -// req.setAttribute("ExceptionThrown", exceptionThrown); -// } -// -// if (Logger.isDebugEnabled()) { -// req.setAttribute("LogLevel", "debug"); -// } -// -// -// StatisticLogger logger = StatisticLogger.getInstance(); -// logger.logErrorOperation(exceptionThrown); -// -// -// // forward this to errorpage-auth.jsp where the HTML error page is -// // generated -// ServletContext context = getServletContext(); -// RequestDispatcher dispatcher = context -// .getRequestDispatcher("/errorpage-auth.jsp"); -// try { -// -// resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, -// MOAIDAuthConstants.HEADER_VALUE_EXPIRES); -// resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, -// MOAIDAuthConstants.HEADER_VALUE_PRAGMA); -// resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, -// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); -// resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, -// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); -// -// dispatcher.forward(req, resp); -// } catch (ServletException e) { -// Logger.error(e); -// } catch (IOException e) { -// Logger.error(e); -// } -// } -// -// /** -// * Handles an error.
> -// *
    -// *
  • Logs the error
  • -// *
  • Places error message and exception thrown into the request as request -// * attributes (to be used by "/errorpage-auth.jsp")
  • -// *
  • Sets HTTP status 500 (internal server error)
  • -// *
-// * -// * @param errorMessage -// * error message -// * @param exceptionThrown -// * exception thrown -// * @param req -// * servlet request -// * @param resp -// * servlet response -// */ -// protected void handleError(String errorMessage, Throwable exceptionThrown, -// HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) { -// -// Throwable loggedException = null; -// -// if (exceptionThrown != null -// && exceptionThrown instanceof ProcessExecutionException) { -// ProcessExecutionException procExc = -// (ProcessExecutionException) exceptionThrown; -// if (procExc.getCause() != null && -// procExc.getCause() instanceof TaskExecutionException) { -// TaskExecutionException taskExc = (TaskExecutionException) procExc.getCause(); -// loggedException = taskExc.getOriginalException(); -// -// } -// } -// -// if (loggedException == null) -// loggedException = exceptionThrown; -// -// -// if (!(loggedException instanceof MOAIDException)) { -// Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); -// -// } else { -// if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { -// Logger.error(loggedException.getMessage(), loggedException); -// -// } else { -// Logger.error(loggedException.getMessage()); -// -// } -// } -// -// IExceptionStore store = DBExceptionStoreImpl.getStore(); -// String id = store.storeException(loggedException); -// -// if (id != null && MiscUtil.isNotEmpty(pendingRequestID)) { -// -// String redirectURL = null; -// -// redirectURL = ServletUtils.getBaseUrl(req); -// -// //TODO: DEVELOPMENT -//// redirectURL += "/dispatcher?" + ERROR_CODE_PARAM + "=" + id -//// + "&" + DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; -// -// resp.setContentType("text/html"); -// resp.setStatus(302); -// -// resp.addHeader("Location", redirectURL); -// Logger.debug("REDIRECT TO: " + redirectURL); -// -// return; -// -// } else { -// -// //Exception can not be stored in database -// handleErrorNoRedirect(errorMessage, loggedException, req, resp); -// } -// } -// -// /** -// * Handles a WrongParametersException. -// * -// * @param req -// * servlet request -// * @param resp -// * servlet response -// */ -// protected void handleWrongParameters(WrongParametersException ex, -// HttpServletRequest req, HttpServletResponse resp) { -// Logger.error(ex.toString()); -// req.setAttribute("WrongParameters", ex.getMessage()); -// -// // forward this to errorpage-auth.jsp where the HTML error page is -// // generated -// ServletContext context = getServletContext(); -// RequestDispatcher dispatcher = context -// .getRequestDispatcher("/errorpage-auth.jsp"); -// try { -// resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, -// MOAIDAuthConstants.HEADER_VALUE_EXPIRES); -// resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, -// MOAIDAuthConstants.HEADER_VALUE_PRAGMA); -// resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, -// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); -// resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, -// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); -// -// dispatcher.forward(req, resp); -// } catch (ServletException e) { -// Logger.error(e); -// } catch (IOException e) { -// Logger.error(e); -// } -// } -// -// -// /** -// * Calls the web application initializer. -// * -// * @see javax.servlet.Servlet#init(ServletConfig) -// */ -// public void init(ServletConfig servletConfig) throws ServletException { -// super.init(servletConfig); -// } -// -// -// /** -// * Set response headers to avoid caching -// * -// * @param request -// * HttpServletRequest -// * @param response -// * HttpServletResponse -// */ -// protected void setNoCachingHeadersInHttpRespone(HttpServletRequest request, -// HttpServletResponse response) { -// response.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, -// MOAIDAuthConstants.HEADER_VALUE_EXPIRES); -// response.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, -// MOAIDAuthConstants.HEADER_VALUE_PRAGMA); -// response.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, -// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL); -// response.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, -// MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE); -// -// } -// -// /** -// * 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; -// } -// -// /** -// * Checks if HTTP requests are allowed -// * -// * @param authURL -// * requestURL -// * @throws AuthenticationException -// * if HTTP requests are not allowed -// * @throws ConfigurationException -// */ -// protected void checkIfHTTPisAllowed(String authURL) -// throws AuthenticationException, ConfigurationException { -// // check if HTTP Connection may be allowed (through -// // FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY) -// -// //Removed from MOA-ID 2.0 config -//// String boolStr = AuthConfigurationProvider -//// .getInstance() -//// .getGenericConfigurationParameter( -//// AuthConfigurationProvider.FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY); -// if ((!authURL.startsWith("https:")) -// //&& (false == BoolUtils.valueOf(boolStr)) -// ) -// throw new AuthenticationException("auth.07", new Object[] { authURL -// + "*" }); -// -// } -// -// -// /** -// * 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; -// } -// -//} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java deleted file mode 100644 index 663a14881..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GenerateIFrameTemplateServlet.java +++ /dev/null @@ -1,168 +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.util.Enumeration; -// -//import javax.servlet.ServletException; -//import javax.servlet.http.HttpServletRequest; -//import javax.servlet.http.HttpServletResponse; -// -//import org.apache.commons.lang.StringEscapeUtils; -// -//import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -//import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -//import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -//import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -//import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -//import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; -//import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -//import at.gv.egovernment.moa.id.process.ExecutionContextImpl; -//import at.gv.egovernment.moa.id.process.ProcessExecutionException; -//import at.gv.egovernment.moa.id.process.api.ExecutionContext; -//import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -//import at.gv.egovernment.moa.logging.Logger; -//import at.gv.egovernment.moa.util.MiscUtil; -// -//public class GenerateIFrameTemplateServlet extends AuthServlet { -// -// private static final long serialVersionUID = 1L; -// -// protected void doGet(HttpServletRequest req, HttpServletResponse resp) -// throws ServletException, IOException { -// Logger.debug("Receive " + GenerateIFrameTemplateServlet.class + " Request"); -// -// String pendingRequestID = null; -// -// try { -// String moasessionid = req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); -// moasessionid = StringEscapeUtils.escapeHtml(moasessionid); -// AuthenticationSession moasession = null; -// try { -// pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moasessionid); -// moasession = AuthenticationSessionStoreage.getSession(moasessionid); -// -// } catch (MOADatabaseException e) { -// Logger.info("MOASession with SessionID="+ moasessionid + " is not found in Database"); -// throw new MOAIDException("init.04", new Object[] { -// moasessionid}); -// -// } catch (Throwable e) { -// Logger.info("No HTTP Session found!"); -// throw new MOAIDException("auth.18", new Object[] {}); -// } -// -// -// -// ExecutionContext ec = new ExecutionContextImpl(); -// // set execution context -// Enumeration reqParamNames = req.getParameterNames(); -// while(reqParamNames.hasMoreElements()) { -// String paramName = reqParamNames.nextElement(); -// if (MiscUtil.isNotEmpty(paramName)) -// ec.put(paramName, req.getParameter(paramName)); -// -// } -// -// ec.put("pendingRequestID", pendingRequestID); -// ec.put(MOAIDAuthConstants.PARAM_SESSIONID, moasessionid); -// -//// String bkuid = req.getParameter(MOAIDAuthConstants.PARAM_BKU); -//// String useMandate = req.getParameter(MOAIDAuthConstants.PARAM_USEMANDATE); -//// String ccc = req.getParameter(MOAIDAuthConstants.PARAM_CCC); -//// ec.put("ccc", moasession.getCcc()); -//// ec.put("useMandate", moasession.getUseMandate()); -//// ec.put("bkuURL", moasession.getBkuURL()); -// -// // select and create process instance -// String processDefinitionId = ModuleRegistration.getInstance().selectProcess(ec); -// if (processDefinitionId == null) { -// Logger.warn("No suitable process found for SessionID " + moasession.getSessionID()); -// throw new MOAIDException("process.02", new Object[] { moasession.getSessionID() }); -// } -// -// String processInstanceId = getProcessEngine().createProcessInstance(processDefinitionId, ec); -// -// // keep process instance id in moa session -// moasession.setProcessInstanceId(processInstanceId); -// -// // make sure moa session has been persisted before running the process -// try { -// AuthenticationSessionStoreage.storeSession(moasession); -// } catch (MOADatabaseException e) { -// Logger.error("Database Error! MOASession is not stored!"); -// throw new MOAIDException("init.04", new Object[] { moasession.getSessionID() }); -// } -// -// Logger.info("BKU is selected -> Start BKU communication ..."); -// -// // start process -// getProcessEngine().start(processInstanceId); -// -// } -// catch (WrongParametersException ex) { -// handleWrongParameters(ex, req, resp); -// } -// -// catch (MOAIDException ex) { -// handleError(null, ex, req, resp, pendingRequestID); -// -// } catch (ProcessExecutionException e) { -// Throwable cause = e.getCause(); -// if (cause != null && cause instanceof TaskExecutionException) { -// Throwable taskCause = cause.getCause(); -// if (taskCause != null && taskCause instanceof WrongParametersException) { -// WrongParametersException internalEx = (WrongParametersException) taskCause; -// handleWrongParameters(internalEx, req, resp); -// return; -// -// } else if (taskCause != null && taskCause instanceof MOAIDException) { -// MOAIDException moaTaskCause = (MOAIDException) taskCause; -// handleError(null, moaTaskCause, req, resp, pendingRequestID); -// return; -// -// } -// } -// -// Logger.error("BKUSelectionServlet has an interal Error.", e); -// -// } catch (Exception e) { -// Logger.error("BKUSelectionServlet has an interal Error.", e); -// -// } -// -// finally { -// -// } -// } -// -// -// -// -// -// -// -// -// -//} -- cgit v1.2.3 From 695cc43865708aa9b97755fcd45fab4498d0eaab Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 18 Feb 2016 14:38:16 +0100 Subject: fix problem with protocol-action implementation validation --- .../moa/id/protocols/AbstractAuthProtocolModulController.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 index 5341951d2..bb89f2e03 100644 --- 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 @@ -184,12 +184,12 @@ public abstract class AbstractAuthProtocolModulController extends AbstractContro // request needs no authentication --> start request processing Class clazz = Class.forName(pendingReq.requestedAction()); if (clazz == null || - !clazz.isInstance(IAction.class)) { + !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); -- cgit v1.2.3 From 9bafb2671b297d39574c346c896347f197282081 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 18 Feb 2016 19:21:10 +0100 Subject: remove AXIS1 implemented WebService for SAML1 --> now a simple Spring controller is used as WebService endpoint --- .../servlet/interceptor/WebFrontEndSecurityInterceptor.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 7835687e8..c5a9ad34b 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 @@ -34,6 +34,7 @@ import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -49,7 +50,15 @@ public class WebFrontEndSecurityInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - + + //only for SAML1 GetAuthenticationData webService functionality + String requestedServlet = request.getServletPath(); + if (MiscUtil.isNotEmpty(requestedServlet) && requestedServlet.startsWith("/services/GetAuthenticationData")) { + Logger.debug("SAML1 GetAuthenticationServices allow access without SSL"); + return true; + + } + //check AuthURL String authURL = HTTPUtils.extractAuthURLFromRequest(request); if (!authURL.startsWith("https:") && !authConfig.isHTTPAuthAllowed()) { -- cgit v1.2.3 From 0d827d781679187d4a73e7b51510539a69a46d79 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 18 Feb 2016 19:22:52 +0100 Subject: fix error handling: always make a redirect to MOA-ID in case of error --- .../moa/id/auth/servlet/AbstractController.java | 45 +++++++++------------- 1 file changed, 18 insertions(+), 27 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index acff2e40e..8c0708fd5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -126,42 +126,33 @@ public abstract class AbstractController extends MOAIDAuthConstants { loggedException = exceptionThrown; try { - //switch to protocol-finalize method to generate a protocol-specific error message - if (MiscUtil.isNotEmpty(pendingRequestID)) { + //switch to protocol-finalize method to generate a protocol-specific error message + + //put exception into transaction store for redirect + String key = Random.nextRandom(); + transactionStorage.put(key, loggedException); - //put exception into transaction store for redirect - String key = Random.nextRandom(); - transactionStorage.put(key, loggedException); - - //build up redirect URL - String redirectURL = null; - redirectURL = ServletUtils.getBaseUrl(req); - redirectURL += "/"+AbstractAuthProtocolModulController.FINALIZEPROTOCOL_ENDPOINT - + "?" + ERROR_CODE_PARAM + "=" + key - + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; + //build up redirect URL + String redirectURL = null; + redirectURL = ServletUtils.getBaseUrl(req); + redirectURL += "/"+AbstractAuthProtocolModulController.FINALIZEPROTOCOL_ENDPOINT + + "?" + ERROR_CODE_PARAM + "=" + key + + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; - resp.setContentType("text/html"); - resp.setStatus(302); + resp.setContentType("text/html"); + resp.setStatus(302); - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); + resp.addHeader("Location", redirectURL); + Logger.debug("REDIRECT TO: " + redirectURL); - return; - - } else { - //write exception into browser window, because protocol-specific error message - // is not possible without pendingRequest - handleErrorNoRedirect(loggedException, req, resp, true); - - } - + return; + } catch (MOADatabaseException e) { Logger.warn("Exception can not be stored to Database.", e); handleErrorNoRedirect(loggedException, req, resp, true); } - - + } /** -- cgit v1.2.3 From 18f7c6609058ed5c3bfb59c625682f4f4a53d75d Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 19 Feb 2016 10:22:11 +0100 Subject: refactor Single Sign-On authentication consents evaluator to get executed by processEngine --- .../id/auth/builder/SendAssertionFormBuilder.java | 78 ++- .../id/auth/modules/AbstractAuthServletTask.java | 20 + .../modules/SingleSignOnConsentsModuleImpl.java | 69 +++ .../tasks/EvaluateSSOConsentsTaskImpl.java | 115 +++++ .../internal/tasks/FinalizeAuthenticationTask.java | 16 +- .../GenerateSSOConsentEvaluatorFrameTask.java | 87 ++++ .../id/auth/servlet/SSOSendAssertionServlet.java | 177 ------- .../moa/id/moduls/AuthenticationManager.java | 550 ++++++++++----------- 8 files changed, 593 insertions(+), 519 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/SingleSignOnConsentsModuleImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateSSOConsentsTaskImpl.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateSSOConsentEvaluatorFrameTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java index d14910319..7121935b0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java @@ -34,7 +34,8 @@ import java.net.URI; import org.apache.commons.io.IOUtils; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.util.FormBuildUtils; import at.gv.egovernment.moa.logging.Logger; @@ -46,8 +47,6 @@ public class SendAssertionFormBuilder { private static final String TEMPLATEBGCOLOR = "style=\"background-color: #COLOR#\""; private static String URL = "#URL#"; - private static String MODUL = "#MODUL#"; - private static String ACTION = "#ACTION#"; private static String ID = "#ID#"; private static String OANAME = "#OAName#"; private static String CONTEXTPATH = "#CONTEXTPATH#"; @@ -56,8 +55,7 @@ public class SendAssertionFormBuilder { private static String SERVLET = CONTEXTPATH+"/SSOSendAssertionServlet"; - private static String getTemplate() { - + private static String getTemplate() { String pathLocation; InputStream input = null; try { @@ -68,12 +66,9 @@ public class SendAssertionFormBuilder { File file = new File(new URI(pathLocation)); input = new FileInputStream(file); - } catch (FileNotFoundException e) { - - Logger.warn("No LoginFormTempaltes found. Use Generic Templates from package."); - - pathLocation = "resources/templates/" + HTMLTEMPLATEFULL; - + } catch (FileNotFoundException e) { + Logger.warn("No LoginFormTempaltes found. Use Generic Templates from package."); + pathLocation = "resources/templates/" + HTMLTEMPLATEFULL; input = Thread.currentThread() .getContextClassLoader() .getResourceAsStream(pathLocation); @@ -82,48 +77,43 @@ public class SendAssertionFormBuilder { return getTemplate(input); - } catch (Exception e) { + } catch (Exception e) { + return null; + + } finally { try { - input.close(); + if (input != null) + input.close(); - } catch (IOException e1) { + } catch (IOException e) { Logger.warn("SendAssertionTemplate inputstream can not be closed.", e); + } - - return null; - } - + } } private static String getTemplate(InputStream input) { + String template = null; + try { - String template = null; - - try { - - StringWriter writer = new StringWriter(); - IOUtils.copy(input, writer); - template = writer.toString(); - template = template.replace(URL, SERVLET); - - } catch (Exception e) { - Logger.error("Failed to read template", e); - - } finally { - try { - input.close(); - - } catch (IOException e) { - Logger.warn("SendAssertionTemplate inputstream can not be closed.", e); - } - } + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer); + template = writer.toString(); + template = template.replace(URL, SERVLET); + + } catch (Exception e) { + Logger.error("Failed to read template", e); + } return template; } - public static String buildForm(String modul, String action, String id, OAAuthParameter oaParam, String contextpath) { + public static String buildForm(IRequest pendingReq) { String value = null; + String contextpath = pendingReq.getAuthURL(); + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + byte[] oatemplate = oaParam.getSendAssertionTemplate(); // OA specific template requires a size of 8 bits minimum if (oatemplate != null && oatemplate.length > 7) { @@ -137,15 +127,7 @@ public class SendAssertionFormBuilder { } if(value != null) { -// if(modul == null) { -// modul = SAML1Protocol.PATH; -// } -// if(action == null) { -// action = SAML1Protocol.GETARTIFACT; -// } - value = value.replace(MODUL, modul); - value = value.replace(ACTION, action); - value = value.replace(ID, id); + value = value.replace(ID, pendingReq.getRequestID()); value = value.replace(OANAME, oaParam.getFriendlyName()); if (contextpath.endsWith("/")) 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 index 68d5ae299..559d4fd4f 100644 --- 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 @@ -12,6 +12,7 @@ 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; @@ -25,6 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; @@ -33,6 +35,7 @@ import at.gv.egovernment.moa.id.moduls.IRequest; 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.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -95,6 +98,23 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { } + /** + * 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) { + String redirectURL = new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), + AbstractAuthProtocolModulController.FINALIZEPROTOCOL_ENDPOINT, 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). 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 new file mode 100644 index 000000000..d64126de6 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/SingleSignOnConsentsModuleImpl.java @@ -0,0 +1,69 @@ +/* + * 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.process.api.ExecutionContext; + +/** + * @author tlenz + * + */ +public class SingleSignOnConsentsModuleImpl implements AuthModule { + + public static final String PARAM_SSO_CONSENTS_EVALUATION = "ssoconsentsevaluation"; + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getPriority() + */ + @Override + public int getPriority() { + return 0; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#selectProcess(at.gv.egovernment.moa.id.process.api.ExecutionContext) + */ + @Override + public String selectProcess(ExecutionContext context) { + Object evaluationObj = context.get(PARAM_SSO_CONSENTS_EVALUATION); + if (evaluationObj != null && evaluationObj instanceof Boolean) { + boolean evaluateSSOConsents = (boolean) evaluationObj; + if (evaluateSSOConsents) { + return "SSOConsentsEvluationProcess"; + + } + } + + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getProcessDefinitions() + */ + @Override + public String[] getProcessDefinitions() { + return new String[] { "classpath:at/gv/egovernment/moa/id/auth/modules/internal/SingleSignOnConsentEvaluator.process.xml" }; + } + +} 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 new file mode 100644 index 000000000..8dcb63550 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateSSOConsentsTaskImpl.java @@ -0,0 +1,115 @@ +/* + * 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.apache.commons.lang.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; + +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.moduls.SSOManager; +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.MiscUtil; + +/** + * Evaluate the Single Sign-On user consent + * + * @author tlenz + * + */ +public class EvaluateSSOConsentsTaskImpl extends AbstractAuthServletTask { + + private static final String PARAM_SSO_CONSENTS = "value"; + + @Autowired private SSOManager ssoManager; + + /* (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 { + //evaluate SSO consents flag + String ssoConsentsString = request.getParameter(PARAM_SSO_CONSENTS); + ssoConsentsString = StringEscapeUtils.escapeHtml(ssoConsentsString); + if (!ParamValidatorUtils.isValidUseMandate(ssoConsentsString)) + throw new WrongParametersException("EvaluateSSOConsentsTaskImpl", PARAM_SSO_CONSENTS, null); + + boolean ssoConsents = false; + if (MiscUtil.isNotEmpty(ssoConsentsString)) + ssoConsents = Boolean.parseBoolean(ssoConsentsString); + + //perform default task initialization + defaultTaskInitialization(request, executionContext); + + //check SSO session cookie and MOASession object + String ssoId = ssoManager.getSSOSessionID(request); + boolean isValidSSOSession = ssoManager.isValidSSOSession(ssoId, pendingReq); + if (!(isValidSSOSession && moasession.isAuthenticated() )) { + Logger.info("Single Sign-On consents evaluator found NO valid SSO session. Stopping authentication process ..."); + throw new AuthenticationException("auth.30", null); + + } + + //Log consents evaluator event to revisionslog + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_FINISHED, String.valueOf(ssoConsents)); + + //user allow single sign-on authentication + if (ssoConsents) { + //authenticate pending-request + pendingReq.setAuthenticated(true); + + //store pending-request + requestStoreage.storePendingRequest(pendingReq); + + //redirect to auth. protocol finalization + performRedirectToProtocolFinialization(pendingReq, response); + + } else { + //user deny single sign-on authentication + throw new AuthenticationException("auth.21", new Object[] {}); + + } + + } 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); + + } + + } + +} 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 index 4fd43b6ba..d1d2cdca8 100644 --- 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 @@ -28,14 +28,12 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; 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.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -93,7 +91,6 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { } - //set MOASession to authenticated and store MOASession moasession.setAuthenticated(true); String newMOASessionID = authenticatedSessionStorage.changeSessionID(moasession); @@ -103,16 +100,9 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { pendingReq.setAuthenticated(true); requestStoreage.storePendingRequest(pendingReq); - Logger.info("AuthProcess finished. Redirect to Protocol Dispatcher."); - - String redirectURL = new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), - AbstractAuthProtocolModulController.FINALIZEPROTOCOL_ENDPOINT, pendingReq.getRequestID()); - - response.setContentType("text/html"); - response.setStatus(302); - response.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - + Logger.info("AuthProcess finished. Redirect to Protocol Dispatcher."); + performRedirectToProtocolFinialization(pendingReq, response); + } catch (MOAIDException 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/GenerateSSOConsentEvaluatorFrameTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateSSOConsentEvaluatorFrameTask.java new file mode 100644 index 000000000..f9f121520 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateSSOConsentEvaluatorFrameTask.java @@ -0,0 +1,87 @@ +/* + * 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.io.PrintWriter; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.auth.builder.SendAssertionFormBuilder; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.logging.Logger; + +/** + * Build a Single Sign-On consents evaluator form + * + * @author tlenz + * + */ +public class GenerateSSOConsentEvaluatorFrameTask 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 { + //perform default task initialization + defaultTaskInitialization(request, executionContext); + + //set authenticated flag to false, because user consents is required + pendingReq.setAuthenticated(false); + + //build consents evaluator form + String form = SendAssertionFormBuilder.buildForm(pendingReq); + + //store pending request + requestStoreage.storePendingRequest(pendingReq); + + //Log consents evaluator event to revisionslog + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_START); + + //write form to response object + response.setContentType("text/html;charset=UTF-8"); + PrintWriter out = new PrintWriter(response.getOutputStream()); + out.print(form); + out.flush(); + + + } 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); + + } + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java deleted file mode 100644 index 4c895e387..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SSOSendAssertionServlet.java +++ /dev/null @@ -1,177 +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 javax.servlet.ServletException; -//import javax.servlet.http.HttpServletRequest; -//import javax.servlet.http.HttpServletResponse; -// -//import org.apache.commons.lang.StringEscapeUtils; -// -//import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -//import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -//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.commons.db.ex.MOADatabaseException; -//import at.gv.egovernment.moa.id.moduls.IRequest; -//import at.gv.egovernment.moa.id.moduls.RequestStorage; -//import at.gv.egovernment.moa.id.moduls.SSOManager; -//import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -//import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -//import at.gv.egovernment.moa.logging.Logger; -//import at.gv.egovernment.moa.util.MiscUtil; -// -//public class SSOSendAssertionServlet extends AuthServlet{ -// -// private static final long serialVersionUID = 1L; -// -// private static final String PARAM = "value"; -// private static final String MODULE = "mod"; -// private static final String ACTION = "action"; -// private static final String ID = "identifier"; -// -// protected void doPost(HttpServletRequest req, HttpServletResponse resp) -// throws ServletException, IOException { -// -// String id = null; -// Logger.debug("Receive " + SSOSendAssertionServlet.class + " Request"); -// try { -// -// Object idObject = req.getParameter(ID); -// -// if (idObject != null && (idObject instanceof String)) { -// id = (String) idObject; -// } -// -// String value = req.getParameter(PARAM); -// value = StringEscapeUtils.escapeHtml(value); -// if (!ParamValidatorUtils.isValidUseMandate(value)) -// throw new WrongParametersException("SSOSendAssertionServlet", PARAM, null); -// -// //get module and action -// Object moduleObject = req.getParameter(MODULE); -// String module = null; -// if (moduleObject != null && (moduleObject instanceof String)) { -// module = (String) moduleObject; -// } -// -// -// Object actionObject = req.getParameter(ACTION); -// String action = null; -// if (actionObject != null && (actionObject instanceof String)) { -// action = (String) actionObject; -// } -// -// if (MiscUtil.isEmpty(module) || MiscUtil.isEmpty(action) || MiscUtil.isEmpty(id)) { -// Logger.warn("No Moduel or Action parameter received!"); -// throw new WrongParametersException("Module or Action is empty", "", "auth.10"); -// } -// -// -// SSOManager ssomanager = SSOManager.getInstance(); -// //get SSO Cookie for Request -// String ssoId = ssomanager.getSSOSessionID(req); -// -// //check SSO session -// 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); -// -// -// AuthenticationSessionStoreage.destroySession(correspondingMOASession); -// -// ssomanager.deleteSSOSessionID(req, resp); -// } -// } -// -// boolean isValidSSOSession = ssomanager.isValidSSOSession(ssoId, null); -// -// String moaSessionID = null; -// -// if (isValidSSOSession) { -// -// -// //check UseMandate flag -// String valueString = null;; -// if ((value != null) && (value.compareTo("") != 0)) { -// valueString = value; -// } else { -// valueString = "false"; -// } -// -// if (valueString.compareToIgnoreCase("true") == 0) { -// moaSessionID = AuthenticationSessionStoreage.getMOASessionSSOID(ssoId); -// AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moaSessionID); -// AuthenticationSessionStoreage.setAuthenticated(moaSessionID, true); -// -// //log event -// //String pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); -// IRequest pendingReq = RequestStorage.getPendingRequest(id); -// MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_FINISHED); -// -// //TODO: only for development!!!!!!! -//// String redirectURL = new DataURLBuilder().buildDataURL(moasession.getAuthURL(), -//// ModulUtils.buildAuthURL(module, action, id), ""); -// -// String redirectURL = "Remove commants in Class:SSOSendAssertionServlet Line:141"; -// -// resp.setContentType("text/html"); -// resp.setStatus(302); -// -// -// resp.addHeader("Location", redirectURL); -// Logger.debug("REDIRECT TO: " + redirectURL); -// -// } -// -// else { -// throw new AuthenticationException("auth.21", new Object[] {}); -// } -// -// } else { -// handleError("SSO Session is not valid", null, req, resp, id); -// } -// -// -// } catch (MOADatabaseException e) { -// handleError("SSO Session is not found", e, req, resp, id); -// -// } catch (WrongParametersException e) { -// handleError("Parameter is not valid", e, req, resp, id); -// -// } catch (AuthenticationException e) { -// handleError(e.getMessage(), e, req, resp, id); -// -// } catch (Exception e) { -// Logger.error("SSOSendAssertion has an interal Error.", e); -// } -// -// } -// -//} 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 4131e49fc..7863c684e 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 @@ -23,7 +23,6 @@ package at.gv.egovernment.moa.id.moduls; import java.io.IOException; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; @@ -53,6 +52,7 @@ 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.exception.MOAIDException; +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.db.dao.session.InterfederationSessionStore; @@ -101,52 +101,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { public AuthenticationManager() { } - - /** - * 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 MOASession exists - * - * @return true if session is already authenticated, otherwise false - * @throws MOAIDException - */ - private boolean tryPerformAuthentication(RequestImpl protocolRequest, AuthenticationSession moaSession) { - - //if no MOASession exist -> authentication is required - if (moaSession == null) { - return false; - } else { - //if MOASession is Found but not authenticated --> authentication is required - if (!moaSession.isAuthenticated()) { - return false; - } - - //if MOASession is already authenticated and protocol-request is authenticated - // --> no authentication is required any more - else if (moaSession.isAuthenticated() && protocolRequest.isAuthenticated()) { - return true; - - // if MOASession is authenticated and SSO is allowed --> authenticate pendingRequest - } else if (!protocolRequest.isAuthenticated() - && moaSession.isAuthenticated() && protocolRequest.needSingleSignOnFunctionality()) { - Logger.debug("Found active MOASession and SSO is allowed --> pendingRequest is authenticted"); - protocolRequest.setAuthenticated(true); - protocolRequest.setMOASessionIdentifier(moaSession.getSessionID()); - return true; - - } - - // force authentication as backup solution - else { - Logger.warn("Authentication-required check find an unsuspected state --> force authentication"); - return false; - - } - } - } - public void performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { performSingleLogOut(httpReq, httpResp, session, pvpReq, null); @@ -159,163 +114,6 @@ public class AuthenticationManager extends MOAIDAuthConstants { } - - private void performSingleLogOut(HttpServletRequest httpReq, - HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq, String authURL) throws MOAIDException { - String pvpSLOIssuer = null; - String inboundRelayState = null; - - if (pvpReq != null) { - MOARequest samlReq = (MOARequest) pvpReq.getRequest(); - LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); - pvpSLOIssuer = logOutReq.getIssuer().getValue(); - inboundRelayState = samlReq.getRelayState(); - - } - - //store active OAs to SLOContaine - List dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(session); - List dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(session); - SLOInformationContainer sloContainer = new SLOInformationContainer(); - sloContainer.setSloRequest(pvpReq); - sloContainer.parseActiveIDPs(dbIDPs, pvpSLOIssuer); - sloContainer.parseActiveOAs(dbOAs, pvpSLOIssuer); - - //terminate MOASession - try { - authenticatedSessionStore.destroySession(session.getSessionID()); - ssoManager.deleteSSOSessionID(httpReq, httpResp); - - } catch (MOADatabaseException e) { - Logger.warn("Delete MOASession FAILED."); - sloContainer.putFailedOA(pvpReq.getAuthURL()); - - } - - //start service provider back channel logout process - Iterator nextOAInterator = sloContainer.getNextBackChannelOA(); - while (nextOAInterator.hasNext()) { - SLOInformationImpl sloDescr = sloContainer.getBackChannelOASessionDescripten(nextOAInterator.next()); - LogoutRequest sloReq = SingleLogOutBuilder.buildSLORequestMessage(sloDescr); - - try { - List 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 " + sloReq.getIssuer().getValue() - + " FAILED. NO LogOut response received."); - sloContainer.putFailedOA(sloReq.getIssuer().getValue()); - - } else { - SAMLVerificationEngine engine = new SAMLVerificationEngine(); - engine.verifySLOResponse(sloResp, - TrustEngineFactory.getSignatureKnownKeysTrustEngine()); - - } - - SingleLogOutBuilder.checkStatusCode(sloContainer, sloResp); - - } catch (SOAPException e) { - Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() - + " FAILED.", e); - sloContainer.putFailedOA(sloReq.getIssuer().getValue()); - - } catch (SecurityException | InvalidProtocolRequestException e) { - Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() - + " FAILED.", e); - sloContainer.putFailedOA(sloReq.getIssuer().getValue()); - - } - } - - //start service provider front channel logout process - try { - if (sloContainer.hasFrontChannelOA()) { - String relayState = Random.nextRandom(); - - Collection> sloDescr = sloContainer.getFrontChannelOASessionDescriptions(); - List sloReqList = new ArrayList(); - for (Entry el : sloDescr) { - LogoutRequest sloReq = SingleLogOutBuilder.buildSLORequestMessage(el.getValue()); - try { - sloReqList.add(SingleLogOutBuilder.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); - - if (MiscUtil.isEmpty(authURL)) - authURL = pvpReq.getAuthURL(); - - String timeOutURL = authURL - + "/idpSingleLogout" - + "?restart=" + relayState; - - VelocityContext context = new VelocityContext(); - context.put("redirectURLs", sloReqList); - context.put("timeoutURL", timeOutURL); - context.put("timeout", SLOTIMEOUT); - ssoManager.printSingleLogOutInfo(context, httpResp); - - - } else { - if (pvpReq != null) { - //send SLO response to SLO request issuer - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, sloContainer.getSloFailedOAs()); - SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); - - } else { - //print SLO information directly - VelocityContext context = new VelocityContext(); - if (sloContainer.getSloFailedOAs() == null || - sloContainer.getSloFailedOAs().size() == 0) - context.put("successMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.00", null)); - else - context.put("errorMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssoManager.printSingleLogOutInfo(context, httpResp); - - } - - } - - } catch (MOADatabaseException e) { - Logger.error("MOA AssertionDatabase ERROR", e); - if (pvpReq != null) { - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); - - }else { - //print SLO information directly - VelocityContext context = new VelocityContext(); - context.put("errorMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssoManager.printSingleLogOutInfo(context, httpResp); - - } - - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - public void performOnlyIDPLogOut(HttpServletRequest request, HttpServletResponse response, String moaSessionID) { Logger.info("Logout"); @@ -387,7 +185,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { //check if interfederation IDP is requested ssoManager.checkInterfederationIsRequested(httpReq, httpResp, pendingReq); - //check SSO session + //check if SSO session cookie is already used if (ssoId != null) { String correspondingMOASession = ssoManager.existsOldSSOSession(ssoId); @@ -402,21 +200,22 @@ public class AuthenticationManager extends MOAIDAuthConstants { ssoManager.deleteSSOSessionID(httpReq, httpResp); } } - + + //check if SSO Session is valid + boolean isValidSSOSession = ssoManager.isValidSSOSession(ssoId, pendingReq); + // check if Service-Provider allows SSO sessions IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - boolean useSSOOA = oaParam.useSSO() || oaParam.isInderfederationIDP(); + boolean useSSOOA = oaParam.useSSO() || oaParam.isInderfederationIDP(); revisionsLogger.logEvent(oaParam, pendingReq, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, pendingReq.getOAURL()); //if a legacy request is used SSO should not be allowed in case of mandate authentication boolean isUseMandateRequested = LegacyHelper.isUseMandateRequested(httpReq); - - //check if SSO Session is valid - boolean isValidSSOSession = ssoManager.isValidSSOSession(ssoId, pendingReq); - + //check if SSO is allowed for the actually executed request + //INFO: Actually, useMandate disables SSO functionality!!!!! boolean isSSOAllowed = (useSSOOA && !isUseMandateRequested); pendingReq.setNeedSingleSignOnFunctionality(isSSOAllowed); @@ -428,6 +227,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { if (moaSession == 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); @@ -436,25 +236,22 @@ public class AuthenticationManager extends MOAIDAuthConstants { } //check if session is already authenticated - boolean tryperform = tryPerformAuthentication((RequestImpl) pendingReq, moaSession); - - //perfom SSO-Consents question if it it required - if (tryperform && isSSOAllowed && oaParam.useSSOQuestion()) { - sendTransmitAssertionQuestion(httpReq, httpResp, pendingReq, oaParam); - return null; - - } - + boolean isSessionAuthenticated = tryPerformAuthentication((RequestImpl) pendingReq, moaSession); + //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 (tryperform) { + if (isSessionAuthenticated) { // Passive authentication ok! - revisionsLogger.logEvent(oaParam, - pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); + revisionsLogger.logEvent(oaParam, pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); return moaSession; } else { @@ -462,7 +259,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { } } else { - if (tryperform) { + if (isSessionAuthenticated) { // Is authenticated .. proceed revisionsLogger.logEvent(oaParam, pendingReq, MOAIDEventConstants.AUTHPROCESS_FINISHED); @@ -476,6 +273,50 @@ public class AuthenticationManager extends MOAIDAuthConstants { } } + /** + * 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 moaSession) { + + //if no MOASession exist -> authentication is required + if (moaSession == null) { + return false; + + } else { + //if MOASession is Found but not authenticated --> authentication is required + if (!moaSession.isAuthenticated()) { + return false; + } + + //if MOASession is already authenticated and protocol-request is authenticated + // --> no authentication is required any more + else if (moaSession.isAuthenticated() && protocolRequest.isAuthenticated()) { + return true; + + // if MOASession is authenticated and SSO is allowed --> authenticate pendingRequest + } else if (!protocolRequest.isAuthenticated() + && moaSession.isAuthenticated() && protocolRequest.needSingleSignOnFunctionality()) { + Logger.debug("Found active MOASession and SSO is allowed --> pendingRequest is authenticted"); + protocolRequest.setAuthenticated(true); + protocolRequest.setMOASessionIdentifier(moaSession.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) @@ -505,37 +346,64 @@ public class AuthenticationManager extends MOAIDAuthConstants { } //create authentication process execution context - try { - // create execution context + ExecutionContext executionContext = new ExecutionContextImpl(); + + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID, + MiscUtil.isNotEmpty( + pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); + + boolean leagacyMode = (legacyallowed && legacyparamavail); + executionContext.put("isLegacyRequest", leagacyMode); + executionContext.put("performBKUSelection", !leagacyMode + && MiscUtil.isEmpty(pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); + + //add leagcy parameters to context + if (leagacyMode) { + Enumeration reqParamNames = httpReq.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (MiscUtil.isNotEmpty(paramName) && + MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName)) + executionContext.put(paramName, 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(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, pendingReq.getRequestID()); - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID, - MiscUtil.isNotEmpty( - pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); + executionContext.put(SingleSignOnConsentsModuleImpl.PARAM_SSO_CONSENTS_EVALUATION, true); - boolean leagacyMode = (legacyallowed && legacyparamavail); - executionContext.put("isLegacyRequest", leagacyMode); - executionContext.put("performBKUSelection", !leagacyMode - && MiscUtil.isEmpty(pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); - - //add leagcy parameters to context - if (leagacyMode) { - Enumeration reqParamNames = httpReq.getParameterNames(); - while(reqParamNames.hasMoreElements()) { - String paramName = reqParamNames.nextElement(); - if (MiscUtil.isNotEmpty(paramName) && - MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName)) - executionContext.put(paramName, httpReq.getParameter(paramName)); - - } - } + //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 " + moasession.getSessionID() ); + Logger.warn("No suitable process found for SessionID " + pendingReq.getRequestID() ); throw new MOAIDException("process.02",new Object[] { - moasession.getSessionID()}); + pendingReq.getRequestID()}); } String processInstanceId = processEngine.createProcessInstance(processDefinitionId, executionContext); @@ -545,18 +413,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { //store pending-request requestStoreage.storePendingRequest(pendingReq); - - - // make sure moa session has been persisted before running the process - try { - authenticatedSessionStore.storeSession(moasession); - - } catch (MOADatabaseException e) { - Logger.error("Database Error! MOASession is not stored!"); - throw new MOAIDException("init.04", new Object[] { - moasession.getSessionID()}); - } - + // start process processEngine.start(processInstanceId); @@ -572,32 +429,163 @@ public class AuthenticationManager extends MOAIDAuthConstants { } } - throw new MOAIDException("process.01", new Object[] { pendingReq.getProcessInstanceId(), moasession }, e); - } + throw new MOAIDException("process.01", new Object[] { pendingReq.getProcessInstanceId(), pendingReq.getRequestID() }, e); + } } - - private void sendTransmitAssertionQuestion(HttpServletRequest request, - HttpServletResponse response, IRequest target, IOAAuthParameters oaParam) - throws ServletException, IOException, MOAIDException { - - //TODO: change to process management version!!!! + + private void performSingleLogOut(HttpServletRequest httpReq, + HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq, String authURL) throws MOAIDException { + String pvpSLOIssuer = null; + String inboundRelayState = null; - //set authenticated flag to false, because user consents is required - target.setAuthenticated(false); + if (pvpReq != null) { + MOARequest samlReq = (MOARequest) pvpReq.getRequest(); + LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); + pvpSLOIssuer = logOutReq.getIssuer().getValue(); + inboundRelayState = samlReq.getRelayState(); + + } + //store active OAs to SLOContaine + List dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(session); + List dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(session); + SLOInformationContainer sloContainer = new SLOInformationContainer(); + sloContainer.setSloRequest(pvpReq); + sloContainer.parseActiveIDPs(dbIDPs, pvpSLOIssuer); + sloContainer.parseActiveOAs(dbOAs, pvpSLOIssuer); + + //terminate MOASession + try { + authenticatedSessionStore.destroySession(session.getSessionID()); + ssoManager.deleteSSOSessionID(httpReq, httpResp); -// String form = SendAssertionFormBuilder.buildForm(target.requestedModule(), -// target.requestedAction(), target.getRequestID(), oaParam, -// target.getAuthURL()); - - String form =null; + } catch (MOADatabaseException e) { + Logger.warn("Delete MOASession FAILED."); + sloContainer.putFailedOA(pvpReq.getAuthURL()); - revisionsLogger.logEvent(target.getOnlineApplicationConfiguration(), - target, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_START); + } + + //start service provider back channel logout process + Iterator nextOAInterator = sloContainer.getNextBackChannelOA(); + while (nextOAInterator.hasNext()) { + SLOInformationImpl sloDescr = sloContainer.getBackChannelOASessionDescripten(nextOAInterator.next()); + LogoutRequest sloReq = SingleLogOutBuilder.buildSLORequestMessage(sloDescr); + + try { + List 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 " + sloReq.getIssuer().getValue() + + " FAILED. NO LogOut response received."); + sloContainer.putFailedOA(sloReq.getIssuer().getValue()); + + } else { + SAMLVerificationEngine engine = new SAMLVerificationEngine(); + engine.verifySLOResponse(sloResp, + TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + + } + + SingleLogOutBuilder.checkStatusCode(sloContainer, sloResp); + + } catch (SOAPException e) { + Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() + + " FAILED.", e); + sloContainer.putFailedOA(sloReq.getIssuer().getValue()); + + } catch (SecurityException | InvalidProtocolRequestException e) { + Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() + + " FAILED.", e); + sloContainer.putFailedOA(sloReq.getIssuer().getValue()); + + } + } + + //start service provider front channel logout process + try { + if (sloContainer.hasFrontChannelOA()) { + String relayState = Random.nextRandom(); + + Collection> sloDescr = sloContainer.getFrontChannelOASessionDescriptions(); + List sloReqList = new ArrayList(); + for (Entry el : sloDescr) { + LogoutRequest sloReq = SingleLogOutBuilder.buildSLORequestMessage(el.getValue()); + try { + sloReqList.add(SingleLogOutBuilder.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); + + if (MiscUtil.isEmpty(authURL)) + authURL = pvpReq.getAuthURL(); + + String timeOutURL = authURL + + "/idpSingleLogout" + + "?restart=" + relayState; + + VelocityContext context = new VelocityContext(); + context.put("redirectURLs", sloReqList); + context.put("timeoutURL", timeOutURL); + context.put("timeout", SLOTIMEOUT); + ssoManager.printSingleLogOutInfo(context, httpResp); + + + } else { + if (pvpReq != null) { + //send SLO response to SLO request issuer + SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); + LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, sloContainer.getSloFailedOAs()); + SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); + + } else { + //print SLO information directly + VelocityContext context = new VelocityContext(); + if (sloContainer.getSloFailedOAs() == null || + sloContainer.getSloFailedOAs().size() == 0) + context.put("successMsg", + MOAIDMessageProvider.getInstance().getMessage("slo.00", null)); + else + context.put("errorMsg", + MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); + ssoManager.printSingleLogOutInfo(context, httpResp); + + } + + } + + } catch (MOADatabaseException e) { + Logger.error("MOA AssertionDatabase ERROR", e); + if (pvpReq != null) { + SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); + LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); + + }else { + //print SLO information directly + VelocityContext context = new VelocityContext(); + context.put("errorMsg", + MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); + ssoManager.printSingleLogOutInfo(context, httpResp); + + } - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(form); - out.flush(); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } } -- cgit v1.2.3 From 7cc2776bfc79dd6e83f2b3c9b642b560a6b1ec94 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 19 Feb 2016 12:08:52 +0100 Subject: optimize authentication process in respect to session-transaction and transaction-store read/write operations --- .../id/auth/modules/AbstractAuthServletTask.java | 58 ++++++++++--------- .../tasks/CreateInterfedeartionRequestTask.java | 4 -- .../internal/tasks/EvaluateBKUSelectionTask.java | 65 ++++------------------ .../internal/tasks/FinalizeAuthenticationTask.java | 47 ++-------------- .../tasks/GenerateBKUSelectionFrameTask.java | 12 +--- .../tasks/RestartAuthProzessManagement.java | 16 +----- .../StartAuthentificationParameterParser.java | 1 + .../AbstractProcessEngineSignalController.java | 7 ++- .../moa/id/moduls/AuthenticationManager.java | 6 +- .../egovernment/moa/id/process/ProcessEngine.java | 13 +++-- .../moa/id/process/ProcessEngineImpl.java | 52 +++++++++++++---- .../at/gv/egovernment/moa/id/process/api/Task.java | 7 ++- .../moa/id/process/springweb/MoaIdTask.java | 29 +++++++++- 13 files changed, 139 insertions(+), 178 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 index 559d4fd4f..8c7583855 100644 --- 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 @@ -1,7 +1,5 @@ package at.gv.egovernment.moa.id.auth.modules; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; @@ -19,13 +17,10 @@ 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.lang.StringEscapeUtils; import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.ObjectUtils; import org.springframework.beans.factory.annotation.Autowired; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -56,31 +51,40 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { protected IRequest pendingReq = null; protected AuthenticationSession moasession = null; - protected void defaultTaskInitialization(HttpServletRequest req, ExecutionContext executionContext) throws MOAIDException, MOADatabaseException { - String pendingRequestID = StringEscapeUtils.escapeHtml( - ObjectUtils.defaultIfNull( - (String) executionContext.get(PARAM_TARGET_PENDINGREQUESTID), - req.getParameter(PARAM_TARGET_PENDINGREQUESTID))); + 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; - if (MiscUtil.isEmpty(pendingRequestID)) { - Logger.info("No PendingRequestID received"); - throw new MOAIDException("auth.10", new Object[]{"VerifyIdentityLink", "pendingRequestID"}); - } + //execute task specific action + execute(executionContext, request, response); - pendingReq = requestStoreage.getPendingRequest(pendingRequestID); + //return pending-request object + return this.pendingReq; + } - if (pendingReq == null) { - Logger.info("No PendingRequest with Id: " + pendingRequestID + " Maybe, a transaction timeout occure."); - throw new MOAIDException("auth.28", new Object[]{pendingRequestID}); - + + /** + * 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 { + String moasessionid = pendingReq.getMOASessionIdentifier(); + if (MiscUtil.isEmpty(moasessionid)) { + Logger.warn("MOASessionID is empty."); + throw new MOAIDException("auth.18", new Object[] {}); } - - //change pending-request ID - String newPendingRequestID = requestStoreage.changePendingRequestID(pendingReq); - executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, newPendingRequestID); - + try { - moasession = authenticatedSessionStorage.getSession(pendingReq.getMOASessionIdentifier()); + moasession = authenticatedSessionStorage.getSession(moasessionid); if (moasession == null) { Logger.warn("MOASessionID is empty."); @@ -88,8 +92,8 @@ public abstract class AbstractAuthServletTask extends MoaIdTask { } } catch (MOADatabaseException e) { - Logger.info("MOASession with SessionID=" + pendingReq.getMOASessionIdentifier() + " is not found in Database"); - throw new MOAIDException("init.04", new Object[] { pendingReq.getMOASessionIdentifier() }); + Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); + throw new MOAIDException("init.04", new Object[] { moasessionid }); } catch (Throwable e) { Logger.info("No HTTP Session found!"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java index d0c12a6f3..951a04cf6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java @@ -55,7 +55,6 @@ import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; @@ -85,9 +84,6 @@ public class CreateInterfedeartionRequestTask extends AbstractAuthServletTask { throws TaskExecutionException { boolean requiredLocalAuthentication = true; - IRequest pendingReq = requestStoreage.getPendingRequest( - (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); - String idpEntityID = (String) executionContext.get(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID); 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 3b18959a5..2f6137244 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 @@ -31,10 +31,8 @@ import org.apache.commons.lang.StringEscapeUtils; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -53,60 +51,19 @@ public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { try { - //load pending request - String pendingReqID = request.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID); - pendingReqID = StringEscapeUtils.escapeHtml(pendingReqID); - pendingReq = requestStoreage.getPendingRequest(pendingReqID); - - if (pendingReq == null) { - Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); - throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); - - } - - //change pending-request ID - String newPendingRequestID = requestStoreage.changePendingRequestID(pendingReq); - executionContext.put(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID, newPendingRequestID); - - String moaSessionID = pendingReq.getMOASessionIdentifier(); - try { - moasession = authenticatedSessionStorage.getSession(moaSessionID); - - if (moasession == null) { - Logger.info("MOASession with SessionID="+ moaSessionID + " is not found in Database"); - throw new MOAIDException("init.04", new Object[] { - moaSessionID}); - - } - - // set parameter execution context - Enumeration reqParamNames = request.getParameterNames(); - while(reqParamNames.hasMoreElements()) { - String paramName = reqParamNames.nextElement(); - if (MiscUtil.isNotEmpty(paramName) && - !MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID.equalsIgnoreCase(paramName)) - executionContext.put(paramName, request.getParameter(paramName)); - - } - - Logger.info("BKU is selected finished -> Start BKU communication ..."); - - } catch (MOADatabaseException e) { - Logger.info("MOASession with SessionID="+ moaSessionID + " is not found in Database"); - throw new MOAIDException("init.04", new Object[] { - moaSessionID}); + // set parameter execution context + Enumeration reqParamNames = request.getParameterNames(); + while(reqParamNames.hasMoreElements()) { + String paramName = reqParamNames.nextElement(); + if (MiscUtil.isNotEmpty(paramName) && + !MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID.equalsIgnoreCase(paramName)) + executionContext.put(paramName, + StringEscapeUtils.escapeHtml(request.getParameter(paramName))); - } catch (Throwable e) { - Logger.info("No HTTP Session found!"); - throw new MOAIDException("auth.18", new Object[] {}); } - - - - - } catch (MOAIDException e) { - throw new TaskExecutionException(pendingReq, e.getMessage(), e); - + + Logger.info("BKU is selected finished -> Start BKU selection evaluation ..."); + } catch (Exception e) { Logger.warn("EvaluateBKUSelectionTask 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/FinalizeAuthenticationTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java index d1d2cdca8..816c05eab 100644 --- 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 @@ -31,11 +31,9 @@ import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -53,44 +51,8 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { throws TaskExecutionException { try { - pendingReq = requestStoreage.getPendingRequest( - (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); - - if (pendingReq == null) { - Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); - throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); - - } - - //get Session from context - String moasessionid = pendingReq.getMOASessionIdentifier(); - if (MiscUtil.isEmpty(moasessionid)) { - Logger.warn("MOASessionID is empty."); - throw new MOAIDException("auth.18", new Object[] {}); - } - - try { - moasession = authenticatedSessionStorage.getSession(moasessionid); - if (moasession == null) { - Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); - throw new MOAIDException("init.04", new Object[] { moasessionid }); - - } - - - } catch (MOADatabaseException e) { - Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); - throw new MOAIDException("init.04", new Object[] { moasessionid }); - - } catch (Throwable e) { - Logger.info("No HTTP Session found!"); - throw new MOAIDException("auth.18", new Object[] {}); - - } finally { - executionContext.remove(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID); - - } - + defaultTaskInitialization(request, executionContext); + //set MOASession to authenticated and store MOASession moasession.setAuthenticated(true); String newMOASessionID = authenticatedSessionStorage.changeSessionID(moasession); @@ -110,8 +72,11 @@ public class FinalizeAuthenticationTask extends AbstractAuthServletTask { 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 47b68bc51..6ff730898 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 @@ -30,7 +30,6 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.LoginFormBuilder; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -53,16 +52,7 @@ public class GenerateBKUSelectionFrameTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { - try { - pendingReq = requestStoreage.getPendingRequest( - (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); - - if (pendingReq == null) { - Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); - throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); - - } - + try { revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUSELECTION_INIT); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java index d7859dd8b..920b0e2b4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java @@ -30,12 +30,10 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.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.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.process.ExecutionContextImpl; import at.gv.egovernment.moa.id.process.ProcessEngine; @@ -57,17 +55,7 @@ public class RestartAuthProzessManagement extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { - IRequest pendingReq = null; - try { - pendingReq = requestStoreage.getPendingRequest( - (String) executionContext.get(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); - - if (pendingReq == null) { - Logger.info("No PendingRequest with Id: " + executionContext.get("pendingRequestID") + " Maybe, a transaction timeout occure."); - throw new MOAIDException("auth.28", new Object[]{executionContext.get("pendingRequestID")}); - - } - + try { //create a new execution context and copy all elements to new context ExecutionContext newec = new ExecutionContextImpl(); Set entries = executionContext.keySet(); @@ -107,7 +95,7 @@ public class RestartAuthProzessManagement extends AbstractAuthServletTask { Logger.info("BKU is selected -> Start BKU communication ..."); // start process - processEngine.start(processInstanceId); + processEngine.start(pendingReq); } catch (MOAIDException e) { 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 3699633bd..b7e95785b 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 @@ -199,6 +199,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ if (!ParamValidatorUtils.isValidTemplate(req, templateURL, oaParam.getTemplateURL())) throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12"); + protocolReq.setGenericDataToSession( MOAIDAuthConstants.AUTHPROCESS_DATA_SECURITYLAYERTEMPLATE, templateURL); 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 index 2abe1582d..8b96b884e 100644 --- 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 @@ -40,6 +40,9 @@ public abstract class AbstractProcessEngineSignalController extends AbstractCont } + //change pending-request ID + requestStorage.changePendingRequestID(pendingReq); + //add transactionID and unique sessionID to Logger TransactionIDUtils.setSessionId(pendingReq.getUniqueSessionIdentifier()); TransactionIDUtils.setTransactionId(pendingReq.getUniqueTransactionIdentifier()); @@ -50,9 +53,7 @@ public abstract class AbstractProcessEngineSignalController extends AbstractCont } // wake up next task - processEngine.signal(pendingReq.getProcessInstanceId()); - - //TODO: + processEngine.signal(pendingReq); } catch (Exception ex) { handleError(null, ex, req, resp, pendingRequestID); 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 7863c684e..f77042bc5 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 @@ -34,6 +34,7 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.apache.commons.lang.StringEscapeUtils; import org.apache.velocity.VelocityContext; import org.opensaml.saml2.core.LogoutRequest; import org.opensaml.saml2.core.LogoutResponse; @@ -364,7 +365,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { String paramName = reqParamNames.nextElement(); if (MiscUtil.isNotEmpty(paramName) && MOAIDAuthConstants.LEGACYPARAMETERWHITELIST.contains(paramName)) - executionContext.put(paramName, httpReq.getParameter(paramName)); + executionContext.put(paramName, + StringEscapeUtils.escapeHtml(httpReq.getParameter(paramName))); } } @@ -415,7 +417,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { requestStoreage.storePendingRequest(pendingReq); // start process - processEngine.start(processInstanceId); + processEngine.start(pendingReq); } catch (ProcessExecutionException e) { Throwable cause = e.getCause(); 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 index 26301d664..b68f170c8 100644 --- 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 @@ -3,6 +3,7 @@ package at.gv.egovernment.moa.id.process; import java.io.InputStream; +import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.process.model.ProcessDefinition; @@ -86,24 +87,24 @@ public interface ProcessEngine { ProcessInstance getProcessInstance(String processInstanceId); /** - * Starts the process using the given {@code processInstanceId}. + * Starts the process using the given {@code pendingReq}. * - * @param processInstanceId - * The process instance id. + * @param pendingReq + * The protocol request for which a process should be started. * @throws ProcessExecutionException * Thrown in case of error. */ - void start(String processInstanceId) throws ProcessExecutionException; + void start(IRequest pendingReq) throws ProcessExecutionException; /** * Resumes process execution after an asynchronous task has been executed. * - * @param processInstanceId + * @param pendingReq * The process instance id. * @throws ProcessExecutionException * Thrown in case of error. */ - void signal(String processInstanceId) throws ProcessExecutionException; + 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 index 6da695d75..437eee63c 100644 --- 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 @@ -15,7 +15,9 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.moduls.IRequest; 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; @@ -116,10 +118,16 @@ public class ProcessEngineImpl implements ProcessEngine { } @Override - public void start(String processInstanceId) throws ProcessExecutionException { - + public void start(IRequest pendingReq) throws ProcessExecutionException { try { - ProcessInstance pi = loadProcessInstance(processInstanceId); + 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()); MDC.put(MDC_CTX_PI_NAME, pi.getId()); @@ -129,9 +137,12 @@ public class ProcessEngineImpl implements ProcessEngine { log.info("Starting process instance '{}'.", pi.getId()); // execute process pi.setState(ProcessInstanceState.STARTED); - execute(pi); + execute(pi, pendingReq); - saveOrUpdateProcessInstance(pi); + //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); @@ -141,10 +152,17 @@ public class ProcessEngineImpl implements ProcessEngine { } @Override - public void signal(String processInstanceId) throws ProcessExecutionException { + public void signal(IRequest pendingReq) throws ProcessExecutionException { try { - ProcessInstance pi = loadProcessInstance(processInstanceId); + 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()); MDC.put(MDC_CTX_PI_NAME, pi.getId()); @@ -154,9 +172,16 @@ public class ProcessEngineImpl implements ProcessEngine { log.info("Waking up process instance '{}'.", pi.getId()); pi.setState(ProcessInstanceState.STARTED); - execute(pi); - saveOrUpdateProcessInstance(pi); + //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); @@ -204,9 +229,10 @@ public class ProcessEngineImpl implements ProcessEngine { /** * 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) throws ProcessExecutionException { + 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."); } @@ -227,7 +253,7 @@ public class ProcessEngineImpl implements ProcessEngine { try { log.info("Executing task implementation for task '{}'.", ti.getId()); log.debug("Execution context before task execution: {}", pi.getExecutionContext().keySet()); - task.execute(pi.getExecutionContext()); + 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) { @@ -245,8 +271,10 @@ public class ProcessEngineImpl implements ProcessEngine { 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()); @@ -284,7 +312,7 @@ public class ProcessEngineImpl implements ProcessEngine { // continue execution in case of StartEvent or Task if (processNode instanceof StartEvent || processNode instanceof TaskInfo) { - execute(pi); + execute(pi, pendingReq); } } 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 index 343b8fe0c..88048d23e 100644 --- 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 @@ -1,6 +1,7 @@ package at.gv.egovernment.moa.id.process.api; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.moduls.IRequest; /** @@ -13,11 +14,13 @@ 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. */ - void execute(ExecutionContext executionContext) throws TaskExecutionException; + IRequest execute(IRequest pendingReq, ExecutionContext executionContext) throws TaskExecutionException; } 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 index fb75fc8d7..b60434b2a 100644 --- 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 @@ -9,6 +9,7 @@ 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.moduls.IRequest; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.process.api.Task; @@ -32,6 +33,7 @@ import at.gv.egovernment.moa.id.process.api.Task; * * * @author tknall + * @author tlenz * */ public abstract class MoaIdTask implements Task { @@ -55,8 +57,31 @@ public abstract class MoaIdTask implements 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 void execute(ExecutionContext executionContext) throws TaskExecutionException { + public IRequest execute(IRequest pendingReq, ExecutionContext executionContext) throws TaskExecutionException { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) { HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); @@ -65,7 +90,7 @@ public abstract class MoaIdTask implements Task { 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."); } - execute(executionContext, request, response); + return internalExecute(pendingReq, executionContext, request, response); } else { throw new IllegalStateException("Task needs to be executed within a Spring web environment."); } -- cgit v1.2.3 From 17896537333aeff69ed35bbd531a01c1fccb0397 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 19 Feb 2016 12:30:37 +0100 Subject: add missing endpoint description --- .../gv/egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 87d41dbf1..84a2b69af 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 @@ -33,6 +33,8 @@ import org.opensaml.saml2.core.LogoutResponse; import org.opensaml.saml2.metadata.SingleLogoutService; 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.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; @@ -64,7 +66,8 @@ public class IDPSingleLogOutServlet extends AbstractController { @Autowired AuthenticationManager authManager; @Autowired IAuthenticationSessionStoreage authenicationStorage; - protected void doGet(HttpServletRequest req, HttpServletResponse resp) + @RequestMapping(value = "/idpSingleLogout", method = {RequestMethod.GET}) + public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Logger.debug("receive IDP SingleLogOut Request"); -- cgit v1.2.3 From 15ed0195ac3819a1a8e872401517df522ac2c04c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 19 Feb 2016 12:31:10 +0100 Subject: add missing @Service annotation --- .../gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java | 3 ++- .../at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index f48d216dd..08aa76e58 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -27,7 +27,6 @@ import javax.servlet.http.HttpServletResponse; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; -import org.opensaml.common.binding.SAMLMessageContext; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.decoding.HTTPRedirectDeflateDecoder; import org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder; @@ -49,6 +48,7 @@ import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.x509.X509Credential; +import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; @@ -66,6 +66,7 @@ import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@Service("PVPRedirectBindingCoder") public class RedirectBinding implements IDecoder, IEncoder { public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index c1e94ff36..d42d91105 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -29,7 +29,6 @@ import javax.servlet.http.HttpServletResponse; import org.opensaml.common.SAMLObject; import org.opensaml.common.binding.BasicSAMLMessageContext; -import org.opensaml.common.binding.SAMLMessageContext; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.binding.encoding.HTTPSOAP11Encoder; import org.opensaml.saml2.core.RequestAbstractType; @@ -46,6 +45,7 @@ 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.stereotype.Service; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; @@ -59,6 +59,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableEx import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@Service("PVPSOAPBindingCoder") public class SoapBinding implements IDecoder, IEncoder { public InboundMessageInterface decode(HttpServletRequest req, -- cgit v1.2.3 From f3010fd5d1d8e423ee6f2a1aaca5441ccfd3f785 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 19 Feb 2016 13:15:50 +0100 Subject: remove unused code and files --- .../moa/id/entrypoints/DispatcherServlet.java | 624 --------------------- 1 file changed, 624 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java deleted file mode 100644 index c7f86c167..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ /dev/null @@ -1,624 +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.entrypoints; -// -//import java.io.IOException; -//import java.util.Iterator; -// -//import javax.servlet.ServletException; -//import javax.servlet.http.HttpServletRequest; -//import javax.servlet.http.HttpServletResponse; -// -//import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -//import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -//import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; -//import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -//import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -//import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; -//import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -//import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -//import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; -//import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -//import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; -//import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -//import at.gv.egovernment.moa.id.auth.servlet.AuthServlet; -//import at.gv.egovernment.moa.id.config.ConfigurationException; -//import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -//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.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.IRequest; -//import at.gv.egovernment.moa.id.moduls.ModulStorage; -//import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; -//import at.gv.egovernment.moa.id.moduls.RequestStorage; -//import at.gv.egovernment.moa.id.moduls.SSOManager; -//import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; -//import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -//import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; -//import at.gv.egovernment.moa.id.util.ErrorResponseUtils; -//import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -//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; -// -//public class DispatcherServlet extends AuthServlet{ -// -// /** -// * -// */ -// private static final long serialVersionUID = 1L; -// -// public static final String PARAM_TARGET_MODULE = "mod"; -// public static final String PARAM_TARGET_ACTION = "action"; -// public static final String PARAM_TARGET_PENDINGREQUESTID = "pendingid"; -// -//// @Override -//// public void init(ServletConfig config) throws ServletException { -//// try { -//// super.init(config); -//// MOAIDAuthInitializer.initialize(); -//// Logger.info(MOAIDMessageProvider.getInstance().getMessage( -//// "init.00", null)); -//// -//// Logger.info("Dispatcher Servlet initialization finished."); -//// -//// } catch (Exception ex) { -//// Logger.fatal( -//// MOAIDMessageProvider.getInstance().getMessage("init.02", -//// null), ex); -//// -//// //throw new ServletException(ex); -//// -//// } -//// -//// } -// -// protected void processRequest(HttpServletRequest req, -// HttpServletResponse resp) throws ServletException, IOException { -// boolean isValidSSOSession = false; -// boolean useSSOOA = false; -// String protocolRequestID = null; -// -// try { -// Logger.debug("REQUEST: " + req.getRequestURI()); -// Logger.debug("QUERY : " + req.getQueryString()); -// -// -//// *** start of error handling *** -// -// String errorid = req.getParameter(ERROR_CODE_PARAM); -// if (errorid != null) { -// -// Throwable throwable = DBExceptionStoreImpl.getStore() -// .fetchException(errorid); -// DBExceptionStoreImpl.getStore().removeException(errorid); -// -// Object idObject = req.getParameter(PARAM_TARGET_PENDINGREQUESTID); -// -// //Map errorRequests = RequestStorage.getPendingRequest(req.getSession()); -// -// String pendingRequestID = null; -// if (idObject != null && (idObject instanceof String)) { -// pendingRequestID = (String) idObject; -// } -// -// if (throwable != null) { -// -// IRequest errorRequest = null; -// if (pendingRequestID != null) { -// errorRequest = RequestStorage.getPendingRequest(pendingRequestID); -// -// } -// -// if (errorRequest != null) { -// RequestStorage.removePendingRequest(pendingRequestID); -// MOAReversionLogger.getInstance().logEvent(errorRequest, MOAIDEventConstants.TRANSACTION_ERROR); -// -// try { -// IModulInfo handlingModule = ModulStorage -// .getModuleByPath(errorRequest -// .requestedModule()); -// if (handlingModule != null) { -// -// if (handlingModule.generateErrorMessage( -// throwable, req, resp, errorRequest)) { -// -// //log Error Message -// StatisticLogger logger = StatisticLogger.getInstance(); -// logger.logErrorOperation(throwable, errorRequest); -// -// //remove MOASession -// AuthenticationSession moaSession = AuthenticationSessionStoreage.getSessionWithPendingRequestID(pendingRequestID); -// if (moaSession != null) -// AuthenticationManager.getInstance().performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); -// -// return; -// -// } else { -// handleErrorNoRedirect(throwable.getMessage(), throwable, -// req, resp); -// -// } -// } -// -// } catch (Throwable e) { -// Logger.error(e); -// handleErrorNoRedirect(throwable.getMessage(), -// throwable, req, resp); -// } -// -// } else { -// handleErrorNoRedirect(throwable.getMessage(), throwable, -// req, resp); -// } -// -// } else -// handleErrorNoRedirect(MOAIDMessageProvider.getInstance().getMessage("auth.26", null), -// null, req, resp); -// -// return; -// } -// -//// *** end of error handling *** -// -// -//// *** start of protocol specific stuff *** -// -// Object moduleObject = req.getParameter(PARAM_TARGET_MODULE); -// String module = null; -// if (moduleObject != null && (moduleObject instanceof String)) { -// module = (String) moduleObject; -// } -// -// if (module == null) { -// module = (String) req.getAttribute(PARAM_TARGET_MODULE); -// } -// -// Object actionObject = req.getParameter(PARAM_TARGET_ACTION); -// String action = null; -// if (actionObject != null && (actionObject instanceof String)) { -// action = (String) actionObject; -// } -// -// if (action == null) { -// action = req.getParameter(PARAM_TARGET_ACTION); -// } -// -// Logger.debug("dispatching to " + module + " protocol " + action); -// -// IModulInfo info = ModulStorage.getModuleByPath(module); -// -// IAction moduleAction = null; -// -// if (info == null) { -// -// Iterator modules = ModulStorage.getAllModules() -// .iterator(); -// while (modules.hasNext()) { -// info = modules.next(); -// moduleAction = info.canHandleRequest(req, resp); -// if (moduleAction != null) { -// action = moduleAction.getDefaultActionName(); -// module = info.getPath(); -// break; -// } -// info = null; -// } -// -// if (moduleAction == null) { -// resp.sendError(HttpServletResponse.SC_NOT_FOUND); -// Logger.error("Protocol " + module -// + " has no module registered"); -// return; -// } -// } -// -// if (moduleAction == null) { -// moduleAction = info.getAction(action); -// -// if (moduleAction == null) { -// resp.sendError(HttpServletResponse.SC_NOT_FOUND); -// Logger.error("Action " + action + " is not available!"); -// return; -// } -// } -// -// //get SSO Cookie for Request -// SSOManager ssomanager = SSOManager.getInstance(); -// String ssoId = ssomanager.getSSOSessionID(req); -// -// IRequest protocolRequest = null; -// String uniqueSessionIdentifier = null; -// -// try { -// Object idObject = req.getParameter(PARAM_TARGET_PENDINGREQUESTID); -// -// if (idObject != null && (idObject instanceof String)) { -// -// protocolRequestID = (String) idObject; -// protocolRequest = RequestStorage.getPendingRequest(protocolRequestID); -// -// //get IRequest if it exits -// if (protocolRequest != null) { -// Logger.debug(DispatcherServlet.class.getName()+": Found PendingRequest with ID " + protocolRequestID); -// -// } else { -// Logger.error("No PendingRequest with ID " + protocolRequestID + " found.!"); -// handleErrorNoRedirect("Während des Anmeldevorgangs ist ein Fehler aufgetreten. Bitte versuchen Sie es noch einmal.", -// null, req, resp); -// return; -// } -// } else { -// try { -// -// //load unique session identifier with SSO-sessionID -// uniqueSessionIdentifier = ssomanager.getUniqueSessionIdentifier(ssoId); -// if (MiscUtil.isEmpty(uniqueSessionIdentifier)) -// uniqueSessionIdentifier = Random.nextRandom(); -// TransactionIDUtils.setSessionId(uniqueSessionIdentifier); -// -// //set transactionID to Logger -// protocolRequestID = Random.nextRandom(); -// TransactionIDUtils.setTransactionId(protocolRequestID); -// -// //log information for security and process reversion -// MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.SESSION_CREATED, uniqueSessionIdentifier); -// MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.TRANSACTION_CREATED, protocolRequestID); -// MOAReversionLogger.getInstance().logEvent(uniqueSessionIdentifier, protocolRequestID, MOAIDEventConstants.TRANSACTION_IP, req.getRemoteAddr()); -// -// protocolRequest = info.preProcess(req, resp, action, uniqueSessionIdentifier, protocolRequestID); -// -// //request is a valid interfederation response -// if (protocolRequest != null && -// protocolRequest.getInterfederationResponse() != null ) { -// Logger.debug("Create new interfederated MOA-Session and add to HTTPRequest"); -// -// //reload SP protocol implementation -// info = ModulStorage.getModuleByPath(protocolRequest.requestedModule()); -// moduleAction = info.getAction(protocolRequest.requestedAction()); -// -// //create interfederated MOASession -// String sessionID = -// AuthenticationSessionStoreage.createInterfederatedSession(protocolRequest, true, ssoId); -// req.getParameterMap().put(MOAIDAuthConstants.PARAM_SESSIONID, new String[]{ sessionID }); -// -// Logger.info("PreProcessing of SSO interfederation response complete. "); -// -// //request is a not valid interfederation response -// } else if (protocolRequest != null && -// MiscUtil.isNotEmpty(protocolRequest.getRequestID())) { -// -// OAAuthParameter oaParams = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(protocolRequest.getOAURL()); -// if (!oaParams.isPerformLocalAuthenticationOnInterfederationError()) { -// // -> send end error to service provider -// Logger.info("Federated authentication for entity " + protocolRequest.getOAURL() -// + " FAILED. Sending error message to service provider."); -// MOAIDException e = new MOAIDException("auth.27", new Object[]{}); -// IModulInfo requestedModul = ModulStorage.getModuleByPath(protocolRequest.requestedModule()); -// if (!requestedModul.generateErrorMessage(e, req, resp, protocolRequest)) -// handleErrorNoRedirect(e.getMessage(), e, req, -// resp); -// -// return; -// -// } else -// //-> Restart local authentication -// Logger.info("Restart authentication with stored " + protocolRequest.requestedModule() -// + " AuthnRequest for OnlineApplication " + protocolRequest.getOAURL()); -// -// //request is a new authentication request -// } else if (protocolRequest != null && -// MiscUtil.isEmpty(protocolRequest.getRequestID())) { -// //Start new Authentication -// protocolRequest.setModule(module); -// -// //if preProcessing has not set a specific action from decoded request -// // then set the default action -// if (MiscUtil.isEmpty(protocolRequest.requestedAction())) -// protocolRequest.setAction(action); -// else -// moduleAction = info.getAction(protocolRequest.requestedAction()); -// -// protocolRequest.setRequestID(protocolRequestID); -// protocolRequest.setSessionIdentifier(uniqueSessionIdentifier); -// RequestStorage.setPendingRequest(protocolRequest); -// Logger.debug(DispatcherServlet.class.getName()+": Create PendingRequest with ID " + protocolRequestID + "."); -// -// -// } else { -// Logger.error("Failed to generate a valid protocol request!"); -// resp.setContentType("text/html;charset=UTF-8"); -// resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!"); -// return; -// -// } -// -// } catch (ProtocolNotActiveException e) { -// resp.getWriter().write(e.getMessage()); -// resp.setContentType("text/html;charset=UTF-8"); -// resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); -// return; -// -// } catch (AuthnRequestValidatorException e) { -// //log Error Message -// StatisticLogger logger = StatisticLogger.getInstance(); -// logger.logErrorOperation(e, e.getErrorRequest()); -// -// //TODO: maybe add some error message handling??? -// -// return; -// -// }catch (InvalidProtocolRequestException e) { -// ErrorResponseUtils utils = ErrorResponseUtils.getInstance(); -// String code = utils.mapInternalErrorToExternalError(e.getMessageId()); -// String descr = e.getMessage(); -// Logger.error("Protocol validation FAILED!"); -// resp.setContentType("text/html;charset=UTF-8"); -// resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Protocol validation FAILED!" + -// "(Errorcode=" + code + -// " | Description=" + descr + ")"); -// return; -// } catch (ConfigurationException e) { -// resp.setContentType("text/html;charset=UTF-8"); -// resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + -// "(Errorcode=9199" -// +" | Description="+ e.getMessage() + ")"); -// return; -// -// } catch (MOAIDException e) { -// Logger.error("Failed to generate a valid protocol request!"); -// resp.setContentType("text/html;charset=UTF-8"); -// resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!" + -// "(Errorcode=6000" -// +" | Description=Das Authentifizierungsprotokoll wurde nicht erkannt oder wird nicht unterst\u00FCzt" + ")"); -// return; -// -// } -// } -// -//// *** end of protocol specific stuff *** -// -// if (protocolRequest != null) -// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), -// protocolRequest, MOAIDEventConstants.AUTHPROTOCOL_TYPE, protocolRequest.requestedModule()); -// -//// *** start handling authentication *** -// -// AuthenticationManager authmanager = AuthenticationManager.getInstance(); -// -// String moasessionID = null; -// String newSSOSessionId = null; -// AuthenticationSession moasession = null; -// IAuthData authData = null; -// -// boolean needAuthentication = moduleAction.needAuthentication(protocolRequest, req, resp); -// -// if (needAuthentication) { -// -// //check if interfederation IDP is requested -// ssomanager.checkInterfederationIsRequested(req, resp, protocolRequest); -// -// //check SSO session -// 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); -// -// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), -// protocolRequest, MOAIDEventConstants.AUTHPROCESS_SSO_INVALID); -// -// AuthenticationSessionStoreage.destroySession(correspondingMOASession); -// ssomanager.deleteSSOSessionID(req, resp); -// } -// } -// -// //load Parameters from OnlineApplicationConfiguration -// OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() -// .getOnlineApplicationParameter(protocolRequest.getOAURL()); -// -// if (oaParam == null) { -// throw new AuthenticationException("auth.00", new Object[] { protocolRequest.getOAURL() }); -// } -// -// -// isValidSSOSession = ssomanager.isValidSSOSession(ssoId, protocolRequest); -// useSSOOA = oaParam.useSSO() || oaParam.isInderfederationIDP(); -// -// -// //if a legacy request is used SSO should not be allowed, actually -// boolean isUseMandateRequested = LegacyHelper.isUseMandateRequested(req); -// -// if (protocolRequest.isPassiv() -// && protocolRequest.forceAuth()) { -// // conflict! -// throw new NoPassivAuthenticationException(); -// } -// -// boolean tryperform = authmanager.tryPerformAuthentication( -// req, resp); -// -// if (tryperform) -// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), -// protocolRequest, MOAIDEventConstants.AUTHPROCESS_FINISHED); -// else -// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), -// protocolRequest, MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, protocolRequest.getOAURL()); -// -// if (protocolRequest.forceAuth()) { -// if (!tryperform) { -// authmanager.doAuthentication(req, resp, -// protocolRequest); -// return; -// } -// } else if (protocolRequest.isPassiv()) { -// if (tryperform || (isValidSSOSession && useSSOOA && !isUseMandateRequested) ) { -// // Passive authentication ok! -// } else { -// throw new NoPassivAuthenticationException(); -// } -// } else { -// if (tryperform || (isValidSSOSession && useSSOOA && !isUseMandateRequested) ) { -// // Is authenticated .. proceed -// } else { -// // Start authentication! -// authmanager.doAuthentication(req, resp, -// protocolRequest); -// return; -// } -// } -// -// if ((useSSOOA || isValidSSOSession)) //TODO: SSO with mandates requires an OVS extension -// { -// -// if (useSSOOA && isValidSSOSession) { -// -// MOAReversionLogger.getInstance().logEvent(protocolRequest.getOnlineApplicationConfiguration(), -// protocolRequest, MOAIDEventConstants.AUTHPROCESS_SSO); -// -// moasessionID = ssomanager.getMOASession(ssoId); -// moasession = AuthenticationSessionStoreage.getSession(moasessionID); -// -// //use new OAParameter -// if (oaParam.useSSOQuestion() && !AuthenticationSessionStoreage.isAuthenticated(moasessionID)) { -// authmanager.sendTransmitAssertionQuestion(req, resp, protocolRequest, oaParam); -// return; -// } -// -// } else { -// moasessionID = (String) req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); -// moasession = AuthenticationSessionStoreage.getSession(moasessionID); -// -// } -// //save SSO session usage in Database -// if (useSSOOA) { -// newSSOSessionId = ssomanager.createSSOSessionInformations(moasessionID, protocolRequest.getOAURL()); -// -// if (MiscUtil.isNotEmpty(newSSOSessionId)) { -// ssomanager.setSSOSessionID(req, resp, newSSOSessionId); -// -// } else { -// ssomanager.deleteSSOSessionID(req, resp); -// -// } -// } -// -// } else { -// moasessionID = (String) req.getParameter(MOAIDAuthConstants.PARAM_SESSIONID); -// moasession = AuthenticationSessionStoreage.getSession(moasessionID); -// moasessionID = AuthenticationSessionStoreage.changeSessionID(moasession); -// -// } -// -// //build authenticationdata from session information and OA configuration -// authData = AuthenticationDataBuilder.buildAuthenticationData(protocolRequest, moasession); -// } -// -//// *** end handling authentication *** -// -//// *** start finalizing authentication (SSO, final redirects, statistic logging etc) *** -// -// SLOInformationInterface assertionID = moduleAction.processRequest(protocolRequest, req, resp, authData); -// -// RequestStorage.removePendingRequest(protocolRequestID); -// -// if (needAuthentication) { -// boolean isSSOSession = MiscUtil.isNotEmpty(newSSOSessionId) && useSSOOA; -// -// if ((useSSOOA || isSSOSession) //TODO: SSO with mandates requires an OVS extension -// && !moasession.getUseMandate()) { -// -// try { -// //Store OA specific SSO session information -// AuthenticationSessionStoreage.addSSOInformation(moasessionID, -// newSSOSessionId, assertionID, protocolRequest); -// -// } catch (AuthenticationException e) { -// Logger.warn("SSO Session information can not be stored -> SSO is not enabled!"); -// -// authmanager.performOnlyIDPLogOut(req, resp, moasessionID); -// isSSOSession = false; -// } -// -// } else { -// authmanager.performOnlyIDPLogOut(req, resp, moasessionID); -// } -// -// //Advanced statistic logging -// StatisticLogger logger = StatisticLogger.getInstance(); -// logger.logSuccessOperation(protocolRequest, authData, isSSOSession); -// -// } -// -//// *** end finalizing authentication *** -// -// } catch (Throwable e) { -// Logger.warn("An authentication error occured: ", e);; -// // Try handle module specific, if not possible rethrow -// if (!info.generateErrorMessage(e, req, resp, protocolRequest)) -// handleErrorNoRedirect(e.getMessage(), e, req, -// resp); -// -// } -// -// //log transaction_destroy to reversionslog -// MOAReversionLogger.getInstance().logEvent(MOAIDEventConstants.TRANSACTION_DESTROYED, protocolRequestID); -// -// } catch (WrongParametersException ex) { -// handleWrongParameters(ex, req, resp); -// -// } catch (MOAIDException ex) { -// handleError(null, ex, req, resp, protocolRequestID); -// -// } catch (Throwable e) { -// handleErrorNoRedirect(e.getMessage(), e, req, -// resp); -// } -// -// finally { -// -// -// TransactionIDUtils.removeTransactionId(); -// TransactionIDUtils.removeSessionId(); -// } -// -// Logger.debug("Clossing Dispatcher processing loop"); -// } -// -// @Override -// protected void doGet(HttpServletRequest req, HttpServletResponse resp) -// throws ServletException, IOException { -// processRequest(req, resp); -// } -// -// @Override -// protected void doPost(HttpServletRequest req, HttpServletResponse resp) -// throws ServletException, IOException { -// processRequest(req, resp); -// } -//} -- cgit v1.2.3 From ca8b83874c03a8719a56816408c8df44d49640f1 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 22 Feb 2016 11:32:11 +0100 Subject: change Spring types --- .../moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java | 4 ++-- .../id/auth/modules/internal/tasks/EvaluateSSOConsentsTaskImpl.java | 2 ++ .../id/auth/modules/internal/tasks/FinalizeAuthenticationTask.java | 4 ++-- .../id/auth/modules/internal/tasks/GenerateBKUSelectionFrameTask.java | 4 ++-- .../modules/internal/tasks/GenerateSSOConsentEvaluatorFrameTask.java | 3 +++ .../id/auth/modules/internal/tasks/RestartAuthProzessManagement.java | 4 ++-- 6 files changed, 13 insertions(+), 8 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 2f6137244..ed88c2aff 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 @@ -28,7 +28,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; @@ -41,7 +41,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author tlenz * */ -@Service("EvaluateBKUSelectionTask") +@Component("EvaluateBKUSelectionTask") public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { /* (non-Javadoc) 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 8dcb63550..d52b76ebd 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 @@ -27,6 +27,7 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; @@ -46,6 +47,7 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author tlenz * */ +@Component("EvaluateSSOConsentsTaskImpl") public class EvaluateSSOConsentsTaskImpl extends AbstractAuthServletTask { private static final String PARAM_SSO_CONSENTS = "value"; 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 index 816c05eab..c8e379bc1 100644 --- 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 @@ -25,7 +25,7 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -39,7 +39,7 @@ import at.gv.egovernment.moa.logging.Logger; * @author tlenz * */ -@Service("FinalizeAuthenticationTask") +@Component("FinalizeAuthenticationTask") public class FinalizeAuthenticationTask extends AbstractAuthServletTask { /* (non-Javadoc) 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 6ff730898..2cf2bfd9b 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 @@ -27,7 +27,7 @@ import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.builder.LoginFormBuilder; @@ -43,7 +43,7 @@ import at.gv.egovernment.moa.logging.Logger; * @author tlenz * */ -@Service("GenerateBKUSelectionFrameTask") +@Component("GenerateBKUSelectionFrameTask") public class GenerateBKUSelectionFrameTask extends AbstractAuthServletTask { /* (non-Javadoc) 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 f9f121520..47afe5795 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 @@ -27,6 +27,8 @@ import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.stereotype.Component; + import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.builder.SendAssertionFormBuilder; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -41,6 +43,7 @@ import at.gv.egovernment.moa.logging.Logger; * @author tlenz * */ +@Component("GenerateSSOConsentEvaluatorFrameTask") public class GenerateSSOConsentEvaluatorFrameTask extends AbstractAuthServletTask { /* (non-Javadoc) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java index 920b0e2b4..e0403f242 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java @@ -28,7 +28,7 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; @@ -44,7 +44,7 @@ import at.gv.egovernment.moa.logging.Logger; * @author tlenz * */ -@Service("RestartAuthProzessManagement") +@Component("RestartAuthProzessManagement") public class RestartAuthProzessManagement extends AbstractAuthServletTask { @Autowired ProcessEngine processEngine; -- cgit v1.2.3 From b1235f66ee1e890f9868724f9faedd222541178b Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 22 Feb 2016 11:34:32 +0100 Subject: refactor PVP implementation to share code with PVP Service-Provider moduls --- .../id/auth/builder/AuthenticationDataBuilder.java | 6 +- .../id/auth/servlet/IDPSingleLogOutServlet.java | 10 +- .../moa/id/data/ISLOInformationContainer.java | 67 +++ .../moa/id/data/SLOInformationContainer.java | 160 ++--- .../moa/id/moduls/AuthenticationManager.java | 31 +- .../gv/egovernment/moa/id/moduls/ModulStorage.java | 94 --- .../gv/egovernment/moa/id/moduls/ModulUtils.java | 46 -- .../gv/egovernment/moa/id/moduls/RequestImpl.java | 6 +- .../gv/egovernment/moa/id/moduls/ServletInfo.java | 53 -- .../gv/egovernment/moa/id/moduls/ServletType.java | 27 - .../moa/id/protocols/pvp2x/MetadataAction.java | 526 +++++++---------- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 90 +-- .../id/protocols/pvp2x/PVPTargetConfiguration.java | 21 +- .../moa/id/protocols/pvp2x/SingleLogOutAction.java | 29 +- .../id/protocols/pvp2x/binding/PostBinding.java | 11 +- .../protocols/pvp2x/binding/RedirectBinding.java | 9 +- .../id/protocols/pvp2x/binding/SoapBinding.java | 7 +- .../pvp2x/builder/AbstractPVPMetadataBuilder.java | 649 +++++++++++++++++++++ .../pvp2x/builder/AttributQueryBuilder.java | 15 +- .../pvp2x/builder/SingleLogOutBuilder.java | 125 +++- .../protocols/pvp2x/config/PVPConfiguration.java | 49 +- .../pvp2x/signer/AbstractCredentialProvider.java | 186 ++++++ .../protocols/pvp2x/signer/CredentialProvider.java | 198 ------- .../pvp2x/signer/IDPCredentialProvider.java | 150 +++++ .../pvp2x/verification/EntityVerifier.java | 29 +- .../pvp2x/verification/SAMLVerificationEngine.java | 237 ++++---- 26 files changed, 1694 insertions(+), 1137 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ISLOInformationContainer.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletInfo.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletType.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/IDPCredentialProvider.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 2f882f41e..1207439dd 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 @@ -126,6 +126,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; @Autowired protected AuthConfiguration authConfig; + @Autowired private AttributQueryBuilder attributQueryBuilder; public IAuthData buildAuthenticationData(IRequest protocolRequest, AuthenticationSession session, List reqAttributes) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { @@ -306,7 +307,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { //build attributQuery request AttributeQuery query = - AttributQueryBuilder.buildAttributQueryRequest(interfIDP.getUserNameID(), endpoint, attributs); + attributQueryBuilder.buildAttributQueryRequest(interfIDP.getUserNameID(), endpoint, attributs); //build SOAP request List xmlObjects = MOASAMLSOAPClient.send(endpoint, query); @@ -325,7 +326,8 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { SAMLVerificationEngine engine = new SAMLVerificationEngine(); engine.verifyIDPResponse(intfResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); - SAMLVerificationEngine.validateAssertion(intfResp, false); + //TODO: find better solution + //SAMLVerificationEngine.validateAssertion(intfResp, false); } catch (Exception e) { Logger.warn("PVP 2.1 assertion validation FAILED.", e); 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 84a2b69af..307b668b7 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 @@ -41,6 +41,7 @@ import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; 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; @@ -65,6 +66,7 @@ public class IDPSingleLogOutServlet extends AbstractController { @Autowired SSOManager ssoManager; @Autowired AuthenticationManager authManager; @Autowired IAuthenticationSessionStoreage authenicationStorage; + @Autowired SingleLogOutBuilder sloBuilder; @RequestMapping(value = "/idpSingleLogout", method = {RequestMethod.GET}) public void doGet(HttpServletRequest req, HttpServletResponse resp) @@ -151,16 +153,16 @@ public class IDPSingleLogOutServlet extends AbstractController { if (MiscUtil.isNotEmpty(restartProcess)) { Logger.info("Restart Single LogOut process after timeout ... "); try { - SLOInformationContainer sloContainer = transactionStorage.get(restartProcess, SLOInformationContainer.class); + ISLOInformationContainer sloContainer = transactionStorage.get(restartProcess, SLOInformationContainer.class); if (sloContainer.hasFrontChannelOA()) sloContainer.putFailedOA("differntent OAs"); String redirectURL = null; if (sloContainer.getSloRequest() != null) { //send SLO response to SLO request issuer - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(sloContainer.getSloRequest()); - LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, sloContainer.getSloRequest(), sloContainer.getSloFailedOAs()); - redirectURL = SingleLogOutBuilder.getFrontChannelSLOMessageURL(sloService, message, req, resp, sloContainer.getSloRequest().getRequest().getRelayState()); + 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()); } else { //print SLO information directly 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 new file mode 100644 index 000000000..18ffc5c6d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ISLOInformationContainer.java @@ -0,0 +1,67 @@ +/* + * 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.Set; +import java.util.Map.Entry; + +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; + +/** + * @author tlenz + * + */ +public interface ISLOInformationContainer { + + boolean hasFrontChannelOA(); + + Set> getFrontChannelOASessionDescriptions(); + + void removeFrontChannelOA(String oaID); + + Iterator 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 getSloFailedOAs(); + + void putFailedOA(String oaID); + +} \ No newline at end of file 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 a4bba8b19..ba7f33821 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 @@ -24,30 +24,20 @@ package at.gv.egovernment.moa.id.data; import java.io.Serializable; import java.util.ArrayList; -import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map.Entry; import java.util.Set; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.NameID; -import org.opensaml.saml2.metadata.SingleLogoutService; - -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.protocols.pvp2x.PVP2XProtocol; 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.exceptions.NOSLOServiceDescriptorException; /** * @author tlenz * */ -public class SLOInformationContainer implements Serializable { - +public class SLOInformationContainer implements Serializable, ISLOInformationContainer { + private static final long serialVersionUID = 7148730740582881862L; private PVPTargetConfiguration sloRequest = null; @@ -55,137 +45,111 @@ public class SLOInformationContainer implements Serializable { private LinkedHashMap activeBackChannelOAs = null; private List sloFailedOAs = null; - - public void parseActiveOAs(List dbOAs, String removeOAID) { - if (activeBackChannelOAs == null) - activeBackChannelOAs = new LinkedHashMap(); - if (activeFrontChannalOAs == null) - activeFrontChannalOAs = new LinkedHashMap(); - if (dbOAs != null) { - for (OASessionStore oa : dbOAs) { - if (!oa.getOaurlprefix().equals(removeOAID)) { - - //Actually only PVP 2.1 support Single LogOut - if (PVP2XProtocol.PATH.equals(oa.getProtocolType())) { - SingleLogoutService sloDesc; - try { - sloDesc = SingleLogOutBuilder.getRequestSLODescriptor(oa.getOaurlprefix()); - - if (sloDesc.getBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) - activeBackChannelOAs.put(oa.getOaurlprefix(), - new SLOInformationImpl( - oa.getAuthURL(), - oa.getAssertionSessionID(), - oa.getUserNameID(), - oa.getUserNameIDFormat(), - oa.getProtocolType(), - sloDesc)); - - else - activeFrontChannalOAs.put(oa.getOaurlprefix(), - new SLOInformationImpl( - oa.getAuthURL(), - oa.getAssertionSessionID(), - oa.getUserNameID(), - oa.getUserNameIDFormat(), - oa.getProtocolType(), - sloDesc)); - - } catch (NOSLOServiceDescriptorException e) { - putFailedOA(oa.getOaurlprefix()); - - } - - } else - putFailedOA(oa.getOaurlprefix()); - } - } - } + /** + * @return the activeFrontChannalOAs + */ + public LinkedHashMap getActiveFrontChannalOAs() { + return activeFrontChannalOAs; } /** - * @param dbIDPs - * @param value + * @param activeFrontChannalOAs the activeFrontChannalOAs to set */ - public void parseActiveIDPs(List dbIDPs, - String removeIDP) { - if (activeBackChannelOAs == null) - activeBackChannelOAs = new LinkedHashMap(); - if (activeFrontChannalOAs == null) - activeFrontChannalOAs = new LinkedHashMap(); - - if (dbIDPs != null) { - for (InterfederationSessionStore el : dbIDPs) { - if (!el.getIdpurlprefix().equals(removeIDP)) { - - SingleLogoutService sloDesc; - try { - sloDesc = SingleLogOutBuilder.getRequestSLODescriptor(el.getIdpurlprefix()); - - activeFrontChannalOAs.put(el.getIdpurlprefix(), - new SLOInformationImpl( - el.getAuthURL(), - el.getSessionIndex(), - el.getUserNameID(), - NameID.TRANSIENT, - PVP2XProtocol.PATH, - sloDesc)); - - } catch (NOSLOServiceDescriptorException e) { - putFailedOA(el.getIdpurlprefix()); - - } - } - } - } + public void setActiveFrontChannalOAs(LinkedHashMap activeFrontChannalOAs) { + this.activeFrontChannalOAs = activeFrontChannalOAs; } - + + /** + * @return the activeBackChannelOAs + */ + public LinkedHashMap getActiveBackChannelOAs() { + return activeBackChannelOAs; + } + + /** + * @param activeBackChannelOAs the activeBackChannelOAs to set + */ + public void setActiveBackChannelOAs(LinkedHashMap activeBackChannelOAs) { + this.activeBackChannelOAs = activeBackChannelOAs; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#hasFrontChannelOA() + */ + @Override public boolean hasFrontChannelOA() { return !activeFrontChannalOAs.isEmpty(); } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#getFrontChannelOASessionDescriptions() + */ + @Override public Set> getFrontChannelOASessionDescriptions() { return activeFrontChannalOAs.entrySet(); } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#removeFrontChannelOA(java.lang.String) + */ + @Override public void removeFrontChannelOA(String oaID) { activeFrontChannalOAs.remove(oaID); } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#getNextBackChannelOA() + */ + @Override public Iterator getNextBackChannelOA() { return activeBackChannelOAs.keySet().iterator(); } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#getBackChannelOASessionDescripten(java.lang.String) + */ + @Override public SLOInformationImpl getBackChannelOASessionDescripten(String oaID) { return activeBackChannelOAs.get(oaID); } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#removeBackChannelOA(java.lang.String) + */ + @Override public void removeBackChannelOA(String oaID) { activeBackChannelOAs.remove(oaID); } - /** - * @return the sloRequest + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#getSloRequest() */ + @Override public PVPTargetConfiguration getSloRequest() { return sloRequest; } - /** - * @param sloRequest the sloRequest to set + /* (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) { this.sloRequest = sloRequest; } - /** - * @return the sloFailedOAs + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#getSloFailedOAs() */ + @Override public List getSloFailedOAs() { return sloFailedOAs; } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.data.ISLOInformationContainer#putFailedOA(java.lang.String) + */ + @Override public void putFailedOA(String oaID) { if (sloFailedOAs == null) sloFailedOAs = new ArrayList(); 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 f77042bc5..39106dc3b 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 @@ -98,10 +98,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { @Autowired private IAuthenticationSessionStoreage authenticatedSessionStore; @Autowired private MOAReversionLogger revisionsLogger; @Autowired protected AuthConfiguration authConfig; - - public AuthenticationManager() { - - } + @Autowired private SingleLogOutBuilder sloBuilder; public void performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { @@ -452,9 +449,9 @@ public class AuthenticationManager extends MOAIDAuthConstants { List dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(session); List dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(session); SLOInformationContainer sloContainer = new SLOInformationContainer(); - sloContainer.setSloRequest(pvpReq); - sloContainer.parseActiveIDPs(dbIDPs, pvpSLOIssuer); - sloContainer.parseActiveOAs(dbOAs, pvpSLOIssuer); + sloContainer.setSloRequest(pvpReq); + sloBuilder.parseActiveIDPs(sloContainer, dbIDPs, pvpSLOIssuer); + sloBuilder.parseActiveOAs(sloContainer, dbOAs, pvpSLOIssuer); //terminate MOASession try { @@ -471,7 +468,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { Iterator nextOAInterator = sloContainer.getNextBackChannelOA(); while (nextOAInterator.hasNext()) { SLOInformationImpl sloDescr = sloContainer.getBackChannelOASessionDescripten(nextOAInterator.next()); - LogoutRequest sloReq = SingleLogOutBuilder.buildSLORequestMessage(sloDescr); + LogoutRequest sloReq = sloBuilder.buildSLORequestMessage(sloDescr); try { List soapResp = MOASAMLSOAPClient.send(sloDescr.getServiceURL(), sloReq); @@ -494,7 +491,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { } - SingleLogOutBuilder.checkStatusCode(sloContainer, sloResp); + sloBuilder.checkStatusCode(sloContainer, sloResp); } catch (SOAPException e) { Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() @@ -517,9 +514,9 @@ public class AuthenticationManager extends MOAIDAuthConstants { Collection> sloDescr = sloContainer.getFrontChannelOASessionDescriptions(); List sloReqList = new ArrayList(); for (Entry el : sloDescr) { - LogoutRequest sloReq = SingleLogOutBuilder.buildSLORequestMessage(el.getValue()); + LogoutRequest sloReq = sloBuilder.buildSLORequestMessage(el.getValue()); try { - sloReqList.add(SingleLogOutBuilder.getFrontChannelSLOMessageURL(el.getValue().getServiceURL(), el.getValue().getBinding(), + sloReqList.add(sloBuilder.getFrontChannelSLOMessageURL(el.getValue().getServiceURL(), el.getValue().getBinding(), sloReq, httpReq, httpResp, relayState)); } catch (Exception e) { @@ -549,9 +546,9 @@ public class AuthenticationManager extends MOAIDAuthConstants { } else { if (pvpReq != null) { //send SLO response to SLO request issuer - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, sloContainer.getSloFailedOAs()); - SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); + LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, sloContainer.getSloFailedOAs()); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); } else { //print SLO information directly @@ -572,9 +569,9 @@ public class AuthenticationManager extends MOAIDAuthConstants { } catch (MOADatabaseException e) { Logger.error("MOA AssertionDatabase ERROR", e); if (pvpReq != null) { - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); + LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); }else { //print SLO information directly diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.java deleted file mode 100644 index e65d77326..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulStorage.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. - *******************************************************************************/ -package at.gv.egovernment.moa.id.moduls; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.ServiceLoader; - -import at.gv.egovernment.moa.logging.Logger; - -public class ModulStorage { - -// private static final String[] modulClasses = new String[]{ -//// "at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol", -// "at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol", -// "at.gv.egovernment.moa.id.protocols.stork2.STORKProtocol", -// "at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20Protocol" -// }; - - private static ServiceLoader protocolModuleLoader = - ServiceLoader.load(IModulInfo.class); - private static List registeredModules = new ArrayList(); - - - public static List getAllModules() { - return registeredModules; - } - - public static IModulInfo getModuleByPath(String modname) { - Iterator it = registeredModules.iterator(); - while (it.hasNext()) { - IModulInfo info = it.next(); - if (info.getPath().equals(modname)) { - return info; - } - } - return null; - } - - static { - Logger.info("Loading protocol modules:"); - if (protocolModuleLoader != null ) { - Iterator moduleLoaderInterator = protocolModuleLoader.iterator(); - while (moduleLoaderInterator.hasNext()) { - try { - IModulInfo modul = moduleLoaderInterator.next(); - Logger.info("Loading Modul Information: " + modul.getName()); - registeredModules.add(modul); - - } catch(Throwable e) { - Logger.error("Check configuration! " + "Some protocol modul" + - " is not a valid IModulInfo", e); - } - } - } - -// for(int i = 0; i < modulClasses.length; i++) { -// String modulClassName = modulClasses[i]; -// try { -// @SuppressWarnings("unchecked") -// Class moduleClass = (Class)Class.forName(modulClassName); -// IModulInfo module = moduleClass.newInstance(); -// Logger.info("Loading Modul Information: " + module.getName()); -// registeredModules.add(module); -// } catch(Throwable e) { -// Logger.error("Check configuration! " + modulClassName + -// " is not a valid IModulInfo", e); -// } -// } - Logger.info("Loading modules done"); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.java deleted file mode 100644 index 13768a343..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ModulUtils.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.moduls; -// -//import at.gv.egovernment.moa.id.entrypoints.DispatcherServlet; -// -// -//public class ModulUtils { -// -// public static final String UNAUTHDISPATCHER = "dispatcher"; -// public static final String AUTHDISPATCHER = "dispatcher"; -// -// public static String buildUnauthURL(String modul, String action, String pendingRequestID) { -// return UNAUTHDISPATCHER + "?" + -// DispatcherServlet.PARAM_TARGET_MODULE + "=" + modul + "&" + -// DispatcherServlet.PARAM_TARGET_ACTION + "=" + action + "&" + -// DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; -// } -// -// public static String buildAuthURL(String modul, String action, String pendingRequestID) { -// return AUTHDISPATCHER + -// "?" + DispatcherServlet.PARAM_TARGET_MODULE + "=" + modul + "&" + -// DispatcherServlet.PARAM_TARGET_ACTION + "=" + action + "&" + -// DispatcherServlet.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; -// } -//} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index bba9f66ae..a1a814e95 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -32,6 +32,7 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.opensaml.saml2.core.Attribute; +import org.springframework.beans.factory.annotation.Autowired; import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; @@ -40,6 +41,7 @@ import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; @@ -78,11 +80,13 @@ public abstract class RequestImpl implements IRequest, Serializable{ private Map genericDataStorage = new HashMap(); + @Autowired protected AttributQueryBuilder attributQueryBuilder; + /** * @throws ConfigurationException * */ - public RequestImpl(HttpServletRequest req) throws ConfigurationException { + public final void initialize(HttpServletRequest req) throws ConfigurationException { //set requestID requestID = Random.nextRandom(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletInfo.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletInfo.java deleted file mode 100644 index 807f789ce..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletInfo.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.moduls; - -import javax.servlet.http.HttpServlet; - - -public class ServletInfo { - Class servletClass; - String servletTarget; - ServletType type; - - public ServletInfo(Class servletClass, - String servletTarget, ServletType type) { - super(); - this.servletClass = servletClass; - this.servletTarget = servletTarget; - this.type = type; - } - - public HttpServlet getServletInstance() - throws InstantiationException, IllegalAccessException { - return servletClass.newInstance(); - } - - public String getTarget() { - return servletTarget; - } - - public ServletType getType() { - return type; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletType.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletType.java deleted file mode 100644 index c8fbfb558..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/ServletType.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.moduls; - -public enum ServletType { - UNAUTH, AUTH, NONE -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java index 5c1c60dc8..d48603a7c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java @@ -22,49 +22,20 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x; -import java.io.StringWriter; +import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.joda.time.DateTime; -import org.opensaml.Configuration; -import org.opensaml.common.xml.SAMLConstants; + +import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.NameIDType; -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.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.security.SecurityException; -import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; 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.X509Credential; -import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; -import org.opensaml.xml.signature.Signature; -import org.opensaml.xml.signature.Signer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import org.w3c.dom.Document; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; @@ -74,103 +45,28 @@ import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; 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.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.logging.Logger; @Service("pvpMetadataService") -public class MetadataAction implements IAction { +public class MetadataAction extends AbstractPVPMetadataBuilder implements IAction { private static final int VALIDUNTIL_IN_HOURS = 24; @Autowired private MOAReversionLogger revisionsLogger; + @Autowired private IDPCredentialProvider credentialProvider; public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { try { - revisionsLogger.logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_PVP_METADATA); - EntitiesDescriptor idpEntitiesDescriptor = - SAML2Utils.createSAMLObject(EntitiesDescriptor.class); - - idpEntitiesDescriptor.setName(PVPConfiguration.getInstance().getIDPIssuerName()); - - idpEntitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); - - DateTime date = new DateTime(); - - idpEntitiesDescriptor.setValidUntil(date.plusHours(VALIDUNTIL_IN_HOURS)); - - EntityDescriptor idpEntityDescriptor = SAML2Utils - .createSAMLObject(EntityDescriptor.class); - - idpEntitiesDescriptor.getEntityDescriptors().add(idpEntityDescriptor); - - //TODO: maybe change EntityID to Metadata URL - //idpEntityDescriptor - // .setEntityID(PVPConfiguration.getInstance().getIDPSSOMetadataService()); - - idpEntityDescriptor - .setEntityID(req.getAuthURLWithOutSlash()); - - idpEntityDescriptor.setValidUntil(date.plusDays(VALIDUNTIL_IN_HOURS)); - - List persons = PVPConfiguration.getInstance() - .getIDPContacts(); - - idpEntityDescriptor.getContactPersons().addAll(persons); - - idpEntityDescriptor.setOrganization(PVPConfiguration.getInstance() - .getIDPOrganisation()); - - X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory(); - //keyInfoFactory.setEmitPublicKeyValue(true); - keyInfoFactory.setEmitEntityIDAsKeyName(true); - keyInfoFactory.setEmitEntityCertificate(true); - - KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - - Credential metadataSigningCredential = CredentialProvider.getIDPMetaDataSigningCredential(); - Signature signature = CredentialProvider - .getIDPSignature(metadataSigningCredential); - - //set KeyInfo Element - SecurityHelper.prepareSignatureParams(signature, metadataSigningCredential, null, null); - - idpEntitiesDescriptor.setSignature(signature); - - //set IDP metadata - idpEntityDescriptor.getRoleDescriptors().add(generateIDPMetadata(req, keyInfoGenerator)); - - //set SP metadata for interfederation - idpEntityDescriptor.getRoleDescriptors().add(generateSPMetadata(req, keyInfoGenerator)); - - DocumentBuilder builder; - DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - - builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(idpEntitiesDescriptor); - out.marshall(idpEntitiesDescriptor, document); - - Signer.signObject(signature); - - 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(); - - String metadataXML = sw.toString(); + //build metadata + String metadataXML = buildPVPMetadata(req.getAuthURLWithOutSlash()); Logger.debug("METADATA: " + metadataXML); httpResp.setContentType("text/xml"); @@ -195,228 +91,232 @@ public class MetadataAction implements IAction { return (PVP2XProtocol.METADATA); } - private RoleDescriptor generateSPMetadata(IRequest req, KeyInfoGenerator keyInfoGenerator) throws CredentialsNotAvailableException, SecurityException, ConfigurationException { + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataValidUntil() + */ + @Override + public int getMetadataValidUntil() { + return VALIDUNTIL_IN_HOURS; + } - Logger.debug("Set SP Metadata key information"); - - SPSSODescriptor spSSODescriptor = SAML2Utils - .createSAMLObject(SPSSODescriptor.class); + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildEntitiesDescriptorAsRootElement() + */ + @Override + public boolean buildEntitiesDescriptorAsRootElement() { + return true; + } - spSSODescriptor.setAuthnRequestsSigned(true); - spSSODescriptor.setWantAssertionsSigned(false); - - - //Set AuthRequest Signing certificate - X509Credential authcredential = CredentialProvider.getIDPAssertionSigningCredential(); - - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); - spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - - //set AuthRequest encryption certificate - - X509Credential authEncCredential = CredentialProvider.getIDPAssertionEncryptionCredential(); - - if (authEncCredential != null) { - KeyDescriptor encryKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - encryKeyDescriptor.setUse(UsageType.ENCRYPTION); - encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); - spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildIDPSSODescriptor() + */ + @Override + public boolean buildIDPSSODescriptor() { + return true; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildSPSSODescriptor() + */ + @Override + public boolean buildSPSSODescriptor() { + return false; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityID() + */ + @Override + public String getEntityIDPostfix() { + //TODO: maybe change EntityID to Metadata URL + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityFriendlyName() + */ + @Override + public String getEntityFriendlyName() { + try { + return PVPConfiguration.getInstance().getIDPIssuerName(); - } else { - Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); + } catch (ConfigurationException e) { + Logger.error("Can not load Metadata entry: EntityID friendlyName.", e); + return null; } - - NameIDFormat persistentnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - persistentnameIDFormat.setFormat(NameIDType.PERSISTENT); - - spSSODescriptor.getNameIDFormats().add(persistentnameIDFormat); - - NameIDFormat transientnameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - transientnameIDFormat.setFormat(NameIDType.TRANSIENT); - - spSSODescriptor.getNameIDFormats().add(transientnameIDFormat); - - NameIDFormat unspecifiednameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - unspecifiednameIDFormat.setFormat(NameIDType.UNSPECIFIED); - - spSSODescriptor.getNameIDFormats().add(unspecifiednameIDFormat); - - //add assertion consumer services - AssertionConsumerService postassertionConsumerService = - SAML2Utils.createSAMLObject(AssertionConsumerService.class); - postassertionConsumerService.setIndex(0); - postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - postassertionConsumerService.setLocation(PVPConfiguration - .getInstance().getSPSSOPostService(req.getAuthURL())); - postassertionConsumerService.setIsDefault(true); - spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); - - AssertionConsumerService redirectassertionConsumerService = - SAML2Utils.createSAMLObject(AssertionConsumerService.class); - redirectassertionConsumerService.setIndex(1); - redirectassertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - redirectassertionConsumerService.setLocation(PVPConfiguration - .getInstance().getSPSSORedirectService(req.getAuthURL())); - spSSODescriptor.getAssertionConsumerServices().add(redirectassertionConsumerService); - - - //add SLO descriptor -// SingleLogoutService postSLOService = -// SAML2Utils.createSAMLObject(SingleLogoutService.class); -// postSLOService.setLocation(PVPConfiguration -// .getInstance().getIDPSSOPostService()); -// postSLOService -// .setBinding(SAMLConstants.SAML2_POST_BINDING_URI); -// spSSODescriptor.getSingleLogoutServices().add(postSLOService); - - SingleLogoutService redirectSLOService = - SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(PVPConfiguration - .getInstance().getSPSSORedirectService(req.getAuthURL())); - redirectSLOService - .setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(redirectSLOService); - - - spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - - AttributeConsumingService attributeService = - SAML2Utils.createSAMLObject(AttributeConsumingService.class); - attributeService.setIndex(0); - attributeService.setIsDefault(true); - ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); - serviceName.setName(new LocalizedString("Default Service", "de")); - attributeService.getNames().add(serviceName); - - return spSSODescriptor; } - - private IDPSSODescriptor generateIDPMetadata(IRequest req, KeyInfoGenerator keyInfoGenerator) throws ConfigurationException, CredentialsNotAvailableException, SecurityException { - - -// //set SignatureMethode -// signature.setSignatureAlgorithm(PVPConstants.DEFAULT_SIGNING_METHODE); -// -// //set DigestMethode -// List contentList = signature.getContentReferences(); -// for (ContentReference content : contentList) { -// -// if (content instanceof SAMLObjectContentReference) { -// -// SAMLObjectContentReference el = (SAMLObjectContentReference) content; -// el.setDigestAlgorithm(PVPConstants.DEFAULT_DIGESTMETHODE); -// -// } -// } - - -// KeyInfoBuilder metadataKeyInfoBuilder = new KeyInfoBuilder(); -// KeyInfo metadataKeyInfo = metadataKeyInfoBuilder.buildObject(); -// //KeyInfoHelper.addCertificate(metadataKeyInfo, metadataSigningCredential.); -// signature.setKeyInfo(metadataKeyInfo ); - - - IDPSSODescriptor idpSSODescriptor = SAML2Utils - .createSAMLObject(IDPSSODescriptor.class); - idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - - idpSSODescriptor.setWantAuthnRequestsSigned(true); - - if (PVPConfiguration.getInstance().getIDPSSOPostService(req.getAuthURL()) != null) { - //add SSO descriptor - SingleSignOnService postSingleSignOnService = SAML2Utils - .createSAMLObject(SingleSignOnService.class); - postSingleSignOnService.setLocation(PVPConfiguration - .getInstance().getIDPSSOPostService(req.getAuthURL())); - postSingleSignOnService - .setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add( - postSingleSignOnService); + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getContactPersonInformation() + */ + @Override + public List getContactPersonInformation() { + try { + return PVPConfiguration.getInstance().getIDPContacts(); - //add SLO descriptor -// SingleLogoutService postSLOService = -// SAML2Utils.createSAMLObject(SingleLogoutService.class); -// postSLOService.setLocation(PVPConfiguration -// .getInstance().getIDPSSOPostService()); -// postSLOService -// .setBinding(SAMLConstants.SAML2_POST_BINDING_URI); -// idpSSODescriptor.getSingleLogoutServices().add(postSLOService); + } catch (ConfigurationException e) { + Logger.warn("Can not load Metadata entry: Contect Person", e); + return null; } + + } - if (PVPConfiguration.getInstance().getIDPSSORedirectService(req.getAuthURL()) != null) { - //add SSO descriptor - SingleSignOnService redirectSingleSignOnService = SAML2Utils - .createSAMLObject(SingleSignOnService.class); - redirectSingleSignOnService.setLocation(PVPConfiguration - .getInstance().getIDPSSORedirectService(req.getAuthURL())); - redirectSingleSignOnService - .setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add( - redirectSingleSignOnService); + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getOrgansiationInformation() + */ + @Override + public Organization getOrgansiationInformation() { + try { + return PVPConfiguration.getInstance().getIDPOrganisation(); + + } catch (ConfigurationException e) { + Logger.warn("Can not load Metadata entry: Organisation", e); + return null; - //add SLO descriptor - SingleLogoutService redirectSLOService = - SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(PVPConfiguration - .getInstance().getIDPSSORedirectService(req.getAuthURL())); - redirectSLOService - .setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleLogoutServices().add(redirectSLOService); } + } - /*if (PVPConfiguration.getInstance().getIDPResolveSOAPService() != null) { - ArtifactResolutionService artifactResolutionService = SAML2Utils - .createSAMLObject(ArtifactResolutionService.class); - - artifactResolutionService - .setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); - artifactResolutionService.setLocation(PVPConfiguration - .getInstance().getIDPResolveSOAPService()); + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataSigningCredentials() + */ + @Override + public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPMetaDataSigningCredential(); + } - artifactResolutionService.setIndex(0); - - idpSSODescriptor.getArtifactResolutionServices().add( - artifactResolutionService); - }*/ - - //set assertion signing key - Credential assertionSigingCredential = CredentialProvider - .getIDPAssertionSigningCredential(); - - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(assertionSigingCredential)); - idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - idpSSODescriptor.getAttributes().addAll(PVPAttributeBuilder.buildSupportedEmptyAttributes()); + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getRequestorResponseSigningCredentials() + */ + @Override + public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPAssertionSigningCredential(); - NameIDFormat persistenNameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - persistenNameIDFormat.setFormat(NameIDType.PERSISTENT); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEncryptionCredentials() + */ + @Override + public Credential getEncryptionCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPAssertionEncryptionCredential(); - idpSSODescriptor.getNameIDFormats().add(persistenNameIDFormat); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSOPostBindingURL() + */ + @Override + public String getIDPWebSSOPostBindingURL() { + return PVPConfiguration.PVP2_IDP_POST; - NameIDFormat transientNameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - transientNameIDFormat.setFormat(NameIDType.TRANSIENT); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSORedirectBindingURL() + */ + @Override + public String getIDPWebSSORedirectBindingURL() { + return PVPConfiguration.PVP2_IDP_REDIRECT; - idpSSODescriptor.getNameIDFormats().add(transientNameIDFormat); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLOPostBindingURL() + */ + @Override + public String getIDPSLOPostBindingURL() { + return PVPConfiguration.PVP2_IDP_POST; - NameIDFormat unspecifiedNameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - unspecifiedNameIDFormat.setFormat(NameIDType.UNSPECIFIED); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLORedirectBindingURL() + */ + @Override + public String getIDPSLORedirectBindingURL() { + return PVPConfiguration.PVP2_IDP_REDIRECT; - idpSSODescriptor.getNameIDFormats().add(unspecifiedNameIDFormat); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServicePostBindingURL() + */ + @Override + public String getSPAssertionConsumerServicePostBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServiceRedirectBindingURL() + */ + @Override + public String getSPAssertionConsumerServiceRedirectBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOPostBindingURL() + */ + @Override + public String getSPSLOPostBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLORedirectBindingURL() + */ + @Override + public String getSPSLORedirectBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOSOAPBindingURL() + */ + @Override + public String getSPSLOSOAPBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleAttributes() + */ + @Override + public List getIDPPossibleAttributes() { + return PVPAttributeBuilder.buildSupportedEmptyAttributes(); - return idpSSODescriptor; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleNameITTypes() + */ + @Override + public List getIDPPossibleNameITTypes() { + return Arrays.asList(NameIDType.PERSISTENT, + NameIDType.TRANSIENT, + NameIDType.UNSPECIFIED); } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPRequiredAttributes() + */ + @Override + public List getSPRequiredAttributes() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAllowedNameITTypes() + */ + @Override + public List getSPAllowedNameITTypes() { + return null; + } + + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java index 6fb03a37d..88f0e3b74 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,13 +22,11 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x; -import java.io.IOException; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.xml.transform.TransformerException; import org.apache.commons.lang.StringEscapeUtils; import org.joda.time.DateTime; @@ -49,7 +47,6 @@ 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.io.MarshallingException; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.signature.SignableXMLObject; import org.springframework.stereotype.Controller; @@ -145,7 +142,8 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { } //create pendingRequest object - PVPTargetConfiguration pendingReq = new PVPTargetConfiguration(req); + PVPTargetConfiguration pendingReq = applicationContext.getBean(PVPTargetConfiguration.class); + pendingReq.initialize(req); pendingReq.setModule(NAME); revisionsLogger.logEvent( @@ -155,7 +153,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); MetadataAction metadataAction = applicationContext.getBean(MetadataAction.class); - metadataAction.processRequest(new PVPTargetConfiguration(req), + metadataAction.processRequest(pendingReq, req, resp, null); } @@ -171,7 +169,8 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { try { //create pendingRequest object - PVPTargetConfiguration pendingReq = new PVPTargetConfiguration(req); + PVPTargetConfiguration pendingReq = applicationContext.getBean(PVPTargetConfiguration.class); + pendingReq.initialize(req); pendingReq.setModule(NAME); revisionsLogger.logEvent(MOAIDEventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); @@ -219,7 +218,8 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { try { //create pendingRequest object - PVPTargetConfiguration pendingReq = new PVPTargetConfiguration(req); + PVPTargetConfiguration pendingReq = applicationContext.getBean(PVPTargetConfiguration.class); + pendingReq.initialize(req); pendingReq.setModule(NAME); revisionsLogger.logEvent(MOAIDEventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); @@ -732,42 +732,42 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { } - /** - * PreProcess AuthResponse and Assertion - * @param msg - */ - private MOAResponse preProcessAuthResponse(MOAResponse msg) { - Logger.debug("Start PVP21 assertion processing... "); - Response samlResp = (Response) msg.getResponse(); - - try { - if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { - - //validate PVP 2.1 assertion - SAMLVerificationEngine.validateAssertion(samlResp, true); - - msg.setSAMLMessage(SAML2Utils.asDOMDocument(samlResp).getDocumentElement()); - return msg; - - } else { - Logger.debug("Receive StatusCode " + samlResp.getStatus().getStatusCode().getValue() - + " from interfederated IDP."); - - } - - } catch (IOException e) { - Logger.warn("Interfederation response marshaling FAILED.", e); - - } catch (MarshallingException e) { - Logger.warn("Interfederation response marshaling FAILED.", e); - - } catch (TransformerException e) { - Logger.warn("Interfederation response marshaling FAILED.", e); - - } catch (AssertionValidationExeption e) { - //error is already logged, to nothing - } - - return null; - } +// /** +// * PreProcess AuthResponse and Assertion +// * @param msg +// */ +// private MOAResponse preProcessAuthResponse(MOAResponse msg) { +// Logger.debug("Start PVP21 assertion processing... "); +// Response samlResp = (Response) msg.getResponse(); +// +// try { +// if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { +// +// //validate PVP 2.1 assertion +// SAMLVerificationEngine.validateAssertion(samlResp, true); +// +// msg.setSAMLMessage(SAML2Utils.asDOMDocument(samlResp).getDocumentElement()); +// return msg; +// +// } else { +// Logger.debug("Receive StatusCode " + samlResp.getStatus().getStatusCode().getValue() +// + " from interfederated IDP."); +// +// } +// +// } catch (IOException e) { +// Logger.warn("Interfederation response marshaling FAILED.", e); +// +// } catch (MarshallingException e) { +// Logger.warn("Interfederation response marshaling FAILED.", e); +// +// } catch (TransformerException e) { +// Logger.warn("Interfederation response marshaling FAILED.", e); +// +// } catch (AssertionValidationExeption e) { +// //error is already logged, to nothing +// } +// +// return null; +// } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index 181e89806..800728bbd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -26,35 +26,26 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import javax.servlet.http.HttpServletRequest; - import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Attribute; 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.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; -import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; 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 { - /** - * @param req - * @throws ConfigurationException - */ - public PVPTargetConfiguration(HttpServletRequest req) - throws ConfigurationException { - super(req); - - } - private static final long serialVersionUID = 4889919265919638188L; InboundMessage request; @@ -132,7 +123,7 @@ public class PVPTargetConfiguration extends RequestImpl { reqAttr.put(attr.getName(), ""); } - return AttributQueryBuilder.buildSAML2AttributeList(this.getOnlineApplicationConfiguration(), reqAttr.keySet().iterator()); + return attributQueryBuilder.buildSAML2AttributeList(this.getOnlineApplicationConfiguration(), reqAttr.keySet().iterator()); } catch (NoMetadataInformationException e) { Logger.warn("NO metadata found for Entity " + getRequest().getEntityID()); 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 8928aaeca..5afa10a72 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 @@ -49,6 +49,7 @@ import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.data.IAuthData; +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; @@ -77,6 +78,8 @@ public class SingleLogOutAction implements IAction { @Autowired private AuthenticationManager authManager; @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; @Autowired private ITransactionStorage transactionStorage; + @Autowired private SingleLogOutBuilder sloBuilder; + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.data.IAuthData) @@ -107,11 +110,11 @@ public class SingleLogOutAction implements IAction { String ssoID = ssomanager.getSSOSessionID(httpReq); if (MiscUtil.isEmpty(ssoID)) { Logger.info("Can not find active Session. Single LogOut not possible!"); - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - //LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, null); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); + //LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, null); Logger.info("Sending SLO success message to requester ..."); - SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); return null; } else { @@ -121,11 +124,11 @@ public class SingleLogOutAction implements IAction { } catch (MOADatabaseException e) { Logger.info("Can not find active Session. Single LogOut not possible!"); - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(pvpReq); - //LogoutResponse message = SingleLogOutBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); - LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, pvpReq, null); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); + //LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); + LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, pvpReq, null); Logger.info("Sending SLO success message to requester ..."); - SingleLogOutBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); + sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, samlReq.getRelayState()); return null; } @@ -175,10 +178,10 @@ public class SingleLogOutAction implements IAction { Object data = SerializationUtils.deserialize(element.getAssertion()); if (data instanceof SLOInformationContainer) { - SLOInformationContainer sloContainer = (SLOInformationContainer) data; + ISLOInformationContainer sloContainer = (ISLOInformationContainer) data; //check status - SingleLogOutBuilder.checkStatusCode(sloContainer, logOutResp); + sloBuilder.checkStatusCode(sloContainer, logOutResp); if (sloContainer.hasFrontChannelOA()) { try { @@ -224,9 +227,9 @@ public class SingleLogOutAction implements IAction { String redirectURL = null; if (sloContainer.getSloRequest() != null) { //send SLO response to SLO request issuer - SingleLogoutService sloService = SingleLogOutBuilder.getResponseSLODescriptor(sloContainer.getSloRequest()); - LogoutResponse message = SingleLogOutBuilder.buildSLOResponseMessage(sloService, sloContainer.getSloRequest(), sloContainer.getSloFailedOAs()); - redirectURL = SingleLogOutBuilder.getFrontChannelSLOMessageURL(sloService, message, httpReq, httpResp, sloContainer.getSloRequest().getRequest().getRelayState()); + SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(sloContainer.getSloRequest()); + LogoutResponse message = sloBuilder.buildSLOResponseMessage(sloService, sloContainer.getSloRequest(), sloContainer.getSloFailedOAs()); + redirectURL = sloBuilder.getFrontChannelSLOMessageURL(sloService, message, httpReq, httpResp, sloContainer.getSloRequest().getRequest().getRelayState()); } else { //print SLO information directly diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index 9e176f724..24bdf4c3c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -47,6 +47,7 @@ import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.x509.X509Credential; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.config.ConfigurationException; @@ -58,8 +59,8 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.validation.MOAPVPSignedRequestPolicyRule; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.util.HTTPUtils; @@ -69,13 +70,15 @@ import at.gv.egovernment.moa.util.MiscUtil; @Service("PVPPostBindingCoder") public class PostBinding implements IDecoder, IEncoder { - + + @Autowired private IDPCredentialProvider credentialProvider; + public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, RequestAbstractType request, String targetLocation, String relayState) throws MessageEncodingException, SecurityException { try { - X509Credential credentials = CredentialProvider + X509Credential credentials = credentialProvider .getIDPAssertionSigningCredential(); //load default PVP security configurations @@ -113,7 +116,7 @@ public class PostBinding implements IDecoder, IEncoder { throws MessageEncodingException, SecurityException { try { - X509Credential credentials = CredentialProvider + X509Credential credentials = credentialProvider .getIDPAssertionSigningCredential(); //load default PVP security configurations diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 08aa76e58..7167d8b7d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -48,6 +48,7 @@ import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.x509.X509Credential; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.config.ConfigurationException; @@ -59,8 +60,8 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; @@ -69,12 +70,14 @@ import at.gv.egovernment.moa.util.MiscUtil; @Service("PVPRedirectBindingCoder") public class RedirectBinding implements IDecoder, IEncoder { + @Autowired private IDPCredentialProvider credentialProvider; + public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, RequestAbstractType request, String targetLocation, String relayState) throws MessageEncodingException, SecurityException { try { - X509Credential credentials = CredentialProvider + X509Credential credentials = credentialProvider .getIDPAssertionSigningCredential(); //load default PVP security configurations @@ -107,7 +110,7 @@ public class RedirectBinding implements IDecoder, IEncoder { StatusResponseType response, String targetLocation, String relayState) throws MessageEncodingException, SecurityException { try { - X509Credential credentials = CredentialProvider + X509Credential credentials = credentialProvider .getIDPAssertionSigningCredential(); //load default PVP security configurations diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index d42d91105..bd60b7a13 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -45,6 +45,7 @@ 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.protocols.pvp2x.PVP2XProtocol; @@ -54,14 +55,16 @@ 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.CredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Service("PVPSOAPBindingCoder") public class SoapBinding implements IDecoder, IEncoder { + @Autowired private IDPCredentialProvider credentialProvider; + public InboundMessageInterface decode(HttpServletRequest req, HttpServletResponse resp, boolean isSPEndPoint) throws MessageDecodingException, SecurityException, PVP2Exception { @@ -142,7 +145,7 @@ public class SoapBinding implements IDecoder, IEncoder { StatusResponseType response, String targetLocation, String relayState) throws MessageEncodingException, SecurityException, PVP2Exception { try { - Credential credentials = CredentialProvider + Credential credentials = credentialProvider .getIDPAssertionSigningCredential(); //load default PVP security configurations diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java new file mode 100644 index 000000000..23870806a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java @@ -0,0 +1,649 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder; + +import java.io.IOException; +import java.io.StringWriter; +import java.security.PrivateKey; +import java.security.interfaces.RSAPrivateKey; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.joda.time.DateTime; +import org.opensaml.Configuration; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.saml2.metadata.SingleLogoutService; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; +import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.signature.SignatureConstants; +import org.opensaml.xml.signature.SignatureException; +import org.opensaml.xml.signature.Signer; +import org.w3c.dom.Document; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ + +public abstract class AbstractPVPMetadataBuilder { + + X509KeyInfoGeneratorFactory keyInfoFactory = null; + + /** + * + */ + public AbstractPVPMetadataBuilder() { + keyInfoFactory = new X509KeyInfoGeneratorFactory(); + keyInfoFactory.setEmitEntityIDAsKeyName(true); + keyInfoFactory.setEmitEntityCertificate(true); + + } + + + /** + * Set metadata valid area + * + * @return valid until in hours [h] + */ + public abstract int getMetadataValidUntil(); + + /** + * Build a SAML2 Entities element as metadata root element + * + * @return true, if the metadata should start with entities element + */ + public abstract boolean buildEntitiesDescriptorAsRootElement(); + + /** + * + * + * @return true, if an IDP SSO-descriptor element should be generated + */ + public abstract boolean buildIDPSSODescriptor(); + + /** + * + * + * @return true, if an SP SSO-descriptor element should be generated + */ + public abstract boolean buildSPSSODescriptor(); + + /** + * Set the PVP entityID for this SAML2 metadata. + * The entityID must be a URL and is public-URL prefix of the server, as minimum. + * If this is null or a empty String, the EntityID is the public-url prefix + * + * @return PVP entityID postfix as String + */ + public abstract String getEntityIDPostfix(); + + /** + * Set a friendlyName for this PVP entity + * + * @return + */ + public abstract String getEntityFriendlyName(); + + /** + * Set the contact information for this metadata entity + * + * @return + */ + public abstract List getContactPersonInformation(); + + /** + * Set organisation information for this metadata entity + * + * @return + */ + public abstract Organization getOrgansiationInformation(); + + + /** + * Set the credential for metadata signing + * + * @return + * @throws CredentialsNotAvailableException + */ + public abstract Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException; + + /** + * Set the credential for request/response signing + * IDP metadata: this credential is used for SAML2 response signing + * SP metadata: this credential is used for SAML2 response signing + * + * @return + * @throws CredentialsNotAvailableException + */ + public abstract Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException; + + /** + * Set the credential for response encryption + * + * @return + * @throws CredentialsNotAvailableException + */ + public abstract Credential getEncryptionCredentials() throws CredentialsNotAvailableException; + + /** + * Set the IDP Post-Binding URL-postfix for WebSSO + * + * @return + */ + public abstract String getIDPWebSSOPostBindingURL(); + + /** + * Set the IDP Redirect-Binding URL-postfix for WebSSO + * + * @return + */ + public abstract String getIDPWebSSORedirectBindingURL(); + + /** + * Set the IDP Post-Binding URL-postfix for Single LogOut + * + * @return + */ + public abstract String getIDPSLOPostBindingURL(); + + /** + * Set the IDP Redirect-Binding URL-postfix for Single LogOut + * + * @return + */ + public abstract String getIDPSLORedirectBindingURL(); + + /** + * Set the SP Post-Binding URL-postfix for for the Assertion-Consumer Service + * + * @return + */ + public abstract String getSPAssertionConsumerServicePostBindingURL(); + + /** + * Set the SP Redirect-Binding URL-postfix for the Assertion-Consumer Service + * + * @return + */ + public abstract String getSPAssertionConsumerServiceRedirectBindingURL(); + + /** + * Set the SP Post-Binding URL-postfix for Single LogOut + * + * @return + */ + public abstract String getSPSLOPostBindingURL(); + + /** + * Set the SP Redirect-Binding URL-postfix for Single LogOut + * + * @return + */ + public abstract String getSPSLORedirectBindingURL(); + + /** + * Set the SP SOAP-Binding URL-postfix for Single LogOut + * + * @return + */ + public abstract String getSPSLOSOAPBindingURL(); + + + /** + * Set all SAML2 attributes which could be provided by this IDP + * + * @return + */ + public abstract List getIDPPossibleAttributes(); + + /** + * Set all nameID types which could be provided by this IDP + * + * @return a List of SAML2 nameID types + */ + public abstract List getIDPPossibleNameITTypes(); + + /** + * Set all SAML2 attributes which are required by the SP + * + * @return + */ + public abstract List getSPRequiredAttributes(); + + /** + * Set all nameID types which allowed from the SP + * + * @return a List of SAML2 nameID types + */ + public abstract List getSPAllowedNameITTypes(); + + /** + * + * Build PVP 2.1 conform SAML2 metadata + * + * @param instancePublicURLPrefix + * Public-URL prefix which should be used to generate URLs. + * The URL String must by without trailing / + * + * @return PVP metadata as XML String + * @throws SecurityException + * @throws ConfigurationException + * @throws CredentialsNotAvailableException + * @throws TransformerFactoryConfigurationError + * @throws MarshallingException + * @throws TransformerException + * @throws ParserConfigurationException + * @throws IOException + * @throws SignatureException + */ + public String buildPVPMetadata(String instancePublicURLPrefix) throws CredentialsNotAvailableException, ConfigurationException, SecurityException, TransformerFactoryConfigurationError, MarshallingException, TransformerException, ParserConfigurationException, IOException, SignatureException { + if (MiscUtil.isEmpty(instancePublicURLPrefix)) { + Logger.error("Metadata generation FAILED! --> PublicURL Prefix is null or empty"); + throw new NullPointerException("PublicURL Prefix is null or empty"); + + } + + //remove trailing slash + if (instancePublicURLPrefix.endsWith("/")) + instancePublicURLPrefix.substring(0, instancePublicURLPrefix.length()-1); + + DateTime date = new DateTime(); + EntityDescriptor entityDescriptor = SAML2Utils + .createSAMLObject(EntityDescriptor.class); + + //set entityID + if (MiscUtil.isNotEmpty(getEntityIDPostfix())) + entityDescriptor.setEntityID(instancePublicURLPrefix + getEntityIDPostfix()); + else + entityDescriptor.setEntityID(instancePublicURLPrefix); + + //set contact and organisation information + List contactPersons = getContactPersonInformation(); + if (contactPersons != null) + entityDescriptor.getContactPersons().addAll(contactPersons); + + Organization organisation = getOrgansiationInformation(); + if (organisation != null) + entityDescriptor.setOrganization(organisation); + + //set IDP metadata + if (buildIDPSSODescriptor()) { + RoleDescriptor idpSSODesc = generateIDPMetadata(instancePublicURLPrefix); + if (idpSSODesc != null) + entityDescriptor.getRoleDescriptors().add(idpSSODesc); + + } + + //set SP metadata for interfederation + if (buildSPSSODescriptor()) { + RoleDescriptor spSSODesc = generateSPMetadata(instancePublicURLPrefix); + if (spSSODesc != null) + entityDescriptor.getRoleDescriptors().add(spSSODesc); + + } + + //set metadata signature parameters + Credential metadataSignCred = getMetadataSigningCredentials(); + Signature signature = getIDPSignature(metadataSignCred); + SecurityHelper.prepareSignatureParams(signature, metadataSignCred, null, null); + + + //initialize XML document builder + DocumentBuilder builder; + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + + builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + + + //build entities descriptor + if (buildEntitiesDescriptorAsRootElement()) { + EntitiesDescriptor entitiesDescriptor = + SAML2Utils.createSAMLObject(EntitiesDescriptor.class); + entitiesDescriptor.setName(getEntityFriendlyName()); + entitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); + entitiesDescriptor.setValidUntil(date.plusHours(getMetadataValidUntil())); + entitiesDescriptor.getEntityDescriptors().add(entityDescriptor); + + entitiesDescriptor.setSignature(signature); + + //marshall document + Marshaller out = Configuration.getMarshallerFactory() + .getMarshaller(entitiesDescriptor); + out.marshall(entitiesDescriptor, document); + + } else { + entityDescriptor.setValidUntil(date.plusHours(getMetadataValidUntil())); + + entityDescriptor.setSignature(signature); + + //marshall document + Marshaller out = Configuration.getMarshallerFactory() + .getMarshaller(entityDescriptor); + out.marshall(entityDescriptor, document); + + } + + //sign metadata + Signer.signObject(signature); + + //transform metadata object to XML string + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); + + StringWriter sw = new StringWriter(); + StreamResult sr = new StreamResult(sw); + DOMSource source = new DOMSource(document); + transformer.transform(source, sr); + sw.close(); + + return sw.toString(); + } + + + private RoleDescriptor generateSPMetadata(String instancePublicURLPrefix) throws CredentialsNotAvailableException, SecurityException, ConfigurationException { + SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); + spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + spSSODescriptor.setAuthnRequestsSigned(true); + spSSODescriptor.setWantAssertionsSigned(false); + + KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); + + //Set AuthRequest Signing certificate + Credential authcredential = getRequestorResponseSigningCredentials(); + if (authcredential == null) { + Logger.warn("SP Metadata generation FAILED! --> Builder has NO request signing-credential. "); + return null; + + } else { + KeyDescriptor signKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + signKeyDescriptor.setUse(UsageType.SIGNING); + signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); + spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); + + } + + //Set assertion encryption credentials + Credential authEncCredential = getEncryptionCredentials(); + + if (authEncCredential != null) { + KeyDescriptor encryKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + encryKeyDescriptor.setUse(UsageType.ENCRYPTION); + encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); + spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); + + } else { + Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); + + } + + //check nameID formates + if (getIDPPossibleNameITTypes() == null || getIDPPossibleNameITTypes().size() == 0) { + Logger.warn("SP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); + return null; + + } else { + for (String format : getSPAllowedNameITTypes()) { + NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); + nameIDFormat.setFormat(format); + spSSODescriptor.getNameIDFormats().add(nameIDFormat); + + } + } + + + //add POST-Binding assertion consumer services + if (MiscUtil.isNotEmpty(getSPAssertionConsumerServicePostBindingURL())) { + AssertionConsumerService postassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); + postassertionConsumerService.setIndex(0); + postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + postassertionConsumerService.setLocation(instancePublicURLPrefix + getSPAssertionConsumerServicePostBindingURL()); + postassertionConsumerService.setIsDefault(true); + spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); + + } + + //add POST-Binding assertion consumer services + if (MiscUtil.isNotEmpty(getSPAssertionConsumerServiceRedirectBindingURL())) { + AssertionConsumerService redirectassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); + redirectassertionConsumerService.setIndex(1); + redirectassertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + redirectassertionConsumerService.setLocation(instancePublicURLPrefix + getSPAssertionConsumerServiceRedirectBindingURL()); + spSSODescriptor.getAssertionConsumerServices().add(redirectassertionConsumerService); + + } + + //validate WebSSO endpoints + if (spSSODescriptor.getAssertionConsumerServices().size() == 0) { + Logger.warn("SP Metadata generation FAILED! --> NO SAML2 AssertionConsumerService endpoint found. "); + return null; + + } + + //add POST-Binding SLO descriptor + if (MiscUtil.isNotEmpty(getSPSLOPostBindingURL())) { + SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + postSLOService.setLocation(instancePublicURLPrefix + getSPSLOPostBindingURL()); + postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + spSSODescriptor.getSingleLogoutServices().add(postSLOService); + + } + + //add POST-Binding SLO descriptor + if (MiscUtil.isNotEmpty(getSPSLORedirectBindingURL())) { + SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + redirectSLOService.setLocation(instancePublicURLPrefix + getSPSLORedirectBindingURL()); + redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + spSSODescriptor.getSingleLogoutServices().add(redirectSLOService); + + } + + //add POST-Binding SLO descriptor + if (MiscUtil.isNotEmpty(getSPSLOSOAPBindingURL())) { + SingleLogoutService soapSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + soapSLOService.setLocation(instancePublicURLPrefix + getSPSLOSOAPBindingURL()); + soapSLOService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); + spSSODescriptor.getSingleLogoutServices().add(soapSLOService); + + } + + + //add required attributes + List reqSPAttr = getSPRequiredAttributes(); + AttributeConsumingService attributeService = SAML2Utils.createSAMLObject(AttributeConsumingService.class); + + attributeService.setIndex(0); + attributeService.setIsDefault(true); + ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); + serviceName.setName(new LocalizedString("Default Service", "en")); + attributeService.getNames().add(serviceName); + + if (reqSPAttr != null && reqSPAttr.size() > 0) { + Logger.debug("Add " + reqSPAttr.size() + " attributes to SP metadata"); + attributeService.getRequestAttributes().addAll(reqSPAttr); + + } else { + Logger.debug("SP metadata contains NO requested attributes."); + + } + + spSSODescriptor.getAttributeConsumingServices().add(attributeService); + + return spSSODescriptor; + } + + private IDPSSODescriptor generateIDPMetadata(String instancePublicURLPrefix) throws ConfigurationException, CredentialsNotAvailableException, SecurityException { + //check response signing credential + Credential responseSignCred = getRequestorResponseSigningCredentials(); + if (responseSignCred == null) { + Logger.warn("IDP Metadata generation FAILED! --> Builder has NO Response signing credential. "); + return null; + + } + + //check nameID formates + if (getIDPPossibleNameITTypes() == null || getIDPPossibleNameITTypes().size() == 0) { + Logger.warn("IDP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); + return null; + + } + + // build SAML2 IDP-SSO descriptor element + IDPSSODescriptor idpSSODescriptor = SAML2Utils + .createSAMLObject(IDPSSODescriptor.class); + + idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + + //set ass default value, because PVP 2.x specification defines this feature as MUST + idpSSODescriptor.setWantAuthnRequestsSigned(true); + + // add WebSSO descriptor for POST-Binding + if (MiscUtil.isNotEmpty(getIDPWebSSOPostBindingURL())) { + SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); + postSingleSignOnService.setLocation(instancePublicURLPrefix + getIDPWebSSOPostBindingURL()); + postSingleSignOnService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); + + } + + // add WebSSO descriptor for Redirect-Binding + if (MiscUtil.isNotEmpty(getIDPWebSSORedirectBindingURL())) { + SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); + postSingleSignOnService.setLocation(instancePublicURLPrefix + getIDPWebSSORedirectBindingURL()); + postSingleSignOnService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); + + } + + //add Single LogOut POST-Binding endpoing + if (MiscUtil.isNotEmpty(getIDPSLOPostBindingURL())) { + SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + postSLOService.setLocation(instancePublicURLPrefix + getIDPSLOPostBindingURL()); + postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + idpSSODescriptor.getSingleLogoutServices().add(postSLOService); + + } + + //add Single LogOut Redirect-Binding endpoing + if (MiscUtil.isNotEmpty(getIDPSLORedirectBindingURL())) { + SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + redirectSLOService.setLocation(instancePublicURLPrefix + getIDPSLORedirectBindingURL()); + redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + idpSSODescriptor.getSingleLogoutServices().add(redirectSLOService); + + } + + //validate WebSSO endpoints + if (idpSSODescriptor.getSingleSignOnServices().size() == 0) { + Logger.warn("IDP Metadata generation FAILED! --> NO SAML2 SingleSignOnService endpoint found. "); + return null; + + } + + //set assertion signing key + KeyDescriptor signKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + signKeyDescriptor.setUse(UsageType.SIGNING); + KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); + signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(getRequestorResponseSigningCredentials())); + idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); + + //set IDP attribute set + idpSSODescriptor.getAttributes().addAll(getIDPPossibleAttributes()); + + //set providable nameID formats + for (String format : getIDPPossibleNameITTypes()) { + NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); + nameIDFormat.setFormat(format); + idpSSODescriptor.getNameIDFormats().add(nameIDFormat); + + } + + return idpSSODescriptor; + + } + + private Signature getIDPSignature(Credential credentials) { + PrivateKey privatekey = credentials.getPrivateKey(); + Signature signer = SAML2Utils.createSAMLObject(Signature.class); + + if (privatekey instanceof RSAPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); + + } else if (privatekey instanceof iaik.security.ecc.ecdsa.ECPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); + + } else { + Logger.warn("Could NOT evaluate the Private-Key type from " + credentials.getEntityId() + " credential."); + + + } + + signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); + signer.setSigningCredential(credentials); + return signer; + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AttributQueryBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AttributQueryBuilder.java index ebbafd4e3..9c097780b 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 @@ -25,7 +25,6 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder; import java.util.ArrayList; import java.util.Iterator; import java.util.List; -import java.util.Set; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -46,17 +45,18 @@ import org.opensaml.xml.signature.Signature; import org.opensaml.xml.signature.SignatureConstants; import org.opensaml.xml.signature.SignatureException; import org.opensaml.xml.signature.Signer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.w3c.dom.Document; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.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.CredentialProvider; 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; import at.gv.egovernment.moa.util.Constants; @@ -65,9 +65,12 @@ import at.gv.egovernment.moa.util.Constants; * @author tlenz * */ +@Service("AttributQueryBuilder") public class AttributQueryBuilder { - public static List buildSAML2AttributeList(IOAAuthParameters oa, Iterator iterator) { + @Autowired IDPCredentialProvider credentialProvider; + + public List buildSAML2AttributeList(IOAAuthParameters oa, Iterator iterator) { Logger.debug("Build OA specific Attributes for AttributQuery request"); @@ -103,7 +106,7 @@ public class AttributQueryBuilder { } - public static AttributeQuery buildAttributQueryRequest(String nameID, + public AttributeQuery buildAttributQueryRequest(String nameID, String endpoint, List requestedAttributes) throws AttributQueryException { @@ -136,7 +139,7 @@ public class AttributQueryBuilder { query.setDestination(endpoint); - X509Credential idpSigningCredential = CredentialProvider.getIDPAssertionSigningCredential(); + X509Credential idpSigningCredential = credentialProvider.getIDPAssertionSigningCredential(); Signature signer = SAML2Utils.createSAMLObject(Signature.class); signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1); 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 dbbc21ec9..959fc7d2d 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,6 +23,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.builder; import java.security.NoSuchAlgorithmException; +import java.util.LinkedHashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; @@ -57,14 +58,20 @@ import org.opensaml.xml.security.x509.X509Credential; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.signature.SignatureConstants; import org.opensaml.xml.signature.Signer; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.w3c.dom.Document; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.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.config.ConfigurationException; +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; @@ -74,7 +81,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NOSLOServiceDescripto 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.CredentialProvider; +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.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; @@ -83,9 +90,12 @@ import at.gv.egovernment.moa.logging.Logger; * @author tlenz * */ +@Service("PVP_SingleLogOutBuilder") public class SingleLogOutBuilder { - public static void checkStatusCode(SLOInformationContainer sloContainer, LogoutResponse logOutResp) { + @Autowired private IDPCredentialProvider credentialProvider; + + public void checkStatusCode(ISLOInformationContainer sloContainer, LogoutResponse logOutResp) { Status status = logOutResp.getStatus(); if (!status.getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { String message = " Message: "; @@ -111,12 +121,12 @@ public class SingleLogOutBuilder { * @param relayState * @return */ - public static String getFrontChannelSLOMessageURL(String serviceURL, String bindingType, + public String getFrontChannelSLOMessageURL(String serviceURL, String bindingType, RequestAbstractType sloReq, HttpServletRequest httpReq, HttpServletResponse httpResp, String relayState) throws MOAIDException { try { - X509Credential credentials = CredentialProvider + X509Credential credentials = credentialProvider .getIDPAssertionSigningCredential(); Logger.debug("create SAML RedirectBinding response"); @@ -143,12 +153,12 @@ public class SingleLogOutBuilder { } } - public static String getFrontChannelSLOMessageURL(SingleLogoutService service, + public String getFrontChannelSLOMessageURL(SingleLogoutService service, StatusResponseType sloResp, HttpServletRequest httpReq, HttpServletResponse httpResp, String relayState) throws MOAIDException { try { - X509Credential credentials = CredentialProvider + X509Credential credentials = credentialProvider .getIDPAssertionSigningCredential(); Logger.debug("create SAML RedirectBinding response"); @@ -171,7 +181,7 @@ public class SingleLogOutBuilder { } } - public static void sendFrontChannelSLOMessage(SingleLogoutService consumerService, + public void sendFrontChannelSLOMessage(SingleLogoutService consumerService, LogoutResponse sloResp, HttpServletRequest req, HttpServletResponse resp, String relayState) throws MOAIDException { IEncoder binding = null; @@ -205,7 +215,7 @@ public class SingleLogOutBuilder { } - public static LogoutRequest buildSLORequestMessage(SLOInformationImpl sloInfo) throws ConfigurationException, MOAIDException { + public LogoutRequest buildSLORequestMessage(SLOInformationImpl sloInfo) throws ConfigurationException, MOAIDException { LogoutRequest sloReq = SAML2Utils.createSAMLObject(LogoutRequest.class); SecureRandomIdentifierGenerator gen; @@ -236,7 +246,7 @@ public class SingleLogOutBuilder { //sign message try { - X509Credential idpSigningCredential = CredentialProvider.getIDPAssertionSigningCredential(); + X509Credential idpSigningCredential = credentialProvider.getIDPAssertionSigningCredential(); Signature signer = SAML2Utils.createSAMLObject(Signature.class); signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); @@ -265,7 +275,7 @@ public class SingleLogOutBuilder { return sloReq; } - public static LogoutResponse buildSLOErrorResponse(SingleLogoutService sloService, PVPTargetConfiguration spRequest, String firstLevelStatusCode) throws ConfigurationException, MOAIDException { + public LogoutResponse buildSLOErrorResponse(SingleLogoutService sloService, PVPTargetConfiguration spRequest, String firstLevelStatusCode) throws ConfigurationException, MOAIDException { LogoutResponse sloResp = buildBasicResponse(sloService, spRequest); Status status = SAML2Utils.createSAMLObject(Status.class); @@ -282,7 +292,7 @@ public class SingleLogOutBuilder { return sloResp; } - public static LogoutResponse buildSLOResponseMessage(SingleLogoutService sloService, PVPTargetConfiguration spRequest, List failedOAs) throws MOAIDException { + public LogoutResponse buildSLOResponseMessage(SingleLogoutService sloService, PVPTargetConfiguration spRequest, List failedOAs) throws MOAIDException { LogoutResponse sloResp = buildBasicResponse(sloService, spRequest); Status status; @@ -307,7 +317,7 @@ public class SingleLogOutBuilder { } - private static LogoutResponse buildBasicResponse(SingleLogoutService sloService, PVPTargetConfiguration spRequest) throws ConfigurationException, MOAIDException { + private LogoutResponse buildBasicResponse(SingleLogoutService sloService, PVPTargetConfiguration spRequest) throws ConfigurationException, MOAIDException { LogoutResponse sloResp = SAML2Utils.createSAMLObject(LogoutResponse.class); Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); issuer.setValue(spRequest.getAuthURLWithOutSlash()); @@ -338,7 +348,7 @@ public class SingleLogOutBuilder { } - public static SingleLogoutService getRequestSLODescriptor(String entityID) throws NOSLOServiceDescriptorException { + public SingleLogoutService getRequestSLODescriptor(String entityID) throws NOSLOServiceDescriptorException { try { EntityDescriptor entity = MOAMetadataProvider.getInstance().getEntityDescriptor(entityID); SSODescriptor spsso = entity.getSPSSODescriptor(SAMLConstants.SAML20P_NS); @@ -379,7 +389,7 @@ public class SingleLogOutBuilder { } - public static SingleLogoutService getResponseSLODescriptor(PVPTargetConfiguration spRequest) throws NoMetadataInformationException, NOSLOServiceDescriptorException { + public SingleLogoutService getResponseSLODescriptor(PVPTargetConfiguration spRequest) throws NoMetadataInformationException, NOSLOServiceDescriptorException { MOARequest moaReq = (MOARequest) spRequest.getRequest(); EntityDescriptor metadata = moaReq.getEntityMetadata(); SSODescriptor ssodesc = metadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS); @@ -415,4 +425,91 @@ public class SingleLogOutBuilder { return sloService; } + public void parseActiveOAs(SLOInformationContainer container, + List dbOAs, String removeOAID) { + if (container.getActiveBackChannelOAs() == null) + container.setActiveBackChannelOAs(new LinkedHashMap()); + if (container.getActiveFrontChannalOAs() == null) + container.setActiveFrontChannalOAs(new LinkedHashMap()); + + + if (dbOAs != null) { + for (OASessionStore oa : dbOAs) { + if (!oa.getOaurlprefix().equals(removeOAID)) { + + //Actually only PVP 2.1 support Single LogOut + if (PVP2XProtocol.PATH.equals(oa.getProtocolType())) { + SingleLogoutService sloDesc; + try { + sloDesc = getRequestSLODescriptor(oa.getOaurlprefix()); + + if (sloDesc.getBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) + container.getActiveBackChannelOAs().put(oa.getOaurlprefix(), + new SLOInformationImpl( + oa.getAuthURL(), + oa.getAssertionSessionID(), + oa.getUserNameID(), + oa.getUserNameIDFormat(), + oa.getProtocolType(), + sloDesc)); + + else + container.getActiveFrontChannalOAs().put(oa.getOaurlprefix(), + new SLOInformationImpl( + oa.getAuthURL(), + oa.getAssertionSessionID(), + oa.getUserNameID(), + oa.getUserNameIDFormat(), + oa.getProtocolType(), + sloDesc)); + + } catch (NOSLOServiceDescriptorException e) { + container.putFailedOA(oa.getOaurlprefix()); + + } + + } else + container.putFailedOA(oa.getOaurlprefix()); + } + } + } + } + + /** + * @param dbIDPs + * @param value + */ + public void parseActiveIDPs(SLOInformationContainer container, + List dbIDPs, String removeIDP) { + if (container.getActiveBackChannelOAs() == null) + container.setActiveBackChannelOAs(new LinkedHashMap()); + if (container.getActiveFrontChannalOAs() == null) + container.setActiveFrontChannalOAs(new LinkedHashMap()); + + if (dbIDPs != null) { + for (InterfederationSessionStore el : dbIDPs) { + if (!el.getIdpurlprefix().equals(removeIDP)) { + + SingleLogoutService sloDesc; + try { + sloDesc = getRequestSLODescriptor(el.getIdpurlprefix()); + + container.getActiveFrontChannalOAs().put(el.getIdpurlprefix(), + new SLOInformationImpl( + el.getAuthURL(), + el.getSessionIndex(), + el.getUserNameID(), + NameID.TRANSIENT, + PVP2XProtocol.PATH, + sloDesc)); + + } catch (NOSLOServiceDescriptorException e) { + container.putFailedOA(el.getIdpurlprefix()); + + } + } + } + } + } + } 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 47d7a29b3..bbf395a6f 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,8 +22,6 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.config; -import iaik.x509.X509Certificate; - import java.io.IOException; import java.net.URL; import java.security.cert.CertificateException; @@ -51,12 +49,11 @@ import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; -import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; +import iaik.x509.X509Certificate; public class PVPConfiguration { @@ -79,18 +76,6 @@ public class PVPConfiguration { public static final String PVP_CONFIG_FILE = "pvp2config.properties"; - public static final String IDP_JAVAKEYSTORE = "idp.ks.file"; - public static final String IDP_KS_PASS = "idp.ks.kspassword"; - - public static final String IDP_KEYALIASMETADATA = "idp.ks.metadata.alias"; - public static final String IDP_KEY_PASSMETADATA = "idp.ks.metadata.keypassword"; - - public static final String IDP_KEYALIASASSERTION = "idp.ks.assertion.sign.alias"; - public static final String IDP_KEY_PASSASSERTION = "idp.ks.assertion.sign.keypassword"; - - public static final String IDP_KEYALIASENCRYTPION = "sp.ks.assertion.encryption.alias"; - public static final String IDP_KEY_PASSENCRYTPION = "sp.ks.assertion.encryption.keypassword"; - public static final String IDP_ISSUER_NAME = "servicename"; public static final String IDP_ORG_NAME = "name.short"; @@ -162,38 +147,6 @@ public class PVPConfiguration { public String getIDPSSOMetadataService(String publicURLPrefix) throws ConfigurationException { return publicURLPrefix + PVP2_METADATA; } - - public String getIDPKeyStoreFilename() { - return FileUtils.makeAbsoluteURL(props.getProperty(IDP_JAVAKEYSTORE), rootDir); - } - - public String getIDPKeyStorePassword() { - return props.getProperty(IDP_KS_PASS).trim(); - } - - public String getIDPKeyAliasMetadata() { - return props.getProperty(IDP_KEYALIASMETADATA).trim(); - } - - public String getIDPKeyPasswordMetadata() { - return props.getProperty(IDP_KEY_PASSMETADATA).trim(); - } - - public String getIDPKeyAliasAssertionSign() { - return props.getProperty(IDP_KEYALIASASSERTION).trim(); - } - - public String getIDPKeyPasswordAssertionSign() { - return props.getProperty(IDP_KEY_PASSASSERTION).trim(); - } - - public String getIDPKeyAliasAssertionEncryption() { - return props.getProperty(IDP_KEYALIASASSERTION).trim(); - } - - public String getIDPKeyPasswordAssertionEncryption() { - return props.getProperty(IDP_KEY_PASSASSERTION).trim(); - } public String getIDPIssuerName() throws ConfigurationException { 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 new file mode 100644 index 000000000..e7df23d61 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java @@ -0,0 +1,186 @@ +/******************************************************************************* + * 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 org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.x509.X509Credential; + +import at.gv.egovernment.moa.id.opemsaml.MOAKeyStoreX509CredentialAdapter; +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 static 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(getFriendlyName() + " Assertion Signing credentials (Alias: " + + getMetadataKeyAlias() + ") is not found or contains no PrivateKey.", null); + + } + return credentials; + } catch (Exception e) { + Logger.error("Failed to generate " + getFriendlyName() + " Metadata Signing credentials"); + e.printStackTrace(); + throw new CredentialsNotAvailableException(e.getMessage(), null); + } + } + + 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(getFriendlyName() + " Assertion Signing credentials (Alias: " + + getSignatureKeyAlias() + ") is not found or contains no PrivateKey.", null); + + } + + return (X509Credential) credentials; + } catch (Exception e) { + Logger.error("Failed to generate " + getFriendlyName() + " Assertion Signing credentials"); + e.printStackTrace(); + throw new CredentialsNotAvailableException(e.getMessage(), null); + } + } + + 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(getFriendlyName() + " Assertion Encryption credentials (Alias: " + + getEncryptionKeyAlias() + ") is not found or contains no PrivateKey.", null); + + } + + return (X509Credential) credentials; + } catch (Exception e) { + Logger.error("Failed to generate " + getFriendlyName() + " Assertion Encryption credentials"); + e.printStackTrace(); + throw new CredentialsNotAvailableException(e.getMessage(), null); + } + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java deleted file mode 100644 index d76e6c2f1..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java +++ /dev/null @@ -1,198 +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.RSAPrivateKey; - -import org.opensaml.xml.security.credential.Credential; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.x509.BasicX509Credential; -import org.opensaml.xml.security.x509.KeyStoreX509CredentialAdapter; -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.config.PVPConfiguration; -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 class CredentialProvider { - - private static KeyStore keyStore = null; - - public static X509Credential getIDPMetaDataSigningCredential() - throws CredentialsNotAvailableException { - PVPConfiguration config = PVPConfiguration.getInstance(); - try { - - if (keyStore == null) - keyStore = KeyStoreUtils.loadKeyStore(config.getIDPKeyStoreFilename(), - config.getIDPKeyStorePassword()); - - MOAKeyStoreX509CredentialAdapter credentials = new MOAKeyStoreX509CredentialAdapter( - keyStore, config.getIDPKeyAliasMetadata(), config - .getIDPKeyPasswordMetadata().toCharArray()); - - credentials.setUsageType(UsageType.SIGNING); - if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { - Logger.error("IDP Metadata Signing credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException("IDP Assertion Signing credentials (Alias: " - + config.getIDPKeyAliasMetadata() + ") is not found or contains no PrivateKey.", null); - - } - return credentials; - } catch (Exception e) { - Logger.error("Failed to generate IDP Metadata Signing credentials"); - e.printStackTrace(); - throw new CredentialsNotAvailableException(e.getMessage(), null); - } - } - - public static X509Credential getIDPAssertionSigningCredential() - throws CredentialsNotAvailableException { - PVPConfiguration config = PVPConfiguration.getInstance(); - try { - if (keyStore == null) - keyStore = KeyStoreUtils.loadKeyStore(config.getIDPKeyStoreFilename(), - config.getIDPKeyStorePassword()); - - MOAKeyStoreX509CredentialAdapter credentials = new MOAKeyStoreX509CredentialAdapter( - keyStore, config.getIDPKeyAliasAssertionSign(), config - .getIDPKeyPasswordAssertionSign().toCharArray()); - - credentials.setUsageType(UsageType.SIGNING); - if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { - Logger.error("IDP Assertion Signing credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException("IDP Assertion Signing credentials (Alias: " - + config.getIDPKeyAliasAssertionSign() + ") is not found or contains no PrivateKey.", null); - - } - - return (X509Credential) credentials; - } catch (Exception e) { - Logger.error("Failed to generate IDP Assertion Signing credentials"); - e.printStackTrace(); - throw new CredentialsNotAvailableException(e.getMessage(), null); - } - } - - public static X509Credential getIDPAssertionEncryptionCredential() - throws CredentialsNotAvailableException { - PVPConfiguration config = PVPConfiguration.getInstance(); - try { - if (keyStore == null) - keyStore = KeyStoreUtils.loadKeyStore(config.getIDPKeyStoreFilename(), - config.getIDPKeyStorePassword()); - - //if no encryption key is configured return null - if (MiscUtil.isEmpty(config.getIDPKeyAliasAssertionEncryption())) - return null; - - MOAKeyStoreX509CredentialAdapter credentials = new MOAKeyStoreX509CredentialAdapter( - keyStore, config.getIDPKeyAliasAssertionEncryption(), config - .getIDPKeyPasswordAssertionEncryption().toCharArray()); - - credentials.setUsageType(UsageType.ENCRYPTION); - - if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { - Logger.error("IDP Assertion Encryption credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException("IDP Assertion Encryption credentials (Alias: " - + config.getIDPKeyAliasAssertionEncryption() + ") is not found or contains no PrivateKey.", null); - - } - - return (X509Credential) credentials; - } catch (Exception e) { - Logger.error("Failed to generate IDP Assertion Encryption credentials"); - e.printStackTrace(); - throw new CredentialsNotAvailableException(e.getMessage(), null); - } - } - - 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 iaik.security.ecc.ecdsa.ECPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); - - } else { - Logger.warn("Could NOT evaluate the Private-Key type from PVP credential."); - - } - - signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); - signer.setSigningCredential(credentials); - return signer; - - } - - public static Credential getSPTrustedCredential(String entityID) - throws CredentialsNotAvailableException { - - iaik.x509.X509Certificate cert = PVPConfiguration.getInstance() - .getTrustEntityCertificate(entityID); - - if (cert == null) { - throw new CredentialsNotAvailableException("ServiceProvider Certificate can not be loaded from Database", null); - } - - BasicX509Credential credential = new BasicX509Credential(); - credential.setEntityId(entityID); - credential.setUsageType(UsageType.SIGNING); - credential.setPublicKey(cert.getPublicKey()); - - return credential; - } - /* - * public static Credential getTrustedCredential() throws - * CredentialsNotAvailableException { String filename = - * PVPConfiguration.getInstance().getTrustEntityCertificate("sp.crt"); - * - * iaik.x509.X509Certificate cert; try { cert = new X509Certificate(new - * FileInputStream(new File(filename))); } catch (CertificateException e) { - * e.printStackTrace(); throw new - * CredentialsNotAvailableException(e.getMessage(), null); } catch - * (FileNotFoundException e) { e.printStackTrace(); throw new - * CredentialsNotAvailableException(e.getMessage(), null); } catch - * (IOException e) { e.printStackTrace(); throw new - * CredentialsNotAvailableException(e.getMessage(), null); } - * - * BasicX509Credential credential = new BasicX509Credential(); - * credential.setEntityId("sp.crt"); - * credential.setUsageType(UsageType.SIGNING); - * credential.setPublicKey(cert.getPublicKey()); - * - * return credential; } - */ -} 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 new file mode 100644 index 000000000..8fb4ec3cf --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/IDPCredentialProvider.java @@ -0,0 +1,150 @@ +/* + * 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.util.Properties; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.util.FileUtils; + +@Service("IDPCredentialProvider") +public class IDPCredentialProvider extends AbstractCredentialProvider { + public static final String IDP_JAVAKEYSTORE = "idp.ks.file"; + public static final String IDP_KS_PASS = "idp.ks.kspassword"; + + public static final String IDP_KEYALIASMETADATA = "idp.ks.metadata.alias"; + public static final String IDP_KEY_PASSMETADATA = "idp.ks.metadata.keypassword"; + + public static final String IDP_KEYALIASASSERTION = "idp.ks.assertion.sign.alias"; + public static final String IDP_KEY_PASSASSERTION = "idp.ks.assertion.sign.keypassword"; + + public static final String IDP_KEYALIASENCRYTPION = "sp.ks.assertion.encryption.alias"; + public static final String IDP_KEY_PASSENCRYTPION = "sp.ks.assertion.encryption.keypassword"; + + + private @Autowired AuthConfiguration authConfig; + private Properties props = null; + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getKeyStoreFilePath() + */ + @Override + public String getKeyStoreFilePath() { + if (props == null) + props = authConfig.getGeneralPVP2ProperiesConfig(); + + return FileUtils.makeAbsoluteURL( + props.getProperty(IDP_JAVAKEYSTORE), + authConfig.getRootConfigFileDir()); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getKeyStorePassword() + */ + @Override + public String getKeyStorePassword() { + if (props == null) + props = authConfig.getGeneralPVP2ProperiesConfig(); + + return props.getProperty(IDP_KS_PASS).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getMetadataKeyAlias() + */ + @Override + public String getMetadataKeyAlias() { + if (props == null) + props = authConfig.getGeneralPVP2ProperiesConfig(); + + return props.getProperty(IDP_KEYALIASMETADATA).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getMetadataKeyPassword() + */ + @Override + public String getMetadataKeyPassword() { + if (props == null) + props = authConfig.getGeneralPVP2ProperiesConfig(); + + return props.getProperty(IDP_KEY_PASSMETADATA).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getSignatureKeyAlias() + */ + @Override + public String getSignatureKeyAlias() { + if (props == null) + props = authConfig.getGeneralPVP2ProperiesConfig(); + + return props.getProperty(IDP_KEYALIASASSERTION).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getSignatureKeyPassword() + */ + @Override + public String getSignatureKeyPassword() { + if (props == null) + props = authConfig.getGeneralPVP2ProperiesConfig(); + + return props.getProperty(IDP_KEY_PASSASSERTION).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getEncryptionKeyAlias() + */ + @Override + public String getEncryptionKeyAlias() { + if (props == null) + props = authConfig.getGeneralPVP2ProperiesConfig(); + + return props.getProperty(IDP_KEYALIASENCRYTPION).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getEncryptionKeyPassword() + */ + @Override + public String getEncryptionKeyPassword() { + if (props == null) + props = authConfig.getGeneralPVP2ProperiesConfig(); + + return props.getProperty(IDP_KEYALIASENCRYTPION).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getCredentialName() + */ + @Override + public String getFriendlyName() { + return "IDP"; + } + +} 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 69c760f19..4650327b4 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 @@ -29,6 +29,8 @@ import org.opensaml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.security.SAMLSignatureProfileValidator; import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.x509.BasicX509Credential; import org.opensaml.xml.signature.SignatureValidator; import org.opensaml.xml.validation.ValidationException; @@ -37,9 +39,10 @@ import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +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.CredentialProvider; +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; @@ -83,8 +86,7 @@ public class EntityVerifier { throw new SAMLRequestNotSignedException(e); } - Credential credential = CredentialProvider - .getSPTrustedCredential(entityDescriptor.getEntityID()); + Credential credential = getSPTrustedCredential(entityDescriptor.getEntityID()); if (credential == null) { throw new NoCredentialsException(entityDescriptor.getEntityID()); } @@ -171,8 +173,7 @@ public class EntityVerifier { + " entryID is used to select the certificate to perform Metadata verification."); } - Credential credential = CredentialProvider - .getSPTrustedCredential(entities.get(0).getEntityID()); + Credential credential = getSPTrustedCredential(entities.get(0).getEntityID()); if (credential == null) { throw new NoCredentialsException("moaID IDP"); @@ -188,5 +189,23 @@ public class EntityVerifier { } } } + + public static Credential getSPTrustedCredential(String entityID) + throws CredentialsNotAvailableException { + + iaik.x509.X509Certificate cert = PVPConfiguration.getInstance() + .getTrustEntityCertificate(entityID); + + if (cert == null) { + throw new CredentialsNotAvailableException("ServiceProvider Certificate can not be loaded from Database", null); + } + + BasicX509Credential credential = new BasicX509Credential(); + credential.setEntityId(entityID); + credential.setUsageType(UsageType.SIGNING); + credential.setPublicKey(cert.getPublicKey()); + + return credential; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index 812e27a36..cc7afa842 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -22,55 +22,34 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.verification; -import java.util.ArrayList; -import java.util.List; - import javax.xml.namespace.QName; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; -import org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.saml2.core.Conditions; -import org.opensaml.saml2.core.EncryptedAssertion; import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.Response; -import org.opensaml.saml2.core.StatusCode; import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.encryption.Decrypter; -import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; import org.opensaml.saml2.metadata.IDPSSODescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.security.MetadataCriteria; import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.xml.encryption.ChainingEncryptedKeyResolver; -import org.opensaml.xml.encryption.DecryptionException; -import org.opensaml.xml.encryption.InlineEncryptedKeyResolver; -import org.opensaml.xml.encryption.SimpleRetrievalMethodEncryptedKeyResolver; import org.opensaml.xml.security.CriteriaSet; import org.opensaml.xml.security.credential.UsageType; import org.opensaml.xml.security.criteria.EntityIDCriteria; import org.opensaml.xml.security.criteria.UsageCriteria; -import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver; -import org.opensaml.xml.security.x509.X509Credential; 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.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; 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.CredentialProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -179,114 +158,114 @@ public class SAMLVerificationEngine { } } - public static void validateAssertion(Response samlResp, boolean validateDestination) throws AssertionValidationExeption { - try { - if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { - List saml2assertions = new ArrayList(); - - List allowedPublicURLPrefix = - AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); - boolean isValidDestination = false; - for (String allowedPreFix : allowedPublicURLPrefix) { - if (validateDestination && samlResp.getDestination().startsWith( - allowedPreFix)) { - isValidDestination = true; - break; - - } - } - if (!isValidDestination) { - Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); - throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); - - } - - //check encrypted Assertion - List encryAssertionList = samlResp.getEncryptedAssertions(); - if (encryAssertionList != null && encryAssertionList.size() > 0) { - //decrypt assertions - - Logger.debug("Found encryped assertion. Start decryption ..."); - - X509Credential authDecCredential = CredentialProvider.getIDPAssertionEncryptionCredential(); - - StaticKeyInfoCredentialResolver skicr = - new StaticKeyInfoCredentialResolver(authDecCredential); - - ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); - encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); - encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); - encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); - - Decrypter samlDecrypter = - new Decrypter(null, skicr, encryptedKeyResolver); - - for (EncryptedAssertion encAssertion : encryAssertionList) { - saml2assertions.add(samlDecrypter.decrypt(encAssertion)); - - } - - Logger.debug("Assertion decryption finished. "); - - } else { - saml2assertions.addAll(samlResp.getAssertions()); - - } - - List validatedassertions = new ArrayList(); - for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { - - try { - performSchemaValidation(saml2assertion.getDOM()); - - Conditions conditions = saml2assertion.getConditions(); - DateTime notbefore = conditions.getNotBefore().minusMinutes(5); - DateTime notafter = conditions.getNotOnOrAfter(); - if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { - Logger.warn("PVP2 Assertion is out of Date. " - + "{ Current : " + new DateTime() - + " NotBefore: " + notbefore - + " NotAfter : " + notafter - + " }");; - - } else { - validatedassertions.add(saml2assertion); - - } - - } catch (SchemaValidationException e) { - - } - } - - if (validatedassertions.isEmpty()) { - Logger.info("No valid PVP 2.1 assertion received."); - throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); - } - - samlResp.getAssertions().clear(); - samlResp.getEncryptedAssertions().clear(); - samlResp.getAssertions().addAll(validatedassertions); - - } else { - Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " - + samlResp.getStatus().getStatusCode().getValue()); - throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " - + samlResp.getStatus().getStatusCode().getValue(), null); - } - - } catch (CredentialsNotAvailableException e) { - Logger.warn("Assertion decrypt FAILED - No Credentials", e); - throw new AssertionValidationExeption("Assertion decrypt FAILED - No Credentials", null, e); - - } catch (DecryptionException e) { - Logger.warn("Assertion decrypt FAILED.", e); - throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); - - } catch (ConfigurationException e) { - throw new AssertionValidationExeption("pvp.12", null, e); - } - } +// public static void validateAssertion(Response samlResp, boolean validateDestination) throws AssertionValidationExeption { +// try { +// if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { +// List saml2assertions = new ArrayList(); +// +// List allowedPublicURLPrefix = +// AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); +// boolean isValidDestination = false; +// for (String allowedPreFix : allowedPublicURLPrefix) { +// if (validateDestination && samlResp.getDestination().startsWith( +// allowedPreFix)) { +// isValidDestination = true; +// break; +// +// } +// } +// if (!isValidDestination) { +// Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); +// throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); +// +// } +// +// //check encrypted Assertion +// List encryAssertionList = samlResp.getEncryptedAssertions(); +// if (encryAssertionList != null && encryAssertionList.size() > 0) { +// //decrypt assertions +// +// Logger.debug("Found encryped assertion. Start decryption ..."); +// +// X509Credential authDecCredential = CredentialProvider.getIDPAssertionEncryptionCredential(); +// +// StaticKeyInfoCredentialResolver skicr = +// new StaticKeyInfoCredentialResolver(authDecCredential); +// +// ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); +// encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); +// encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); +// encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); +// +// Decrypter samlDecrypter = +// new Decrypter(null, skicr, encryptedKeyResolver); +// +// for (EncryptedAssertion encAssertion : encryAssertionList) { +// saml2assertions.add(samlDecrypter.decrypt(encAssertion)); +// +// } +// +// Logger.debug("Assertion decryption finished. "); +// +// } else { +// saml2assertions.addAll(samlResp.getAssertions()); +// +// } +// +// List validatedassertions = new ArrayList(); +// for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { +// +// try { +// performSchemaValidation(saml2assertion.getDOM()); +// +// Conditions conditions = saml2assertion.getConditions(); +// DateTime notbefore = conditions.getNotBefore().minusMinutes(5); +// DateTime notafter = conditions.getNotOnOrAfter(); +// if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { +// Logger.warn("PVP2 Assertion is out of Date. " +// + "{ Current : " + new DateTime() +// + " NotBefore: " + notbefore +// + " NotAfter : " + notafter +// + " }");; +// +// } else { +// validatedassertions.add(saml2assertion); +// +// } +// +// } catch (SchemaValidationException e) { +// +// } +// } +// +// if (validatedassertions.isEmpty()) { +// Logger.info("No valid PVP 2.1 assertion received."); +// throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); +// } +// +// samlResp.getAssertions().clear(); +// samlResp.getEncryptedAssertions().clear(); +// samlResp.getAssertions().addAll(validatedassertions); +// +// } else { +// Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " +// + samlResp.getStatus().getStatusCode().getValue()); +// throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " +// + samlResp.getStatus().getStatusCode().getValue(), null); +// } +// +// } catch (CredentialsNotAvailableException e) { +// Logger.warn("Assertion decrypt FAILED - No Credentials", e); +// throw new AssertionValidationExeption("Assertion decrypt FAILED - No Credentials", null, e); +// +// } catch (DecryptionException e) { +// Logger.warn("Assertion decrypt FAILED.", e); +// throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); +// +// } catch (ConfigurationException e) { +// throw new AssertionValidationExeption("pvp.12", null, e); +// } +// } private static void performSchemaValidation(Element source) throws SchemaValidationException { -- cgit v1.2.3 From f441b49a4eadb475396217901bbbc49973ca8107 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 22 Feb 2016 11:35:18 +0100 Subject: add first parts of new federated authentication modul --- .../tasks/CreateInterfedeartionRequestTask.java | 296 --------------------- .../tasks/ReceiveInterfederationResponseTask.java | 56 ---- .../pvp2x/SP/tasks/AbstractAuthnRequestTask.java | 293 ++++++++++++++++++++ .../pvp2x/SP/tasks/AbstractAuthnResponseTask.java | 53 ++++ 4 files changed, 346 insertions(+), 352 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnRequestTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnResponseTask.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java deleted file mode 100644 index 951a04cf6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateInterfedeartionRequestTask.java +++ /dev/null @@ -1,296 +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.lang.reflect.InvocationTargetException; -import java.security.NoSuchAlgorithmException; - -import javax.servlet.http.HttpServletRequest; -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.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.saml2.metadata.provider.MetadataProviderException; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.xml.security.SecurityException; -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.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.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ -@Service("CreateInterfedeartionRequestTask") -public class CreateInterfedeartionRequestTask 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 { - boolean requiredLocalAuthentication = true; - - String idpEntityID = - (String) executionContext.get(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID); - - if (MiscUtil.isEmpty(idpEntityID)) { - Logger.info("Interfederation not possible -> not inderfederation IDP EntityID found!"); - throw new TaskExecutionException(pendingReq, "Interfederation not possible", new MOAIDException("No inderfederation-IDP EntityID found.", null)); - - } - - //TODO: create MOASession - //TODO: set relayState to MOASession - //TODO: add support for requested attributes (from context and from metadata) - - - try { - OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(idpEntityID); - IOAAuthParameters sp = pendingReq.getOnlineApplicationConfiguration(); - - String requestedIDP = pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); - - if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) { - Logger.info("Requested interfederation IDP " + requestedIDP + " is not valid for interfederation."); - Logger.debug("isInderfederationIDP:" + String.valueOf(idp.isInderfederationIDP()) - + " isInboundSSOAllowed:" + String.valueOf(idp.isInboundSSOInterfederationAllowed())); - Logger.info("Switch to local authentication on this IDP ... "); - - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, true); - return; - - } - - - - - EntityDescriptor idpEntity = MOAMetadataProvider.getInstance(). - getEntityDescriptor(idpEntityID); - - if (idpEntity != null ) { - - //fetch endpoint from IDP metadata - SingleSignOnService redirectEndpoint = null; - for (SingleSignOnService sss : - idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS).getSingleSignOnServices()) { - - // use POST binding as default if it exists - //TODO: maybe use RedirectBinding as default - if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { - redirectEndpoint = sss; - - } else if ( sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) && - redirectEndpoint == null ) - redirectEndpoint = sss; - } - - if (redirectEndpoint != null) { - - AuthnRequest authReq = SAML2Utils - .createSAMLObject(AuthnRequest.class); - SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); - authReq.setID(gen.generateIdentifier()); - - //send passive AuthnRequest - authReq.setIsPassive(idp.isPassivRequestUsedForInterfederation()); - - authReq.setAssertionConsumerServiceIndex(0); - authReq.setIssueInstant(new DateTime()); - Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - issuer.setValue(pendingReq.getAuthURLWithOutSlash()); - - issuer.setFormat(NameIDType.ENTITY); - authReq.setIssuer(issuer); - NameIDPolicy policy = SAML2Utils - .createSAMLObject(NameIDPolicy.class); - policy.setAllowCreate(true); - policy.setFormat(NameID.TRANSIENT); - authReq.setNameIDPolicy(policy); - - authReq.setDestination(redirectEndpoint.getLocation()); - - RequestedAuthnContext reqAuthContext = - SAML2Utils.createSAMLObject(RequestedAuthnContext.class); - - AuthnContextClassRef authnClassRef = - SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - - //check if STORK protocol module is in ClassPath - Object storkRequst = null; - Integer storkSecClass = null; - try { - storkRequst = Class.forName("at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest").newInstance(); - if (storkRequst != null && - pendingReq.getClass().isInstance(storkRequst)) { - Object storkAuthnRequest = pendingReq.getClass().getMethod("getStorkAuthnRequest", null).invoke(pendingReq, null); - storkSecClass = (Integer) storkAuthnRequest.getClass().getMethod("getQaa", null).invoke(storkAuthnRequest, null); - - } - - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { - - - } - - - if (sp != null && sp.isSTORKPVPGateway()){ - //use PVP SecClass instead of STORK QAA level - String secClass = null; - if (storkRequst != null && - pendingReq.getClass().isInstance(storkRequst)) { - - try { - secClass = PVPtoSTORKMapper.getInstance().mapToSecClass( - PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); - - } catch (Exception e) { - Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); - - } - } - - if (MiscUtil.isNotEmpty(secClass)) - authnClassRef.setAuthnContextClassRef(secClass); - else - authnClassRef.setAuthnContextClassRef("http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3"); - - } else { - if (storkRequst != null && - pendingReq.getClass().isInstance(storkRequst)) { - //use requested QAA level from STORK request - try { - authnClassRef.setAuthnContextClassRef( - PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); - Logger.debug("Use STORK-QAA level " + authnClassRef.getAuthnContextClassRef() - + " from STORK request"); - - } catch (Exception e) { - Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); - - } - - } - - if (MiscUtil.isEmpty(authnClassRef.getAuthnContextClassRef())) - authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4"); - - } - - reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); - reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); - authReq.setRequestedAuthnContext(reqAuthContext); - - IEncoder binding = null; - if (redirectEndpoint.getBinding().equals( - SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = new RedirectBinding(); - - } else if (redirectEndpoint.getBinding().equals( - SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = new PostBinding(); - - } - - binding.encodeRequest(request, response, authReq, - redirectEndpoint.getLocation(), pendingReq.getRequestID()); - - //build and send request without an error - requiredLocalAuthentication = false; - - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_IDP, idpEntity.getEntityID()); - - - } else { - Logger.warn("Requested IDP " + requestedIDP - + " does not support POST or Redirect Binding."); - - } - - } else { - Logger.warn("Requested IDP " + requestedIDP - + " is not found in InterFederation configuration"); - - } - - } catch (MetadataProviderException e) { - Logger.error("IDP metadata error." , e); - - } catch (NoSuchAlgorithmException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (MessageEncodingException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (SecurityException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (PVP2Exception e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (ConfigurationException e1) { - Logger.error("Build IDP authentication request FAILED.", e1); - - } - - //set flag for next step - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, - requiredLocalAuthentication); - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.java deleted file mode 100644 index 77aab8ddb..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/ReceiveInterfederationResponseTask.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.auth.modules.internal.tasks; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.springframework.stereotype.Service; - -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; - -/** - * @author tlenz - * - */ -@Service("ReceiveInterfederationResponseTask") -public class ReceiveInterfederationResponseTask 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 { - - //TODO: validate SAML2 assertion - //TODO: move attributeQuery from AuthenticationDataBuilder to her - //TODO: add SAML2 interfederation Response to MOASession - //TODO: update AuthenticationDataBuilder to use Response from MOASession if exists - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnRequestTask.java new file mode 100644 index 000000000..c8c115f82 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnRequestTask.java @@ -0,0 +1,293 @@ +/* + * 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.SP.tasks; +import java.lang.reflect.InvocationTargetException; +import java.security.NoSuchAlgorithmException; + +import javax.servlet.http.HttpServletRequest; +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.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.xml.security.SecurityException; + +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.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.exceptions.PVP2Exception; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +public abstract class AbstractAuthnRequestTask 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 { + boolean requiredLocalAuthentication = true; + + String idpEntityID = + (String) executionContext.get(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID); + + if (MiscUtil.isEmpty(idpEntityID)) { + Logger.info("Interfederation not possible -> not inderfederation IDP EntityID found!"); + throw new TaskExecutionException(pendingReq, "Interfederation not possible", new MOAIDException("No inderfederation-IDP EntityID found.", null)); + + } + + //TODO: create MOASession + //TODO: set relayState to MOASession + //TODO: add support for requested attributes (from context and from metadata) + + + try { + OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(idpEntityID); + IOAAuthParameters sp = pendingReq.getOnlineApplicationConfiguration(); + + String requestedIDP = pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + + if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) { + Logger.info("Requested interfederation IDP " + requestedIDP + " is not valid for interfederation."); + Logger.debug("isInderfederationIDP:" + String.valueOf(idp.isInderfederationIDP()) + + " isInboundSSOAllowed:" + String.valueOf(idp.isInboundSSOInterfederationAllowed())); + Logger.info("Switch to local authentication on this IDP ... "); + + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, true); + return; + + } + + + + + EntityDescriptor idpEntity = MOAMetadataProvider.getInstance(). + getEntityDescriptor(idpEntityID); + + if (idpEntity != null ) { + + //fetch endpoint from IDP metadata + SingleSignOnService redirectEndpoint = null; + for (SingleSignOnService sss : + idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS).getSingleSignOnServices()) { + + // use POST binding as default if it exists + //TODO: maybe use RedirectBinding as default + if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { + redirectEndpoint = sss; + + } else if ( sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) && + redirectEndpoint == null ) + redirectEndpoint = sss; + } + + if (redirectEndpoint != null) { + + AuthnRequest authReq = SAML2Utils + .createSAMLObject(AuthnRequest.class); + SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); + authReq.setID(gen.generateIdentifier()); + + //send passive AuthnRequest + authReq.setIsPassive(idp.isPassivRequestUsedForInterfederation()); + + authReq.setAssertionConsumerServiceIndex(0); + authReq.setIssueInstant(new DateTime()); + Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); + issuer.setValue(pendingReq.getAuthURLWithOutSlash()); + + issuer.setFormat(NameIDType.ENTITY); + authReq.setIssuer(issuer); + NameIDPolicy policy = SAML2Utils + .createSAMLObject(NameIDPolicy.class); + policy.setAllowCreate(true); + policy.setFormat(NameID.TRANSIENT); + authReq.setNameIDPolicy(policy); + + authReq.setDestination(redirectEndpoint.getLocation()); + + RequestedAuthnContext reqAuthContext = + SAML2Utils.createSAMLObject(RequestedAuthnContext.class); + + AuthnContextClassRef authnClassRef = + SAML2Utils.createSAMLObject(AuthnContextClassRef.class); + + //check if STORK protocol module is in ClassPath + Object storkRequst = null; + Integer storkSecClass = null; + try { + storkRequst = Class.forName("at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest").newInstance(); + if (storkRequst != null && + pendingReq.getClass().isInstance(storkRequst)) { + Object storkAuthnRequest = pendingReq.getClass().getMethod("getStorkAuthnRequest", null).invoke(pendingReq, null); + storkSecClass = (Integer) storkAuthnRequest.getClass().getMethod("getQaa", null).invoke(storkAuthnRequest, null); + + } + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { + + + } + + + if (sp != null && sp.isSTORKPVPGateway()){ + //use PVP SecClass instead of STORK QAA level + String secClass = null; + if (storkRequst != null && + pendingReq.getClass().isInstance(storkRequst)) { + + try { + secClass = PVPtoSTORKMapper.getInstance().mapToSecClass( + PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); + + } catch (Exception e) { + Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); + + } + } + + if (MiscUtil.isNotEmpty(secClass)) + authnClassRef.setAuthnContextClassRef(secClass); + else + authnClassRef.setAuthnContextClassRef("http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3"); + + } else { + if (storkRequst != null && + pendingReq.getClass().isInstance(storkRequst)) { + //use requested QAA level from STORK request + try { + authnClassRef.setAuthnContextClassRef( + PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); + Logger.debug("Use STORK-QAA level " + authnClassRef.getAuthnContextClassRef() + + " from STORK request"); + + } catch (Exception e) { + Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); + + } + + } + + if (MiscUtil.isEmpty(authnClassRef.getAuthnContextClassRef())) + authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4"); + + } + + reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); + reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); + authReq.setRequestedAuthnContext(reqAuthContext); + + IEncoder binding = null; + if (redirectEndpoint.getBinding().equals( + SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { + binding = new RedirectBinding(); + + } else if (redirectEndpoint.getBinding().equals( + SAMLConstants.SAML2_POST_BINDING_URI)) { + binding = new PostBinding(); + + } + + binding.encodeRequest(request, response, authReq, + redirectEndpoint.getLocation(), pendingReq.getRequestID()); + + //build and send request without an error + requiredLocalAuthentication = false; + + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_IDP, idpEntity.getEntityID()); + + + } else { + Logger.warn("Requested IDP " + requestedIDP + + " does not support POST or Redirect Binding."); + + } + + } else { + Logger.warn("Requested IDP " + requestedIDP + + " is not found in InterFederation configuration"); + + } + + } catch (MetadataProviderException e) { + Logger.error("IDP metadata error." , e); + + } catch (NoSuchAlgorithmException e) { + Logger.error("Build IDP authentication request FAILED.", e); + + } catch (MessageEncodingException e) { + Logger.error("Build IDP authentication request FAILED.", e); + + } catch (SecurityException e) { + Logger.error("Build IDP authentication request FAILED.", e); + + } catch (PVP2Exception e) { + Logger.error("Build IDP authentication request FAILED.", e); + + } catch (ConfigurationException e1) { + Logger.error("Build IDP authentication request FAILED.", e1); + + } + + //set flag for next step + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, + requiredLocalAuthentication); + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnResponseTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnResponseTask.java new file mode 100644 index 000000000..6ce8fab59 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnResponseTask.java @@ -0,0 +1,53 @@ +/* + * 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.SP.tasks; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; + +/** + * @author tlenz + * + */ +public abstract class AbstractAuthnResponseTask 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 { + + //TODO: validate SAML2 assertion + //TODO: move attributeQuery from AuthenticationDataBuilder to her + //TODO: add SAML2 interfederation Response to MOASession + //TODO: update AuthenticationDataBuilder to use Response from MOASession if exists + + } + +} -- cgit v1.2.3 From f81e455bfc1bdd23ce89bfcc0b626210417d0cbb Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 22 Feb 2016 12:27:38 +0100 Subject: fix some refactoring problems --- .../id/auth/builder/AuthenticationDataBuilder.java | 5 +- .../gv/egovernment/moa/id/moduls/RequestImpl.java | 13 +-- .../id/protocols/pvp2x/AuthenticationAction.java | 79 +++++++++++++- .../id/protocols/pvp2x/PVPTargetConfiguration.java | 7 +- .../pvp2x/builder/AbstractPVPMetadataBuilder.java | 4 +- .../pvp2x/requestHandler/AuthnRequestHandler.java | 121 --------------------- .../pvp2x/requestHandler/IRequestHandler.java | 40 ------- .../pvp2x/requestHandler/RequestManager.java | 70 ------------ 8 files changed, 87 insertions(+), 252 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/IRequestHandler.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 1207439dd..dbf95f604 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 @@ -1085,8 +1085,9 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } if (saml1Requst != null && protocolRequest.getClass().isInstance(saml1Requst)) - target = protocolRequest.getGenericData("target", String.class); - else + target = protocolRequest.getGenericData( + MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, String.class); + else target = oaParam.getTarget(); String bpkBase64 = new BPKBuilder().buildBPK(baseID, target); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index a1a814e95..961700651 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -25,15 +25,13 @@ 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.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; -import org.opensaml.saml2.core.Attribute; -import org.springframework.beans.factory.annotation.Autowired; - import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.id.commons.MOAIDConstants; @@ -41,7 +39,6 @@ import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; @@ -79,9 +76,7 @@ public abstract class RequestImpl implements IRequest, Serializable{ private Map genericDataStorage = new HashMap(); - - @Autowired protected AttributQueryBuilder attributQueryBuilder; - + /** * @throws ConfigurationException * @@ -169,9 +164,9 @@ public abstract class RequestImpl implements IRequest, Serializable{ /** * This method map the protocol specific requested attributes to PVP 2.1 attributes. * - * @return List of PVP 2.1 attributes with maps all protocol specific attributes + * @return List of PVP 2.1 attribute names with maps all protocol specific attributes */ - public abstract List getRequestedAttributes(); + public abstract Collection getRequestedAttributes(); public void setOAURL(String value) { oaURL = value; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java index eb4cb8a18..f64aacc6d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java @@ -25,6 +25,17 @@ 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.auth.exception.MOAIDException; @@ -33,22 +44,80 @@ 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.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.requestHandler.RequestManager; +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.exceptions.BindingNotSupportedException; +import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.logging.Logger; @Service("PVPAuthenticationRequestAction") public class AuthenticationAction implements IAction { + @Autowired ApplicationContext context; + public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { PVPTargetConfiguration pvpRequest = (PVPTargetConfiguration) req; - SLOInformationImpl sloInformation = (SLOInformationImpl) RequestManager.getInstance().handle(pvpRequest, httpReq, httpResp, authData); + //get basic information + MOARequest moaRequest = (MOARequest) pvpRequest.getRequest(); + AuthnRequest authnRequest = (AuthnRequest) moaRequest.getSamlRequest(); + EntityDescriptor peerEntity = moaRequest.getEntityMetadata(); + + AssertionConsumerService consumerService = + SAML2Utils.createSAMLObject(AssertionConsumerService.class); + consumerService.setBinding(pvpRequest.getBinding()); + consumerService.setLocation(pvpRequest.getConsumerURL()); + + DateTime date = new DateTime(); + + SLOInformationImpl sloInformation = new SLOInformationImpl(); + + //build Assertion + Assertion assertion = PVP2AssertionBuilder.buildAssertion(pvpRequest, authnRequest, authData, + peerEntity, date, consumerService, sloInformation); + + Response authResponse = AuthResponseBuilder.buildResponse(pvpRequest.getAuthURL(), authnRequest, date, assertion); + + IEncoder binding = null; + + if (consumerService.getBinding().equals( + SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { + binding = context.getBean(RedirectBinding.class); + + } else if (consumerService.getBinding().equals( + SAMLConstants.SAML2_POST_BINDING_URI)) { + binding = context.getBean(PostBinding.class); + + } + + if (binding == null) { + throw new BindingNotSupportedException(consumerService.getBinding()); + } + + try { + binding.encodeRespone(httpReq, httpResp, authResponse, + consumerService.getLocation(), moaRequest.getRelayState()); + + //set protocol type + sloInformation.setProtocolType(req.requestedModule()); + 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); - //set protocol type - sloInformation.setProtocolType(req.requestedModule()); + } - return sloInformation; } public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index 800728bbd..27773a248 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -22,12 +22,12 @@ *******************************************************************************/ 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.Attribute; import org.opensaml.saml2.core.impl.AuthnRequestImpl; import org.opensaml.saml2.metadata.AttributeConsumingService; import org.opensaml.saml2.metadata.RequestedAttribute; @@ -81,7 +81,7 @@ public class PVPTargetConfiguration extends RequestImpl { * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes() */ @Override - public List getRequestedAttributes() { + public Collection getRequestedAttributes() { Map reqAttr = new HashMap(); for (String el : PVP2XProtocol.DEFAULTREQUESTEDATTRFORINTERFEDERATION) @@ -123,7 +123,8 @@ public class PVPTargetConfiguration extends RequestImpl { reqAttr.put(attr.getName(), ""); } - return attributQueryBuilder.buildSAML2AttributeList(this.getOnlineApplicationConfiguration(), reqAttr.keySet().iterator()); + //return attributQueryBuilder.buildSAML2AttributeList(this.getOnlineApplicationConfiguration(), reqAttr.keySet().iterator()); + return reqAttr.keySet(); } catch (NoMetadataInformationException e) { Logger.warn("NO metadata found for Entity " + getRequest().getEntityID()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java index 23870806a..0212f8f1c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java @@ -439,7 +439,7 @@ public abstract class AbstractPVPMetadataBuilder { } //check nameID formates - if (getIDPPossibleNameITTypes() == null || getIDPPossibleNameITTypes().size() == 0) { + if (getSPAllowedNameITTypes() == null || getSPAllowedNameITTypes().size() == 0) { Logger.warn("SP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); return null; @@ -448,7 +448,7 @@ public abstract class AbstractPVPMetadataBuilder { NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); nameIDFormat.setFormat(format); spSSODescriptor.getNameIDFormats().add(nameIDFormat); - + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java deleted file mode 100644 index 4fbca5b13..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java +++ /dev/null @@ -1,121 +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.requestHandler; - -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 at.gv.egovernment.moa.id.auth.exception.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.protocols.pvp2x.PVPConstants; -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.builder.AuthResponseBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.BindingNotSupportedException; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.logging.Logger; - -public class AuthnRequestHandler implements IRequestHandler, PVPConstants { - - public boolean handleObject(InboundMessage obj) { - - return (obj instanceof MOARequest && - ((MOARequest)obj).getSamlRequest() instanceof AuthnRequest); - } - - public SLOInformationInterface process(PVPTargetConfiguration obj, HttpServletRequest req, - HttpServletResponse resp, IAuthData authData) throws MOAIDException { - if (!handleObject(obj.getRequest())) { - throw new MOAIDException("pvp2.13", null); - } - - //get basic information - MOARequest moaRequest = (MOARequest) obj.getRequest(); - AuthnRequest authnRequest = (AuthnRequest) moaRequest.getSamlRequest(); - EntityDescriptor peerEntity = moaRequest.getEntityMetadata(); - - AssertionConsumerService consumerService = - SAML2Utils.createSAMLObject(AssertionConsumerService.class); - consumerService.setBinding(obj.getBinding()); - consumerService.setLocation(obj.getConsumerURL()); - - DateTime date = new DateTime(); - - SLOInformationImpl sloInformation = new SLOInformationImpl(); - - //build Assertion - Assertion assertion = PVP2AssertionBuilder.buildAssertion(obj, authnRequest, authData, - peerEntity, date, consumerService, sloInformation); - - Response authResponse = AuthResponseBuilder.buildResponse(obj.getAuthURL(), authnRequest, date, assertion); - - IEncoder binding = null; - - if (consumerService.getBinding().equals( - SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = new RedirectBinding(); - - } else if (consumerService.getBinding().equals( - SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = new PostBinding(); - - } - - if (binding == null) { - throw new BindingNotSupportedException(consumerService.getBinding()); - } - - try { - binding.encodeRespone(req, resp, authResponse, - consumerService.getLocation(), moaRequest.getRelayState()); - - 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); - - } - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/IRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/IRequestHandler.java deleted file mode 100644 index 293dccf6c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/IRequestHandler.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.requestHandler; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; - -public interface IRequestHandler { - public boolean handleObject(InboundMessage obj); - - public SLOInformationInterface process(PVPTargetConfiguration pvpRequest, HttpServletRequest req, - HttpServletResponse resp, IAuthData authData) throws MOAIDException; -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.java deleted file mode 100644 index f26b2a735..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/RequestManager.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.protocols.pvp2x.requestHandler; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SAMLRequestNotSupported; - -public class RequestManager { - - private static RequestManager instance = null; - - private List handler; - - public static synchronized RequestManager getInstance() { - if(instance == null) { - instance = new RequestManager(); - } - return instance; - } - - private RequestManager() { - handler = new ArrayList(); - handler.add(new AuthnRequestHandler()); - - } - - public SLOInformationInterface handle(PVPTargetConfiguration pvpRequest, HttpServletRequest req, HttpServletResponse resp, IAuthData authData) - throws SAMLRequestNotSupported, MOAIDException { - Iterator it = handler.iterator(); - while(it.hasNext()) { - IRequestHandler handler = it.next(); - if(handler.handleObject(pvpRequest.getRequest())) { - return handler.process(pvpRequest, req, resp, authData); - } - } - - // not handled - throw new SAMLRequestNotSupported(); - } -} -- cgit v1.2.3 From 1415029cd821ddcc8a3375b5f5e1473747e0d2d7 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 22 Feb 2016 12:58:15 +0100 Subject: make method public --- .../moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index 065118e2b..7c7941b68 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -434,7 +434,7 @@ public class PVP2AssertionBuilder implements PVPConstants { * @throws ConfigurationException */ - private static Assertion buildGenericAssertion(String authURL, String entityID, DateTime date, + public static Assertion buildGenericAssertion(String authURL, String entityID, DateTime date, AuthnContextClassRef authnContextClassRef, List attrList, NameID subjectNameID, SubjectConfirmationData subjectConfirmationData, String sessionIndex, DateTime isValidTo) throws ConfigurationException { -- cgit v1.2.3 From dd2be368cdceab6b02bf9a73b6db08a05be53e69 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 22 Feb 2016 14:27:32 +0100 Subject: fix possible problem with federated assertion validation --- .../moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index 812e27a36..bf9a61fe4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -195,7 +195,7 @@ public class SAMLVerificationEngine { } } - if (!isValidDestination) { + if (!isValidDestination && validateDestination) { Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); -- cgit v1.2.3 From f354a38c6287f4834389f3430289ae14241c8066 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 22 Feb 2016 14:35:05 +0100 Subject: fix merge problem --- .../pvp2x/verification/SAMLVerificationEngine.java | 237 ++++++++++----------- 1 file changed, 108 insertions(+), 129 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index bf9a61fe4..f7e753273 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -22,55 +22,34 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.verification; -import java.util.ArrayList; -import java.util.List; - import javax.xml.namespace.QName; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; -import org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.saml2.core.Conditions; -import org.opensaml.saml2.core.EncryptedAssertion; import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.Response; -import org.opensaml.saml2.core.StatusCode; import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.encryption.Decrypter; -import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; import org.opensaml.saml2.metadata.IDPSSODescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.security.MetadataCriteria; import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.xml.encryption.ChainingEncryptedKeyResolver; -import org.opensaml.xml.encryption.DecryptionException; -import org.opensaml.xml.encryption.InlineEncryptedKeyResolver; -import org.opensaml.xml.encryption.SimpleRetrievalMethodEncryptedKeyResolver; import org.opensaml.xml.security.CriteriaSet; import org.opensaml.xml.security.credential.UsageType; import org.opensaml.xml.security.criteria.EntityIDCriteria; import org.opensaml.xml.security.criteria.UsageCriteria; -import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver; -import org.opensaml.xml.security.x509.X509Credential; 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.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; 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.CredentialProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -179,114 +158,114 @@ public class SAMLVerificationEngine { } } - public static void validateAssertion(Response samlResp, boolean validateDestination) throws AssertionValidationExeption { - try { - if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { - List saml2assertions = new ArrayList(); - - List allowedPublicURLPrefix = - AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); - boolean isValidDestination = false; - for (String allowedPreFix : allowedPublicURLPrefix) { - if (validateDestination && samlResp.getDestination().startsWith( - allowedPreFix)) { - isValidDestination = true; - break; - - } - } - if (!isValidDestination && validateDestination) { - Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); - throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); - - } - - //check encrypted Assertion - List encryAssertionList = samlResp.getEncryptedAssertions(); - if (encryAssertionList != null && encryAssertionList.size() > 0) { - //decrypt assertions - - Logger.debug("Found encryped assertion. Start decryption ..."); - - X509Credential authDecCredential = CredentialProvider.getIDPAssertionEncryptionCredential(); - - StaticKeyInfoCredentialResolver skicr = - new StaticKeyInfoCredentialResolver(authDecCredential); - - ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); - encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); - encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); - encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); - - Decrypter samlDecrypter = - new Decrypter(null, skicr, encryptedKeyResolver); - - for (EncryptedAssertion encAssertion : encryAssertionList) { - saml2assertions.add(samlDecrypter.decrypt(encAssertion)); - - } - - Logger.debug("Assertion decryption finished. "); - - } else { - saml2assertions.addAll(samlResp.getAssertions()); - - } - - List validatedassertions = new ArrayList(); - for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { - - try { - performSchemaValidation(saml2assertion.getDOM()); - - Conditions conditions = saml2assertion.getConditions(); - DateTime notbefore = conditions.getNotBefore().minusMinutes(5); - DateTime notafter = conditions.getNotOnOrAfter(); - if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { - Logger.warn("PVP2 Assertion is out of Date. " - + "{ Current : " + new DateTime() - + " NotBefore: " + notbefore - + " NotAfter : " + notafter - + " }");; - - } else { - validatedassertions.add(saml2assertion); - - } - - } catch (SchemaValidationException e) { - - } - } - - if (validatedassertions.isEmpty()) { - Logger.info("No valid PVP 2.1 assertion received."); - throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); - } - - samlResp.getAssertions().clear(); - samlResp.getEncryptedAssertions().clear(); - samlResp.getAssertions().addAll(validatedassertions); - - } else { - Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " - + samlResp.getStatus().getStatusCode().getValue()); - throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " - + samlResp.getStatus().getStatusCode().getValue(), null); - } - - } catch (CredentialsNotAvailableException e) { - Logger.warn("Assertion decrypt FAILED - No Credentials", e); - throw new AssertionValidationExeption("Assertion decrypt FAILED - No Credentials", null, e); - - } catch (DecryptionException e) { - Logger.warn("Assertion decrypt FAILED.", e); - throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); - - } catch (ConfigurationException e) { - throw new AssertionValidationExeption("pvp.12", null, e); - } - } +// public static void validateAssertion(Response samlResp, boolean validateDestination) throws AssertionValidationExeption { +// try { +// if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { +// List saml2assertions = new ArrayList(); +// +// List allowedPublicURLPrefix = +// AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); +// boolean isValidDestination = false; +// for (String allowedPreFix : allowedPublicURLPrefix) { +// if (validateDestination && samlResp.getDestination().startsWith( +// allowedPreFix)) { +// isValidDestination = true; +// break; +// +// } +// } +// if (!isValidDestination && validateDestination) { +// Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); +// throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); +// +// } +// +// //check encrypted Assertion +// List encryAssertionList = samlResp.getEncryptedAssertions(); +// if (encryAssertionList != null && encryAssertionList.size() > 0) { +// //decrypt assertions +// +// Logger.debug("Found encryped assertion. Start decryption ..."); +// +// X509Credential authDecCredential = CredentialProvider.getIDPAssertionEncryptionCredential(); +// +// StaticKeyInfoCredentialResolver skicr = +// new StaticKeyInfoCredentialResolver(authDecCredential); +// +// ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); +// encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); +// encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); +// encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); +// +// Decrypter samlDecrypter = +// new Decrypter(null, skicr, encryptedKeyResolver); +// +// for (EncryptedAssertion encAssertion : encryAssertionList) { +// saml2assertions.add(samlDecrypter.decrypt(encAssertion)); +// +// } +// +// Logger.debug("Assertion decryption finished. "); +// +// } else { +// saml2assertions.addAll(samlResp.getAssertions()); +// +// } +// +// List validatedassertions = new ArrayList(); +// for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { +// +// try { +// performSchemaValidation(saml2assertion.getDOM()); +// +// Conditions conditions = saml2assertion.getConditions(); +// DateTime notbefore = conditions.getNotBefore().minusMinutes(5); +// DateTime notafter = conditions.getNotOnOrAfter(); +// if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { +// Logger.warn("PVP2 Assertion is out of Date. " +// + "{ Current : " + new DateTime() +// + " NotBefore: " + notbefore +// + " NotAfter : " + notafter +// + " }");; +// +// } else { +// validatedassertions.add(saml2assertion); +// +// } +// +// } catch (SchemaValidationException e) { +// +// } +// } +// +// if (validatedassertions.isEmpty()) { +// Logger.info("No valid PVP 2.1 assertion received."); +// throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); +// } +// +// samlResp.getAssertions().clear(); +// samlResp.getEncryptedAssertions().clear(); +// samlResp.getAssertions().addAll(validatedassertions); +// +// } else { +// Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " +// + samlResp.getStatus().getStatusCode().getValue()); +// throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " +// + samlResp.getStatus().getStatusCode().getValue(), null); +// } +// +// } catch (CredentialsNotAvailableException e) { +// Logger.warn("Assertion decrypt FAILED - No Credentials", e); +// throw new AssertionValidationExeption("Assertion decrypt FAILED - No Credentials", null, e); +// +// } catch (DecryptionException e) { +// Logger.warn("Assertion decrypt FAILED.", e); +// throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); +// +// } catch (ConfigurationException e) { +// throw new AssertionValidationExeption("pvp.12", null, e); +// } +// } private static void performSchemaValidation(Element source) throws SchemaValidationException { -- cgit v1.2.3 From cbdb6946d5af7de63afebf5ad256743303f00935 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 24 Feb 2016 06:21:22 +0100 Subject: refactor PVP protocol implementation to resuse code in other modules --- .../moa/id/auth/MOAIDAuthConstants.java | 4 +- .../id/auth/builder/AuthenticationDataBuilder.java | 50 +- .../id/auth/modules/BKUSelectionModuleImpl.java | 3 +- .../internal/tasks/EvaluateBKUSelectionTask.java | 3 + .../tasks/RestartAuthProzessManagement.java | 10 +- .../moa/id/moduls/AuthenticationManager.java | 12 +- .../id/protocols/pvp2x/AttributQueryAction.java | 5 +- .../id/protocols/pvp2x/AuthenticationAction.java | 12 +- .../moa/id/protocols/pvp2x/MetadataAction.java | 257 +------- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 112 +--- .../moa/id/protocols/pvp2x/binding/IEncoder.java | 24 +- .../id/protocols/pvp2x/binding/PostBinding.java | 35 +- .../protocols/pvp2x/binding/RedirectBinding.java | 43 +- .../id/protocols/pvp2x/binding/SoapBinding.java | 21 +- .../pvp2x/builder/AbstractPVPMetadataBuilder.java | 649 --------------------- .../pvp2x/builder/PVPMetadataBuilder.java | 460 +++++++++++++++ .../pvp2x/builder/SingleLogOutBuilder.java | 3 +- .../pvp2x/config/IDPPVPMetadataConfiguration.java | 288 +++++++++ .../config/IPVPMetadataBuilderConfiguration.java | 217 +++++++ .../pvp2x/verification/SAMLVerificationEngine.java | 236 ++++---- 20 files changed, 1231 insertions(+), 1213 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index d76021bbd..1a9018563 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -174,8 +174,10 @@ public class MOAIDAuthConstants extends MOAIDConstants{ //AuthnRequest IssueInstant validation public static final int TIME_JITTER = 5; //all 5 minutes time jitter - public static final String PROCESSCONTEXT_INTERFEDERATION_ENTITYID = "interfederationIDPEntityID"; + public static final String PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH = "interfederationAuthentication"; public static final String PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION = "requireLocalAuthentication"; + public static final String PROCESSCONTEXT_PERFORM_BKUSELECTION = "performBKUSelection"; + public static final String PROCESSCONTEXT_ISLEGACYREQUEST = "isLegacyRequest"; //General protocol-request data-store keys public static final String AUTHPROCESS_DATA_TARGET = "authProces_Target"; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index dbf95f604..8a9999d85 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java @@ -104,7 +104,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; @@ -127,24 +126,13 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; @Autowired protected AuthConfiguration authConfig; @Autowired private AttributQueryBuilder attributQueryBuilder; + @Autowired private SAMLVerificationEngine samlVerificationEngine; public IAuthData buildAuthenticationData(IRequest protocolRequest, - AuthenticationSession session, List reqAttributes) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { - - - String oaID = protocolRequest.getOAURL(); - if (oaID == null) { - throw new WrongParametersException("StartAuthentication", - PARAM_OA, "auth.12"); - } - - // check parameter - if (!ParamValidatorUtils.isValidOA(oaID)) - throw new WrongParametersException("StartAuthentication", - PARAM_OA, "auth.12"); - + AuthenticationSession session, List reqAttributes) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { AuthenticationData authdata = null; + //only needed for SAML1 legacy support try { //check if SAML1 authentication module is in Classpath Class saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); @@ -165,15 +153,14 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { authdata = new AuthenticationData(); } - - + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { authdata = new AuthenticationData(); } - //reuse some parameters if it is a reauthentication - OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, oaID, protocolRequest.requestedModule()); + //reuse some parameters if it is a Service-Provider reauthentication + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, protocolRequest.getOAURL(), protocolRequest.requestedModule()); if (activeOA != null) { authdata.setSessionIndex(activeOA.getAssertionSessionID()); authdata.setNameID(activeOA.getUserNameID()); @@ -193,7 +180,8 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } } - + + //search federated IDP information in MOASession InterfederationSessionStore interfIDP = authenticatedSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); IOAAuthParameters oaParam = null; @@ -201,20 +189,22 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { //get OnlineApplication from MOA-ID-Auth configuration oaParam = protocolRequest.getOnlineApplicationConfiguration(); - //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway + //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway if (oaParam.isSTORKPVPGateway()) oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, protocolRequest); } else { - //build OnlineApplication dynamic from requested attributes + //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) oaParam = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes, interfIDP); } - if (interfIDP != null ) { - //IDP is a chained interfederated IDP and Authentication is requested + if (interfIDP != null ) { + //authentication by using a federated IDP if (oaParam.isInderfederationIDP() && protocolRequest instanceof PVPTargetConfiguration && !(((PVPTargetConfiguration)protocolRequest).getRequest() instanceof AttributeQuery)) { + //IDP is a chained interfederated IDP and Authentication is requested + //only set minimal response attributes authdata.setQAALevel(interfIDP.getQAALevel()); authdata.setBPK(interfIDP.getUserNameID()); @@ -290,12 +280,15 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } + //get SAML2 Response from federated IDP Response intfResp = (Response) req.getGenericData( RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, MOAResponse.class).getResponse(); - AssertionAttributeExtractor extractor = - new AssertionAttributeExtractor(intfResp); - + + //initialize Attribute extractor + AssertionAttributeExtractor extractor = new AssertionAttributeExtractor(intfResp); + + //check if SAML2 Assertion contains already all required attributes if (!extractor.containsAllRequiredAttributes()) { Logger.info("Received assertion does no contain a minimum set of attributes. Starting AttributeQuery process ..."); //collect attributes by using BackChannel communication @@ -323,8 +316,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { //validate PVP 2.1 response try { - SAMLVerificationEngine engine = new SAMLVerificationEngine(); - engine.verifyIDPResponse(intfResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + samlVerificationEngine.verifyIDPResponse(intfResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); //TODO: find better solution //SAMLVerificationEngine.validateAssertion(intfResp, false); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java index 8b02a5bf6..c96167e71 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/BKUSelectionModuleImpl.java @@ -22,6 +22,7 @@ */ package at.gv.egovernment.moa.id.auth.modules; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.process.api.ExecutionContext; /** @@ -44,7 +45,7 @@ public class BKUSelectionModuleImpl implements AuthModule { @Override public String selectProcess(ExecutionContext context) { boolean performBKUSelection = false; - Object performBKUSelectionObj = context.get("performBKUSelection"); + Object performBKUSelectionObj = context.get(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION); if (performBKUSelectionObj != null && performBKUSelectionObj instanceof Boolean) performBKUSelection = (boolean) performBKUSelectionObj; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java index ed88c2aff..bd8dd709f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateBKUSelectionTask.java @@ -62,6 +62,9 @@ public class EvaluateBKUSelectionTask extends AbstractAuthServletTask { } + //remove BKU-selection flag from context + executionContext.remove(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION); + Logger.info("BKU is selected finished -> Start BKU selection evaluation ..."); } catch (Exception e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java index e0403f242..ddda86ecc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java @@ -64,11 +64,7 @@ public class RestartAuthProzessManagement extends AbstractAuthServletTask { } - //remove BKU selection flag - newec.remove("performBKUSelection"); - - - Logger.debug("Swicht to specific authentication process after BKU is selected"); + Logger.debug("Select new auth.-process and restart restart process-engine ... "); // select and create new process instance String processDefinitionId = ModuleRegistration.getInstance().selectProcess(newec); @@ -91,8 +87,8 @@ public class RestartAuthProzessManagement extends AbstractAuthServletTask { throw new MOAIDException("init.04", new Object[] { pendingReq.getRequestID() }); } - - Logger.info("BKU is selected -> Start BKU communication ..."); + + Logger.info("Restart process-engine with auth.process:" + processDefinitionId); // start process processEngine.start(pendingReq); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 39106dc3b..22561e435 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -99,6 +99,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { @Autowired private MOAReversionLogger revisionsLogger; @Autowired protected AuthConfiguration authConfig; @Autowired private SingleLogOutBuilder sloBuilder; + @Autowired private SAMLVerificationEngine samlVerificationEngine; public void performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { @@ -346,13 +347,15 @@ public class AuthenticationManager extends MOAIDAuthConstants { //create authentication process execution context ExecutionContext executionContext = new ExecutionContextImpl(); - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID, + //set interfederation authentication flag + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH, MiscUtil.isNotEmpty( pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); + //set legacy mode or BKU-selection flags boolean leagacyMode = (legacyallowed && legacyparamavail); - executionContext.put("isLegacyRequest", leagacyMode); - executionContext.put("performBKUSelection", !leagacyMode + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_ISLEGACYREQUEST, leagacyMode); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION, !leagacyMode && MiscUtil.isEmpty(pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class))); //add leagcy parameters to context @@ -485,8 +488,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { sloContainer.putFailedOA(sloReq.getIssuer().getValue()); } else { - SAMLVerificationEngine engine = new SAMLVerificationEngine(); - engine.verifySLOResponse(sloResp, + samlVerificationEngine.verifySLOResponse(sloResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java index 36145375b..bd6399377 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java @@ -52,6 +52,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; @@ -64,6 +65,7 @@ public class AttributQueryAction implements IAction { @Autowired IAuthenticationSessionStoreage authenticationSessionStorage; @Autowired private AuthenticationDataBuilder authDataBuilder; + @Autowired private IDPCredentialProvider pvpCredentials; private final static List DEFAULTSTORKATTRIBUTES = Arrays.asList( new String[]{PVPConstants.EID_STORK_TOKEN_NAME}); @@ -114,7 +116,8 @@ public class AttributQueryAction implements IAction { try { SoapBinding decoder = new SoapBinding(); - decoder.encodeRespone(httpReq, httpResp, authResponse, null, null); + decoder.encodeRespone(httpReq, httpResp, authResponse, null, null, + pvpCredentials.getIDPAssertionSigningCredential()); return null; } catch (MessageEncodingException e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java index f64aacc6d..21f505bf1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java @@ -35,7 +35,6 @@ import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -51,13 +50,13 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.BindingNotSupportedException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; @Service("PVPAuthenticationRequestAction") public class AuthenticationAction implements IAction { - - @Autowired ApplicationContext context; + @Autowired IDPCredentialProvider pvpCredentials; public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { @@ -88,11 +87,11 @@ public class AuthenticationAction implements IAction { if (consumerService.getBinding().equals( SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = context.getBean(RedirectBinding.class); + binding = new RedirectBinding(); } else if (consumerService.getBinding().equals( SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = context.getBean(PostBinding.class); + binding = new PostBinding(); } @@ -102,7 +101,8 @@ public class AuthenticationAction implements IAction { try { binding.encodeRespone(httpReq, httpResp, authResponse, - consumerService.getLocation(), moaRequest.getRelayState()); + consumerService.getLocation(), moaRequest.getRelayState(), + pvpCredentials.getIDPAssertionSigningCredential()); //set protocol type sloInformation.setProtocolType(req.requestedModule()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java index d48603a7c..15fe1e9d7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java @@ -22,43 +22,33 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x; -import java.util.Arrays; -import java.util.List; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.core.NameIDType; -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.Organization; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.xml.security.credential.Credential; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPMetadataBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.IDPPVPMetadataConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.logging.Logger; @Service("pvpMetadataService") -public class MetadataAction extends AbstractPVPMetadataBuilder implements IAction { +public class MetadataAction implements IAction { - private static final int VALIDUNTIL_IN_HOURS = 24; + @Autowired private MOAReversionLogger revisionsLogger; @Autowired private IDPCredentialProvider credentialProvider; + @Autowired private PVPMetadataBuilder metadatabuilder; public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { @@ -66,7 +56,10 @@ public class MetadataAction extends AbstractPVPMetadataBuilder implements IActio revisionsLogger.logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_PVP_METADATA); //build metadata - String metadataXML = buildPVPMetadata(req.getAuthURLWithOutSlash()); + IPVPMetadataBuilderConfiguration metadataConfig = + new IDPPVPMetadataConfiguration(req.getAuthURLWithOutSlash(), credentialProvider); + + String metadataXML = metadatabuilder.buildPVPMetadata(metadataConfig); Logger.debug("METADATA: " + metadataXML); httpResp.setContentType("text/xml"); @@ -87,236 +80,12 @@ public class MetadataAction extends AbstractPVPMetadataBuilder implements IActio return false; } - public String getDefaultActionName() { - return (PVP2XProtocol.METADATA); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataValidUntil() - */ - @Override - public int getMetadataValidUntil() { - return VALIDUNTIL_IN_HOURS; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildEntitiesDescriptorAsRootElement() - */ - @Override - public boolean buildEntitiesDescriptorAsRootElement() { - return true; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildIDPSSODescriptor() - */ - @Override - public boolean buildIDPSSODescriptor() { - return true; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildSPSSODescriptor() - */ - @Override - public boolean buildSPSSODescriptor() { - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityID() - */ - @Override - public String getEntityIDPostfix() { - //TODO: maybe change EntityID to Metadata URL - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityFriendlyName() - */ - @Override - public String getEntityFriendlyName() { - try { - return PVPConfiguration.getInstance().getIDPIssuerName(); - - } catch (ConfigurationException e) { - Logger.error("Can not load Metadata entry: EntityID friendlyName.", e); - return null; - - } - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getContactPersonInformation() - */ - @Override - public List getContactPersonInformation() { - try { - return PVPConfiguration.getInstance().getIDPContacts(); - - } catch (ConfigurationException e) { - Logger.warn("Can not load Metadata entry: Contect Person", e); - return null; - - } - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getOrgansiationInformation() - */ - @Override - public Organization getOrgansiationInformation() { - try { - return PVPConfiguration.getInstance().getIDPOrganisation(); - - } catch (ConfigurationException e) { - Logger.warn("Can not load Metadata entry: Organisation", e); - return null; - - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataSigningCredentials() - */ - @Override - public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException { - return credentialProvider.getIDPMetaDataSigningCredential(); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getRequestorResponseSigningCredentials() - */ - @Override - public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException { - return credentialProvider.getIDPAssertionSigningCredential(); - - } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEncryptionCredentials() + * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() */ @Override - public Credential getEncryptionCredentials() throws CredentialsNotAvailableException { - return credentialProvider.getIDPAssertionEncryptionCredential(); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSOPostBindingURL() - */ - @Override - public String getIDPWebSSOPostBindingURL() { - return PVPConfiguration.PVP2_IDP_POST; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSORedirectBindingURL() - */ - @Override - public String getIDPWebSSORedirectBindingURL() { - return PVPConfiguration.PVP2_IDP_REDIRECT; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLOPostBindingURL() - */ - @Override - public String getIDPSLOPostBindingURL() { - return PVPConfiguration.PVP2_IDP_POST; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLORedirectBindingURL() - */ - @Override - public String getIDPSLORedirectBindingURL() { - return PVPConfiguration.PVP2_IDP_REDIRECT; - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServicePostBindingURL() - */ - @Override - public String getSPAssertionConsumerServicePostBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServiceRedirectBindingURL() - */ - @Override - public String getSPAssertionConsumerServiceRedirectBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOPostBindingURL() - */ - @Override - public String getSPSLOPostBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLORedirectBindingURL() - */ - @Override - public String getSPSLORedirectBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOSOAPBindingURL() - */ - @Override - public String getSPSLOSOAPBindingURL() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleAttributes() - */ - @Override - public List getIDPPossibleAttributes() { - return PVPAttributeBuilder.buildSupportedEmptyAttributes(); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleNameITTypes() - */ - @Override - public List getIDPPossibleNameITTypes() { - return Arrays.asList(NameIDType.PERSISTENT, - NameIDType.TRANSIENT, - NameIDType.UNSPECIFIED); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPRequiredAttributes() - */ - @Override - public List getSPRequiredAttributes() { - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAllowedNameITTypes() - */ - @Override - public List getSPAllowedNameITTypes() { - return null; + public String getDefaultActionName() { + return "IDP - PVP Metadata action"; } - - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java index 88f0e3b74..08d9f67b6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java @@ -48,7 +48,9 @@ import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.ws.security.SecurityPolicyException; import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.x509.X509Credential; import org.opensaml.xml.signature.SignableXMLObject; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @@ -81,6 +83,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SLOException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.CheckMandateAttributes; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.id.protocols.pvp2x.validation.AuthnRequestValidator; @@ -96,6 +99,9 @@ import at.gv.egovernment.moa.util.MiscUtil; @Controller public class PVP2XProtocol extends AbstractAuthProtocolModulController { + @Autowired IDPCredentialProvider pvpCredentials; + @Autowired SAMLVerificationEngine samlVerificationEngine; + public static final String NAME = PVP2XProtocol.class.getName(); public static final String PATH = "id_pvp2x"; @@ -182,8 +188,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); //get POST-Binding decoder implementation - PostBinding coder = applicationContext.getBean(PostBinding.class); - InboundMessage msg = (InboundMessage) coder.decode(req, resp, false); + InboundMessage msg = (InboundMessage) new PostBinding().decode(req, resp, false); pendingReq.setRequest(msg); //preProcess Message @@ -231,8 +236,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); //get POST-Binding decoder implementation - RedirectBinding coder = applicationContext.getBean(RedirectBinding.class); - InboundMessage msg = (InboundMessage) coder.decode(req, resp, false); + InboundMessage msg = (InboundMessage) new RedirectBinding().decode(req, resp, false); pendingReq.setRequest(msg); //preProcess Message @@ -270,8 +274,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { } if(!msg.isVerified()) { - SAMLVerificationEngine engine = new SAMLVerificationEngine(); - engine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + samlVerificationEngine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); msg.setVerified(true); } @@ -301,53 +304,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { pendingReq, MOAIDEventConstants.AUTHPROTOCOL_TYPE, PATH); //switch to session authentication - performAuthentication(request, response, pendingReq); - -// else if (msg instanceof MOAResponse && -// ((MOAResponse)msg).getResponse() instanceof Response) { -// //load service provider AuthRequest from session -// -// IRequest obj = RequestStorage.getPendingRequest(msg.getRelayState()); -// if (obj instanceof RequestImpl) { -// RequestImpl iReqSP = (RequestImpl) obj; -// -// MOAReversionLogger.getInstance().logEvent(iReqSP, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHRESPONSE); -// -// MOAResponse processedMsg = preProcessAuthResponse((MOAResponse) msg); -// -// if ( processedMsg != null ) { -// iReqSP.setInterfederationResponse(processedMsg); -// -// MOAReversionLogger.getInstance().logEvent(iReqSP, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_REVEIVED); -// -// Logger.info("Receive a valid assertion from IDP " + msg.getEntityID() -// + ". Switch to original transaction with ID " + iReqSP.getRequestID()); -// TransactionIDUtils.setTransactionId(iReqSP.getRequestID()); -// TransactionIDUtils.setSessionId(iReqSP.getSessionIdentifier()); -// -// } else { -// Logger.info("Interfederated IDP " + msg.getEntityID() + " has NO valid SSO session." -// +". Switch back local authentication process ..."); -// -// SSOManager ssomanager = SSOManager.getInstance(); -// ssomanager.removeInterfederatedSSOIDP(msg.getEntityID(), request); -// -// iReqSP.setRequestedIDP(null); -// -// } -// -// return iReqSP; -// -// } -// -// Logger.error("Stored PVP21 authrequest from service provider has an unsuppored type."); -// return null; - -// } - - - - + performAuthentication(request, response, pendingReq); } public boolean generateErrorMessage(Throwable e, @@ -424,11 +381,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { encoder = new RedirectBinding(); - - } else if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_ARTIFACT_BINDING_URI)) { - // TODO: not supported YET!! - //binding = new ArtifactBinding(); - + } else if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { encoder = new PostBinding(); @@ -445,8 +398,10 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { if (pvpRequest.getRequest() != null) relayState = pvpRequest.getRequest().getRelayState(); + X509Credential signCred = pvpCredentials.getIDPAssertionSigningCredential(); + encoder.encodeRespone(request, response, samlResponse, pvpRequest.getConsumerURL(), - relayState); + relayState, signCred); return true; } @@ -731,43 +686,4 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHREQUEST); } - -// /** -// * PreProcess AuthResponse and Assertion -// * @param msg -// */ -// private MOAResponse preProcessAuthResponse(MOAResponse msg) { -// Logger.debug("Start PVP21 assertion processing... "); -// Response samlResp = (Response) msg.getResponse(); -// -// try { -// if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { -// -// //validate PVP 2.1 assertion -// SAMLVerificationEngine.validateAssertion(samlResp, true); -// -// msg.setSAMLMessage(SAML2Utils.asDOMDocument(samlResp).getDocumentElement()); -// return msg; -// -// } else { -// Logger.debug("Receive StatusCode " + samlResp.getStatus().getStatusCode().getValue() -// + " from interfederated IDP."); -// -// } -// -// } catch (IOException e) { -// Logger.warn("Interfederation response marshaling FAILED.", e); -// -// } catch (MarshallingException e) { -// Logger.warn("Interfederation response marshaling FAILED.", e); -// -// } catch (TransformerException e) { -// Logger.warn("Interfederation response marshaling FAILED.", e); -// -// } catch (AssertionValidationExeption e) { -// //error is already logged, to nothing -// } -// -// return null; -// } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java index de5548a44..3b2fb3687 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java @@ -29,24 +29,40 @@ import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.saml2.core.StatusResponseType; import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.credential.Credential; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; public interface IEncoder { + + /** + * + * @param req The http request + * @param resp The http response + * @param request The SAML2 request object + * @param targetLocation URL, where the request should be transmit + * @param relayState token for session handling + * @param credentials Credential to sign the request object + * @throws MessageEncodingException + * @throws SecurityException + * @throws PVP2Exception + */ public void encodeRequest(HttpServletRequest req, - HttpServletResponse resp, RequestAbstractType request, String targetLocation, String relayState) + HttpServletResponse resp, RequestAbstractType request, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException, PVP2Exception; /** * Encoder SAML Response * @param req The http request * @param resp The http response - * @param response The repsonse object - * @param targetLocation + * @param response The SAML2 repsonse object + * @param targetLocation URL, where the request should be transmit + * @param relayState token for session handling + * @param credentials Credential to sign the response object * @throws MessageEncodingException * @throws SecurityException */ public void encodeRespone(HttpServletRequest req, - HttpServletResponse resp, StatusResponseType response, String targetLocation, String relayState) + HttpServletResponse resp, StatusResponseType response, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException, PVP2Exception; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index 24bdf4c3c..ebb4b2991 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -46,9 +46,7 @@ import org.opensaml.ws.transport.http.HttpServletRequestAdapter; import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.x509.X509Credential; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import org.opensaml.xml.security.credential.Credential; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; @@ -59,8 +57,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.validation.MOAPVPSignedRequestPolicyRule; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.util.HTTPUtils; @@ -68,18 +64,15 @@ import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -@Service("PVPPostBindingCoder") public class PostBinding implements IDecoder, IEncoder { - - @Autowired private IDPCredentialProvider credentialProvider; - + public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState) + RequestAbstractType request, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException { try { - X509Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); +// X509Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -102,9 +95,9 @@ public class PostBinding implements IDecoder, IEncoder { encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); } catch (Exception e) { e.printStackTrace(); throw new SecurityException(e); @@ -112,12 +105,12 @@ public class PostBinding implements IDecoder, IEncoder { } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState) + StatusResponseType response, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException { try { - X509Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); +// X509Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -143,9 +136,9 @@ public class PostBinding implements IDecoder, IEncoder { context.setRelayState(relayState); encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); } catch (Exception e) { e.printStackTrace(); throw new SecurityException(e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 7167d8b7d..0ff18d903 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -47,9 +47,7 @@ import org.opensaml.ws.transport.http.HttpServletRequestAdapter; import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.x509.X509Credential; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import org.opensaml.xml.security.credential.Credential; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; @@ -60,25 +58,20 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -@Service("PVPRedirectBindingCoder") public class RedirectBinding implements IDecoder, IEncoder { - - @Autowired private IDPCredentialProvider credentialProvider; public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState) + RequestAbstractType request, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException { - try { - X509Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); +// try { +// X509Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -100,18 +93,18 @@ public class RedirectBinding implements IDecoder, IEncoder { context.setRelayState(relayState); encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); - } +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); +// } } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState) - throws MessageEncodingException, SecurityException { - try { - X509Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); + StatusResponseType response, String targetLocation, String relayState, + Credential credentials) throws MessageEncodingException, SecurityException { +// try { +// X509Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -133,10 +126,10 @@ public class RedirectBinding implements IDecoder, IEncoder { context.setRelayState(relayState); encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); - } +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); +// } } public InboundMessageInterface decode(HttpServletRequest req, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index bd60b7a13..cc3553551 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -46,7 +46,6 @@ import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.signature.SignableXMLObject; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; @@ -55,12 +54,10 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -@Service("PVPSOAPBindingCoder") public class SoapBinding implements IDecoder, IEncoder { @Autowired private IDPCredentialProvider credentialProvider; @@ -136,17 +133,17 @@ public class SoapBinding implements IDecoder, IEncoder { } public void encodeRequest(HttpServletRequest req, HttpServletResponse resp, - RequestAbstractType request, String targetLocation, String relayState) + RequestAbstractType request, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException, PVP2Exception { } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation, String relayState) + StatusResponseType response, String targetLocation, String relayState, Credential credentials) throws MessageEncodingException, SecurityException, PVP2Exception { - try { - Credential credentials = credentialProvider - .getIDPAssertionSigningCredential(); +// try { +// Credential credentials = credentialProvider +// .getIDPAssertionSigningCredential(); //load default PVP security configurations MOADefaultBootstrap.initializeDefaultPVPConfiguration(); @@ -160,10 +157,10 @@ public class SoapBinding implements IDecoder, IEncoder { context.setOutboundMessageTransport(responseAdapter); encoder.encode(context); - } catch (CredentialsNotAvailableException e) { - e.printStackTrace(); - throw new SecurityException(e); - } +// } catch (CredentialsNotAvailableException e) { +// e.printStackTrace(); +// throw new SecurityException(e); +// } } public String getSAML2BindingName() { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java deleted file mode 100644 index 0212f8f1c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AbstractPVPMetadataBuilder.java +++ /dev/null @@ -1,649 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.pvp2x.builder; - -import java.io.IOException; -import java.io.StringWriter; -import java.security.PrivateKey; -import java.security.interfaces.RSAPrivateKey; -import java.util.List; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.joda.time.DateTime; -import org.opensaml.Configuration; -import org.opensaml.common.xml.SAMLConstants; -import org.opensaml.saml2.core.Attribute; -import org.opensaml.saml2.metadata.AssertionConsumerService; -import org.opensaml.saml2.metadata.AttributeConsumingService; -import org.opensaml.saml2.metadata.ContactPerson; -import org.opensaml.saml2.metadata.EntitiesDescriptor; -import org.opensaml.saml2.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.IDPSSODescriptor; -import org.opensaml.saml2.metadata.KeyDescriptor; -import org.opensaml.saml2.metadata.LocalizedString; -import org.opensaml.saml2.metadata.NameIDFormat; -import org.opensaml.saml2.metadata.Organization; -import org.opensaml.saml2.metadata.RequestedAttribute; -import org.opensaml.saml2.metadata.RoleDescriptor; -import org.opensaml.saml2.metadata.SPSSODescriptor; -import org.opensaml.saml2.metadata.ServiceName; -import org.opensaml.saml2.metadata.SingleLogoutService; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.xml.io.Marshaller; -import org.opensaml.xml.io.MarshallingException; -import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.SecurityHelper; -import org.opensaml.xml.security.credential.Credential; -import org.opensaml.xml.security.credential.UsageType; -import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; -import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; -import org.opensaml.xml.signature.Signature; -import org.opensaml.xml.signature.SignatureConstants; -import org.opensaml.xml.signature.SignatureException; -import org.opensaml.xml.signature.Signer; -import org.w3c.dom.Document; - -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ - -public abstract class AbstractPVPMetadataBuilder { - - X509KeyInfoGeneratorFactory keyInfoFactory = null; - - /** - * - */ - public AbstractPVPMetadataBuilder() { - keyInfoFactory = new X509KeyInfoGeneratorFactory(); - keyInfoFactory.setEmitEntityIDAsKeyName(true); - keyInfoFactory.setEmitEntityCertificate(true); - - } - - - /** - * Set metadata valid area - * - * @return valid until in hours [h] - */ - public abstract int getMetadataValidUntil(); - - /** - * Build a SAML2 Entities element as metadata root element - * - * @return true, if the metadata should start with entities element - */ - public abstract boolean buildEntitiesDescriptorAsRootElement(); - - /** - * - * - * @return true, if an IDP SSO-descriptor element should be generated - */ - public abstract boolean buildIDPSSODescriptor(); - - /** - * - * - * @return true, if an SP SSO-descriptor element should be generated - */ - public abstract boolean buildSPSSODescriptor(); - - /** - * Set the PVP entityID for this SAML2 metadata. - * The entityID must be a URL and is public-URL prefix of the server, as minimum. - * If this is null or a empty String, the EntityID is the public-url prefix - * - * @return PVP entityID postfix as String - */ - public abstract String getEntityIDPostfix(); - - /** - * Set a friendlyName for this PVP entity - * - * @return - */ - public abstract String getEntityFriendlyName(); - - /** - * Set the contact information for this metadata entity - * - * @return - */ - public abstract List getContactPersonInformation(); - - /** - * Set organisation information for this metadata entity - * - * @return - */ - public abstract Organization getOrgansiationInformation(); - - - /** - * Set the credential for metadata signing - * - * @return - * @throws CredentialsNotAvailableException - */ - public abstract Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException; - - /** - * Set the credential for request/response signing - * IDP metadata: this credential is used for SAML2 response signing - * SP metadata: this credential is used for SAML2 response signing - * - * @return - * @throws CredentialsNotAvailableException - */ - public abstract Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException; - - /** - * Set the credential for response encryption - * - * @return - * @throws CredentialsNotAvailableException - */ - public abstract Credential getEncryptionCredentials() throws CredentialsNotAvailableException; - - /** - * Set the IDP Post-Binding URL-postfix for WebSSO - * - * @return - */ - public abstract String getIDPWebSSOPostBindingURL(); - - /** - * Set the IDP Redirect-Binding URL-postfix for WebSSO - * - * @return - */ - public abstract String getIDPWebSSORedirectBindingURL(); - - /** - * Set the IDP Post-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getIDPSLOPostBindingURL(); - - /** - * Set the IDP Redirect-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getIDPSLORedirectBindingURL(); - - /** - * Set the SP Post-Binding URL-postfix for for the Assertion-Consumer Service - * - * @return - */ - public abstract String getSPAssertionConsumerServicePostBindingURL(); - - /** - * Set the SP Redirect-Binding URL-postfix for the Assertion-Consumer Service - * - * @return - */ - public abstract String getSPAssertionConsumerServiceRedirectBindingURL(); - - /** - * Set the SP Post-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getSPSLOPostBindingURL(); - - /** - * Set the SP Redirect-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getSPSLORedirectBindingURL(); - - /** - * Set the SP SOAP-Binding URL-postfix for Single LogOut - * - * @return - */ - public abstract String getSPSLOSOAPBindingURL(); - - - /** - * Set all SAML2 attributes which could be provided by this IDP - * - * @return - */ - public abstract List getIDPPossibleAttributes(); - - /** - * Set all nameID types which could be provided by this IDP - * - * @return a List of SAML2 nameID types - */ - public abstract List getIDPPossibleNameITTypes(); - - /** - * Set all SAML2 attributes which are required by the SP - * - * @return - */ - public abstract List getSPRequiredAttributes(); - - /** - * Set all nameID types which allowed from the SP - * - * @return a List of SAML2 nameID types - */ - public abstract List getSPAllowedNameITTypes(); - - /** - * - * Build PVP 2.1 conform SAML2 metadata - * - * @param instancePublicURLPrefix - * Public-URL prefix which should be used to generate URLs. - * The URL String must by without trailing / - * - * @return PVP metadata as XML String - * @throws SecurityException - * @throws ConfigurationException - * @throws CredentialsNotAvailableException - * @throws TransformerFactoryConfigurationError - * @throws MarshallingException - * @throws TransformerException - * @throws ParserConfigurationException - * @throws IOException - * @throws SignatureException - */ - public String buildPVPMetadata(String instancePublicURLPrefix) throws CredentialsNotAvailableException, ConfigurationException, SecurityException, TransformerFactoryConfigurationError, MarshallingException, TransformerException, ParserConfigurationException, IOException, SignatureException { - if (MiscUtil.isEmpty(instancePublicURLPrefix)) { - Logger.error("Metadata generation FAILED! --> PublicURL Prefix is null or empty"); - throw new NullPointerException("PublicURL Prefix is null or empty"); - - } - - //remove trailing slash - if (instancePublicURLPrefix.endsWith("/")) - instancePublicURLPrefix.substring(0, instancePublicURLPrefix.length()-1); - - DateTime date = new DateTime(); - EntityDescriptor entityDescriptor = SAML2Utils - .createSAMLObject(EntityDescriptor.class); - - //set entityID - if (MiscUtil.isNotEmpty(getEntityIDPostfix())) - entityDescriptor.setEntityID(instancePublicURLPrefix + getEntityIDPostfix()); - else - entityDescriptor.setEntityID(instancePublicURLPrefix); - - //set contact and organisation information - List contactPersons = getContactPersonInformation(); - if (contactPersons != null) - entityDescriptor.getContactPersons().addAll(contactPersons); - - Organization organisation = getOrgansiationInformation(); - if (organisation != null) - entityDescriptor.setOrganization(organisation); - - //set IDP metadata - if (buildIDPSSODescriptor()) { - RoleDescriptor idpSSODesc = generateIDPMetadata(instancePublicURLPrefix); - if (idpSSODesc != null) - entityDescriptor.getRoleDescriptors().add(idpSSODesc); - - } - - //set SP metadata for interfederation - if (buildSPSSODescriptor()) { - RoleDescriptor spSSODesc = generateSPMetadata(instancePublicURLPrefix); - if (spSSODesc != null) - entityDescriptor.getRoleDescriptors().add(spSSODesc); - - } - - //set metadata signature parameters - Credential metadataSignCred = getMetadataSigningCredentials(); - Signature signature = getIDPSignature(metadataSignCred); - SecurityHelper.prepareSignatureParams(signature, metadataSignCred, null, null); - - - //initialize XML document builder - DocumentBuilder builder; - DocumentBuilderFactory factory = DocumentBuilderFactory - .newInstance(); - - builder = factory.newDocumentBuilder(); - Document document = builder.newDocument(); - - - //build entities descriptor - if (buildEntitiesDescriptorAsRootElement()) { - EntitiesDescriptor entitiesDescriptor = - SAML2Utils.createSAMLObject(EntitiesDescriptor.class); - entitiesDescriptor.setName(getEntityFriendlyName()); - entitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); - entitiesDescriptor.setValidUntil(date.plusHours(getMetadataValidUntil())); - entitiesDescriptor.getEntityDescriptors().add(entityDescriptor); - - entitiesDescriptor.setSignature(signature); - - //marshall document - Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(entitiesDescriptor); - out.marshall(entitiesDescriptor, document); - - } else { - entityDescriptor.setValidUntil(date.plusHours(getMetadataValidUntil())); - - entityDescriptor.setSignature(signature); - - //marshall document - Marshaller out = Configuration.getMarshallerFactory() - .getMarshaller(entityDescriptor); - out.marshall(entityDescriptor, document); - - } - - //sign metadata - Signer.signObject(signature); - - //transform metadata object to XML string - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - - StringWriter sw = new StringWriter(); - StreamResult sr = new StreamResult(sw); - DOMSource source = new DOMSource(document); - transformer.transform(source, sr); - sw.close(); - - return sw.toString(); - } - - - private RoleDescriptor generateSPMetadata(String instancePublicURLPrefix) throws CredentialsNotAvailableException, SecurityException, ConfigurationException { - SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); - spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - spSSODescriptor.setAuthnRequestsSigned(true); - spSSODescriptor.setWantAssertionsSigned(false); - - KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - - //Set AuthRequest Signing certificate - Credential authcredential = getRequestorResponseSigningCredentials(); - if (authcredential == null) { - Logger.warn("SP Metadata generation FAILED! --> Builder has NO request signing-credential. "); - return null; - - } else { - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); - spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - } - - //Set assertion encryption credentials - Credential authEncCredential = getEncryptionCredentials(); - - if (authEncCredential != null) { - KeyDescriptor encryKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - encryKeyDescriptor.setUse(UsageType.ENCRYPTION); - encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); - spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); - - } else { - Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); - - } - - //check nameID formates - if (getSPAllowedNameITTypes() == null || getSPAllowedNameITTypes().size() == 0) { - Logger.warn("SP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); - return null; - - } else { - for (String format : getSPAllowedNameITTypes()) { - NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - nameIDFormat.setFormat(format); - spSSODescriptor.getNameIDFormats().add(nameIDFormat); - - } - } - - - //add POST-Binding assertion consumer services - if (MiscUtil.isNotEmpty(getSPAssertionConsumerServicePostBindingURL())) { - AssertionConsumerService postassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - postassertionConsumerService.setIndex(0); - postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - postassertionConsumerService.setLocation(instancePublicURLPrefix + getSPAssertionConsumerServicePostBindingURL()); - postassertionConsumerService.setIsDefault(true); - spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); - - } - - //add POST-Binding assertion consumer services - if (MiscUtil.isNotEmpty(getSPAssertionConsumerServiceRedirectBindingURL())) { - AssertionConsumerService redirectassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); - redirectassertionConsumerService.setIndex(1); - redirectassertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - redirectassertionConsumerService.setLocation(instancePublicURLPrefix + getSPAssertionConsumerServiceRedirectBindingURL()); - spSSODescriptor.getAssertionConsumerServices().add(redirectassertionConsumerService); - - } - - //validate WebSSO endpoints - if (spSSODescriptor.getAssertionConsumerServices().size() == 0) { - Logger.warn("SP Metadata generation FAILED! --> NO SAML2 AssertionConsumerService endpoint found. "); - return null; - - } - - //add POST-Binding SLO descriptor - if (MiscUtil.isNotEmpty(getSPSLOPostBindingURL())) { - SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - postSLOService.setLocation(instancePublicURLPrefix + getSPSLOPostBindingURL()); - postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(postSLOService); - - } - - //add POST-Binding SLO descriptor - if (MiscUtil.isNotEmpty(getSPSLORedirectBindingURL())) { - SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(instancePublicURLPrefix + getSPSLORedirectBindingURL()); - redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(redirectSLOService); - - } - - //add POST-Binding SLO descriptor - if (MiscUtil.isNotEmpty(getSPSLOSOAPBindingURL())) { - SingleLogoutService soapSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - soapSLOService.setLocation(instancePublicURLPrefix + getSPSLOSOAPBindingURL()); - soapSLOService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); - spSSODescriptor.getSingleLogoutServices().add(soapSLOService); - - } - - - //add required attributes - List reqSPAttr = getSPRequiredAttributes(); - AttributeConsumingService attributeService = SAML2Utils.createSAMLObject(AttributeConsumingService.class); - - attributeService.setIndex(0); - attributeService.setIsDefault(true); - ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); - serviceName.setName(new LocalizedString("Default Service", "en")); - attributeService.getNames().add(serviceName); - - if (reqSPAttr != null && reqSPAttr.size() > 0) { - Logger.debug("Add " + reqSPAttr.size() + " attributes to SP metadata"); - attributeService.getRequestAttributes().addAll(reqSPAttr); - - } else { - Logger.debug("SP metadata contains NO requested attributes."); - - } - - spSSODescriptor.getAttributeConsumingServices().add(attributeService); - - return spSSODescriptor; - } - - private IDPSSODescriptor generateIDPMetadata(String instancePublicURLPrefix) throws ConfigurationException, CredentialsNotAvailableException, SecurityException { - //check response signing credential - Credential responseSignCred = getRequestorResponseSigningCredentials(); - if (responseSignCred == null) { - Logger.warn("IDP Metadata generation FAILED! --> Builder has NO Response signing credential. "); - return null; - - } - - //check nameID formates - if (getIDPPossibleNameITTypes() == null || getIDPPossibleNameITTypes().size() == 0) { - Logger.warn("IDP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); - return null; - - } - - // build SAML2 IDP-SSO descriptor element - IDPSSODescriptor idpSSODescriptor = SAML2Utils - .createSAMLObject(IDPSSODescriptor.class); - - idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - - //set ass default value, because PVP 2.x specification defines this feature as MUST - idpSSODescriptor.setWantAuthnRequestsSigned(true); - - // add WebSSO descriptor for POST-Binding - if (MiscUtil.isNotEmpty(getIDPWebSSOPostBindingURL())) { - SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); - postSingleSignOnService.setLocation(instancePublicURLPrefix + getIDPWebSSOPostBindingURL()); - postSingleSignOnService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); - - } - - // add WebSSO descriptor for Redirect-Binding - if (MiscUtil.isNotEmpty(getIDPWebSSORedirectBindingURL())) { - SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); - postSingleSignOnService.setLocation(instancePublicURLPrefix + getIDPWebSSORedirectBindingURL()); - postSingleSignOnService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); - - } - - //add Single LogOut POST-Binding endpoing - if (MiscUtil.isNotEmpty(getIDPSLOPostBindingURL())) { - SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - postSLOService.setLocation(instancePublicURLPrefix + getIDPSLOPostBindingURL()); - postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); - idpSSODescriptor.getSingleLogoutServices().add(postSLOService); - - } - - //add Single LogOut Redirect-Binding endpoing - if (MiscUtil.isNotEmpty(getIDPSLORedirectBindingURL())) { - SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); - redirectSLOService.setLocation(instancePublicURLPrefix + getIDPSLORedirectBindingURL()); - redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); - idpSSODescriptor.getSingleLogoutServices().add(redirectSLOService); - - } - - //validate WebSSO endpoints - if (idpSSODescriptor.getSingleSignOnServices().size() == 0) { - Logger.warn("IDP Metadata generation FAILED! --> NO SAML2 SingleSignOnService endpoint found. "); - return null; - - } - - //set assertion signing key - KeyDescriptor signKeyDescriptor = SAML2Utils - .createSAMLObject(KeyDescriptor.class); - signKeyDescriptor.setUse(UsageType.SIGNING); - KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); - signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(getRequestorResponseSigningCredentials())); - idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); - - //set IDP attribute set - idpSSODescriptor.getAttributes().addAll(getIDPPossibleAttributes()); - - //set providable nameID formats - for (String format : getIDPPossibleNameITTypes()) { - NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); - nameIDFormat.setFormat(format); - idpSSODescriptor.getNameIDFormats().add(nameIDFormat); - - } - - return idpSSODescriptor; - - } - - private Signature getIDPSignature(Credential credentials) { - PrivateKey privatekey = credentials.getPrivateKey(); - Signature signer = SAML2Utils.createSAMLObject(Signature.class); - - if (privatekey instanceof RSAPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); - - } else if (privatekey instanceof iaik.security.ecc.ecdsa.ECPrivateKey) { - signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); - - } else { - Logger.warn("Could NOT evaluate the Private-Key type from " + credentials.getEntityId() + " credential."); - - - } - - signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); - signer.setSigningCredential(credentials); - return signer; - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java new file mode 100644 index 000000000..3418ffb69 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java @@ -0,0 +1,460 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.pvp2x.builder; + +import java.io.IOException; +import java.io.StringWriter; +import java.security.PrivateKey; +import java.security.interfaces.RSAPrivateKey; +import java.util.List; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.joda.time.DateTime; +import org.opensaml.Configuration; +import org.opensaml.common.xml.SAMLConstants; +import org.opensaml.saml2.metadata.AssertionConsumerService; +import org.opensaml.saml2.metadata.AttributeConsumingService; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.KeyDescriptor; +import org.opensaml.saml2.metadata.LocalizedString; +import org.opensaml.saml2.metadata.NameIDFormat; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.ServiceName; +import org.opensaml.saml2.metadata.SingleLogoutService; +import org.opensaml.saml2.metadata.SingleSignOnService; +import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.security.SecurityException; +import org.opensaml.xml.security.SecurityHelper; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.credential.UsageType; +import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; +import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; +import org.opensaml.xml.signature.Signature; +import org.opensaml.xml.signature.SignatureConstants; +import org.opensaml.xml.signature.SignatureException; +import org.opensaml.xml.signature.Signer; +import org.springframework.stereotype.Service; +import org.w3c.dom.Document; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ + +@Service("PVPMetadataBuilder") +public class PVPMetadataBuilder { + + X509KeyInfoGeneratorFactory keyInfoFactory = null; + + /** + * + */ + public PVPMetadataBuilder() { + keyInfoFactory = new X509KeyInfoGeneratorFactory(); + keyInfoFactory.setEmitEntityIDAsKeyName(true); + keyInfoFactory.setEmitEntityCertificate(true); + + } + + + /** + * + * Build PVP 2.1 conform SAML2 metadata + * + * @param config + * PVPMetadataBuilder configuration + * + * @return PVP metadata as XML String + * @throws SecurityException + * @throws ConfigurationException + * @throws CredentialsNotAvailableException + * @throws TransformerFactoryConfigurationError + * @throws MarshallingException + * @throws TransformerException + * @throws ParserConfigurationException + * @throws IOException + * @throws SignatureException + */ + public String buildPVPMetadata(IPVPMetadataBuilderConfiguration config) throws CredentialsNotAvailableException, ConfigurationException, SecurityException, TransformerFactoryConfigurationError, MarshallingException, TransformerException, ParserConfigurationException, IOException, SignatureException { + DateTime date = new DateTime(); + EntityDescriptor entityDescriptor = SAML2Utils + .createSAMLObject(EntityDescriptor.class); + + //set entityID + entityDescriptor.setEntityID(config.getEntityID()); + + //set contact and organisation information + List contactPersons = config.getContactPersonInformation(); + if (contactPersons != null) + entityDescriptor.getContactPersons().addAll(contactPersons); + + Organization organisation = config.getOrgansiationInformation(); + if (organisation != null) + entityDescriptor.setOrganization(organisation); + + //set IDP metadata + if (config.buildIDPSSODescriptor()) { + RoleDescriptor idpSSODesc = generateIDPMetadata(config); + if (idpSSODesc != null) + entityDescriptor.getRoleDescriptors().add(idpSSODesc); + + } + + //set SP metadata for interfederation + if (config.buildSPSSODescriptor()) { + RoleDescriptor spSSODesc = generateSPMetadata(config); + if (spSSODesc != null) + entityDescriptor.getRoleDescriptors().add(spSSODesc); + + } + + //set metadata signature parameters + Credential metadataSignCred = config.getMetadataSigningCredentials(); + Signature signature = getIDPSignature(metadataSignCred); + SecurityHelper.prepareSignatureParams(signature, metadataSignCred, null, null); + + + //initialize XML document builder + DocumentBuilder builder; + DocumentBuilderFactory factory = DocumentBuilderFactory + .newInstance(); + + builder = factory.newDocumentBuilder(); + Document document = builder.newDocument(); + + + //build entities descriptor + if (config.buildEntitiesDescriptorAsRootElement()) { + EntitiesDescriptor entitiesDescriptor = + SAML2Utils.createSAMLObject(EntitiesDescriptor.class); + entitiesDescriptor.setName(config.getEntityFriendlyName()); + entitiesDescriptor.setID(SAML2Utils.getSecureIdentifier()); + entitiesDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); + entitiesDescriptor.getEntityDescriptors().add(entityDescriptor); + + entitiesDescriptor.setSignature(signature); + + //marshall document + Marshaller out = Configuration.getMarshallerFactory() + .getMarshaller(entitiesDescriptor); + out.marshall(entitiesDescriptor, document); + + } else { + entityDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); + + entityDescriptor.setSignature(signature); + + //marshall document + Marshaller out = Configuration.getMarshallerFactory() + .getMarshaller(entityDescriptor); + out.marshall(entityDescriptor, document); + + } + + //sign metadata + Signer.signObject(signature); + + //transform metadata object to XML string + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); + + StringWriter sw = new StringWriter(); + StreamResult sr = new StreamResult(sw); + DOMSource source = new DOMSource(document); + transformer.transform(source, sr); + sw.close(); + + return sw.toString(); + } + + + private RoleDescriptor generateSPMetadata(IPVPMetadataBuilderConfiguration config) throws CredentialsNotAvailableException, SecurityException, ConfigurationException { + SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); + spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + spSSODescriptor.setAuthnRequestsSigned(true); + spSSODescriptor.setWantAssertionsSigned(false); + + KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); + + //Set AuthRequest Signing certificate + Credential authcredential = config.getRequestorResponseSigningCredentials(); + if (authcredential == null) { + Logger.warn("SP Metadata generation FAILED! --> Builder has NO request signing-credential. "); + return null; + + } else { + KeyDescriptor signKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + signKeyDescriptor.setUse(UsageType.SIGNING); + signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authcredential)); + spSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); + + } + + //Set assertion encryption credentials + Credential authEncCredential = config.getEncryptionCredentials(); + + if (authEncCredential != null) { + KeyDescriptor encryKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + encryKeyDescriptor.setUse(UsageType.ENCRYPTION); + encryKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(authEncCredential)); + spSSODescriptor.getKeyDescriptors().add(encryKeyDescriptor); + + } else { + Logger.warn("No Assertion Encryption-Key defined. This setting is not recommended!"); + + } + + //check nameID formates + if (config.getSPAllowedNameITTypes() == null || config.getSPAllowedNameITTypes().size() == 0) { + Logger.warn("SP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); + return null; + + } else { + for (String format : config.getSPAllowedNameITTypes()) { + NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); + nameIDFormat.setFormat(format); + spSSODescriptor.getNameIDFormats().add(nameIDFormat); + + } + } + + + //add POST-Binding assertion consumer services + if (MiscUtil.isNotEmpty(config.getSPAssertionConsumerServicePostBindingURL())) { + AssertionConsumerService postassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); + postassertionConsumerService.setIndex(0); + postassertionConsumerService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + postassertionConsumerService.setLocation(config.getSPAssertionConsumerServicePostBindingURL()); + postassertionConsumerService.setIsDefault(true); + spSSODescriptor.getAssertionConsumerServices().add(postassertionConsumerService); + + } + + //add POST-Binding assertion consumer services + if (MiscUtil.isNotEmpty(config.getSPAssertionConsumerServiceRedirectBindingURL())) { + AssertionConsumerService redirectassertionConsumerService = SAML2Utils.createSAMLObject(AssertionConsumerService.class); + redirectassertionConsumerService.setIndex(1); + redirectassertionConsumerService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + redirectassertionConsumerService.setLocation(config.getSPAssertionConsumerServiceRedirectBindingURL()); + spSSODescriptor.getAssertionConsumerServices().add(redirectassertionConsumerService); + + } + + //validate WebSSO endpoints + if (spSSODescriptor.getAssertionConsumerServices().size() == 0) { + Logger.warn("SP Metadata generation FAILED! --> NO SAML2 AssertionConsumerService endpoint found. "); + return null; + + } + + //add POST-Binding SLO descriptor + if (MiscUtil.isNotEmpty(config.getSPSLOPostBindingURL())) { + SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + postSLOService.setLocation(config.getSPSLOPostBindingURL()); + postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + spSSODescriptor.getSingleLogoutServices().add(postSLOService); + + } + + //add POST-Binding SLO descriptor + if (MiscUtil.isNotEmpty(config.getSPSLORedirectBindingURL())) { + SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + redirectSLOService.setLocation(config.getSPSLORedirectBindingURL()); + redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + spSSODescriptor.getSingleLogoutServices().add(redirectSLOService); + + } + + //add POST-Binding SLO descriptor + if (MiscUtil.isNotEmpty(config.getSPSLOSOAPBindingURL())) { + SingleLogoutService soapSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + soapSLOService.setLocation(config.getSPSLOSOAPBindingURL()); + soapSLOService.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); + spSSODescriptor.getSingleLogoutServices().add(soapSLOService); + + } + + + //add required attributes + List reqSPAttr = config.getSPRequiredAttributes(); + AttributeConsumingService attributeService = SAML2Utils.createSAMLObject(AttributeConsumingService.class); + + attributeService.setIndex(0); + attributeService.setIsDefault(true); + ServiceName serviceName = SAML2Utils.createSAMLObject(ServiceName.class); + serviceName.setName(new LocalizedString("Default Service", "en")); + attributeService.getNames().add(serviceName); + + if (reqSPAttr != null && reqSPAttr.size() > 0) { + Logger.debug("Add " + reqSPAttr.size() + " attributes to SP metadata"); + attributeService.getRequestAttributes().addAll(reqSPAttr); + + } else { + Logger.debug("SP metadata contains NO requested attributes."); + + } + + spSSODescriptor.getAttributeConsumingServices().add(attributeService); + + return spSSODescriptor; + } + + private IDPSSODescriptor generateIDPMetadata(IPVPMetadataBuilderConfiguration config) throws ConfigurationException, CredentialsNotAvailableException, SecurityException { + //check response signing credential + Credential responseSignCred = config.getRequestorResponseSigningCredentials(); + if (responseSignCred == null) { + Logger.warn("IDP Metadata generation FAILED! --> Builder has NO Response signing credential. "); + return null; + + } + + //check nameID formates + if (config.getIDPPossibleNameITTypes() == null || config.getIDPPossibleNameITTypes().size() == 0) { + Logger.warn("IDP Metadata generation FAILED! --> Builder has NO provideable SAML2 nameIDFormats. "); + return null; + + } + + // build SAML2 IDP-SSO descriptor element + IDPSSODescriptor idpSSODescriptor = SAML2Utils + .createSAMLObject(IDPSSODescriptor.class); + + idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); + + //set ass default value, because PVP 2.x specification defines this feature as MUST + idpSSODescriptor.setWantAuthnRequestsSigned(true); + + // add WebSSO descriptor for POST-Binding + if (MiscUtil.isNotEmpty(config.getIDPWebSSOPostBindingURL())) { + SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); + postSingleSignOnService.setLocation(config.getIDPWebSSOPostBindingURL()); + postSingleSignOnService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); + + } + + // add WebSSO descriptor for Redirect-Binding + if (MiscUtil.isNotEmpty(config.getIDPWebSSORedirectBindingURL())) { + SingleSignOnService postSingleSignOnService = SAML2Utils.createSAMLObject(SingleSignOnService.class); + postSingleSignOnService.setLocation(config.getIDPWebSSORedirectBindingURL()); + postSingleSignOnService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + idpSSODescriptor.getSingleSignOnServices().add(postSingleSignOnService); + + } + + //add Single LogOut POST-Binding endpoing + if (MiscUtil.isNotEmpty(config.getIDPSLOPostBindingURL())) { + SingleLogoutService postSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + postSLOService.setLocation(config.getIDPSLOPostBindingURL()); + postSLOService.setBinding(SAMLConstants.SAML2_POST_BINDING_URI); + idpSSODescriptor.getSingleLogoutServices().add(postSLOService); + + } + + //add Single LogOut Redirect-Binding endpoing + if (MiscUtil.isNotEmpty(config.getIDPSLORedirectBindingURL())) { + SingleLogoutService redirectSLOService = SAML2Utils.createSAMLObject(SingleLogoutService.class); + redirectSLOService.setLocation(config.getIDPSLORedirectBindingURL()); + redirectSLOService.setBinding(SAMLConstants.SAML2_REDIRECT_BINDING_URI); + idpSSODescriptor.getSingleLogoutServices().add(redirectSLOService); + + } + + //validate WebSSO endpoints + if (idpSSODescriptor.getSingleSignOnServices().size() == 0) { + Logger.warn("IDP Metadata generation FAILED! --> NO SAML2 SingleSignOnService endpoint found. "); + return null; + + } + + //set assertion signing key + KeyDescriptor signKeyDescriptor = SAML2Utils + .createSAMLObject(KeyDescriptor.class); + signKeyDescriptor.setUse(UsageType.SIGNING); + KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); + signKeyDescriptor.setKeyInfo(keyInfoGenerator.generate(config.getRequestorResponseSigningCredentials())); + idpSSODescriptor.getKeyDescriptors().add(signKeyDescriptor); + + //set IDP attribute set + idpSSODescriptor.getAttributes().addAll(config.getIDPPossibleAttributes()); + + //set providable nameID formats + for (String format : config.getIDPPossibleNameITTypes()) { + NameIDFormat nameIDFormat = SAML2Utils.createSAMLObject(NameIDFormat.class); + nameIDFormat.setFormat(format); + idpSSODescriptor.getNameIDFormats().add(nameIDFormat); + + } + + return idpSSODescriptor; + + } + + private Signature getIDPSignature(Credential credentials) { + PrivateKey privatekey = credentials.getPrivateKey(); + Signature signer = SAML2Utils.createSAMLObject(Signature.class); + + if (privatekey instanceof RSAPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA256); + + } else if (privatekey instanceof iaik.security.ecc.ecdsa.ECPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); + + } else { + Logger.warn("Could NOT evaluate the Private-Key type from " + credentials.getEntityId() + " credential."); + + + } + + signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); + signer.setSigningCredential(credentials); + return signer; + + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java index 959fc7d2d..a7fc8295a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java @@ -201,7 +201,8 @@ public class SingleLogOutBuilder { try { binding.encodeRespone(req, resp, sloResp, - consumerService.getLocation(), relayState); + consumerService.getLocation(), relayState, + credentialProvider.getIDPAssertionSigningCredential()); } catch (MessageEncodingException e) { Logger.error("Message Encoding exception", e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java new file mode 100644 index 000000000..e0994ff19 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IDPPVPMetadataConfiguration.java @@ -0,0 +1,288 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.pvp2x.config; + +import java.util.Arrays; +import java.util.List; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.security.credential.Credential; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfiguration { + + private static final int VALIDUNTIL_IN_HOURS = 24; + + private String authURL; + private IDPCredentialProvider credentialProvider; + + public IDPPVPMetadataConfiguration(String authURL, IDPCredentialProvider credentialProvider) { + this.authURL = authURL; + this.credentialProvider = credentialProvider; + + } + + public String getDefaultActionName() { + return (PVP2XProtocol.METADATA); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataValidUntil() + */ + @Override + public int getMetadataValidUntil() { + return VALIDUNTIL_IN_HOURS; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildEntitiesDescriptorAsRootElement() + */ + @Override + public boolean buildEntitiesDescriptorAsRootElement() { + return true; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildIDPSSODescriptor() + */ + @Override + public boolean buildIDPSSODescriptor() { + return true; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildSPSSODescriptor() + */ + @Override + public boolean buildSPSSODescriptor() { + return false; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityID() + */ + @Override + public String getEntityID() { + return authURL; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityFriendlyName() + */ + @Override + public String getEntityFriendlyName() { + try { + return PVPConfiguration.getInstance().getIDPIssuerName(); + + } catch (ConfigurationException e) { + Logger.error("Can not load Metadata entry: EntityID friendlyName.", e); + return null; + + } + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getContactPersonInformation() + */ + @Override + public List getContactPersonInformation() { + try { + return PVPConfiguration.getInstance().getIDPContacts(); + + } catch (ConfigurationException e) { + Logger.warn("Can not load Metadata entry: Contect Person", e); + return null; + + } + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getOrgansiationInformation() + */ + @Override + public Organization getOrgansiationInformation() { + try { + return PVPConfiguration.getInstance().getIDPOrganisation(); + + } catch (ConfigurationException e) { + Logger.warn("Can not load Metadata entry: Organisation", e); + return null; + + } + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataSigningCredentials() + */ + @Override + public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPMetaDataSigningCredential(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getRequestorResponseSigningCredentials() + */ + @Override + public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPAssertionSigningCredential(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEncryptionCredentials() + */ + @Override + public Credential getEncryptionCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPAssertionEncryptionCredential(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSOPostBindingURL() + */ + @Override + public String getIDPWebSSOPostBindingURL() { + return authURL + PVPConfiguration.PVP2_IDP_POST; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSORedirectBindingURL() + */ + @Override + public String getIDPWebSSORedirectBindingURL() { + return authURL + PVPConfiguration.PVP2_IDP_REDIRECT; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLOPostBindingURL() + */ + @Override + public String getIDPSLOPostBindingURL() { + return authURL + PVPConfiguration.PVP2_IDP_POST; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLORedirectBindingURL() + */ + @Override + public String getIDPSLORedirectBindingURL() { + return authURL + PVPConfiguration.PVP2_IDP_REDIRECT; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServicePostBindingURL() + */ + @Override + public String getSPAssertionConsumerServicePostBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServiceRedirectBindingURL() + */ + @Override + public String getSPAssertionConsumerServiceRedirectBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOPostBindingURL() + */ + @Override + public String getSPSLOPostBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLORedirectBindingURL() + */ + @Override + public String getSPSLORedirectBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOSOAPBindingURL() + */ + @Override + public String getSPSLOSOAPBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleAttributes() + */ + @Override + public List getIDPPossibleAttributes() { + return PVPAttributeBuilder.buildSupportedEmptyAttributes(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleNameITTypes() + */ + @Override + public List getIDPPossibleNameITTypes() { + return Arrays.asList(NameIDType.PERSISTENT, + NameIDType.TRANSIENT, + NameIDType.UNSPECIFIED); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPRequiredAttributes() + */ + @Override + public List getSPRequiredAttributes() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAllowedNameITTypes() + */ + @Override + public List getSPAllowedNameITTypes() { + return null; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java new file mode 100644 index 000000000..52096fd19 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPMetadataBuilderConfiguration.java @@ -0,0 +1,217 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.pvp2x.config; + +import java.util.List; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.security.credential.Credential; + +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; + +/** + * @author tlenz + * + */ +public interface IPVPMetadataBuilderConfiguration { + + + /** + * Set metadata valid area + * + * @return valid until in hours [h] + */ + public int getMetadataValidUntil(); + + /** + * Build a SAML2 Entities element as metadata root element + * + * @return true, if the metadata should start with entities element + */ + public boolean buildEntitiesDescriptorAsRootElement(); + + /** + * + * + * @return true, if an IDP SSO-descriptor element should be generated + */ + public boolean buildIDPSSODescriptor(); + + /** + * + * + * @return true, if an SP SSO-descriptor element should be generated + */ + public boolean buildSPSSODescriptor(); + + /** + * Set the PVP entityID for this SAML2 metadata. + * The entityID must be an URL and must be start with the public-URL prefix of the server + * + * @return PVP entityID postfix as String + */ + public String getEntityID(); + + /** + * Set a friendlyName for this PVP entity + * + * @return + */ + public String getEntityFriendlyName(); + + /** + * Set the contact information for this metadata entity + * + * @return + */ + public List getContactPersonInformation(); + + /** + * Set organisation information for this metadata entity + * + * @return + */ + public Organization getOrgansiationInformation(); + + + /** + * Set the credential for metadata signing + * + * @return + * @throws CredentialsNotAvailableException + */ + public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException; + + /** + * Set the credential for request/response signing + * IDP metadata: this credential is used for SAML2 response signing + * SP metadata: this credential is used for SAML2 response signing + * + * @return + * @throws CredentialsNotAvailableException + */ + public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException; + + /** + * Set the credential for response encryption + * + * @return + * @throws CredentialsNotAvailableException + */ + public Credential getEncryptionCredentials() throws CredentialsNotAvailableException; + + /** + * Set the IDP Post-Binding URL for WebSSO + * + * @return + */ + public String getIDPWebSSOPostBindingURL(); + + /** + * Set the IDP Redirect-Binding URL for WebSSO + * + * @return + */ + public String getIDPWebSSORedirectBindingURL(); + + /** + * Set the IDP Post-Binding URL for Single LogOut + * + * @return + */ + public String getIDPSLOPostBindingURL(); + + /** + * Set the IDP Redirect-Binding URL for Single LogOut + * + * @return + */ + public String getIDPSLORedirectBindingURL(); + + /** + * Set the SP Post-Binding URL for for the Assertion-Consumer Service + * + * @return + */ + public String getSPAssertionConsumerServicePostBindingURL(); + + /** + * Set the SP Redirect-Binding URL for the Assertion-Consumer Service + * + * @return + */ + public String getSPAssertionConsumerServiceRedirectBindingURL(); + + /** + * Set the SP Post-Binding URL for Single LogOut + * + * @return + */ + public String getSPSLOPostBindingURL(); + + /** + * Set the SP Redirect-Binding URL for Single LogOut + * + * @return + */ + public String getSPSLORedirectBindingURL(); + + /** + * Set the SP SOAP-Binding URL for Single LogOut + * + * @return + */ + public String getSPSLOSOAPBindingURL(); + + + /** + * Set all SAML2 attributes which could be provided by this IDP + * + * @return + */ + public List getIDPPossibleAttributes(); + + /** + * Set all nameID types which could be provided by this IDP + * + * @return a List of SAML2 nameID types + */ + public List getIDPPossibleNameITTypes(); + + /** + * Set all SAML2 attributes which are required by the SP + * + * @return + */ + public List getSPRequiredAttributes(); + + /** + * Set all nameID types which allowed from the SP + * + * @return a List of SAML2 nameID types + */ + public List getSPAllowedNameITTypes(); +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index f7e753273..5e44c9057 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -22,29 +22,50 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.verification; +import java.util.ArrayList; +import java.util.List; + import javax.xml.namespace.QName; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; +import org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.common.xml.SAMLSchemaBuilder; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.EncryptedAssertion; import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.core.StatusCode; import org.opensaml.saml2.core.StatusResponseType; +import org.opensaml.saml2.encryption.Decrypter; +import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; import org.opensaml.saml2.metadata.IDPSSODescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.security.MetadataCriteria; import org.opensaml.security.SAMLSignatureProfileValidator; +import org.opensaml.xml.encryption.ChainingEncryptedKeyResolver; +import org.opensaml.xml.encryption.DecryptionException; +import org.opensaml.xml.encryption.InlineEncryptedKeyResolver; +import org.opensaml.xml.encryption.SimpleRetrievalMethodEncryptedKeyResolver; import org.opensaml.xml.security.CriteriaSet; +import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.credential.UsageType; import org.opensaml.xml.security.criteria.EntityIDCriteria; import org.opensaml.xml.security.criteria.UsageCriteria; +import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver; import org.opensaml.xml.signature.SignatureTrustEngine; import org.opensaml.xml.validation.ValidationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.w3c.dom.Element; import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; @@ -53,8 +74,11 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; +@Service("SAMLVerificationEngine") public class SAMLVerificationEngine { + @Autowired AuthConfiguration authConfig; + public void verify(InboundMessage msg, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { try { if (msg instanceof MOARequest && @@ -158,116 +182,110 @@ public class SAMLVerificationEngine { } } -// public static void validateAssertion(Response samlResp, boolean validateDestination) throws AssertionValidationExeption { -// try { -// if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { -// List saml2assertions = new ArrayList(); -// -// List allowedPublicURLPrefix = -// AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); -// boolean isValidDestination = false; -// for (String allowedPreFix : allowedPublicURLPrefix) { -// if (validateDestination && samlResp.getDestination().startsWith( -// allowedPreFix)) { -// isValidDestination = true; -// break; -// -// } -// } -// if (!isValidDestination && validateDestination) { -// Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); -// throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); -// -// } -// -// //check encrypted Assertion -// List encryAssertionList = samlResp.getEncryptedAssertions(); -// if (encryAssertionList != null && encryAssertionList.size() > 0) { -// //decrypt assertions -// -// Logger.debug("Found encryped assertion. Start decryption ..."); -// -// X509Credential authDecCredential = CredentialProvider.getIDPAssertionEncryptionCredential(); -// -// StaticKeyInfoCredentialResolver skicr = -// new StaticKeyInfoCredentialResolver(authDecCredential); -// -// ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); -// encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); -// encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); -// encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); -// -// Decrypter samlDecrypter = -// new Decrypter(null, skicr, encryptedKeyResolver); -// -// for (EncryptedAssertion encAssertion : encryAssertionList) { -// saml2assertions.add(samlDecrypter.decrypt(encAssertion)); -// -// } -// -// Logger.debug("Assertion decryption finished. "); -// -// } else { -// saml2assertions.addAll(samlResp.getAssertions()); -// -// } -// -// List validatedassertions = new ArrayList(); -// for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { -// -// try { -// performSchemaValidation(saml2assertion.getDOM()); -// -// Conditions conditions = saml2assertion.getConditions(); -// DateTime notbefore = conditions.getNotBefore().minusMinutes(5); -// DateTime notafter = conditions.getNotOnOrAfter(); -// if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { -// Logger.warn("PVP2 Assertion is out of Date. " -// + "{ Current : " + new DateTime() -// + " NotBefore: " + notbefore -// + " NotAfter : " + notafter -// + " }");; -// -// } else { -// validatedassertions.add(saml2assertion); -// -// } -// -// } catch (SchemaValidationException e) { -// -// } -// } -// -// if (validatedassertions.isEmpty()) { -// Logger.info("No valid PVP 2.1 assertion received."); -// throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); -// } -// -// samlResp.getAssertions().clear(); -// samlResp.getEncryptedAssertions().clear(); -// samlResp.getAssertions().addAll(validatedassertions); -// -// } else { -// Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " -// + samlResp.getStatus().getStatusCode().getValue()); -// throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " -// + samlResp.getStatus().getStatusCode().getValue(), null); -// } -// -// } catch (CredentialsNotAvailableException e) { -// Logger.warn("Assertion decrypt FAILED - No Credentials", e); -// throw new AssertionValidationExeption("Assertion decrypt FAILED - No Credentials", null, e); -// -// } catch (DecryptionException e) { -// Logger.warn("Assertion decrypt FAILED.", e); -// throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); -// -// } catch (ConfigurationException e) { -// throw new AssertionValidationExeption("pvp.12", null, e); -// } -// } + public void validateAssertion(Response samlResp, boolean validateDestination, Credential assertionDecryption) throws AssertionValidationExeption { + try { + if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { + List saml2assertions = new ArrayList(); + + //validate destination URL + List allowedPublicURLPrefix = authConfig.getPublicURLPrefix(); + boolean isValidDestination = false; + for (String allowedPreFix : allowedPublicURLPrefix) { + if (validateDestination && samlResp.getDestination().startsWith( + allowedPreFix)) { + isValidDestination = true; + break; + + } + } + if (!isValidDestination && validateDestination) { + Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); + throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); + + } + + //check encrypted Assertion + List encryAssertionList = samlResp.getEncryptedAssertions(); + if (encryAssertionList != null && encryAssertionList.size() > 0) { + //decrypt assertions + + Logger.debug("Found encryped assertion. Start decryption ..."); + + StaticKeyInfoCredentialResolver skicr = + new StaticKeyInfoCredentialResolver(assertionDecryption); + + ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); + encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); + encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); + encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); + + Decrypter samlDecrypter = + new Decrypter(null, skicr, encryptedKeyResolver); + + for (EncryptedAssertion encAssertion : encryAssertionList) { + saml2assertions.add(samlDecrypter.decrypt(encAssertion)); + + } + + Logger.debug("Assertion decryption finished. "); + + } else { + saml2assertions.addAll(samlResp.getAssertions()); + + } + + List validatedassertions = new ArrayList(); + for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { + + try { + performSchemaValidation(saml2assertion.getDOM()); + + Conditions conditions = saml2assertion.getConditions(); + DateTime notbefore = conditions.getNotBefore().minusMinutes(5); + DateTime notafter = conditions.getNotOnOrAfter(); + if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { + Logger.warn("PVP2 Assertion is out of Date. " + + "{ Current : " + new DateTime() + + " NotBefore: " + notbefore + + " NotAfter : " + notafter + + " }");; + + } else { + validatedassertions.add(saml2assertion); + + } + + } catch (SchemaValidationException e) { + + } + } + + if (validatedassertions.isEmpty()) { + Logger.info("No valid PVP 2.1 assertion received."); + throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); + } + + samlResp.getAssertions().clear(); + samlResp.getEncryptedAssertions().clear(); + samlResp.getAssertions().addAll(validatedassertions); + + } else { + Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " + + samlResp.getStatus().getStatusCode().getValue()); + throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " + + samlResp.getStatus().getStatusCode().getValue(), null); + } + + } catch (DecryptionException e) { + Logger.warn("Assertion decrypt FAILED.", e); + throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); + + } catch (ConfigurationException e) { + throw new AssertionValidationExeption("pvp.12", null, e); + } + } - private static void performSchemaValidation(Element source) throws SchemaValidationException { + private void performSchemaValidation(Element source) throws SchemaValidationException { String err = null; try { -- cgit v1.2.3 From 101f582d457f3e0bbd42083521360d18168fbd84 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 24 Feb 2016 06:22:18 +0100 Subject: add federated IDP authentication modul --- .../pvp2x/SP/tasks/AbstractAuthnRequestTask.java | 293 --------------------- .../pvp2x/SP/tasks/AbstractAuthnResponseTask.java | 53 ---- .../pvp2x/builder/PVPAuthnRequestBuilder.java | 172 ++++++++++++ .../IPVPAuthnRequestBuilderConfiguruation.java | 114 ++++++++ .../exceptions/AuthnRequestBuildException.java | 47 ++++ .../AuthnResponseValidationException.java | 48 ++++ .../storage/DBAuthenticationSessionStoreage.java | 68 ++--- .../id/storage/IAuthenticationSessionStoreage.java | 4 +- 8 files changed, 405 insertions(+), 394 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnRequestTask.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnResponseTask.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestBuildException.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnResponseValidationException.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnRequestTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnRequestTask.java deleted file mode 100644 index c8c115f82..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnRequestTask.java +++ /dev/null @@ -1,293 +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.SP.tasks; -import java.lang.reflect.InvocationTargetException; -import java.security.NoSuchAlgorithmException; - -import javax.servlet.http.HttpServletRequest; -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.metadata.EntityDescriptor; -import org.opensaml.saml2.metadata.SingleSignOnService; -import org.opensaml.saml2.metadata.provider.MetadataProviderException; -import org.opensaml.ws.message.encoder.MessageEncodingException; -import org.opensaml.xml.security.SecurityException; - -import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.binding.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.exceptions.PVP2Exception; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; -import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; -import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * @author tlenz - * - */ -public abstract class AbstractAuthnRequestTask 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 { - boolean requiredLocalAuthentication = true; - - String idpEntityID = - (String) executionContext.get(MOAIDAuthConstants.PROCESSCONTEXT_INTERFEDERATION_ENTITYID); - - if (MiscUtil.isEmpty(idpEntityID)) { - Logger.info("Interfederation not possible -> not inderfederation IDP EntityID found!"); - throw new TaskExecutionException(pendingReq, "Interfederation not possible", new MOAIDException("No inderfederation-IDP EntityID found.", null)); - - } - - //TODO: create MOASession - //TODO: set relayState to MOASession - //TODO: add support for requested attributes (from context and from metadata) - - - try { - OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(idpEntityID); - IOAAuthParameters sp = pendingReq.getOnlineApplicationConfiguration(); - - String requestedIDP = pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); - - if (!idp.isInderfederationIDP() || !idp.isInboundSSOInterfederationAllowed()) { - Logger.info("Requested interfederation IDP " + requestedIDP + " is not valid for interfederation."); - Logger.debug("isInderfederationIDP:" + String.valueOf(idp.isInderfederationIDP()) - + " isInboundSSOAllowed:" + String.valueOf(idp.isInboundSSOInterfederationAllowed())); - Logger.info("Switch to local authentication on this IDP ... "); - - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, true); - return; - - } - - - - - EntityDescriptor idpEntity = MOAMetadataProvider.getInstance(). - getEntityDescriptor(idpEntityID); - - if (idpEntity != null ) { - - //fetch endpoint from IDP metadata - SingleSignOnService redirectEndpoint = null; - for (SingleSignOnService sss : - idpEntity.getIDPSSODescriptor(SAMLConstants.SAML20P_NS).getSingleSignOnServices()) { - - // use POST binding as default if it exists - //TODO: maybe use RedirectBinding as default - if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) { - redirectEndpoint = sss; - - } else if ( sss.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI) && - redirectEndpoint == null ) - redirectEndpoint = sss; - } - - if (redirectEndpoint != null) { - - AuthnRequest authReq = SAML2Utils - .createSAMLObject(AuthnRequest.class); - SecureRandomIdentifierGenerator gen = new SecureRandomIdentifierGenerator(); - authReq.setID(gen.generateIdentifier()); - - //send passive AuthnRequest - authReq.setIsPassive(idp.isPassivRequestUsedForInterfederation()); - - authReq.setAssertionConsumerServiceIndex(0); - authReq.setIssueInstant(new DateTime()); - Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - issuer.setValue(pendingReq.getAuthURLWithOutSlash()); - - issuer.setFormat(NameIDType.ENTITY); - authReq.setIssuer(issuer); - NameIDPolicy policy = SAML2Utils - .createSAMLObject(NameIDPolicy.class); - policy.setAllowCreate(true); - policy.setFormat(NameID.TRANSIENT); - authReq.setNameIDPolicy(policy); - - authReq.setDestination(redirectEndpoint.getLocation()); - - RequestedAuthnContext reqAuthContext = - SAML2Utils.createSAMLObject(RequestedAuthnContext.class); - - AuthnContextClassRef authnClassRef = - SAML2Utils.createSAMLObject(AuthnContextClassRef.class); - - //check if STORK protocol module is in ClassPath - Object storkRequst = null; - Integer storkSecClass = null; - try { - storkRequst = Class.forName("at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest").newInstance(); - if (storkRequst != null && - pendingReq.getClass().isInstance(storkRequst)) { - Object storkAuthnRequest = pendingReq.getClass().getMethod("getStorkAuthnRequest", null).invoke(pendingReq, null); - storkSecClass = (Integer) storkAuthnRequest.getClass().getMethod("getQaa", null).invoke(storkAuthnRequest, null); - - } - - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { - - - } - - - if (sp != null && sp.isSTORKPVPGateway()){ - //use PVP SecClass instead of STORK QAA level - String secClass = null; - if (storkRequst != null && - pendingReq.getClass().isInstance(storkRequst)) { - - try { - secClass = PVPtoSTORKMapper.getInstance().mapToSecClass( - PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); - - } catch (Exception e) { - Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); - - } - } - - if (MiscUtil.isNotEmpty(secClass)) - authnClassRef.setAuthnContextClassRef(secClass); - else - authnClassRef.setAuthnContextClassRef("http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3"); - - } else { - if (storkRequst != null && - pendingReq.getClass().isInstance(storkRequst)) { - //use requested QAA level from STORK request - try { - authnClassRef.setAuthnContextClassRef( - PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); - Logger.debug("Use STORK-QAA level " + authnClassRef.getAuthnContextClassRef() - + " from STORK request"); - - } catch (Exception e) { - Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); - - } - - } - - if (MiscUtil.isEmpty(authnClassRef.getAuthnContextClassRef())) - authnClassRef.setAuthnContextClassRef("http://www.stork.gov.eu/1.0/citizenQAALevel/4"); - - } - - reqAuthContext.setComparison(AuthnContextComparisonTypeEnumeration.MINIMUM); - reqAuthContext.getAuthnContextClassRefs().add(authnClassRef); - authReq.setRequestedAuthnContext(reqAuthContext); - - IEncoder binding = null; - if (redirectEndpoint.getBinding().equals( - SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { - binding = new RedirectBinding(); - - } else if (redirectEndpoint.getBinding().equals( - SAMLConstants.SAML2_POST_BINDING_URI)) { - binding = new PostBinding(); - - } - - binding.encodeRequest(request, response, authReq, - redirectEndpoint.getLocation(), pendingReq.getRequestID()); - - //build and send request without an error - requiredLocalAuthentication = false; - - revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_IDP, idpEntity.getEntityID()); - - - } else { - Logger.warn("Requested IDP " + requestedIDP - + " does not support POST or Redirect Binding."); - - } - - } else { - Logger.warn("Requested IDP " + requestedIDP - + " is not found in InterFederation configuration"); - - } - - } catch (MetadataProviderException e) { - Logger.error("IDP metadata error." , e); - - } catch (NoSuchAlgorithmException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (MessageEncodingException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (SecurityException e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (PVP2Exception e) { - Logger.error("Build IDP authentication request FAILED.", e); - - } catch (ConfigurationException e1) { - Logger.error("Build IDP authentication request FAILED.", e1); - - } - - //set flag for next step - executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, - requiredLocalAuthentication); - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnResponseTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnResponseTask.java deleted file mode 100644 index 6ce8fab59..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/SP/tasks/AbstractAuthnResponseTask.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.SP.tasks; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; -import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.process.api.ExecutionContext; - -/** - * @author tlenz - * - */ -public abstract class AbstractAuthnResponseTask 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 { - - //TODO: validate SAML2 assertion - //TODO: move attributeQuery from AuthenticationDataBuilder to her - //TODO: add SAML2 interfederation Response to MOASession - //TODO: update AuthenticationDataBuilder to use Response from MOASession if exists - - } - -} 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 new file mode 100644 index 000000000..312bb823d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java @@ -0,0 +1,172 @@ +/* + * 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.NameIDPolicy; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.core.RequestedAuthnContext; +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.stereotype.Service; + +import at.gv.egovernment.moa.id.moduls.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; + +/** + * @author tlenz + * + */ +@Service("PVPAuthnRequestBuilder") +public class PVPAuthnRequestBuilder { + + + /** + * 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[]{idpEntity.getEntityID()}); + + } else + authReq.setDestination(endpoint.getLocation()); + + + //set basic AuthnRequest information + 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); + } + + //TODO: implement requested attributes + //maybe: config.getRequestedAttributes(); + + //select message encoder + IEncoder binding = null; + if (endpoint.getBinding().equals( + SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { + binding = new RedirectBinding(); + + } else if (endpoint.getBinding().equals( + SAMLConstants.SAML2_POST_BINDING_URI)) { + binding = new PostBinding(); + + } + + //encode message + binding.encodeRequest(null, httpResp, authReq, + endpoint.getLocation(), pendingReq.getRequestID(), config.getAuthnRequestSigningCredential()); + } + +} 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 new file mode 100644 index 000000000..d51231044 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java @@ -0,0 +1,114 @@ +/* + * 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; + +/** + * @author tlenz + * + */ +public interface IPVPAuthnRequestBuilderConfiguruation { + + /** + * 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(); + +} 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 new file mode 100644 index 000000000..eebaf6c9e --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestBuildException.java @@ -0,0 +1,47 @@ +/* + * 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/AuthnResponseValidationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnResponseValidationException.java new file mode 100644 index 000000000..957f9af1d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnResponseValidationException.java @@ -0,0 +1,48 @@ +/* + * 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/storage/DBAuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java index 743caec55..cfdb4426b 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 @@ -32,6 +32,7 @@ import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.fasterxml.jackson.core.JsonProcessingException; @@ -47,8 +48,7 @@ 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.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.EncryptedData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; @@ -65,6 +65,8 @@ import at.gv.egovernment.moa.util.MiscUtil; @Service("AuthenticationSessionStoreage") public class DBAuthenticationSessionStoreage implements IAuthenticationSessionStoreage{ + @Autowired AuthConfiguration authConfig; + private static JsonMapper mapper = new JsonMapper(); @Override @@ -749,44 +751,30 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } } - public String createInterfederatedSession(IRequest req, boolean isAuthenticated, String ssoID) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException { + public void createInterfederatedSession(IRequest req, boolean isAuthenticated) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException { AuthenticatedSessionStore dbsession = null; + Date now = new Date(); - //search for active SSO session - if (MiscUtil.isNotEmpty(ssoID)) { - String moaSession = getMOASessionSSOID(ssoID); - if (MiscUtil.isNotEmpty(moaSession)) { - try { - dbsession = searchInDatabase(moaSession, true); - - }catch (MOADatabaseException e) { + //search for active session + String moaSession = getMOASessionSSOID(req.getMOASessionIdentifier()); + if (MiscUtil.isNotEmpty(moaSession)) { + try { + dbsession = searchInDatabase(moaSession, true); - } - } - } - - String id = null; - Date now = new Date(); - //create new MOASession if any exists - AuthenticationSession session = null; - if (dbsession == null) { - id = Random.nextRandom(); - dbsession = new AuthenticatedSessionStore(); - dbsession.setSessionid(id); - dbsession.setCreated(now); - dbsession.setPendingRequestID(req.getRequestID()); - session = new AuthenticationSession(id, now); + }catch (MOADatabaseException e) { + Logger.error("NO MOASession found but MOASession MUST already exist!"); + throw e; + } + } - } else { - id = dbsession.getSessionid(); - session = decryptSession(dbsession); + AuthenticationSession session = decryptSession(dbsession); - } - - dbsession.setInterfederatedSSOSession(true); + //set Session parameters + session.setAuthenticated(isAuthenticated); dbsession.setAuthenticated(isAuthenticated); + dbsession.setInterfederatedSSOSession(true); dbsession.setUpdated(now); - session.setAuthenticated(true); + encryptSession(session, dbsession); //add interfederation information @@ -816,16 +804,8 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt idp.setIdpurlprefix(interFedEntityID); idp.setAuthURL(req.getAuthURL()); - try { - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance(). - getOnlineApplicationParameter(idp.getIdpurlprefix()); - idp.setStoreSSOInformation(oa.isInterfederationSSOStorageAllowed()); - - } catch (ConfigurationException e) { - Logger.warn("MOASession could not be created."); - throw new MOADatabaseException(e); - - } + OAAuthParameter oa = authConfig.getOnlineApplicationParameter(idp.getIdpurlprefix()); + idp.setStoreSSOInformation(oa.isInterfederationSSOStorageAllowed()); idp.setMoasession(dbsession); idpList.add(idp); @@ -839,14 +819,12 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt //store AssertionStore element to Database try { MOASessionDBUtils.saveOrUpdate(dbsession); - Logger.debug("MOASession with sessionID=" + id + " is stored in Database"); } catch (MOADatabaseException e) { Logger.warn("MOASession could not be created."); throw new MOADatabaseException(e); } - return id; } @Override 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 e89713b2e..2fd540a67 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 @@ -242,14 +242,12 @@ public interface IAuthenticationSessionStoreage { * * @param req Pending request * @param isAuthenticated true if the session should be marked as authenticated, otherwise false - * @param ssoID Single Sign-On session identifer - * @return MOASessionID of new created MOASession * @throws MOADatabaseException * @throws AssertionAttributeExtractorExeption * @throws BuildException */ @Deprecated - public String createInterfederatedSession(IRequest req, boolean isAuthenticated, String ssoID) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException; + public void createInterfederatedSession(IRequest req, boolean isAuthenticated) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException; /** * Search an active federation IDP which could be used for federated Single Sign-On by using an AttributeQuery -- cgit v1.2.3 From f981c4104724a916d937a0a903e16f5e7da7e4df Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 24 Feb 2016 06:36:41 +0100 Subject: fix bug in SAML1 legacy-mode selection --- .../auth/PropertyBasedAuthConfigurationProvider.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 d78b9b2ce..ed2f4d96b 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 @@ -350,11 +350,19 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide List legacy = new ArrayList(); try { - if (configuration.getBooleanValue(MOAIDConfigurationConstants.GENERAL_PROTOCOLS_SAML1_LEGACY, false)) - legacy.add("id_saml1"); - + if (configuration.getBooleanValue(MOAIDConfigurationConstants.GENERAL_PROTOCOLS_SAML1_LEGACY, false)) { + try { + Class saml1Protocol = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol"); + legacy.add(saml1Protocol.getName()); + + } catch (ClassNotFoundException e) { + Logger.warn("SAML1 Protocol implementation is not found, but SAML1 legacy-mode is active.. "); + + } + + } if (configuration.getBooleanValue(MOAIDConfigurationConstants.GENERAL_PROTOCOLS_PVP2X_LEGACY, false)) - legacy.add(PVP2XProtocol.PATH); + legacy.add(PVP2XProtocol.NAME); } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { Logger.warn("Load legacy protocol configuration property FAILED.", e); -- cgit v1.2.3 From 0933effb8fbb28e330bbea7bcff859ee05e3af0c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 24 Feb 2016 08:09:50 +0100 Subject: update some method headers --- .../builder/assertion/PVP2AssertionBuilder.java | 23 +++++++++--------- .../pvp2x/signer/AbstractCredentialProvider.java | 28 ++++++++++++++++++++++ 2 files changed, 39 insertions(+), 12 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index 94e30238a..af22a2d7e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -132,7 +132,7 @@ public class PVP2AssertionBuilder implements PVPConstants { SubjectConfirmationData subjectConfirmationData = null; - return buildGenericAssertion(pendingReq, attrQuery.getIssuer().getValue(), date, + return buildGenericAssertion(pendingReq.getAuthURL(), attrQuery.getIssuer().getValue(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, new DateTime(authData.getSsoSessionValidTo().getTime())); } @@ -410,12 +410,12 @@ public class PVP2AssertionBuilder implements PVPConstants { sloInformation.setNameIDFormat(subjectNameID.getFormat()); sloInformation.setSessionIndex(sessionIndex); - return buildGenericAssertion(pendingReq, peerEntity.getEntityID(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, subjectConfirmationData.getNotOnOrAfter()); + return buildGenericAssertion(pendingReq.getAuthURL(), peerEntity.getEntityID(), date, authnContextClassRef, attrList, subjectNameID, subjectConfirmationData, sessionIndex, subjectConfirmationData.getNotOnOrAfter()); } /** * - * @param pendingReq IDP PublicURL PreFix + * @param issuer IDP EntityID * @param entityID Service Provider EntityID * @param date * @param authnContextClassRef @@ -428,7 +428,7 @@ public class PVP2AssertionBuilder implements PVPConstants { * @throws ConfigurationException */ - public static Assertion buildGenericAssertion(IRequest pendingReq, String entityID, DateTime date, + public static Assertion buildGenericAssertion(String issuer, String entityID, DateTime date, AuthnContextClassRef authnContextClassRef, List attrList, NameID subjectNameID, SubjectConfirmationData subjectConfirmationData, String sessionIndex, DateTime isValidTo) throws ConfigurationException { @@ -478,15 +478,14 @@ public class PVP2AssertionBuilder implements PVPConstants { assertion.setConditions(conditions); - Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - - String authURL = pendingReq.getAuthURL(); - if (authURL.endsWith("/")) - authURL = authURL.substring(0, authURL.length()-1); - issuer.setValue(authURL); - issuer.setFormat(NameID.ENTITY); + 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(issuer); + assertion.setIssuer(issuerObj); assertion.setSubject(subject); assertion.setID(SAML2Utils.getSecureIdentifier()); assertion.setIssueInstant(date); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java index e7df23d61..4c9a1e59f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java @@ -23,11 +23,17 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.signer; import java.security.KeyStore; +import java.security.PrivateKey; +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; @@ -183,4 +189,26 @@ public abstract class AbstractCredentialProvider { throw new CredentialsNotAvailableException(e.getMessage(), null); } } + + 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 iaik.security.ecc.ecdsa.ECPrivateKey) { + signer.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_ECDSA_SHA1); + + } else { + Logger.warn("Could NOT evaluate the Private-Key type from " + credentials.getEntityId() + " credential."); + + + } + + signer.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS); + signer.setSigningCredential(credentials); + return signer; + + } } -- cgit v1.2.3 From 07e6b72e9f0d3edb1e6295d4c27d1e7675b79543 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 24 Feb 2016 13:19:11 +0100 Subject: update error messageing into Web-browser --- .../moa/id/auth/servlet/AbstractController.java | 42 +++++++++++++++++----- 1 file changed, 34 insertions(+), 8 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index 8c0708fd5..49035aba3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -56,6 +56,7 @@ 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.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.id.util.ServletUtils; import at.gv.egovernment.moa.id.util.VelocityProvider; @@ -98,7 +99,7 @@ public abstract class AbstractController extends MOAIDAuthConstants { } @ExceptionHandler({IOException.class}) - public void IOExceptionHandler(HttpServletResponse resp, IOException exception) { + public void IOExceptionHandler(HttpServletResponse resp, Throwable exception) { Logger.error("Internel Server Error." , exception); resp.setContentType("text/html;charset=UTF-8"); resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); @@ -136,8 +137,11 @@ public abstract class AbstractController extends MOAIDAuthConstants { String redirectURL = null; redirectURL = ServletUtils.getBaseUrl(req); redirectURL += "/"+AbstractAuthProtocolModulController.FINALIZEPROTOCOL_ENDPOINT - + "?" + ERROR_CODE_PARAM + "=" + key - + "&" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingRequestID; + + "?" + 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); @@ -178,8 +182,13 @@ public abstract class AbstractController extends MOAIDAuthConstants { if (throwable instanceof MOAIDException || throwable instanceof ProcessExecutionException) internalMOAIDExceptionHandler(req, resp, (Exception)throwable, false); - else - GenericExceptionHandler(resp, (Exception)throwable); + else { + //write generic message for general exceptions + String msg = MOAIDMessageProvider.getInstance().getMessage("internal.00", null); + writeHTMLErrorResponse(resp, msg, "9199", (Exception) throwable); + + } + } /** @@ -213,7 +222,22 @@ public abstract class AbstractController extends MOAIDAuthConstants { " | Description=" + descr + ")"); } + + private void writeHTMLErrorResponse(HttpServletResponse httpResp, String msg, String errorCode, Exception error) throws IOException { + VelocityContext context = new VelocityContext(); + //add errorcode and errormessage + context.put("errorMsg", msg); + context.put("errorCode", errorCode); + + //add stacktrace if debug is enabled + if (Logger.isTraceEnabled()) { + context.put("stacktrace", getStacktraceFromException(error)); + + } + + } + private void writeHTMLErrorResponse(HttpServletResponse httpResp, Exception error) throws IOException { VelocityContext context = new VelocityContext(); @@ -222,11 +246,13 @@ public abstract class AbstractController extends MOAIDAuthConstants { context.put("errorCode", ErrorResponseUtils.getInstance().getResponseErrorCode(error)); //add stacktrace if debug is enabled - if (Logger.isDebugEnabled()) { + if (Logger.isTraceEnabled()) { context.put("stacktrace", getStacktraceFromException(error)); } - + } + + private void writeHTMLErrorResponse(HttpServletResponse httpResp, VelocityContext context) throws IOException { try { InputStream is = null; String pathLocation = null; @@ -260,7 +286,7 @@ public abstract class AbstractController extends MOAIDAuthConstants { } } catch (Exception e) { Logger.error("Error-message form can not created.", e); - GenericExceptionHandler(httpResp, error); + IOExceptionHandler(httpResp, e); } } -- cgit v1.2.3 From cdbce8328bb9e3115ed3a6446ecb3df75d6b9822 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 24 Feb 2016 13:19:46 +0100 Subject: remove not required functions from BKU-selection form-builder --- .../at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java | 8 -------- 1 file changed, 8 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java index c22432d0d..4bcda3517 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java @@ -135,14 +135,6 @@ public class LoginFormBuilder { } if(value != null) { -// if(modul == null) { -// modul = SAML1Protocol.PATH; -// } -// if(action == null) { -// action = SAML1Protocol.GETARTIFACT; -// } - value = value.replace(MODUL, modul); - value = value.replace(ACTION, action); value = value.replace(OANAME, oaParam.getFriendlyName()); value = value.replace(CONTEXTPATH, contextpath); value = value.replace(MOASESSIONID, moaSessionID); -- cgit v1.2.3 From 3bee4536dce4136d83d6d815e6118e94f1efe8fd Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 24 Feb 2016 14:02:43 +0100 Subject: add or move some log messages --- .../moa/id/auth/MOAIDAuthInitializer.java | 22 +++++++++++++++++++--- .../AbstractAuthProtocolModulController.java | 2 ++ 2 files changed, 21 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 5968736f8..ce158d7fe 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 @@ -5,6 +5,8 @@ package at.gv.egovernment.moa.id.auth; import java.io.IOException; import java.security.GeneralSecurityException; +import java.security.Provider; +import java.security.Security; import javax.activation.CommandMap; import javax.activation.MailcapCommandMap; @@ -204,12 +206,11 @@ public class MOAIDAuthInitializer implements WebApplicationInitializer { Logger.warn(MOAIDMessageProvider.getInstance().getMessage( "init.01", null), e); } - - Logger.info("Loading security providers."); + + Logger.info("Loading Java security providers."); IAIK.addAsProvider(); ECCProvider.addAsProvider(); - // Initializes SSLSocketFactory store SSLUtils.initialize(); @@ -242,6 +243,21 @@ public class MOAIDAuthInitializer implements WebApplicationInitializer { } + + //IAIK.addAsProvider(); + //ECCProvider.addAsProvider(); + + Security.insertProviderAt(IAIK.getInstance(), 0); + Security.addProvider(new ECCProvider()); + + if (Logger.isDebugEnabled()) { + Logger.debug("Loaded Security Provider:"); + Provider[] providerList = Security.getProviders(); + for (int i=0; i Date: Wed, 24 Feb 2016 15:20:22 +0100 Subject: fix bug, which brakes the error handling --- .../at/gv/egovernment/moa/id/auth/servlet/AbstractController.java | 4 ++++ .../moa/id/protocols/AbstractAuthProtocolModulController.java | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index 49035aba3..8567d7834 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -236,6 +236,8 @@ public abstract class AbstractController extends MOAIDAuthConstants { } + writeHTMLErrorResponse(httpResp, context); + } private void writeHTMLErrorResponse(HttpServletResponse httpResp, Exception error) throws IOException { @@ -250,6 +252,8 @@ public abstract class AbstractController extends MOAIDAuthConstants { context.put("stacktrace", getStacktraceFromException(error)); } + + writeHTMLErrorResponse(httpResp, context); } private void writeHTMLErrorResponse(HttpServletResponse httpResp, VelocityContext context) throws IOException { 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 index 0b2fe879a..e6f08abd9 100644 --- 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 @@ -207,8 +207,9 @@ public abstract class AbstractAuthProtocolModulController extends AbstractContro try { Class clazz = Class.forName(protocolRequest.requestedModule()); + if (clazz == null || - !clazz.isInstance(IModulInfo.class)) { + !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."); -- cgit v1.2.3 From 14b1e1a2840a210754ac063ee3aa0b6884bf6ce9 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 25 Feb 2016 07:20:48 +0100 Subject: change PVP code to make it more reusable --- .../AbstractProcessEngineSignalController.java | 2 +- .../pvp2x/signer/IDPCredentialProvider.java | 43 ++++++++++++++++++---- 2 files changed, 37 insertions(+), 8 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 index 8b96b884e..6be0fce90 100644 --- 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 @@ -23,7 +23,7 @@ import at.gv.egovernment.moa.logging.Logger; */ public abstract class AbstractProcessEngineSignalController extends AbstractController { - @Autowired ProcessEngine processEngine; + @Autowired protected ProcessEngine processEngine; protected void signalProcessManagement(HttpServletRequest req, HttpServletResponse resp) throws IOException { String pendingRequestID = StringEscapeUtils.escapeHtml(getPendingRequestId(req)); 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 8fb4ec3cf..abc4eb4a9 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 @@ -29,6 +29,7 @@ import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.util.FileUtils; +import at.gv.egovernment.moa.util.MiscUtil; @Service("IDPCredentialProvider") public class IDPCredentialProvider extends AbstractCredentialProvider { @@ -70,7 +71,11 @@ public class IDPCredentialProvider extends AbstractCredentialProvider { if (props == null) props = authConfig.getGeneralPVP2ProperiesConfig(); - return props.getProperty(IDP_KS_PASS).trim(); + String value = props.getProperty(IDP_KS_PASS); + if (MiscUtil.isNotEmpty(value)) + return value.trim(); + else + return null; } /* (non-Javadoc) @@ -81,7 +86,11 @@ public class IDPCredentialProvider extends AbstractCredentialProvider { if (props == null) props = authConfig.getGeneralPVP2ProperiesConfig(); - return props.getProperty(IDP_KEYALIASMETADATA).trim(); + String value = props.getProperty(IDP_KEYALIASMETADATA); + if (MiscUtil.isNotEmpty(value)) + return value.trim(); + else + return null; } /* (non-Javadoc) @@ -92,7 +101,11 @@ public class IDPCredentialProvider extends AbstractCredentialProvider { if (props == null) props = authConfig.getGeneralPVP2ProperiesConfig(); - return props.getProperty(IDP_KEY_PASSMETADATA).trim(); + String value = props.getProperty(IDP_KEY_PASSMETADATA); + if (MiscUtil.isNotEmpty(value)) + return value.trim(); + else + return null; } /* (non-Javadoc) @@ -103,7 +116,11 @@ public class IDPCredentialProvider extends AbstractCredentialProvider { if (props == null) props = authConfig.getGeneralPVP2ProperiesConfig(); - return props.getProperty(IDP_KEYALIASASSERTION).trim(); + String value = props.getProperty(IDP_KEYALIASASSERTION); + if (MiscUtil.isNotEmpty(value)) + return value.trim(); + else + return null; } /* (non-Javadoc) @@ -114,7 +131,11 @@ public class IDPCredentialProvider extends AbstractCredentialProvider { if (props == null) props = authConfig.getGeneralPVP2ProperiesConfig(); - return props.getProperty(IDP_KEY_PASSASSERTION).trim(); + String value = props.getProperty(IDP_KEY_PASSASSERTION); + if (MiscUtil.isNotEmpty(value)) + return value.trim(); + else + return null; } /* (non-Javadoc) @@ -125,7 +146,11 @@ public class IDPCredentialProvider extends AbstractCredentialProvider { if (props == null) props = authConfig.getGeneralPVP2ProperiesConfig(); - return props.getProperty(IDP_KEYALIASENCRYTPION).trim(); + String value = props.getProperty(IDP_KEYALIASENCRYTPION); + if (MiscUtil.isNotEmpty(value)) + return value.trim(); + else + return null; } /* (non-Javadoc) @@ -136,7 +161,11 @@ public class IDPCredentialProvider extends AbstractCredentialProvider { if (props == null) props = authConfig.getGeneralPVP2ProperiesConfig(); - return props.getProperty(IDP_KEYALIASENCRYTPION).trim(); + String value = props.getProperty(IDP_KEY_PASSENCRYTPION); + if (MiscUtil.isNotEmpty(value)) + return value.trim(); + else + return null; } /* (non-Javadoc) -- cgit v1.2.3 From 1f88acc4f47eb8b9e01ff3c9d8262871fe314b42 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 25 Feb 2016 10:26:41 +0100 Subject: add 'isAbortedByUser' flag to pending-request to indicate that this request is aborted, but the auth. process is not broken --- .../tasks/EvaluateSSOConsentsTaskImpl.java | 22 +++++++------ .../at/gv/egovernment/moa/id/moduls/IRequest.java | 14 +++++++++ .../gv/egovernment/moa/id/moduls/RequestImpl.java | 19 ++++++++++-- .../protocols/ProtocolFinalizationController.java | 36 ++++++++++++---------- 4 files changed, 62 insertions(+), 29 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 d52b76ebd..5b53a43bd 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 @@ -90,19 +90,21 @@ public class EvaluateSSOConsentsTaskImpl extends AbstractAuthServletTask { if (ssoConsents) { //authenticate pending-request pendingReq.setAuthenticated(true); - - //store pending-request - requestStoreage.storePendingRequest(pendingReq); - - //redirect to auth. protocol finalization - performRedirectToProtocolFinialization(pendingReq, response); - + pendingReq.setAbortedByUser(false); + } else { //user deny single sign-on authentication - throw new AuthenticationException("auth.21", new Object[] {}); - + Logger.debug("User deny the Single Sign-On authentication for SP: " + pendingReq.getOAURL()); + pendingReq.setAbortedByUser(true); + } - + + //store pending-request + requestStoreage.storePendingRequest(pendingReq); + + //redirect to auth. protocol finalization + performRedirectToProtocolFinialization(pendingReq, response); + } catch (MOAIDException e) { throw new TaskExecutionException(pendingReq, e.getMessage(), e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java index f5d381e42..e1edb6b77 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java @@ -175,4 +175,18 @@ public interface IRequest { * @return Service-Provider configuration */ public IOAAuthParameters getOnlineApplicationConfiguration(); + + /** + * Indicates, if this pending-request is aborted by the user + * + * @return true, if it is aborted, otherwise false + */ + public boolean isAbortedByUser(); + + /** + * Set the 'isAboredByUser' flag of this pending-request + * + * @param b true, if the user has abort the authentication process, otherwise false + */ + public void setAbortedByUser(boolean isAborted); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index 961700651..4dade61fa 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -69,13 +69,17 @@ public abstract class RequestImpl implements IRequest, Serializable{ private boolean passiv = false; private boolean force = false; - - private boolean needAuthentication = true; - private boolean isAuthenticated = 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 genericDataStorage = new HashMap(); + /** * @throws ConfigurationException @@ -324,6 +328,15 @@ public abstract class RequestImpl implements IRequest, Serializable{ } + 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); 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 index 8c3f2c946..009ef4b6d 100644 --- 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 @@ -33,6 +33,7 @@ import org.springframework.web.bind.annotation.RequestMethod; 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.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.moduls.IRequest; @@ -74,10 +75,7 @@ public class ProtocolFinalizationController extends AbstractAuthProtocolModulCon //build protocol-specific error message if possible buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); - - //log Error Message - statisticLogger.logErrorOperation(throwable, pendingReq); - + //get MOASession for this pendingRequest AuthenticationSession moaSession = authenticatedSessionStorage.getSession( @@ -132,19 +130,25 @@ public class ProtocolFinalizationController extends AbstractAuthProtocolModulCon if (moaSession == null) { Logger.error("No MOASession with ID " + sessionID + " found.!"); handleErrorNoRedirect(new MOAIDException("auth.02", new Object[]{sessionID}), req, resp, true); - return; - } - - //check if MOASession and pending-request are authenticated - if (moaSession.isAuthenticated() && pendingReq.isAuthenticated()) { - finalizeAuthenticationProcess(req, resp, pendingReq, moaSession); - } else { - Logger.error("MOASession oder Pending-Request are not authenticated --> Abort authentication process!"); - handleErrorNoRedirect(new MOAIDException("auth.20", null), req, resp, true); - return; - + + //check if pending-request has 'abortedByUser' flag set + if (pendingReq.isAbortedByUser()) { + buildProtocolSpecificErrorResponse( + new AuthenticationException("auth.21", new Object[] {}), + req, resp, pendingReq); + + //check if MOASession and pending-request are authenticated + } else if (moaSession.isAuthenticated() && pendingReq.isAuthenticated()) { + finalizeAuthenticationProcess(req, resp, pendingReq, moaSession); + + } 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) { @@ -156,7 +160,7 @@ public class ProtocolFinalizationController extends AbstractAuthProtocolModulCon //remove pending-request if (pendingReq != null) - requestStorage.removePendingRequest(pendingReq.getRequestID()); + requestStorage.removePendingRequest(pendingReq.getRequestID()); } -- cgit v1.2.3 From 19f91c16f69b97c70ffe9a290305737bd351aae8 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 25 Feb 2016 12:17:29 +0100 Subject: solve problems with LogOut and Single LogOut --- .../moa/id/auth/servlet/AbstractController.java | 7 +-- .../id/auth/servlet/IDPSingleLogOutServlet.java | 2 +- .../moa/id/auth/servlet/LogOutServlet.java | 2 +- .../moa/id/data/SLOInformationImpl.java | 24 +++++++-- .../moa/id/data/SLOInformationInterface.java | 7 +++ .../moa/id/moduls/AuthenticationManager.java | 32 +++++++---- .../AbstractAuthProtocolModulController.java | 63 ++++++++++++++-------- .../protocols/ProtocolFinalizationController.java | 23 ++++---- .../id/protocols/pvp2x/AuthenticationAction.java | 2 + .../pvp2x/builder/SingleLogOutBuilder.java | 7 ++- 10 files changed, 119 insertions(+), 50 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index 8567d7834..396ffb53d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -197,15 +197,16 @@ public abstract class AbstractController extends MOAIDAuthConstants { * @param loggedException Exception to log */ protected void logExceptionToTechnicalLog(Throwable loggedException) { - if (!(loggedException instanceof MOAIDException)) { + if (!( loggedException instanceof MOAIDException + || loggedException instanceof ProcessExecutionException )) { Logger.error("Receive an internal error: Message=" + loggedException.getMessage(), loggedException); } else { if (Logger.isDebugEnabled() || Logger.isTraceEnabled()) { - Logger.error(loggedException.getMessage(), loggedException); + Logger.warn(loggedException.getMessage(), loggedException); } else { - Logger.error(loggedException.getMessage()); + Logger.info(loggedException.getMessage()); } } 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 307b668b7..6631a1d53 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 @@ -71,7 +71,7 @@ public class IDPSingleLogOutServlet extends AbstractController { @RequestMapping(value = "/idpSingleLogout", method = {RequestMethod.GET}) public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - Logger.debug("receive IDP SingleLogOut Request"); + Logger.debug("Receive IDP-initiated SingleLogOut"); String authURL = HTTPUtils.extractAuthURLFromRequest(req); 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 4ed276814..4fcf166c9 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 @@ -76,7 +76,7 @@ public class LogOutServlet { @RequestMapping(value = "/LogOut", method = {RequestMethod.POST, RequestMethod.GET}) public void performLogOut(HttpServletRequest req, HttpServletResponse resp) throws IOException { - Logger.debug("receive LogOut Request"); + Logger.debug("Receive simple LogOut Request"); String redirectUrl = (String) req.getParameter(REDIRECT_URL); 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 index 55a56056d..2d84bf472 100644 --- 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 @@ -40,16 +40,18 @@ public class SLOInformationImpl implements SLOInformationInterface, Serializable private String binding = null; private String serviceURL = null; private String authURL = null; + private String spEntityID = null; - public SLOInformationImpl(String authURL, String sessionID, String nameID, String nameIDFormat, String protocolType) { - new SLOInformationImpl(authURL, sessionID, nameID, nameIDFormat, protocolType, 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 sessionID, String nameID, String nameIDFormat, String protocolType, SingleLogoutService sloService) { + 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); @@ -72,6 +74,14 @@ public class SLOInformationImpl implements SLOInformationInterface, Serializable } + + /** + * @return the spEntityID + */ + public String getSpEntityID() { + return spEntityID; + } + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.data.SLOInformationInterface#getSessionIndex() */ @@ -161,6 +171,14 @@ public class SLOInformationImpl implements SLOInformationInterface, Serializable 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 index b2241f8ed..31fdaacfd 100644 --- 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 @@ -59,5 +59,12 @@ public interface SLOInformationInterface{ */ 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/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 22561e435..d76c6d526 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 @@ -115,7 +115,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { public void performOnlyIDPLogOut(HttpServletRequest request, HttpServletResponse response, String moaSessionID) { - Logger.info("Logout"); + Logger.info("Remove active user-session"); if(moaSessionID == null) { moaSessionID = (String) request.getParameter(PARAM_SESSIONID); @@ -440,6 +440,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { String pvpSLOIssuer = null; String inboundRelayState = null; + Logger.debug("Start technical Single LogOut process ... "); + if (pvpReq != null) { MOARequest samlReq = (MOARequest) pvpReq.getRequest(); LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); @@ -455,18 +457,25 @@ public class AuthenticationManager extends MOAIDAuthConstants { sloContainer.setSloRequest(pvpReq); sloBuilder.parseActiveIDPs(sloContainer, dbIDPs, pvpSLOIssuer); sloBuilder.parseActiveOAs(sloContainer, dbOAs, pvpSLOIssuer); - + + Logger.debug("Active SSO Service-Provider: " + + " BackChannel:" + sloContainer.getActiveBackChannelOAs().size() + + " FrontChannel:" + sloContainer.getActiveFrontChannalOAs().size() + + " NO_SLO_Support:" + sloContainer.getSloFailedOAs().size()); + //terminate MOASession try { authenticatedSessionStore.destroySession(session.getSessionID()); - ssoManager.deleteSSOSessionID(httpReq, httpResp); - + ssoManager.deleteSSOSessionID(httpReq, httpResp); + Logger.debug("Active SSO Session on IDP is remove."); + } catch (MOADatabaseException e) { Logger.warn("Delete MOASession FAILED."); sloContainer.putFailedOA(pvpReq.getAuthURL()); } + Logger.trace("Starting Service-Provider logout process ... "); //start service provider back channel logout process Iterator nextOAInterator = sloContainer.getNextBackChannelOA(); while (nextOAInterator.hasNext()) { @@ -474,6 +483,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { LogoutRequest sloReq = sloBuilder.buildSLORequestMessage(sloDescr); try { + Logger.trace("Send backchannel SLO Request to " + sloDescr.getSpEntityID()); List soapResp = MOASAMLSOAPClient.send(sloDescr.getServiceURL(), sloReq); LogoutResponse sloResp = null; @@ -483,9 +493,9 @@ public class AuthenticationManager extends MOAIDAuthConstants { } if (sloResp == null) { - Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() + Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() + " FAILED. NO LogOut response received."); - sloContainer.putFailedOA(sloReq.getIssuer().getValue()); + sloContainer.putFailedOA(sloDescr.getSpEntityID()); } else { samlVerificationEngine.verifySLOResponse(sloResp, @@ -496,14 +506,14 @@ public class AuthenticationManager extends MOAIDAuthConstants { sloBuilder.checkStatusCode(sloContainer, sloResp); } catch (SOAPException e) { - Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() + Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() + " FAILED.", e); - sloContainer.putFailedOA(sloReq.getIssuer().getValue()); + sloContainer.putFailedOA(sloDescr.getSpEntityID()); } catch (SecurityException | InvalidProtocolRequestException e) { - Logger.warn("Single LogOut for OA " + sloReq.getIssuer().getValue() + Logger.warn("Single LogOut for OA " + sloDescr.getSpEntityID() + " FAILED.", e); - sloContainer.putFailedOA(sloReq.getIssuer().getValue()); + sloContainer.putFailedOA(sloDescr.getSpEntityID()); } } @@ -516,6 +526,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { Collection> sloDescr = sloContainer.getFrontChannelOASessionDescriptions(); List sloReqList = new ArrayList(); for (Entry 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(), 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 index e6f08abd9..bf00cadaf 100644 --- 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 @@ -34,6 +34,7 @@ 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.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; @@ -99,9 +100,32 @@ public abstract class AbstractAuthProtocolModulController extends AbstractContro } catch (Exception e) { buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); + removeUserSession(pendingReq, req, resp); + } } + + protected String createNewSSOSessionCookie(HttpServletRequest req, HttpServletResponse resp, + IRequest pendingReq, AuthenticationSession 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 * @@ -118,21 +142,7 @@ public abstract class AbstractAuthProtocolModulController extends AbstractContro //if Single Sign-On functionality is enabled for this request if (pendingReq.needSingleSignOnFunctionality()) { - - Logger.debug("Add SSO information to MOASession."); - - //Store SSO information into database - 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); - - } + newSSOSessionId = createNewSSOSessionCookie(req, resp, pendingReq, moaSession); } @@ -202,6 +212,23 @@ public abstract class AbstractAuthProtocolModulController extends AbstractContro } + protected void removeUserSession(IRequest pendingReq, HttpServletRequest req, + HttpServletResponse resp) { + try { + AuthenticationSession moaSession = authenticatedSessionStorage.getSession( + pendingReq.getMOASessionIdentifier()); + + if (moaSession != null) + authmanager.performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); + + } catch (MOADatabaseException e) { + Logger.error("Remove user-session FAILED." , e); + + } + + + } + protected void buildProtocolSpecificErrorResponse(Throwable throwable, HttpServletRequest req, HttpServletResponse resp, IRequest protocolRequest) throws IOException { try { @@ -226,12 +253,6 @@ public abstract class AbstractAuthProtocolModulController extends AbstractContro //log Error Message statisticLogger.logErrorOperation(throwable, protocolRequest); - //remove MOASession - AuthenticationSession moaSession = authenticatedSessionStorage.getSession( - protocolRequest.getMOASessionIdentifier()); - if (moaSession != null) - authmanager.performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); - return; } else { 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 index 009ef4b6d..a9fc994ec 100644 --- 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 @@ -75,15 +75,9 @@ public class ProtocolFinalizationController extends AbstractAuthProtocolModulCon //build protocol-specific error message if possible buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); - - //get MOASession for this pendingRequest - AuthenticationSession moaSession = - authenticatedSessionStorage.getSession( - pendingReq.getMOASessionIdentifier()); - - //remove MOASession if someone is found - if (moaSession != null) - authmanager.performOnlyIDPLogOut(req, resp, moaSession.getSessionID()); + + //remove active user-session + removeUserSession(pendingReq, req, resp); return; @@ -135,9 +129,18 @@ public class ProtocolFinalizationController extends AbstractAuthProtocolModulCon //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 ( !(moaSession.isAuthenticated() + && pendingReq.needSingleSignOnFunctionality()) ) { + removeUserSession(pendingReq, req, resp); + + } //check if MOASession and pending-request are authenticated } else if (moaSession.isAuthenticated() && pendingReq.isAuthenticated()) { @@ -155,6 +158,8 @@ public class ProtocolFinalizationController extends AbstractAuthProtocolModulCon Logger.error("Finalize authentication protocol FAILED." , e); buildProtocolSpecificErrorResponse(e, req, resp, pendingReq); + removeUserSession(pendingReq, req, resp); + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java index 21f505bf1..2882f20e1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java @@ -76,6 +76,7 @@ public class AuthenticationAction implements IAction { DateTime date = new DateTime(); SLOInformationImpl sloInformation = new SLOInformationImpl(); + //build Assertion Assertion assertion = PVP2AssertionBuilder.buildAssertion(pvpRequest, authnRequest, authData, @@ -106,6 +107,7 @@ public class AuthenticationAction implements IAction { //set protocol type sloInformation.setProtocolType(req.requestedModule()); + sloInformation.setSpEntityID(req.getOnlineApplicationConfiguration().getPublicURLPrefix()); return sloInformation; } catch (MessageEncodingException e) { 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 a7fc8295a..cffc9378a 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 @@ -439,7 +439,7 @@ public class SingleLogOutBuilder { if (!oa.getOaurlprefix().equals(removeOAID)) { //Actually only PVP 2.1 support Single LogOut - if (PVP2XProtocol.PATH.equals(oa.getProtocolType())) { + if (PVP2XProtocol.NAME.equals(oa.getProtocolType())) { SingleLogoutService sloDesc; try { sloDesc = getRequestSLODescriptor(oa.getOaurlprefix()); @@ -447,7 +447,8 @@ public class SingleLogOutBuilder { if (sloDesc.getBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) container.getActiveBackChannelOAs().put(oa.getOaurlprefix(), new SLOInformationImpl( - oa.getAuthURL(), + oa.getAuthURL(), + oa.getOaurlprefix(), oa.getAssertionSessionID(), oa.getUserNameID(), oa.getUserNameIDFormat(), @@ -458,6 +459,7 @@ public class SingleLogOutBuilder { container.getActiveFrontChannalOAs().put(oa.getOaurlprefix(), new SLOInformationImpl( oa.getAuthURL(), + oa.getOaurlprefix(), oa.getAssertionSessionID(), oa.getUserNameID(), oa.getUserNameIDFormat(), @@ -498,6 +500,7 @@ public class SingleLogOutBuilder { container.getActiveFrontChannalOAs().put(el.getIdpurlprefix(), new SLOInformationImpl( el.getAuthURL(), + el.getIdpurlprefix(), el.getSessionIndex(), el.getUserNameID(), NameID.TRANSIENT, -- cgit v1.2.3 From afe6acdbabf17194cf2deb7df47c70399f9d23ab Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 25 Feb 2016 14:31:49 +0100 Subject: generate CSS und JS for GUI dynamically. Now all html templates must not include it's on CSS and JS as inline code --- .../moa/id/auth/builder/GUILayoutBuilder.java | 157 +++++++++++++++++++++ .../moa/id/auth/builder/LoginFormBuilder.java | 4 +- .../id/auth/servlet/GUILayoutBuilderServlet.java | 126 +++++++++++++++++ .../GeneralProcessEngineSignalController.java | 2 + .../gv/egovernment/moa/id/util/FormBuildUtils.java | 10 +- 5 files changed, 295 insertions(+), 4 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GUILayoutBuilder.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GUILayoutBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GUILayoutBuilder.java new file mode 100644 index 000000000..b95cbbc16 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GUILayoutBuilder.java @@ -0,0 +1,157 @@ +/* + * 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.builder; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.net.URI; + +import org.apache.commons.io.IOUtils; + +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.util.FormBuildUtils; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +public class GUILayoutBuilder { + private static final String CSS_LAYOUTTEMPLATE = "css_template.css"; + private static final String JS_LAYOUTTEMPLATE = "javascript_tempalte.js"; + private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; + + private static String CONTEXTPATH = "#CONTEXTPATH#"; + private static String MOASESSIONID = "#SESSIONID#"; + private static String AUTH_URL = "#AUTH_URL#"; + private static String BKU_ONLINE = "#ONLINE#"; + private static String BKU_HANDY = "#HANDY#"; + private static String BKU_LOCAL = "#LOCAL#"; + + + public static String buildCSS(IRequest pendingReq, String authURL) { + return buildForm(pendingReq, authURL, CSS_LAYOUTTEMPLATE); + + } + + public static String buildJS(IRequest pendingReq, String authURL) { + return buildForm(pendingReq, authURL, JS_LAYOUTTEMPLATE); + + } + + + + private static String getTemplate(String templateName) { + String pathLocation; + InputStream input = null; + try { + String rootconfigdir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); + pathLocation = rootconfigdir + HTMLTEMPLATESDIR + templateName; + + try { + File file = new File(new URI(pathLocation)); + input = new FileInputStream(file); + + } catch (FileNotFoundException e) { + Logger.warn("No LoginFormTempaltes found. Use Generic Templates from package."); + pathLocation = "resources/templates/" + templateName; + input = Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream(pathLocation); + + } + + return getTemplate(input); + + } catch (Exception e) { + return null; + + } finally { + try { + if (input != null) + input.close(); + + } catch (IOException e) { + Logger.warn("SendAssertionTemplate inputstream can not be closed.", e); + + } + } + } + + private static String getTemplate(InputStream input) { + String template = null; + try { + + StringWriter writer = new StringWriter(); + IOUtils.copy(input, writer); + template = writer.toString(); + + } catch (Exception e) { + Logger.error("Failed to read template", e); + + } + return template; + } + + private static String buildForm(IRequest pendingReq, String authURL, String templateName) { + //load default GUI-Layout template template + String value = getTemplate(templateName); + + if (pendingReq != null) { + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + + if(value != null) { + //only for BKU-Selection step and JavaScript generation + value = value.replace(AUTH_URL, LoginFormBuilder.SERVLET); + + value = value.replace(CONTEXTPATH, pendingReq.getAuthURL()); + value = value.replace(MOASESSIONID, pendingReq.getRequestID()); + + value = value.replace(BKU_ONLINE, IOAAuthParameters.ONLINEBKU); + value = value.replace(BKU_HANDY, IOAAuthParameters.HANDYBKU); + value = value.replace(BKU_LOCAL, IOAAuthParameters.LOCALBKU); + + + value = FormBuildUtils.customiceLayoutBKUSelection(value, + oaParam.isShowMandateCheckBox(), + oaParam.isOnlyMandateAllowed(), + oaParam.getFormCustomizaten(), + oaParam.isShowStorkLogin()); + } + + } else { + value = FormBuildUtils.defaultLayoutBKUSelection(value); + value = value.replace(CONTEXTPATH, authURL); + + } + + return value; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java index 4bcda3517..e1aa41ce2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java @@ -47,8 +47,6 @@ public class LoginFormBuilder { private static final String HTMLTEMPLATEFULL = "loginFormFull.html"; private static String AUTH_URL = "#AUTH_URL#"; - private static String MODUL = "#MODUL#"; - private static String ACTION = "#ACTION#"; private static String OANAME = "#OAName#"; private static String BKU_ONLINE = "#ONLINE#"; private static String BKU_HANDY = "#HANDY#"; @@ -57,7 +55,7 @@ public class LoginFormBuilder { private static String MOASESSIONID = "#SESSIONID#"; private static String PEPSLIST = "#PEPSLIST#"; - private static String SERVLET = CONTEXTPATH+"/GenerateIframeTemplate"; + public static String SERVLET = CONTEXTPATH+"/GenerateIframeTemplate"; private static String getTemplate() { String pathLocation =""; 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 new file mode 100644 index 000000000..1d9a57b48 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java @@ -0,0 +1,126 @@ +/* + * 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 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.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.GUILayoutBuilder; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.moduls.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; + +/** + * @author tlenz + * + */ +@Controller +public class GUILayoutBuilderServlet extends AbstractController { + + public static final String ENDPOINT_CSS = "/css/buildCSS"; + public static final String ENDPOINT_JS = "/js/buildJS"; + + @Autowired AuthConfiguration authConfig; + @Autowired IRequestStorage requestStoreage; + + public GUILayoutBuilderServlet() { + super(); + Logger.debug("Registering servlet " + getClass().getName() + + " with mappings '" + ENDPOINT_CSS + + "' and '" + ENDPOINT_JS + "'."); + + } + + @RequestMapping(value = "/css/buildCSS", method = {RequestMethod.GET}) + public void buildCSS(HttpServletRequest req, HttpServletResponse resp) throws IOException { + IRequest pendingReq = extractPendingRequest(req); + + //build Service-Provider specific CSS + String css = GUILayoutBuilder.buildCSS(pendingReq, HTTPUtils.extractAuthURLFromRequest(req)); + + resp.setContentType("text/css;charset=UTF-8"); + writeResponse(resp, css, "CSS"); + + } + + @RequestMapping(value = "/js/buildJS", method = {RequestMethod.GET}) + public void buildJavaScript(HttpServletRequest req, HttpServletResponse resp) throws IOException { + IRequest pendingReq = extractPendingRequest(req); + + //build Service-Provider specific CSS + String js = GUILayoutBuilder.buildJS(pendingReq, HTTPUtils.extractAuthURLFromRequest(req)); + + resp.setContentType("text/javascript;charset=UTF-8"); + writeResponse(resp, js, "JavaScript"); + + } + + private void writeResponse(HttpServletResponse resp, String value, String ressourceID) throws IOException { + if (MiscUtil.isNotEmpty(value)) { + PrintWriter out = new PrintWriter(resp.getOutputStream()); + out.print(value); + out.flush(); + + } else { + Logger.warn("GUI ressource: " + ressourceID + " generation FAILED."); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Created resource failed"); + + } + + } + + private IRequest extractPendingRequest(HttpServletRequest req) { + try { + String authURL = HTTPUtils.extractAuthURLFromRequest(req); + String pendingReqID = StringEscapeUtils.escapeHtml( + req.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); + + if (MiscUtil.isNotEmpty(pendingReqID) && authConfig.getPublicURLPrefix().contains(authURL)) { + IRequest pendingReq = requestStorage.getPendingRequest(pendingReqID); + if (pendingReq != null) + return pendingReq; + + } + + Logger.info("Prohibit GUI-Layout builder-request. No pending-request or wrong auth-URL."); + + } catch (Exception e) { + Logger.warn("GUI-Layout builder-servlet has an error during request-preprocessing.", e); + } + + return null; + } +} 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 6bccd5b88..26a0488ca 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 @@ -39,6 +39,8 @@ import org.springframework.web.bind.annotation.RequestMethod; public class GeneralProcessEngineSignalController extends AbstractProcessEngineSignalController { + + @RequestMapping(value = {"/GenerateIframeTemplate", "/SSOSendAssertionServlet", "/signalProcess" diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/FormBuildUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/FormBuildUtils.java index d3ac574f8..9a1237b80 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/FormBuildUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/FormBuildUtils.java @@ -26,7 +26,6 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.util.MiscUtil; public class FormBuildUtils { @@ -123,6 +122,15 @@ public class FormBuildUtils { public static Map getDefaultMap() { return defaultmap; } + + /** + * @param value + * @return + */ + public static String defaultLayoutBKUSelection(String value) { + return customiceLayoutBKUSelection(value, false, false, getDefaultMap(), false); + + } } -- cgit v1.2.3 From 1e94ef8839add787001c14d03fc29cf1b84c85b9 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 25 Feb 2016 14:41:43 +0100 Subject: fix nullpointer exception --- .../egovernment/moa/id/data/SLOInformationContainer.java | 14 ++++++++++++-- .../id/protocols/pvp2x/builder/SingleLogOutBuilder.java | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 ba7f33821..fd1749129 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 @@ -41,10 +41,20 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon private static final long serialVersionUID = 7148730740582881862L; private PVPTargetConfiguration sloRequest = null; - private LinkedHashMap activeFrontChannalOAs = null; - private LinkedHashMap activeBackChannelOAs = null; + private LinkedHashMap activeFrontChannalOAs; + private LinkedHashMap activeBackChannelOAs; private List sloFailedOAs = null; + /** + * + */ + public SLOInformationContainer() { + this.activeBackChannelOAs = new LinkedHashMap(); + this.activeFrontChannalOAs = new LinkedHashMap(); + this.sloFailedOAs = new ArrayList(); + + } + /** * @return the activeFrontChannalOAs 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 cffc9378a..63452bee0 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 @@ -504,7 +504,7 @@ public class SingleLogOutBuilder { el.getSessionIndex(), el.getUserNameID(), NameID.TRANSIENT, - PVP2XProtocol.PATH, + PVP2XProtocol.NAME, sloDesc)); } catch (NOSLOServiceDescriptorException e) { -- cgit v1.2.3 From 3eabe96b7e8ba03c9c6d3a17f80022436b40f45d Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 25 Feb 2016 14:45:28 +0100 Subject: catch exceptions in IDP initiated SLO implementation --- .../egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 6631a1d53..513b410f1 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 @@ -139,13 +139,9 @@ public class IDPSingleLogOutServlet extends AbstractController { } } } - } catch (MOADatabaseException e) { - //TODO: insert error Handling - e.printStackTrace(); + } catch (Exception e) { + handleErrorNoRedirect(e, req, resp, false); - } catch (MOAIDException e) { - // TODO Auto-generated catch block - e.printStackTrace(); } } else if (restartProcessObj != null && restartProcessObj instanceof String) { -- cgit v1.2.3 From c5fb48eb80fc9194983041909961ac3873f7653f Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 25 Feb 2016 15:45:00 +0100 Subject: Update GUI components --- .../moa/id/auth/servlet/AbstractController.java | 25 +++++++++++++--------- .../id/auth/servlet/IDPSingleLogOutServlet.java | 6 ++++-- .../WebFrontEndSecurityInterceptor.java | 6 ++++-- .../moa/id/moduls/AuthenticationManager.java | 1 + .../gv/egovernment/moa/id/moduls/SSOManager.java | 4 ++-- 5 files changed, 26 insertions(+), 16 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index 396ffb53d..36390ba62 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -56,6 +56,7 @@ 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.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.id.util.ServletUtils; @@ -73,6 +74,7 @@ public abstract class AbstractController extends MOAIDAuthConstants { private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; private static final String HTMLTEMPLATEFULL = "error_message.html"; + private static String CONTEXTPATH = "#CONTEXTPATH#"; @Autowired protected StatisticLogger statisticLogger; @Autowired protected IRequestStorage requestStorage; @@ -185,7 +187,7 @@ public abstract class AbstractController extends MOAIDAuthConstants { else { //write generic message for general exceptions String msg = MOAIDMessageProvider.getInstance().getMessage("internal.00", null); - writeHTMLErrorResponse(resp, msg, "9199", (Exception) throwable); + writeHTMLErrorResponse(req, resp, msg, "9199", (Exception) throwable); } @@ -224,7 +226,7 @@ public abstract class AbstractController extends MOAIDAuthConstants { } - private void writeHTMLErrorResponse(HttpServletResponse httpResp, String msg, String errorCode, Exception error) throws IOException { + private void writeHTMLErrorResponse(HttpServletRequest req, HttpServletResponse httpResp, String msg, String errorCode, Exception error) throws IOException { VelocityContext context = new VelocityContext(); //add errorcode and errormessage @@ -237,11 +239,11 @@ public abstract class AbstractController extends MOAIDAuthConstants { } - writeHTMLErrorResponse(httpResp, context); + writeHTMLErrorResponse(req, httpResp, context); } - private void writeHTMLErrorResponse(HttpServletResponse httpResp, Exception error) throws IOException { + private void writeHTMLErrorResponse(HttpServletRequest req, HttpServletResponse httpResp, Exception error) throws IOException { VelocityContext context = new VelocityContext(); //add errorcode and errormessage @@ -254,11 +256,14 @@ public abstract class AbstractController extends MOAIDAuthConstants { } - writeHTMLErrorResponse(httpResp, context); + writeHTMLErrorResponse(req, httpResp, context); } - private void writeHTMLErrorResponse(HttpServletResponse httpResp, VelocityContext context) throws IOException { - try { + private void writeHTMLErrorResponse(HttpServletRequest req, HttpServletResponse httpResp, VelocityContext context) throws IOException { + try { + String authURL = HTTPUtils.extractAuthURLFromRequest(req); + context.put(CONTEXTPATH, authURL); + InputStream is = null; String pathLocation = null; try { @@ -362,15 +367,15 @@ public abstract class AbstractController extends MOAIDAuthConstants { } else if (e instanceof ConfigurationException) { //send HTML formated error message - writeHTMLErrorResponse(resp, (MOAIDException) e); + writeHTMLErrorResponse(req, resp, (MOAIDException) e); } else if (e instanceof MOAIDException) { //send HTML formated error message - writeHTMLErrorResponse(resp, e); + writeHTMLErrorResponse(req, resp, e); } else if (e instanceof ProcessExecutionException) { //send HTML formated error message - writeHTMLErrorResponse(resp, e); + writeHTMLErrorResponse(req, resp, e); } 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 513b410f1..427bb9464 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 @@ -62,7 +62,7 @@ import at.gv.egovernment.moa.util.URLEncoder; */ @Controller public class IDPSingleLogOutServlet extends AbstractController { - + @Autowired SSOManager ssoManager; @Autowired AuthenticationManager authManager; @Autowired IAuthenticationSessionStoreage authenicationStorage; @@ -111,7 +111,9 @@ public class IDPSingleLogOutServlet extends AbstractController { else context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - + + context.put(SSOManager.CONTEXTPATH, authURL); + ssoManager.printSingleLogOutInfo(context, resp); } catch (MOAIDException e) { 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 c5a9ad34b..ce384d1a0 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 @@ -50,7 +50,7 @@ public class WebFrontEndSecurityInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { - + //only for SAML1 GetAuthenticationData webService functionality String requestedServlet = request.getServletPath(); if (MiscUtil.isNotEmpty(requestedServlet) && requestedServlet.startsWith("/services/GetAuthenticationData")) { @@ -61,7 +61,9 @@ public class WebFrontEndSecurityInterceptor implements HandlerInterceptor { //check AuthURL String authURL = HTTPUtils.extractAuthURLFromRequest(request); - if (!authURL.startsWith("https:") && !authConfig.isHTTPAuthAllowed()) { + if (!authURL.startsWith("https:") && !authConfig.isHTTPAuthAllowed() && + !authConfig.getPublicURLPrefix().contains(authURL)) { + Logger.info("Receive request, which is not in IDP URL-Prefix whitelist."); String errorMsg = MOAIDMessageProvider.getInstance().getMessage("auth.07", new Object[] { authURL + "*" }); Logger.info(errorMsg); response.sendError( 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 d76c6d526..73d682c21 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 @@ -554,6 +554,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { context.put("redirectURLs", sloReqList); context.put("timeoutURL", timeOutURL); context.put("timeout", SLOTIMEOUT); + context.put(SSOManager.CONTEXTPATH, authURL); ssoManager.printSingleLogOutInfo(context, httpResp); 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 89d50425b..856410d7b 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 @@ -61,10 +61,10 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @Service("MOAID_SSOManager") -public class SSOManager { - +public class SSOManager { private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; private static final String HTMLTEMPLATEFULL = "slo_template.html"; + public static String CONTEXTPATH = "#CONTEXTPATH#"; private static final String SSOCOOKIE = "MOA_ID_SSO"; private static final String SSOINTERFEDERATION = "MOA_INTERFEDERATION_SSO"; -- cgit v1.2.3 From 5fbe97c878c39e4081b7c2c670c1f2916652ee9c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 26 Feb 2016 07:18:24 +0100 Subject: fix wrong placeholder in default GUI templates --- .../at/gv/egovernment/moa/id/auth/servlet/AbstractController.java | 2 +- .../egovernment/moa/id/auth/servlet/IDPSingleLogOutServlet.java | 8 +++----- .../at/gv/egovernment/moa/id/moduls/AuthenticationManager.java | 7 +++---- .../src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java | 7 ++++--- 4 files changed, 11 insertions(+), 13 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index 36390ba62..d5fc90023 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -74,7 +74,7 @@ public abstract class AbstractController extends MOAIDAuthConstants { private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; private static final String HTMLTEMPLATEFULL = "error_message.html"; - private static String CONTEXTPATH = "#CONTEXTPATH#"; + private static String CONTEXTPATH = "contextPath"; @Autowired protected StatisticLogger statisticLogger; @Autowired protected IRequestStorage requestStorage; 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 427bb9464..9397f1132 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 @@ -111,10 +111,8 @@ public class IDPSingleLogOutServlet extends AbstractController { else context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - - context.put(SSOManager.CONTEXTPATH, authURL); - ssoManager.printSingleLogOutInfo(context, resp); + ssoManager.printSingleLogOutInfo(context, resp, authURL); } catch (MOAIDException e) { handleErrorNoRedirect(e, req, resp, false); @@ -209,7 +207,7 @@ public class IDPSingleLogOutServlet extends AbstractController { MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); try { - ssoManager.printSingleLogOutInfo(context, resp); + ssoManager.printSingleLogOutInfo(context, resp, authURL); } catch (MOAIDException e) { e.printStackTrace(); @@ -223,7 +221,7 @@ public class IDPSingleLogOutServlet extends AbstractController { context.put("successMsg", MOAIDMessageProvider.getInstance().getMessage("slo.02", null)); try { - ssoManager.printSingleLogOutInfo(context, resp); + ssoManager.printSingleLogOutInfo(context, resp, authURL); } catch (MOAIDException e) { e.printStackTrace(); 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 73d682c21..a97486097 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 @@ -554,8 +554,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { context.put("redirectURLs", sloReqList); context.put("timeoutURL", timeOutURL); context.put("timeout", SLOTIMEOUT); - context.put(SSOManager.CONTEXTPATH, authURL); - ssoManager.printSingleLogOutInfo(context, httpResp); + ssoManager.printSingleLogOutInfo(context, httpResp, authURL); } else { @@ -575,7 +574,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { else context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssoManager.printSingleLogOutInfo(context, httpResp); + ssoManager.printSingleLogOutInfo(context, httpResp, authURL); } @@ -593,7 +592,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { VelocityContext context = new VelocityContext(); context.put("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssoManager.printSingleLogOutInfo(context, httpResp); + ssoManager.printSingleLogOutInfo(context, httpResp, authURL); } 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 856410d7b..3b7c99d5a 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 @@ -64,7 +64,7 @@ import at.gv.egovernment.moa.util.MiscUtil; public class SSOManager { private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; private static final String HTMLTEMPLATEFULL = "slo_template.html"; - public static String CONTEXTPATH = "#CONTEXTPATH#"; + public static String CONTEXTPATH = "contextPath"; private static final String SSOCOOKIE = "MOA_ID_SSO"; private static final String SSOINTERFEDERATION = "MOA_INTERFEDERATION_SSO"; @@ -313,9 +313,10 @@ public class SSOManager { } - public void printSingleLogOutInfo(VelocityContext context, HttpServletResponse httpResp) throws MOAIDException { + public void printSingleLogOutInfo(VelocityContext context, HttpServletResponse httpResp, String authURL) throws MOAIDException { try { Logger.trace("Initialize VelocityEngine..."); + context.put(CONTEXTPATH, authURL); InputStream is = null; String pathLocation = null; @@ -362,7 +363,7 @@ public class SSOManager { BufferedReader reader = new BufferedReader(new InputStreamReader(is )); //set default elements to velocity context - context.put("contextpath", authConfig.getPublicURLPrefix()); + //context.put(CONTEXTPATH, authConfig.getPublicURLPrefix()); StringWriter writer = new StringWriter(); //velocityEngine.evaluate(context, writer, "SLO_Template", reader); -- cgit v1.2.3 From 35f18cb4d51e6c42b5dd8edd9fd5d541d6a8b919 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 26 Feb 2016 07:19:19 +0100 Subject: change some log-messges --- .../moa/id/auth/servlet/GUILayoutBuilderServlet.java | 14 ++++++++------ .../moa/id/protocols/ProtocolFinalizationController.java | 8 +++++--- 2 files changed, 13 insertions(+), 9 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 1d9a57b48..3f9093a21 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 @@ -103,19 +103,21 @@ public class GUILayoutBuilderServlet extends AbstractController { } private IRequest extractPendingRequest(HttpServletRequest req) { - try { - String authURL = HTTPUtils.extractAuthURLFromRequest(req); + try { String pendingReqID = StringEscapeUtils.escapeHtml( req.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); - if (MiscUtil.isNotEmpty(pendingReqID) && authConfig.getPublicURLPrefix().contains(authURL)) { + if (MiscUtil.isNotEmpty(pendingReqID)) { IRequest pendingReq = requestStorage.getPendingRequest(pendingReqID); - if (pendingReq != null) + if (pendingReq != null) { + Logger.trace("GUI-Layout builder: Pending-request:" + + pendingReqID + " found -> Build specific template"); return pendingReq; - + + } } - Logger.info("Prohibit GUI-Layout builder-request. No pending-request or wrong auth-URL."); + Logger.trace("GUI-Layout builder: No pending-request found -> Use default templates"); } catch (Exception e) { Logger.warn("GUI-Layout builder-servlet has an error during request-preprocessing.", e); 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 index a9fc994ec..0ab630dc2 100644 --- 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 @@ -67,10 +67,12 @@ public class ProtocolFinalizationController extends AbstractAuthProtocolModulCon try { //load stored exception from database Throwable throwable = transactionStorage.get(errorid, Throwable.class); - transactionStorage.remove(errorid); - + if (throwable != null) { - if (pendingReq != null) { + //remove exception if it was found + transactionStorage.remove(errorid); + + if (pendingReq != null) { revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR); //build protocol-specific error message if possible -- cgit v1.2.3 From de3619a6721b6a666efcaeef12d9a9e2dd3b8c44 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 1 Mar 2016 10:16:12 +0100 Subject: add HolderOfKey PVP-Attribute builder for testing --- .../protocols/builder/attributes/HolderOfKey.java | 67 ++++++++++++++++++++++ .../moa/id/protocols/pvp2x/PVPConstants.java | 4 ++ 2 files changed, 71 insertions(+) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/HolderOfKey.java (limited to 'id/server/idserverlib/src/main/java/at') 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 new file mode 100644 index 000000000..4def39d54 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/HolderOfKey.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * 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 at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.config.auth.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.Base64Utils; + +public class HolderOfKey implements IPVPAttributeBuilder { + + public String getName() { + return PVP_HOLDEROFKEY_NAME; + } + + public ATT build(IOAAuthParameters oaParam, IAuthData authData, + IAttributeGenerator g) throws AttributeException { + + try { + byte[] certEncoded = authData.getGenericData( + MOAIDAuthConstants.MOASESSION_DATA_HOLDEROFKEY_CERTIFICATE, + byte[].class); + + if (certEncoded != null) { + return g.buildStringAttribute(PVP_HOLDEROFKEY_FRIENDLY_NAME, PVP_HOLDEROFKEY_NAME, + Base64Utils.encode(certEncoded)); + + } + + } + catch (IOException e) { + Logger.info("Encode AuthBlock BASE64 failed."); + } + throw new UnavailableAttributeException(PVP_HOLDEROFKEY_NAME); + + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(PVP_HOLDEROFKEY_NAME, PVP_HOLDEROFKEY_NAME); + } + +} 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 dc0cab8c3..1d2754e3f 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 @@ -274,4 +274,8 @@ public interface PVPConstants { 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_VERSION_OID; + public static final String PVP_HOLDEROFKEY_FRIENDLY_NAME = "HOLDER-OF-KEY-CERTIFICATE"; } -- cgit v1.2.3 From 8e2dd0373e5569da0838865ad09eacf2cd5ff948 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 1 Mar 2016 15:25:28 +0100 Subject: move double dataObject to moa-id-lib --- .../java/at/gv/egovernment/moa/id/data/Pair.java | 45 ++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Pair.java (limited to 'id/server/idserverlib/src/main/java/at') 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 new file mode 100644 index 000000000..0b46345d3 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Pair.java @@ -0,0 +1,45 @@ +/******************************************************************************* + * 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 { + 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 Pair newInstance(final P1 newFirst, final P2 newSecond) { + return new Pair(newFirst, newSecond); + } +} -- cgit v1.2.3 From 48fd33725c53136fe505067b93390b39e19c41b7 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 2 Mar 2016 11:20:36 +0100 Subject: temporarily commit to save state --- .../moa/id/auth/MOAIDAuthConstants.java | 2 + .../id/auth/builder/AuthenticationDataBuilder.java | 274 +++++++++++---------- .../builder/DynamicOAAuthParameterBuilder.java | 2 +- .../id/data/FederatedAuthenticatenContainer.java | 125 ++++++++++ .../moa/id/moduls/AuthenticationManager.java | 3 +- .../at/gv/egovernment/moa/id/moduls/IRequest.java | 10 + .../gv/egovernment/moa/id/moduls/RequestImpl.java | 2 +- .../gv/egovernment/moa/id/moduls/SSOManager.java | 10 +- ...MandateLegalPersonFullNameAttributeBuilder.java | 40 +-- ...andateLegalPersonSourcePinAttributeBuilder.java | 62 ++--- ...teLegalPersonSourcePinTypeAttributeBuilder.java | 56 +++-- .../MandateNaturalPersonBPKAttributeBuilder.java | 82 +++--- ...dateNaturalPersonBirthDateAttributeBuilder.java | 73 ++++-- ...ateNaturalPersonFamilyNameAttributeBuilder.java | 47 ++-- ...dateNaturalPersonGivenNameAttributeBuilder.java | 49 ++-- .../MandateProfRepDescAttributeBuilder.java | 45 ++-- .../MandateProfRepOIDAttributeBuilder.java | 21 +- .../attributes/MandateTypeAttributeBuilder.java | 31 ++- .../id/protocols/pvp2x/AttributQueryAction.java | 33 ++- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 94 ++++++- .../moa/id/protocols/pvp2x/PVPConstants.java | 2 +- .../id/protocols/pvp2x/PVPTargetConfiguration.java | 6 + .../moa/id/protocols/pvp2x/binding/IDecoder.java | 3 +- .../id/protocols/pvp2x/binding/PostBinding.java | 8 +- .../protocols/pvp2x/binding/RedirectBinding.java | 7 +- .../id/protocols/pvp2x/binding/SoapBinding.java | 5 +- .../pvp2x/builder/PVPAttributeBuilder.java | 19 +- .../pvp2x/builder/PVPAuthnRequestBuilder.java | 23 +- .../builder/assertion/PVP2AssertionBuilder.java | 6 +- .../pvp2x/config/IDPPVPMetadataConfiguration.java | 8 + .../IPVPAuthnRequestBuilderConfiguruation.java | 15 ++ .../config/IPVPMetadataBuilderConfiguration.java | 7 + .../pvp2x/metadata/MOAMetadataProvider.java | 113 +-------- .../pvp2x/metadata/SimpleMOAMetadataProvider.java | 135 ++++++++++ .../pvp2x/utils/AssertionAttributeExtractor.java | 14 +- .../pvp2x/verification/TrustEngineFactory.java | 8 +- .../metadata/MOASPMetadataSignatureFilter.java | 130 ++++++++++ .../metadata/SchemaValidationFilter.java | 7 +- .../storage/DBAuthenticationSessionStoreage.java | 53 ++-- .../id/storage/IAuthenticationSessionStoreage.java | 11 +- 40 files changed, 1096 insertions(+), 545 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/FederatedAuthenticatenContainer.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MOASPMetadataSignatureFilter.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index 1a9018563..c7ef73b47 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -184,5 +184,7 @@ public class MOAIDAuthConstants extends MOAIDConstants{ public static final String AUTHPROCESS_DATA_TARGETFRIENDLYNAME = "authProces_TargetFriendlyName"; public static final String AUTHPROCESS_DATA_SECURITYLAYERTEMPLATE = "authProces_SecurityLayerTemplate"; + //General MOASession data-store keys + public static final String MOASESSION_DATA_HOLDEROFKEY_CERTIFICATE = "holderofkey_cert"; } 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 8a9999d85..999f289e0 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 @@ -45,10 +45,6 @@ import javax.xml.bind.Marshaller; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeQuery; import org.opensaml.saml2.core.AuthnStatement; -import org.opensaml.saml2.core.Response; -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 org.w3c.dom.Element; @@ -82,7 +78,6 @@ import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.data.AuthenticationRoleFactory; import at.gv.egovernment.moa.id.data.IAuthData; @@ -91,7 +86,6 @@ import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; 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.AssertionAttributeExtractorExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; @@ -99,7 +93,6 @@ 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.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; @@ -125,140 +118,62 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; @Autowired protected AuthConfiguration authConfig; - @Autowired private AttributQueryBuilder attributQueryBuilder; - @Autowired private SAMLVerificationEngine samlVerificationEngine; - public IAuthData buildAuthenticationData(IRequest protocolRequest, - AuthenticationSession session, List reqAttributes) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { - AuthenticationData authdata = null; + public IAuthData buildAuthenticationDataForAttributQuery(IRequest pendingReq, + AuthenticationSession session, List reqAttributes) { + AuthenticationData authdata = new AuthenticationData(); - //only needed for SAML1 legacy support try { - //check if SAML1 authentication module is in Classpath - Class saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); - IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); - if (saml1RequstTemplate != null && - saml1RequstTemplate.isInstance(protocolRequest)) { - //request is SAML1 --> invoke SAML1 protocol specific methods - if (session.getExtendedSAMLAttributesOA() == null) { - saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, new ArrayList()); - - } else { - saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, session.getExtendedSAMLAttributesOA()); - } + //mark AttributeQuery as used if it exists + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); + if (activeOA != null) { + //reuse some parameters if it is a Service-Provider reauthentication + authdata.setSessionIndex(activeOA.getAssertionSessionID()); + authdata.setNameID(activeOA.getUserNameID()); + authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); - authdata = (AuthenticationData) saml1authdata; - - } else { - authdata = new AuthenticationData(); - - } - - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { - authdata = new AuthenticationData(); - - } - - //reuse some parameters if it is a Service-Provider reauthentication - OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, protocolRequest.getOAURL(), protocolRequest.requestedModule()); - if (activeOA != null) { - authdata.setSessionIndex(activeOA.getAssertionSessionID()); - authdata.setNameID(activeOA.getUserNameID()); - authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); - - //mark AttributeQuery as used - if ( protocolRequest instanceof PVPTargetConfiguration && - ((PVPTargetConfiguration) protocolRequest).getRequest() instanceof MOARequest && - ((PVPTargetConfiguration) protocolRequest).getRequest().getInboundMessage() instanceof AttributeQuery) { - try { - activeOA.setAttributeQueryUsed(true); - MOASessionDBUtils.saveOrUpdate(activeOA); + //mark + if ( pendingReq instanceof PVPTargetConfiguration && + ((PVPTargetConfiguration) pendingReq).getRequest() instanceof MOARequest && + ((PVPTargetConfiguration) pendingReq).getRequest().getInboundMessage() instanceof AttributeQuery) { + try { + activeOA.setAttributeQueryUsed(true); + MOASessionDBUtils.saveOrUpdate(activeOA); - } catch (MOADatabaseException e) { - Logger.error("MOASession interfederation information can not stored to database.", e); + } catch (MOADatabaseException e) { + Logger.error("MOASession interfederation information can not stored to database.", e); - } + } + } } - } - - //search federated IDP information in MOASession - InterfederationSessionStore interfIDP = authenticatedSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); - IOAAuthParameters oaParam = null; - if (reqAttributes == null) { - //get OnlineApplication from MOA-ID-Auth configuration - oaParam = protocolRequest.getOnlineApplicationConfiguration(); - - //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway - if (oaParam.isSTORKPVPGateway()) - oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, protocolRequest); - - } else { - //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) - oaParam = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes, interfIDP); + getAuthDataFromInterfederation(authdata, session, spConfig, pendingReq, interfIDP, idp, reqAttributes); - } - - if (interfIDP != null ) { - //authentication by using a federated IDP - if (oaParam.isInderfederationIDP() && protocolRequest instanceof PVPTargetConfiguration && - !(((PVPTargetConfiguration)protocolRequest).getRequest() instanceof AttributeQuery)) { - //IDP is a chained interfederated IDP and Authentication is requested - - //only set minimal response attributes - authdata.setQAALevel(interfIDP.getQAALevel()); - authdata.setBPK(interfIDP.getUserNameID()); - - } else { - //get attributes from interfederated IDP - OAAuthParameter idp = authConfig.getOnlineApplicationParameter(interfIDP.getIdpurlprefix()); - getAuthDataFromInterfederation(authdata, session, oaParam, protocolRequest, interfIDP, idp, reqAttributes); + + + + + + //mark attribute request as used + try { + interfIDP.setAttributesRequested(true); + MOASessionDBUtils.saveOrUpdate(interfIDP); + + } catch (MOADatabaseException e) { + Logger.error("MOASession interfederation information can not stored to database.", e); - //mark attribute request as used - try { - interfIDP.setAttributesRequested(true); - MOASessionDBUtils.saveOrUpdate(interfIDP); - - } catch (MOADatabaseException e) { - Logger.error("MOASession interfederation information can not stored to database.", e); - - } } - } else { - //build AuthenticationData from MOASession - buildAuthDataFormMOASession(authdata, session, oaParam, protocolRequest); - - } - return authdata; + return authdata; + + } catch (DynamicOABuildException e) { + //TODO: + + } } - /** - * @param req - * @param session - * @param reqAttributes - * @return - * @throws WrongParametersException - * @throws ConfigurationException - * @throws BuildException - * @throws DynamicOABuildException - */ - public IAuthData buildAuthenticationData(IRequest req, - AuthenticationSession session) throws WrongParametersException, ConfigurationException, BuildException, DynamicOABuildException { - return buildAuthenticationData(req, session, null); - } - /** - * @param authdata - * @param session - * @param oaParam - * @param protocolRequest - * @param interfIDP - * @param idp - * @param reqQueryAttr - * @throws ConfigurationException - */ private void getAuthDataFromInterfederation( AuthenticationData authdata, AuthenticationSession session, IOAAuthParameters oaParam, IRequest req, @@ -363,6 +278,76 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } + + public IAuthData buildAuthenticationData(IRequest pendingReq, + AuthenticationSession session) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { + AuthenticationData authdata = null; + + //only needed for SAML1 legacy support + try { + //check if SAML1 authentication module is in Classpath + Class saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); + IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); + if (saml1RequstTemplate != null && + saml1RequstTemplate.isInstance(pendingReq)) { + //request is SAML1 --> invoke SAML1 protocol specific methods + if (session.getExtendedSAMLAttributesOA() == null) { + saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, new ArrayList()); + + } else { + saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, session.getExtendedSAMLAttributesOA()); + } + + authdata = (AuthenticationData) saml1authdata; + + } else { + authdata = new AuthenticationData(); + + } + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { + authdata = new AuthenticationData(); + + } + + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); + //reuse authentication information in case of service-provider reauthentication + if (activeOA != null) { + authdata.setSessionIndex(activeOA.getAssertionSessionID()); + authdata.setNameID(activeOA.getUserNameID()); + authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); + + } + + //get OnlineApplication from MOA-ID-Auth configuration + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + + //TODO: move to eIDAS-Code in case of ISA1.18 action is enabled for eIDAS + //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway + if (oaParam.isSTORKPVPGateway()) + oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, pendingReq); + + //check if minimal response is required + + //TODO check if really required + Boolean isMinimalFrontChannelResp = pendingReq.getGenericData( + PVPTargetConfiguration.DATAID_INTERFEDERATION_MINIMAL_FRONTCHANNEL_RESP, Boolean.class); + if (isMinimalFrontChannelResp != null && isMinimalFrontChannelResp) { + //only set minimal response attributes + authdata.setQAALevel( + pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_QAALEVEL, String.class)); + authdata.setBPK( + pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_NAMEID, String.class)); + + } else { + //build AuthenticationData from MOASession + buildAuthDataFormMOASession(authdata, session, oaParam, pendingReq); + + } + + return authdata; + } + private void buildAuthDataFormInterfederationResponse( AuthenticationData authData, AuthenticationSession session, @@ -982,19 +967,45 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { MISMandate mandate = session.getMISMandate(); - authData.setMISMandate(mandate); - authData.setUseMandate(session.getUseMandate()); + if (session.getUseMandate() && mandate == null) { + Logger.error("Mandate is requested but NO mandate-data is found!."); + throw new BuildException("builder.00", new Object[]{ + "Mandate", "Mandate is requested but NO mandate-data is found!"}); + + } + authData.setMandateReferenceValue(session.getMandateReferenceValue()); + if (mandate != null) { + //set MIS mandate to authdata + authData.setMISMandate(mandate); + authData.setUseMandate(session.getUseMandate()); + + } else { + //check if ELGA mandates exists + String mandateType = session.getGenericDataFromSession( + PVPConstants.MANDATE_TYPE_NAME, String.class); + if (MiscUtil.isNotEmpty(mandateType)) { + //switch to mandate-mode for authdata generation, because mandate-information + // is directly included in MOA-Session as PVP attributes + Logger.debug("AuthDataBuilder find directly included 'MandateType' attribute." + + " --> Switch to mandate-mode for authdata generation."); + authData.setUseMandate(true); + + } + + + } + if (session.getUseMandate() && session.isOW() && mandate != null && MiscUtil.isNotEmpty(mandate.getOWbPK())) { authData.setBPK(mandate.getOWbPK()); authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); - + //TODO: check in case of mandates for business services authData.setIdentityLink(identityLink); Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); - + } else { buildOAspecificbPK(protocolRequest, oaParam, authData, identityLink.getIdentificationValue(), @@ -1004,7 +1015,10 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } - + //TODO + } catch (BuildException e) { + throw e; + } catch (Throwable ex) { throw new BuildException("builder.00", new Object[]{ "AuthenticationData", ex.toString()}, ex); 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 79b09503f..ab43f2f79 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 @@ -45,7 +45,7 @@ import at.gv.egovernment.moa.util.Constants; */ public class DynamicOAAuthParameterBuilder { - public static IOAAuthParameters buildFromAttributeQuery(List reqAttributes, InterfederationSessionStore interfIDP) throws DynamicOABuildException { + public static IOAAuthParameters buildFromAttributeQuery(OAAuthParameter oa, List reqAttributes, InterfederationSessionStore interfIDP) throws DynamicOABuildException { Logger.debug("Build dynamic OAConfiguration from AttributeQuery and interfederation information"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/FederatedAuthenticatenContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/FederatedAuthenticatenContainer.java new file mode 100644 index 000000000..9af247714 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/FederatedAuthenticatenContainer.java @@ -0,0 +1,125 @@ +/* + * 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.util.Random; + +/** + * @author tlenz + * + */ +public class FederatedAuthenticatenContainer implements Serializable { + + /** + * + */ + private static final long serialVersionUID = 6075571915585105988L; + + private String id; + private String moaSessionID; + + private String idpEntityID; + private String userNameID; + private String userQAALevel; + + /** + * Build a new data-container for federated authentication with Attribute-Query + * + */ + public FederatedAuthenticatenContainer() { + this.id = Random.nextRandom(); + + } + + /** + * Get the identifier of this container + * + * @return the identifier of this container, but never null + */ + public String getId() { + return id; + } + + /** + * Get the MOASessionID, of the corresponding MOASession + * + * @return the moaSessionID, or null if no MOASession exists + */ + public String getMoaSessionID() { + return moaSessionID; + } + /** + * @param moaSessionID the moaSessionID to set + */ + public void setMoaSessionID(String moaSessionID) { + this.moaSessionID = moaSessionID; + } + /** + * Get the Entity of the federated IDP, which has the authentication data + * + * @return the idpEntityID, but never null + */ + public String getIdpEntityID() { + return idpEntityID; + } + /** + * @param idpEntityID the idpEntityID to set + */ + public void setIdpEntityID(String idpEntityID) { + this.idpEntityID = idpEntityID; + } + /** + * Get the SAML2 NameID of the user, which is used to identify the user on the federated IDP + * + * @return the SAML2 NameID, but never null + */ + public String getUserNameID() { + return userNameID; + } + /** + * @param userNameID the userNameID to set + */ + public void setUserNameID(String userNameID) { + this.userNameID = userNameID; + } + /** + * Get the SAML2 QAA-level, which should be send to the federated IDP + * + * @return the userQAALevel, but never null + */ + public String getUserQAALevel() { + return userQAALevel; + } + /** + * @param userQAALevel the userQAALevel to set + */ + public void setUserQAALevel(String userQAALevel) { + this.userQAALevel = userQAALevel; + } + + + + +} 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 a97486097..21ef38732 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 @@ -70,6 +70,7 @@ 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.SAMLVerificationEngine; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; @@ -499,7 +500,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { } else { samlVerificationEngine.verifySLOResponse(sloResp, - TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + TrustEngineFactory.getSignatureKnownKeysTrustEngine(MOAMetadataProvider.getInstance())); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java index e1edb6b77..d5d0e6c48 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java @@ -22,6 +22,8 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; +import java.util.Collection; + import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; @@ -189,4 +191,12 @@ public interface IRequest { * @param b true, if the user has abort the authentication process, otherwise false */ public void setAbortedByUser(boolean isAborted); + + /** + * This method get a Set of PVP 2.1 attribute, which are request by this pending-request. + * + * @return A set of PVP attribute names or null if no attributes are requested + * or the Service Provider, which sends this request needs no attributes + */ + public Collection getRequestedAttributes(); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index 4dade61fa..e05bedac8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -48,7 +48,7 @@ public abstract class RequestImpl implements IRequest, Serializable{ public static final String DATAID_INTERFEDERATIOIDP_URL = "interIDPURL"; public static final String DATAID_INTERFEDERATIOIDP_RESPONSE = "interIDPResponse"; - public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; + public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; private static final long serialVersionUID = 1L; 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 3b7c99d5a..db4022cdc 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 @@ -150,12 +150,11 @@ public class SSOManager { return false; } - //check if request starts an interfederated SSO session + //check if stored SSO session is a federated SSO session if (protocolRequest != null && - protocolRequest instanceof RequestImpl && - storedSession.isInterfederatedSSOSession() && - !storedSession.isAuthenticated()) { - + storedSession.isInterfederatedSSOSession()) { + //in case of federated SSO session, jump to federated IDP for authentication + String interfederationIDP = protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); @@ -164,6 +163,7 @@ 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()); 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 7144ebe6d..67eb92d9b 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 @@ -27,12 +27,12 @@ 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.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; public class MandateLegalPersonFullNameAttributeBuilder implements IPVPAttributeBuilder { @@ -43,22 +43,32 @@ public class MandateLegalPersonFullNameAttributeBuilder implements IPVPAttribute public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator 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(); - } - CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); - if (corporation == null) { - Logger.error("No corporation mandate"); - throw new NoMandateDataAttributeException(); - } + //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(); + + } + CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); + if (corporation == null) { + Logger.error("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, - corporation.getFullName()); + fullName); + } 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 12dc8877b..9474cd832 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,14 +26,13 @@ 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.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; public class MandateLegalPersonSourcePinAttributeBuilder implements IPVPAttributeBuilder { @@ -44,36 +43,39 @@ public class MandateLegalPersonSourcePinAttributeBuilder implements IPVPAttribu public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator g) throws AttributeException { if(authData.isUseMandate()) { - Element mandate = authData.getMandate(); - if(mandate == null) { - throw new NoMandateDataAttributeException(); + + //get PVP attribute directly, if exists + String sourcePin = authData.getGenericData(MANDATE_LEG_PER_SOURCE_PIN_NAME, String.class); + + if (MiscUtil.isEmpty(sourcePin)) { + 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.error("No corporation mandate"); + throw new NoMandateDataAttributeException(); + + } + if(corporation.getIdentification().size() == 0) { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAttributeException(); + + } + + sourcePin = corporation.getIdentification().get(0).getValue().getValue(); + } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if(mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); - if(corporation == null) { - Logger.error("No corporation mandate"); - throw new NoMandateDataAttributeException(); - } - IdentificationType id = null; - if(corporation.getIdentification().size() == 0) { - Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAttributeException(); - } - id = corporation.getIdentification().get(0); - /*if(authSession.getBusinessService()) { - id = MandateBuilder.getWBPKIdentification(corporation); - } else { - id = MandateBuilder.getBPKIdentification(corporation); - }*/ - /*if(id == null) { - Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAttributeException(); - }*/ + return g.buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_FRIENDLY_NAME, - MANDATE_LEG_PER_SOURCE_PIN_NAME, id.getValue().getValue()); + MANDATE_LEG_PER_SOURCE_PIN_NAME, sourcePin); } return null; 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 a7a9a757b..8391c8230 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,14 +26,13 @@ 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.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; public class MandateLegalPersonSourcePinTypeAttributeBuilder implements IPVPAttributeBuilder { @@ -44,32 +43,37 @@ public class MandateLegalPersonSourcePinTypeAttributeBuilder implements IPVPAttr public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator g) throws AttributeException { if (authData.isUseMandate()) { - Element mandate = authData.getMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); + //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 = 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.error("No corporate mandate"); + throw new NoMandateDataAttributeException(); + + } + if (corporation.getIdentification().size() == 0) { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAttributeException(); + + } + sourcePinType = corporation.getIdentification().get(0).getType(); + } - Mandate mandateObject = MandateBuilder.buildMandate(mandate); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - CorporateBodyType corporation = mandateObject.getMandator().getCorporateBody(); - if (corporation == null) { - Logger.error("No corporate mandate"); - throw new NoMandateDataAttributeException(); - } - IdentificationType id = null; - if (corporation.getIdentification().size() == 0) { - Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAttributeException(); - } - id = corporation.getIdentification().get(0); - /* - * id = MandateBuilder.getBPKIdentification(corporate); if (id == null) { - * Logger.error("Failed to generate IdentificationType"); throw new - * NoMandateDataAttributeException(); } - */ + return g.buildStringAttribute(MANDATE_LEG_PER_SOURCE_PIN_TYPE_FRIENDLY_NAME, MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME, - id.getType()); + sourcePinType); } 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 be6372913..df077a631 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 @@ -30,13 +30,13 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.PhysicalPers import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; 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; public class MandateNaturalPersonBPKAttributeBuilder implements IPVPAttributeBuilder { @@ -45,49 +45,53 @@ public class MandateNaturalPersonBPKAttributeBuilder implements IPVPAttributeBui } public ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator 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.error("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } - IdentificationType id = null; - id = physicalPerson.getIdentification().get(0); - if (id == null) { - Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAttributeException(); - } + IAttributeGenerator g) throws AttributeException { + if (authData.isUseMandate()) { - String bpk; - try { + //get PVP attribute directly, if exists + 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.error("No physicalPerson mandate"); + throw new NoMandateDataAttributeException(); + } + IdentificationType id = null; + id = physicalPerson.getIdentification().get(0); + if (id == null) { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAttributeException(); + } - if (id.getType().equals(Constants.URN_PREFIX_BASEID)) { - if (oaParam.getBusinessService()) { - bpk = new BPKBuilder().buildWBPK(id.getValue().getValue(), oaParam.getIdentityLinkDomainIdentifier()); + try { + if (id.getType().equals(Constants.URN_PREFIX_BASEID)) { + if (oaParam.getBusinessService()) { + bpk = new BPKBuilder().buildWBPK(id.getValue().getValue(), oaParam.getIdentityLinkDomainIdentifier()); + + } else { + bpk = new BPKBuilder().buildBPK(id.getValue().getValue(), oaParam.getTarget()); + + } - } + } else + bpk = id.getValue().getValue(); - else { - bpk = new BPKBuilder().buildBPK(id.getValue().getValue(), oaParam.getTarget()); - - } + } + catch (BuildException e) { + Logger.error("Failed to generate IdentificationType"); + throw new NoMandateDataAttributeException(); - } else - bpk = id.getValue().getValue(); - - } - catch (BuildException e) { - Logger.error("Failed to generate IdentificationType"); - throw new NoMandateDataAttributeException(); + } } return g.buildStringAttribute(MANDATE_NAT_PER_BPK_FRIENDLY_NAME, MANDATE_NAT_PER_BPK_NAME, bpk); 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 e644f49e4..663e927fc 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 @@ -32,13 +32,13 @@ 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.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.InvalidDateFormatAttributeException; 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; public class MandateNaturalPersonBirthDateAttributeBuilder implements IPVPAttributeBuilder { @@ -49,33 +49,56 @@ public class MandateNaturalPersonBirthDateAttributeBuilder implements IPVPAttrib public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator 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.error("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } - String dateOfBirth = physicalPerson.getDateOfBirth(); - try { - DateFormat mandateFormat = new SimpleDateFormat(MandateBuilder.MANDATE_DATE_OF_BIRTH_FORMAT); - Date date = mandateFormat.parse(dateOfBirth); - DateFormat pvpDateFormat = new SimpleDateFormat(MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN); - String dateString = pvpDateFormat.format(date); + //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.error("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); + + } + catch (ParseException e) { + Logger.warn("MIS mandate birthday has an incorrect formt. (Value:" + dateOfBirth, e); + throw new InvalidDateFormatAttributeException(); + + } + + } else { + try { + DateFormat pvpDateFormat = new SimpleDateFormat(MANDATE_NAT_PER_BIRTHDATE_FORMAT_PATTERN); + pvpDateFormat.setLenient(false); + pvpDateFormat.parse(birthDayString); + + } catch (ParseException e) { + Logger.warn("Format of direct included PVP Attribute " + MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME + + " has an incorrect formt. (Value:" + birthDayString, e); + throw new InvalidDateFormatAttributeException(); + } - return g.buildStringAttribute(MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, MANDATE_NAT_PER_BIRTHDATE_NAME, dateString); - } - catch (ParseException e) { - e.printStackTrace(); - throw new InvalidDateFormatAttributeException(); } + + return g.buildStringAttribute(MANDATE_NAT_PER_BIRTHDATE_FRIENDLY_NAME, MANDATE_NAT_PER_BIRTHDATE_NAME, birthDayString); } return null; 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 fa3ad691d..dd49b2a1e 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 @@ -30,12 +30,12 @@ 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.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; public class MandateNaturalPersonFamilyNameAttributeBuilder implements IPVPAttributeBuilder { @@ -46,29 +46,38 @@ public class MandateNaturalPersonFamilyNameAttributeBuilder implements IPVPAttr public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator 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.error("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } - StringBuilder sb = new StringBuilder(); - Iterator 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()); + 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.error("No physicalPerson mandate"); + throw new NoMandateDataAttributeException(); + } + + StringBuilder sb = new StringBuilder(); + Iterator 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, sb.toString()); + MANDATE_NAT_PER_FAMILY_NAME_NAME, familyName); } 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 4c725c1c5..8948f1227 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 @@ -29,12 +29,12 @@ 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.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; public class MandateNaturalPersonGivenNameAttributeBuilder implements IPVPAttributeBuilder { @@ -44,29 +44,36 @@ public class MandateNaturalPersonGivenNameAttributeBuilder implements IPVPAttrib public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator 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.error("No physicalPerson mandate"); - throw new NoMandateDataAttributeException(); - } - - StringBuilder sb = new StringBuilder(); - Iterator gNamesit = physicalPerson.getName().getGivenName().iterator(); + if (authData.isUseMandate()) { + //get PVP attribute directly, if exists + String givenName = authData.getGenericData(MANDATE_NAT_PER_BPK_NAME, String.class); - while (gNamesit.hasNext()) { - sb.append(" " + gNamesit.next()); + 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.error("No physicalPerson mandate"); + throw new NoMandateDataAttributeException(); + } + + StringBuilder sb = new StringBuilder(); + Iterator 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, sb.toString()); + return g.buildStringAttribute(MANDATE_NAT_PER_GIVEN_NAME_FRIENDLY_NAME, MANDATE_NAT_PER_GIVEN_NAME_NAME, givenName); } 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 e70326114..d1da36aa3 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 @@ -26,7 +26,6 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; @@ -42,35 +41,37 @@ public class MandateProfRepDescAttributeBuilder implements IPVPAttributeBuilder public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator g) throws AttributeException { - if(authData.isUseMandate()) { - String text = null; + if(authData.isUseMandate()) { + String profRepName = authData.getGenericData(MANDATE_PROF_REP_DESC_NAME, String.class); - MISMandate misMandate = authData.getMISMandate(); - - if(misMandate == null) { - throw new NoMandateDataAttributeException(); - } - - text = misMandate.getTextualDescriptionOfOID(); - - if (MiscUtil.isEmpty(text)) { - Element mandate = authData.getMandate(); - if (mandate == null) { + if (MiscUtil.isEmpty(profRepName)) { + MISMandate misMandate = authData.getMISMandate(); + + if(misMandate == null) { throw new NoMandateDataAttributeException(); } - Mandate mandateObject = MandateBuilder.buildMandate(authData.getMandate()); - if (mandateObject == null) { - throw new NoMandateDataAttributeException(); - } - - text = mandateObject.getAnnotation(); + profRepName = misMandate.getTextualDescriptionOfOID(); + + if (MiscUtil.isEmpty(profRepName)) { + Element mandate = authData.getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + } + Mandate mandateObject = MandateBuilder.buildMandate(authData.getMandate()); + if (mandateObject == null) { + throw new NoMandateDataAttributeException(); + } + + profRepName = mandateObject.getAnnotation(); + + } } - if(MiscUtil.isNotEmpty(text)) + if(MiscUtil.isNotEmpty(profRepName)) return g.buildStringAttribute(MANDATE_PROF_REP_DESC_FRIENDLY_NAME, - MANDATE_PROF_REP_DESC_NAME, text); + MANDATE_PROF_REP_DESC_NAME, profRepName); } 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 89e9198b6..3cfc40d22 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 @@ -23,7 +23,6 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; @@ -38,19 +37,23 @@ public class MandateProfRepOIDAttributeBuilder implements IPVPAttributeBuilder { public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator g) throws AttributeException { - if (authData.isUseMandate()) { + if (authData.isUseMandate()) { + String profRepOID = authData.getGenericData(MANDATE_PROF_REP_OID_NAME, String.class); - MISMandate mandate = authData.getMISMandate(); - if (mandate == null) { - throw new NoMandateDataAttributeException(); + if (MiscUtil.isEmpty(profRepOID)) { + MISMandate mandate = authData.getMISMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + } + + profRepOID = mandate.getProfRep(); + } - - String oid = mandate.getProfRep(); - if(MiscUtil.isEmpty(oid)) + if(MiscUtil.isEmpty(profRepOID)) return null; else - return g.buildStringAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, MANDATE_PROF_REP_OID_NAME, oid); + return g.buildStringAttribute(MANDATE_PROF_REP_OID_FRIENDLY_NAME, MANDATE_PROF_REP_OID_NAME, profRepOID); } 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 040174e26..573f0584a 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 @@ -26,11 +26,11 @@ import org.w3c.dom.Element; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; import at.gv.egovernment.moa.id.util.MandateBuilder; +import at.gv.egovernment.moa.util.MiscUtil; public class MandateTypeAttributeBuilder implements IPVPAttributeBuilder { @@ -40,17 +40,26 @@ public class MandateTypeAttributeBuilder implements IPVPAttributeBuilder { public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator 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(); - } + if (authData.isUseMandate()) { + //get PVP attribute directly, if exists + String mandateType = authData.getGenericData(MANDATE_TYPE_NAME, String.class); - return g.buildStringAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME, mandateObject.getAnnotation()); + if (MiscUtil.isEmpty(mandateType)) { + Element mandate = authData.getMandate(); + if (mandate == null) { + throw new NoMandateDataAttributeException(); + + } + 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 null; 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 bd6399377..c733e662a 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 @@ -50,7 +50,6 @@ import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.SoapBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AttributQueryException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; @@ -80,31 +79,29 @@ public class AttributQueryAction implements IAction { * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.data.IAuthData) */ @Override - public SLOInformationInterface processRequest(IRequest req, + public SLOInformationInterface processRequest(IRequest pendingReq, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { - if (req instanceof PVPTargetConfiguration && - ((PVPTargetConfiguration) req).getRequest() instanceof MOARequest && - ((MOARequest)((PVPTargetConfiguration) req).getRequest()).getSamlRequest() instanceof AttributeQuery) { + if (pendingReq instanceof PVPTargetConfiguration && + ((PVPTargetConfiguration) pendingReq).getRequest() instanceof MOARequest && + ((MOARequest)((PVPTargetConfiguration) pendingReq).getRequest()).getSamlRequest() instanceof AttributeQuery) { - AttributeQuery attrQuery = (AttributeQuery)((MOARequest)((PVPTargetConfiguration) req).getRequest()).getSamlRequest(); + //set time reference + DateTime date = new DateTime(); - //load moaSession - String nameID = attrQuery.getSubject().getNameID().getValue(); + //load session and request information + AuthenticationSession moaSession = + pendingReq.getGenericData(PVPTargetConfiguration.DATAID_MOASESSION, AuthenticationSession.class); + + AttributeQuery attrQuery = + (AttributeQuery)((MOARequest)((PVPTargetConfiguration) pendingReq).getRequest()).getSamlRequest(); - AuthenticationSession session = authenticationSessionStorage.getSessionWithUserNameID(nameID); - if (session == null) { - Logger.warn("AttributeQuery nameID does not match to an active single sign-on session."); - throw new AttributQueryException("AttributeQuery nameID does not match to an active single sign-on session.", null); - - } - - DateTime date = new DateTime(); - //generate authData - authData = authDataBuilder.buildAuthenticationData(req, session, attrQuery.getAttributes()); + //generate authData for AttributQueryRequest + authData = authDataBuilder.buildAuthenticationDataForAttributQuery(pendingReq, moaSession, attrQuery.getAttributes()); + //add default attributes in case of mandates or STORK is in use List attrList = addDefaultAttributes(attrQuery, authData); 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 08d9f67b6..57c1aa8af 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java @@ -57,11 +57,15 @@ import org.springframework.web.bind.annotation.RequestMethod; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.builder.DynamicOAAuthParameterBuilder; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; @@ -83,6 +87,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SLOException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; +import at.gv.egovernment.moa.id.protocols.pvp2x.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; @@ -188,7 +193,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); //get POST-Binding decoder implementation - InboundMessage msg = (InboundMessage) new PostBinding().decode(req, resp, false); + InboundMessage msg = (InboundMessage) new PostBinding().decode(req, resp, MOAMetadataProvider.getInstance(), false); pendingReq.setRequest(msg); //preProcess Message @@ -236,7 +241,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { req.getRemoteAddr()); //get POST-Binding decoder implementation - InboundMessage msg = (InboundMessage) new RedirectBinding().decode(req, resp, false); + InboundMessage msg = (InboundMessage) new RedirectBinding().decode(req, resp, MOAMetadataProvider.getInstance(), false); pendingReq.setRequest(msg); //preProcess Message @@ -261,9 +266,57 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { } + //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 }); + + } + + try { + //create pendingRequest object + PVPTargetConfiguration 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 SoapBinding().decode(req, resp, MOAMetadataProvider.getInstance(), false); + 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); + throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); + + } catch (SecurityException e) { + String samlRequest = req.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + + } catch (Throwable e) { + String samlRequest = req.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + + throw new MOAIDException(e.getMessage(), new Object[] {}); + } + } + - public void preProcess(HttpServletRequest request, + private void preProcess(HttpServletRequest request, HttpServletResponse response, PVPTargetConfiguration pendingReq) throws Throwable { InboundMessage msg = pendingReq.getRequest(); @@ -274,7 +327,8 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { } if(!msg.isVerified()) { - samlVerificationEngine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + samlVerificationEngine.verify(msg, + TrustEngineFactory.getSignatureKnownKeysTrustEngine(MOAMetadataProvider.getInstance())); msg.setVerified(true); } @@ -521,7 +575,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12"); - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(moaRequest.getEntityID()); + OAAuthParameter oa = authConfig.getOnlineApplicationParameter(moaRequest.getEntityID()); 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); @@ -533,17 +587,39 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { throw new AttributQueryException("Interfederation IDP does not allow outgoing SSO interfederation.", null); } + + //check active MOASession + String nameID = attrQuery.getSubject().getNameID().getValue(); + AuthenticationSession session = authenticatedSessionStorage.getSessionWithUserNameID(nameID); + if (session == null) { + Logger.warn("AttributeQuery nameID does not match to an active single sign-on session."); + throw new AttributQueryException("AttributeQuery nameID does not match to an active single sign-on session.", null); + } + + //search federated IDP information for this MOASession + + + InterfederationSessionStore interfIDP = + authenticatedSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); + + //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) and configuration + IOAAuthParameters spConfig = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(oa, attrQuery.getAttributes(), interfIDP); + + //set preProcessed information into pending-request pendingReq.setRequest(moaRequest); pendingReq.setOAURL(moaRequest.getEntityID()); - pendingReq.setOnlineApplicationConfiguration(oa); + pendingReq.setOnlineApplicationConfiguration(spConfig); pendingReq.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); - //Attribute-Query Request needs authentication - pendingReq.setNeedAuthentication(true); - + //Attribute-Query Request needs authentication, because session MUST be already authenticated + pendingReq.setNeedAuthentication(false); + //set protocol action, which should be executed after authentication pendingReq.setAction(AttributQueryAction.class.getName()); + + //add moasession + pendingReq.setGenericDataToSession(PVPTargetConfiguration.DATAID_MOASESSION, session); //write revisionslog entry revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_ATTRIBUTQUERY); 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 1d2754e3f..c2b61aaa7 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 @@ -276,6 +276,6 @@ public interface PVPConstants { 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_VERSION_OID; + 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"; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index 27773a248..a8e02c317 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -46,6 +46,12 @@ import at.gv.egovernment.moa.logging.Logger; @Scope(value = BeanDefinition.SCOPE_PROTOTYPE) public class PVPTargetConfiguration extends RequestImpl { + public static final String DATAID_MOASESSION = "moasession"; + 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_ATTRQUERYCONTAINERID = "attrQueryContainerID"; + private static final long serialVersionUID = 4889919265919638188L; InboundMessage request; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java index 6619876dc..86b31f1eb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IDecoder.java @@ -25,6 +25,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.binding; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.ws.message.decoder.MessageDecodingException; import org.opensaml.xml.security.SecurityException; @@ -33,7 +34,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface public interface IDecoder { public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, boolean isSPEndPoint) + HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint) throws MessageDecodingException, SecurityException, PVP2Exception; public boolean handleDecode(String action, HttpServletRequest req); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index ebb4b2991..6d376faa0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -37,6 +37,7 @@ 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; @@ -56,7 +57,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.validation.MOAPVPSignedRequestPolicyRule; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.util.HTTPUtils; @@ -146,7 +146,7 @@ public class PostBinding implements IDecoder, IEncoder { } public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, boolean isSPEndPoint) throws MessageDecodingException, + HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint) throws MessageDecodingException, SecurityException { HTTPPostDecoder decode = new HTTPPostDecoder(new BasicParserPool()); @@ -168,13 +168,13 @@ public class PostBinding implements IDecoder, IEncoder { throw new SecurityException(e); } - messageContext.setMetadataProvider(MOAMetadataProvider.getInstance()); + messageContext.setMetadataProvider(metadataProvider); //set security policy context BasicSecurityPolicy policy = new BasicSecurityPolicy(); policy.getPolicyRules().add( new MOAPVPSignedRequestPolicyRule( - TrustEngineFactory.getSignatureKnownKeysTrustEngine(), + TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider), messageContext.getPeerEntityRole())); SecurityPolicyResolver secResolver = new StaticSecurityPolicyResolver(policy); messageContext.setSecurityPolicyResolver(secResolver); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 0ff18d903..683a72e67 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -38,6 +38,7 @@ 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; @@ -133,7 +134,7 @@ public class RedirectBinding implements IDecoder, IEncoder { } public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, boolean isSPEndPoint) throws MessageDecodingException, + HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint) throws MessageDecodingException, SecurityException { HTTPRedirectDeflateDecoder decode = new HTTPRedirectDeflateDecoder( @@ -159,10 +160,10 @@ public class RedirectBinding implements IDecoder, IEncoder { } - messageContext.setMetadataProvider(MOAMetadataProvider.getInstance()); + messageContext.setMetadataProvider(metadataProvider); SAML2HTTPRedirectDeflateSignatureRule signatureRule = new SAML2HTTPRedirectDeflateSignatureRule( - TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + TrustEngineFactory.getSignatureKnownKeysTrustEngine(metadataProvider)); SAML2AuthnRequestsSignedRule signedRole = new SAML2AuthnRequestsSignedRule(); BasicSecurityPolicy policy = new BasicSecurityPolicy(); policy.getPolicyRules().add(signatureRule); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index cc3553551..12b571ed1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -34,6 +34,7 @@ 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; @@ -63,7 +64,7 @@ public class SoapBinding implements IDecoder, IEncoder { @Autowired private IDPCredentialProvider credentialProvider; public InboundMessageInterface decode(HttpServletRequest req, - HttpServletResponse resp, boolean isSPEndPoint) throws MessageDecodingException, + HttpServletResponse resp, MetadataProvider metadataProvider, boolean isSPEndPoint) throws MessageDecodingException, SecurityException, PVP2Exception { HTTPSOAP11Decoder soapDecoder = new HTTPSOAP11Decoder(new BasicParserPool()); BasicSAMLMessageContext messageContext = @@ -71,7 +72,7 @@ public class SoapBinding implements IDecoder, IEncoder { messageContext .setInboundMessageTransport(new HttpServletRequestAdapter( req)); - messageContext.setMetadataProvider(MOAMetadataProvider.getInstance()); + messageContext.setMetadataProvider(metadataProvider); //TODO: update in a futher version: // requires a special SignedSOAPRequestPolicyRole because diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java index 23ea4d7ee..164583f77 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java @@ -29,24 +29,22 @@ import java.util.List; import java.util.ServiceLoader; import org.opensaml.saml2.core.Attribute; - -import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator; +import org.opensaml.saml2.metadata.RequestedAttribute; import at.gv.egovernment.moa.id.config.auth.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 { @@ -148,4 +146,13 @@ public class PVPAttributeBuilder { 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; + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java index 312bb823d..0a0be2a2c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java @@ -33,9 +33,11 @@ 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.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.SingleSignOnService; import org.opensaml.ws.message.encoder.MessageEncodingException; @@ -51,6 +53,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestBuildExce 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 @@ -98,7 +101,7 @@ public class PVPAuthnRequestBuilder { 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[]{idpEntity.getEntityID()}); + throw new AuthnRequestBuildException("sp.pvp2.00", new Object[]{config.getSPNameForLogging(), idpEntity.getEntityID()}); } else authReq.setDestination(endpoint.getLocation()); @@ -148,7 +151,23 @@ public class PVPAuthnRequestBuilder { 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.getSubjectNameIDFormat())) + subjectNameID.setFormat(config.getSubjectNameIDFormat()); + else + subjectNameID.setFormat(NameID.TRANSIENT); + + reqSubject.setNameID(subjectNameID); + authReq.setSubject(reqSubject ); + + } + //TODO: implement requested attributes //maybe: config.getRequestedAttributes(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index af22a2d7e..03cfe27d7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -284,6 +284,7 @@ public class PVP2AssertionBuilder implements PVPConstants { NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); //build nameID and nameID Format from moasession + //TODO: nameID generation if (authData.isUseMandate()) { Element mandate = authData.getMandate(); if(mandate == null) { @@ -395,7 +396,10 @@ public class PVP2AssertionBuilder implements PVPConstants { subjectNameID.setValue(authData.getNameID()); sessionIndex = authData.getSessionIndex(); - } else + } + + // + if (MiscUtil.isEmpty(sessionIndex)) sessionIndex = SAML2Utils.getSecureIdentifier(); SubjectConfirmationData subjectConfirmationData = SAML2Utils 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 e0994ff19..9a51e75e4 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 @@ -285,4 +285,12 @@ public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfigura return null; } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration#getSPNameForLogging() + */ + @Override + public String getSPNameForLogging() { + return "MOA-ID-Auth"; + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java index d51231044..e209d0bc5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java @@ -32,6 +32,13 @@ import org.opensaml.xml.security.credential.Credential; */ 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 * @@ -110,5 +117,13 @@ public interface IPVPAuthnRequestBuilderConfiguruation { * @return SubjectNameID, or null if no SubjectNameID should be used */ public String getSubjectNameID(); + + /** + * Define the format of the subjectNameID, which is included in authn-request + * + * + * @return nameIDFormat, of SAML2 'transient' if nothing is defined + */ + public String getSubjectNameIDFormat(); } 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 index 52096fd19..56274535b 100644 --- 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 @@ -39,6 +39,13 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableEx 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 * 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 03fa686f9..6e87abb06 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 @@ -31,12 +31,9 @@ import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Timer; -import javax.net.ssl.SSLHandshakeException; import javax.xml.namespace.QName; -import org.apache.commons.httpclient.MOAHttpClient; import org.opensaml.saml2.metadata.EntitiesDescriptor; import org.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.RoleDescriptor; @@ -47,20 +44,13 @@ 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 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.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing; import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -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.id.protocols.pvp2x.verification.metadata.InterfederatedIDPPublicServiceFilter; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.PVPMetadataFilterChain; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.SchemaValidationFilter; @@ -68,7 +58,8 @@ import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; -public class MOAMetadataProvider implements ObservableMetadataProvider, IGarbageCollectorProcessing { +public class MOAMetadataProvider extends SimpleMOAMetadataProvider + implements ObservableMetadataProvider, IGarbageCollectorProcessing { private static MOAMetadataProvider instance = null; private static Object mutex = new Object(); @@ -151,10 +142,9 @@ public class MOAMetadataProvider implements ObservableMetadataProvider, IGarbage String oaFriendlyName = oaParam.getFriendlyName(); ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - HTTPMetadataProvider newMetadataProvider = createNewHTTPMetaDataProvider(metadataURL, - cert, oaFriendlyName, - buildMetadataFilterChain(oaParam, metadataURL, - cert)); + HTTPMetadataProvider newMetadataProvider = createNewHTTPMetaDataProvider(metadataURL, + buildMetadataFilterChain(oaParam, metadataURL, cert), + oaFriendlyName); chainProvider.addMetadataProvider(newMetadataProvider); @@ -264,11 +254,9 @@ public class MOAMetadataProvider implements ObservableMetadataProvider, IGarbage Logger.info("Loading metadata for: " + oaFriendlyName); httpProvider = createNewHTTPMetaDataProvider( - metadataurl, - cert, - oaFriendlyName, - buildMetadataFilterChain(oaParam, metadataurl, - cert)); + metadataurl, + buildMetadataFilterChain(oaParam, metadataurl, cert), + oaFriendlyName); if (httpProvider != null) providersinuse.put(metadataurl, httpProvider); @@ -389,10 +377,8 @@ public class MOAMetadataProvider implements ObservableMetadataProvider, IGarbage if (!providersinuse.containsKey(metadataurl)) { httpProvider = createNewHTTPMetaDataProvider( metadataurl, - cert, - oaFriendlyName, - buildMetadataFilterChain(oaParam, metadataurl, - cert)); + buildMetadataFilterChain(oaParam, metadataurl, cert), + oaFriendlyName); if (httpProvider != null) providersinuse.put(metadataurl, httpProvider); @@ -450,86 +436,7 @@ public class MOAMetadataProvider implements ObservableMetadataProvider, IGarbage return filterChain; } - - private HTTPMetadataProvider createNewHTTPMetaDataProvider(String metadataURL, byte[] certificate, String oaName, PVPMetadataFilterChain filter) { - HTTPMetadataProvider httpProvider = null; - Timer timer= null; - MOAHttpClient httpClient = null; - try { - httpClient = new MOAHttpClient(); - - if (metadataURL.startsWith("https:")) { - try { - MOAHttpProtocolSocketFactory protoSocketFactory = new MOAHttpProtocolSocketFactory( - PVPConstants.SSLSOCKETFACTORYNAME, - AuthConfigurationProviderFactory.getInstance().getCertstoreDirectory(), - AuthConfigurationProviderFactory.getInstance().getTrustedCACertificates(), - null, - AuthConfiguration.DEFAULT_X509_CHAININGMODE, - AuthConfigurationProviderFactory.getInstance().isTrustmanagerrevoationchecking()); - - httpClient.setCustomSSLTrustStore(metadataURL, protoSocketFactory); - - } catch (MOAHttpProtocolSocketFactoryException e) { - Logger.warn("MOA SSL-TrustStore can not initialized. Use default Java TrustStore."); - - } - } - - timer = new Timer(); - httpProvider = new HTTPMetadataProvider(timer, httpClient, - metadataURL); - httpProvider.setParserPool(new BasicParserPool()); - httpProvider.setRequireValidMetadata(true); - httpProvider.setMinRefreshDelay(1000*60*15); //15 minutes - httpProvider.setMaxRefreshDelay(1000*60*60*24); //24 hours - //httpProvider.setRefreshDelayFactor(0.1F); - - if (filter == null) { - filter = new PVPMetadataFilterChain(metadataURL, certificate); - } - 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.error( - "Failed to add Metadata file for " - + oaName + "[ " - + 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; - } - public boolean requireValidMetadata() { return internalProvider.requireValidMetadata(); } 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 new file mode 100644 index 000000000..6d646c609 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java @@ -0,0 +1,135 @@ +/* + * 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.util.Timer; + +import javax.net.ssl.SSLHandshakeException; + +import org.apache.commons.httpclient.MOAHttpClient; +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.BasicParserPool; + +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.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SchemaValidationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SignatureValidationException; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +public abstract class SimpleMOAMetadataProvider implements MetadataProvider{ + + /** + * 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 + * + * @return SAML2 Metadata Provider + */ + protected HTTPMetadataProvider createNewHTTPMetaDataProvider(String metadataURL, MetadataFilter filter, String IdForLogging ) { + HTTPMetadataProvider httpProvider = null; + Timer timer= null; + MOAHttpClient httpClient = null; + try { + httpClient = new MOAHttpClient(); + + if (metadataURL.startsWith("https:")) { + try { + MOAHttpProtocolSocketFactory protoSocketFactory = new MOAHttpProtocolSocketFactory( + PVPConstants.SSLSOCKETFACTORYNAME, + AuthConfigurationProviderFactory.getInstance().getCertstoreDirectory(), + AuthConfigurationProviderFactory.getInstance().getTrustedCACertificates(), + null, + AuthConfiguration.DEFAULT_X509_CHAININGMODE, + AuthConfigurationProviderFactory.getInstance().isTrustmanagerrevoationchecking()); + + httpClient.setCustomSSLTrustStore(metadataURL, protoSocketFactory); + + } catch (MOAHttpProtocolSocketFactoryException e) { + Logger.warn("MOA SSL-TrustStore can not initialized. Use default Java TrustStore."); + + } + } + + timer = new Timer(); + httpProvider = new HTTPMetadataProvider(timer, httpClient, + metadataURL); + httpProvider.setParserPool(new BasicParserPool()); + 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.error( + "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/utils/AssertionAttributeExtractor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java index 9c294245f..8787df82d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java @@ -24,9 +24,11 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.utils; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; 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; @@ -111,7 +113,7 @@ public class AssertionAttributeExtractor { * * @return */ - public boolean containsAllRequiredAttributes(List attributeNameList) { + public boolean containsAllRequiredAttributes(Collection attributeNameList) { //first check if a bPK or an encrypted bPK is available if (attributs.containsKey(PVPConstants.ENC_BPK_LIST_NAME) || @@ -152,6 +154,16 @@ public class AssertionAttributeExtractor { } + /** + * Return all include PVP attribute names + * + * @return + */ + public Set getAllIncludeAttributeNames() { + return attributs.keySet(); + + } + // public PersonalAttributeList getSTORKAttributes() { // return storkAttributes; // } 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 index 67a91f6e1..3ea124db6 100644 --- 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 @@ -25,6 +25,7 @@ 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; @@ -35,8 +36,6 @@ 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 at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; //import edu.internet2.middleware.shibboleth.common.security.MetadataPKIXValidationInformationResolver; public class TrustEngineFactory { @@ -65,11 +64,10 @@ public class TrustEngineFactory { // } // } - public static SignatureTrustEngine getSignatureKnownKeysTrustEngine() { + public static SignatureTrustEngine getSignatureKnownKeysTrustEngine(MetadataProvider provider) { MetadataCredentialResolver resolver; - resolver = new MetadataCredentialResolver( - MOAMetadataProvider.getInstance()); + resolver = new MetadataCredentialResolver(provider); List keyInfoProvider = new ArrayList(); keyInfoProvider.add(new DSAKeyValueProvider()); 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 new file mode 100644 index 000000000..f67c475bb --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MOASPMetadataSignatureFilter.java @@ -0,0 +1,130 @@ +/* + * 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.io.IOException; +import java.io.StringWriter; + +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.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.provider.FilterException; +import org.opensaml.saml2.metadata.provider.MetadataFilter; +import org.opensaml.xml.XMLObject; + +import at.gv.egovernment.moa.id.auth.builder.SignatureVerificationUtils; +import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +public class MOASPMetadataSignatureFilter implements MetadataFilter { + + private String trustProfileID = null; + + /** + * + */ + public MOASPMetadataSignatureFilter(String trustProfileID) { + this.trustProfileID = trustProfileID; + + } + + + /* (non-Javadoc) + * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) + */ + @Override + public void doFilter(XMLObject metadata) throws FilterException { + if (metadata instanceof EntityDescriptor) { + if (((EntityDescriptor) metadata).isSigned()) { + EntityDescriptor entityDes = (EntityDescriptor) metadata; + //check signature; + try { + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); + StringWriter sw = new StringWriter(); + StreamResult sr = new StreamResult(sw); + DOMSource source = new DOMSource(metadata.getDOM()); + transformer.transform(source, sr); + sw.close(); + String metadataXML = sw.toString(); + + SignatureVerificationUtils sigVerify = + new SignatureVerificationUtils(); + VerifyXMLSignatureResponse result = sigVerify.verify( + metadataXML.getBytes(), trustProfileID); + + //check signature-verification result + if (result.getSignatureCheckCode() != 0) { + Logger.warn("Metadata signature-verification FAILED!" + + " Metadata: " + entityDes.getEntityID() + + " StatusCode:" + result.getSignatureCheckCode()); + throw new FilterException("Metadata signature-verification FAILED!" + + " Metadata: " + entityDes.getEntityID() + + " StatusCode:" + result.getSignatureCheckCode()); + + } + + if (result.getCertificateCheckCode() != 0) { + Logger.warn("Metadata certificate-verification FAILED!" + + " Metadata: " + entityDes.getEntityID() + + " StatusCode:" + result.getCertificateCheckCode()); + throw new FilterException("Metadata certificate-verification FAILED!" + + " Metadata: " + entityDes.getEntityID() + + " StatusCode:" + result.getCertificateCheckCode()); + + } + + + } catch (MOAIDException | TransformerFactoryConfigurationError | TransformerException | IOException e) { + Logger.error("Metadata verification has an interal error.", e); + throw new FilterException("Metadata verification has an interal error." + + " Message:" + e.getMessage()); + + } + + + } else { + Logger.warn("Metadata root-element MUST be signed."); + throw new FilterException("Metadata root-element MUST be signed.'"); + + } + + } else { + Logger.warn("Metadata root-element is not of type 'EntityDescriptor'"); + throw new FilterException("Metadata root-element is not of type 'EntityDescriptor'"); + + } + + } + +} 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 index 1aca587c9..69fe0ee6a 100644 --- 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 @@ -22,16 +22,13 @@ */ package at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata; -import org.opensaml.saml2.metadata.provider.FilterException; -import org.opensaml.saml2.metadata.provider.MetadataFilter; -import org.opensaml.xml.XMLObject; - 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.config.ConfigurationException; 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 cfdb4426b..c190ad779 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java @@ -53,9 +53,8 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.EncryptedData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; 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; @@ -95,9 +94,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt Date now = new Date(); dbsession.setCreated(now); dbsession.setUpdated(now); - - dbsession.setPendingRequestID(target.getRequestID()); - + //set additional session informations AuthenticationSessionExtensions sessionExt = new AuthenticationSessionExtensions(); sessionExt.setUniqueSessionId(target.getUniqueSessionIdentifier()); @@ -443,6 +440,10 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } + //set additional information for AttributeQuery + activeOA.setAttQueryContainerID(protocolRequest.getGenericData( + PVPTargetConfiguration.DATAID_INTERFEDERATION_ATTRQUERYCONTAINERID, String.class)); + List activeOAs = dbsession.getActiveOAsessions(); activeOAs.add(activeOA); dbsession.setActiveOAsessions(activeOAs); @@ -461,7 +462,6 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt dbsession.setSSOSession(true); dbsession.setSSOsessionid(SSOSessionID); dbsession.setAuthenticated(false); - dbsession.setPendingRequestID("empty"); //Store MOASession session.saveOrUpdate(dbsession); @@ -751,7 +751,8 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } } - public void createInterfederatedSession(IRequest req, boolean isAuthenticated) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException { + @Override + public void addFederatedSessionInformation(IRequest req, String idpEntityID, AssertionAttributeExtractor extractor) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException { AuthenticatedSessionStore dbsession = null; Date now = new Date(); @@ -766,23 +767,27 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt throw e; } } + + dbsession.setUpdated(now); + //decrypt MOASession AuthenticationSession session = decryptSession(dbsession); - //set Session parameters - session.setAuthenticated(isAuthenticated); - dbsession.setAuthenticated(isAuthenticated); - dbsession.setInterfederatedSSOSession(true); - dbsession.setUpdated(now); - + //federated Session are never authenticated locally, + // because they get always authentication information from federated IDP + session.setAuthenticated(false); + dbsession.setAuthenticated(false); + + //encrypt MOASession encryptSession(session, dbsession); + + //mark as federated SSO session + dbsession.setInterfederatedSSOSession(true); //add interfederation information List idpList = dbsession.getInderfederation(); - - MOAResponse interfederationResp = req.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, MOAResponse.class); - String interFedEntityID = interfederationResp.getEntityID(); - + + //check if federated IDP is already stored InterfederationSessionStore idp = null; if (idpList == null) { idpList = new ArrayList(); @@ -791,7 +796,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } else { for (InterfederationSessionStore el : idpList) { //resue old entry if interfederation IDP is reused for authentication - if (el.getIdpurlprefix().equals(interFedEntityID)) + if (el.getIdpurlprefix().equals(idpEntityID)) idp = el; } @@ -801,7 +806,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt if (idp == null) { idp = new InterfederationSessionStore(); idp.setCreated(now); - idp.setIdpurlprefix(interFedEntityID); + idp.setIdpurlprefix(idpEntityID); idp.setAuthURL(req.getAuthURL()); OAAuthParameter oa = authConfig.getOnlineApplicationParameter(idp.getIdpurlprefix()); @@ -809,12 +814,11 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt idp.setMoasession(dbsession); idpList.add(idp); - } - AssertionAttributeExtractor extract = new AssertionAttributeExtractor(interfederationResp.getResponse()); - idp.setSessionIndex(extract.getSessionIndex()); - idp.setUserNameID(extract.getNameID()); + } + idp.setSessionIndex(extractor.getSessionIndex()); + idp.setUserNameID(extractor.getNameID()); idp.setAttributesRequested(false); - idp.setQAALevel(extract.getQAALevel()); + idp.setQAALevel(extractor.getQAALevel()); //store AssertionStore element to Database try { @@ -1024,4 +1028,5 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt throw 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 2fd540a67..aaa54fbb9 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 @@ -36,6 +36,7 @@ import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; /** * @author tlenz @@ -238,16 +239,16 @@ public interface IAuthenticationSessionStoreage { /** - * Create a MOASession from interfederation information + * Add information of the federated IDP to MOASession * - * @param req Pending request - * @param isAuthenticated true if the session should be marked as authenticated, otherwise false + * @param req Pending request of the service-provider request, never null + * @param idpEntityID The SAML2 EntityID of the federated IDP, never null + * @param extractor AssertionAttributeExtractor which holds the SAML2 response of the federated IDP, never null * @throws MOADatabaseException * @throws AssertionAttributeExtractorExeption * @throws BuildException */ - @Deprecated - public void createInterfederatedSession(IRequest req, boolean isAuthenticated) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException; + public void addFederatedSessionInformation(IRequest req, String idpEntityID, AssertionAttributeExtractor extractor) throws MOADatabaseException, AssertionAttributeExtractorExeption, BuildException; /** * Search an active federation IDP which could be used for federated Single Sign-On by using an AttributeQuery -- cgit v1.2.3 From da937437e46e06365072820aa555d4cb3f9f9110 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 2 Mar 2016 22:10:36 +0100 Subject: next parts of new federated authentication implementation --- .../id/auth/builder/AuthenticationDataBuilder.java | 226 ++++++++++++--------- .../builder/DynamicOAAuthParameterBuilder.java | 71 ++----- .../id/data/FederatedAuthenticatenContainer.java | 125 ------------ .../id/protocols/pvp2x/AttributQueryAction.java | 30 ++- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 17 +- .../id/protocols/pvp2x/PVPTargetConfiguration.java | 2 - .../storage/DBAuthenticationSessionStoreage.java | 8 +- .../id/storage/IAuthenticationSessionStoreage.java | 4 +- 8 files changed, 178 insertions(+), 305 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/FederatedAuthenticatenContainer.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationDataBuilder.java index 999f289e0..8b9918eab 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 @@ -32,6 +32,7 @@ import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.List; +import java.util.Set; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -45,6 +46,9 @@ import javax.xml.bind.Marshaller; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.core.AttributeQuery; import org.opensaml.saml2.core.AuthnStatement; +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.Element; @@ -77,7 +81,9 @@ import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.data.AuthenticationRoleFactory; import at.gv.egovernment.moa.id.data.IAuthData; @@ -86,13 +92,16 @@ import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; 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.AssertionAttributeExtractorExeption; 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.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.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; @@ -118,9 +127,11 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { @Autowired private IAuthenticationSessionStoreage authenticatedSessionStorage; @Autowired protected AuthConfiguration authConfig; + @Autowired private AttributQueryBuilder attributQueryBuilder; + @Autowired private SAMLVerificationEngine samlVerificationEngine; public IAuthData buildAuthenticationDataForAttributQuery(IRequest pendingReq, - AuthenticationSession session, List reqAttributes) { + AuthenticationSession session, List reqAttributes, InterfederationSessionStore nextIDPInformation) throws MOAIDException { AuthenticationData authdata = new AuthenticationData(); try { @@ -146,134 +157,147 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } } - - getAuthDataFromInterfederation(authdata, session, spConfig, pendingReq, interfIDP, idp, reqAttributes); - - - - + //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) and configuration + IOAAuthParameters spConfig = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes); - //mark attribute request as used - try { - interfIDP.setAttributesRequested(true); - MOASessionDBUtils.saveOrUpdate(interfIDP); - - } catch (MOADatabaseException e) { - Logger.error("MOASession interfederation information can not stored to database.", e); + //search federated IDP information for this MOASession + if (nextIDPInformation != null) { + Logger.info("Find active federated IDP information." + + ". --> Request next IDP:" + nextIDPInformation.getIdpurlprefix() + + " for authentication information."); + + //load configuration of next IDP + OAAuthParameter idp = authConfig.getOnlineApplicationParameter(nextIDPInformation.getIdpurlprefix()); + if (idp == null) { + Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() + + "is not loadable."); + throw new MOAIDException("auth.32", new Object[]{nextIDPInformation.getIdpurlprefix()}); + + } + + //check if next IDP config allows inbound messages + if (!idp.isInboundSSOInterfederationAllowed()) { + Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() + + "disallow inbound authentication messages."); + throw new MOAIDException("auth.33", new Object[]{nextIDPInformation.getIdpurlprefix()}); + + } + + //check next IDP service area policy. BusinessService IDPs can only request wbPKs + if (!spConfig.getBusinessService() && !idp.isIDPPublicService()) { + Logger.error("Interfederated IDP " + idp.getPublicURLPrefix() + + " has a BusinessService-IDP but requests PublicService attributes."); + throw new MOAIDException("auth.34", new Object[]{nextIDPInformation.getIdpurlprefix()}); + + } + + //validation complete --> start AttributeQuery Request + getAuthDataFromInterfederation(authdata, reqAttributes, nextIDPInformation, idp); + + } else { + Logger.debug("Build authData for AttributQuery from local MOASession."); + buildAuthDataFormMOASession(authdata, session, spConfig, pendingReq); } - - + return authdata; - - } catch (DynamicOABuildException e) { - //TODO: - + + } catch (MOAIDException e) { + throw e; } } private void getAuthDataFromInterfederation( - AuthenticationData authdata, AuthenticationSession session, - IOAAuthParameters oaParam, IRequest req, - InterfederationSessionStore interfIDP, OAAuthParameter idp, List reqQueryAttr) throws BuildException, ConfigurationException{ + AuthenticationData authdata, List reqQueryAttr, + InterfederationSessionStore nextIDPInfo, OAAuthParameter nextIDPConfig ) throws MOAIDException{ + String idpEnityID = nextIDPConfig.getPublicURLPrefix(); + AssertionAttributeExtractor extractor; try { - List attributs = null; - - //IDP is a chained interfederated IDP and request is of type AttributQuery - if (oaParam.isInderfederationIDP() && req instanceof PVPTargetConfiguration && - (((PVPTargetConfiguration)req).getRequest() instanceof AttributeQuery) && - reqQueryAttr != null) { - attributs = reqQueryAttr; - - //IDP is a service provider IDP and request interfederated IDP to collect attributes - } else { - //get PVP 2.1 attributes from protocol specific requested attributes - attributs = (List) req.getGenericData(RequestImpl.DATAID_REQUESTED_ATTRIBUTES); + Logger.debug("Starting AttributeQuery process ..."); + //collect attributes by using BackChannel communication + String endpoint = nextIDPConfig.getIDPAttributQueryServiceURL(); + if (MiscUtil.isEmpty(endpoint)) { + Logger.error("No AttributeQueryURL for interfederationIDP " + idpEnityID); + throw new ConfigurationException("config.26", new Object[]{idpEnityID}); } - - //get SAML2 Response from federated IDP - Response intfResp = - (Response) req.getGenericData( - RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, MOAResponse.class).getResponse(); - - //initialize Attribute extractor - AssertionAttributeExtractor extractor = new AssertionAttributeExtractor(intfResp); - - //check if SAML2 Assertion contains already all required attributes - if (!extractor.containsAllRequiredAttributes()) { - Logger.info("Received assertion does no contain a minimum set of attributes. Starting AttributeQuery process ..."); - //collect attributes by using BackChannel communication - String endpoint = idp.getIDPAttributQueryServiceURL(); - if (MiscUtil.isEmpty(endpoint)) { - Logger.error("No AttributeQueryURL for interfederationIDP " + idp.getPublicURLPrefix()); - throw new ConfigurationException("No AttributeQueryURL for interfederationIDP " + idp.getPublicURLPrefix(), null); - } - //build attributQuery request - AttributeQuery query = - attributQueryBuilder.buildAttributQueryRequest(interfIDP.getUserNameID(), endpoint, attributs); + //build attributQuery request + AttributeQuery query = attributQueryBuilder.buildAttributQueryRequest(nextIDPInfo.getUserNameID(), endpoint, reqQueryAttr); - //build SOAP request - List xmlObjects = MOASAMLSOAPClient.send(endpoint, query); + //build SOAP request + List 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."}); - if (xmlObjects.size() == 0) { - Logger.error("Receive emptry AttributeQuery response-body."); - throw new AttributQueryException("Receive emptry AttributeQuery response-body.", null); - - } + } + + Response intfResp; + if (xmlObjects.get(0) instanceof Response) { + intfResp = (Response) xmlObjects.get(0); - if (xmlObjects.get(0) instanceof Response) { - intfResp = (Response) xmlObjects.get(0); - - //validate PVP 2.1 response - try { - samlVerificationEngine.verifyIDPResponse(intfResp, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); - - //TODO: find better solution - //SAMLVerificationEngine.validateAssertion(intfResp, false); - - } catch (Exception e) { - Logger.warn("PVP 2.1 assertion validation FAILED.", e); - throw new AssertionValidationExeption("PVP 2.1 assertion validation FAILED.", null, e); + //validate PVP 2.1 response + try { + samlVerificationEngine.verifyIDPResponse(intfResp, + TrustEngineFactory.getSignatureKnownKeysTrustEngine( + MOAMetadataProvider.getInstance())); + + //create assertion attribute extractor from AttributeQuery response + extractor = new AssertionAttributeExtractor(intfResp); + + //copy attributes into authData object + Set includedAttrNames = extractor.getAllIncludeAttributeNames(); + for (String el : includedAttrNames) { + authdata.setGenericData(el, extractor.getSingleAttributeValue(el)); + Logger.debug("Add PVP-attribute " + el + " into authData objext"); + } - - } else { - Logger.error("Receive AttributeQuery response-body include no PVP 2.1 response"); - throw new AttributQueryException("Receive AttributeQuery response-body include no PVP 2.1 response.", null); - + + + } catch (Exception e) { + Logger.warn("PVP 2.1 assertion validation FAILED.", e); + throw new AssertionValidationExeption("auth.27", + new Object[]{idpEnityID, e.getMessage()}, e); } - - //create assertion attribute extractor from AttributeQuery response - extractor = new AssertionAttributeExtractor(intfResp); - + } else { - Logger.info("Interfedation response include all attributes with are required. Skip AttributQuery request step. "); + 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"}); + + } + + try { + //mark attribute request as used + if (nextIDPInfo.isStoreSSOInformation()) { + nextIDPInfo.setAttributesRequested(true); + MOASessionDBUtils.saveOrUpdate(nextIDPInfo); + + //delete federated IDP from Session + } else { + MOASessionDBUtils.delete(nextIDPInfo); + + } + + } catch (MOADatabaseException e) { + Logger.error("MOASession interfederation information can not stored to database.", e); } - //parse response information to authData - buildAuthDataFormInterfederationResponse(authdata, session, extractor, oaParam, req); - + } catch (SOAPException e) { throw new BuildException("builder.06", null, e); } catch (SecurityException e) { throw new BuildException("builder.06", null, e); - - } catch (AttributQueryException e) { - throw new BuildException("builder.06", null, e); - - } catch (BuildException e) { - throw new BuildException("builder.06", null, e); - - } catch (AssertionValidationExeption e) { - throw new BuildException("builder.06", null, e); - - } catch (AssertionAttributeExtractorExeption e) { - throw new BuildException("builder.06", null, e); + + } catch (org.opensaml.xml.security.SecurityException e1) { + throw new BuildException("builder.06", null, e1); } } 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 ab43f2f79..8c0de1121 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 @@ -38,6 +38,7 @@ import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; +import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -45,65 +46,35 @@ import at.gv.egovernment.moa.util.Constants; */ public class DynamicOAAuthParameterBuilder { - public static IOAAuthParameters buildFromAttributeQuery(OAAuthParameter oa, List reqAttributes, InterfederationSessionStore interfIDP) throws DynamicOABuildException { + public static IOAAuthParameters buildFromAttributeQuery(List reqAttributes) throws DynamicOABuildException { Logger.debug("Build dynamic OAConfiguration from AttributeQuery and interfederation information"); - try { - DynamicOAAuthParameters dynamicOA = new DynamicOAAuthParameters(); - - for (Attribute attr : reqAttributes) { - //get Target or BusinessService from request - if (attr.getName().equals(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME)) { - String attrValue = attr.getAttributeValues().get(0).getDOM().getTextContent(); - if (attrValue.startsWith(Constants.URN_PREFIX_CDID)) { - dynamicOA.setBusinessService(false); - dynamicOA.setTarget(attrValue.substring((Constants.URN_PREFIX_CDID + "+").length())); - - } else if( attrValue.startsWith(Constants.URN_PREFIX_WBPK) || - attrValue.startsWith(Constants.URN_PREFIX_STORK) ) { - dynamicOA.setBusinessService(true); - dynamicOA.setTarget(attrValue); - - } else { - Logger.error("Sector identification " + attrValue + " is not a valid Target or BusinessServiceArea"); - throw new DynamicOABuildException("Sector identification " + attrValue + " is not a valid Target or BusinessServiceArea", null); - - } - - } + DynamicOAAuthParameters dynamicOA = new DynamicOAAuthParameters(); - } - - if (interfIDP != null) { - //load interfederated IDP informations - OAAuthParameter idp = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(interfIDP.getIdpurlprefix()); - if (idp == null) { - Logger.warn("Interfederated IDP configuration is not loadable."); - throw new DynamicOABuildException("Interfederated IDP configuration is not loadable.", null); + for (Attribute attr : reqAttributes) { + //get Target or BusinessService from request + if (attr.getName().equals(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME)) { + String attrValue = attr.getAttributeValues().get(0).getDOM().getTextContent(); + if (attrValue.startsWith(Constants.URN_PREFIX_CDID)) { + dynamicOA.setBusinessService(false); + dynamicOA.setTarget(attrValue.substring((Constants.URN_PREFIX_CDID + "+").length())); + + } else if( attrValue.startsWith(Constants.URN_PREFIX_WBPK) || + attrValue.startsWith(Constants.URN_PREFIX_STORK) ) { + dynamicOA.setBusinessService(true); + dynamicOA.setTarget(attrValue); + + } else { + Logger.error("Sector identification " + attrValue + " is not a valid Target or BusinessServiceArea"); + throw new DynamicOABuildException("Sector identification " + attrValue + " is not a valid Target or BusinessServiceArea", null); } - - dynamicOA.setApplicationID(idp.getPublicURLPrefix()); - dynamicOA.setInderfederatedIDP(idp.isInderfederationIDP()); - dynamicOA.setIDPQueryURL(idp.getIDPAttributQueryServiceURL()); - //check if IDP service area policy. BusinessService IDPs can only request wbPKs - if (!dynamicOA.getBusinessService() && !idp.isIDPPublicService()) { - Logger.error("Interfederated IDP " + idp.getPublicURLPrefix() - + " has a BusinessService-IDP but requests PublicService attributes."); - throw new DynamicOABuildException("Interfederated IDP " + idp.getPublicURLPrefix() - + " has a BusinessService-IDP but requests PublicService attributes.", null); - - } } - return dynamicOA; - - } catch (ConfigurationException e) { - Logger.warn("Internel server errror. Basic configuration load failed.", e); - throw new DynamicOABuildException("Basic configuration load failed.", null); - } + } + return dynamicOA; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/FederatedAuthenticatenContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/FederatedAuthenticatenContainer.java deleted file mode 100644 index 9af247714..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/FederatedAuthenticatenContainer.java +++ /dev/null @@ -1,125 +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.util.Random; - -/** - * @author tlenz - * - */ -public class FederatedAuthenticatenContainer implements Serializable { - - /** - * - */ - private static final long serialVersionUID = 6075571915585105988L; - - private String id; - private String moaSessionID; - - private String idpEntityID; - private String userNameID; - private String userQAALevel; - - /** - * Build a new data-container for federated authentication with Attribute-Query - * - */ - public FederatedAuthenticatenContainer() { - this.id = Random.nextRandom(); - - } - - /** - * Get the identifier of this container - * - * @return the identifier of this container, but never null - */ - public String getId() { - return id; - } - - /** - * Get the MOASessionID, of the corresponding MOASession - * - * @return the moaSessionID, or null if no MOASession exists - */ - public String getMoaSessionID() { - return moaSessionID; - } - /** - * @param moaSessionID the moaSessionID to set - */ - public void setMoaSessionID(String moaSessionID) { - this.moaSessionID = moaSessionID; - } - /** - * Get the Entity of the federated IDP, which has the authentication data - * - * @return the idpEntityID, but never null - */ - public String getIdpEntityID() { - return idpEntityID; - } - /** - * @param idpEntityID the idpEntityID to set - */ - public void setIdpEntityID(String idpEntityID) { - this.idpEntityID = idpEntityID; - } - /** - * Get the SAML2 NameID of the user, which is used to identify the user on the federated IDP - * - * @return the SAML2 NameID, but never null - */ - public String getUserNameID() { - return userNameID; - } - /** - * @param userNameID the userNameID to set - */ - public void setUserNameID(String userNameID) { - this.userNameID = userNameID; - } - /** - * Get the SAML2 QAA-level, which should be send to the federated IDP - * - * @return the userQAALevel, but never null - */ - public String getUserQAALevel() { - return userQAALevel; - } - /** - * @param userQAALevel the userQAALevel to set - */ - public void setUserQAALevel(String userQAALevel) { - this.userQAALevel = userQAALevel; - } - - - - -} 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 c733e662a..042eeeed8 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 @@ -41,8 +41,13 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; +import at.gv.egovernment.moa.id.auth.builder.DynamicOAAuthParameterBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; +import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.data.FederatedAuthenticatenContainer; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IAction; @@ -53,7 +58,9 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionB import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -62,9 +69,10 @@ import at.gv.egovernment.moa.logging.Logger; @Service("AttributQueryAction") public class AttributQueryAction implements IAction { - @Autowired IAuthenticationSessionStoreage authenticationSessionStorage; + @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; @Autowired private AuthenticationDataBuilder authDataBuilder; @Autowired private IDPCredentialProvider pvpCredentials; + @Autowired private ITransactionStorage transactionStorage; private final static List DEFAULTSTORKATTRIBUTES = Arrays.asList( new String[]{PVPConstants.EID_STORK_TOKEN_NAME}); @@ -90,16 +98,22 @@ public class AttributQueryAction implements IAction { //set time reference DateTime date = new DateTime(); - //load session and request information - AuthenticationSession moaSession = - pendingReq.getGenericData(PVPTargetConfiguration.DATAID_MOASESSION, AuthenticationSession.class); - + //get Single Sign-On information for the Service-Provider + // which sends the Attribute-Query request + AuthenticationSession moaSession = authenticationSessionStorage.getSession(pendingReq.getMOASessionIdentifier()); + if (moaSession == null) { + Logger.warn("No MOASession with ID:" + pendingReq.getMOASessionIdentifier() + " FOUND."); + throw new MOAIDException("auth.02", new Object[]{pendingReq.getMOASessionIdentifier()}); + } + + InterfederationSessionStore nextIDPInformation = + authenticationSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(moaSession.getSessionID()); + AttributeQuery attrQuery = (AttributeQuery)((MOARequest)((PVPTargetConfiguration) pendingReq).getRequest()).getSamlRequest(); - - + //generate authData for AttributQueryRequest - authData = authDataBuilder.buildAuthenticationDataForAttributQuery(pendingReq, moaSession, attrQuery.getAttributes()); + authData = authDataBuilder.buildAuthenticationDataForAttributQuery(pendingReq, moaSession, attrQuery.getAttributes(), nextIDPInformation); //add default attributes in case of mandates or STORK is in use 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 57c1aa8af..4dbc35041 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 @@ -593,23 +593,14 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { AuthenticationSession session = authenticatedSessionStorage.getSessionWithUserNameID(nameID); if (session == null) { Logger.warn("AttributeQuery nameID does not match to an active single sign-on session."); - throw new AttributQueryException("AttributeQuery nameID does not match to an active single sign-on session.", null); + throw new AttributQueryException("auth.31", null); } - //search federated IDP information for this MOASession - - - InterfederationSessionStore interfIDP = - authenticatedSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(session); - - //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) and configuration - IOAAuthParameters spConfig = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(oa, attrQuery.getAttributes(), interfIDP); - //set preProcessed information into pending-request pendingReq.setRequest(moaRequest); pendingReq.setOAURL(moaRequest.getEntityID()); - pendingReq.setOnlineApplicationConfiguration(spConfig); + pendingReq.setOnlineApplicationConfiguration(oa); pendingReq.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI); //Attribute-Query Request needs authentication, because session MUST be already authenticated @@ -619,8 +610,8 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { pendingReq.setAction(AttributQueryAction.class.getName()); //add moasession - pendingReq.setGenericDataToSession(PVPTargetConfiguration.DATAID_MOASESSION, session); - + pendingReq.setMOASessionIdentifier(session.getSessionID()); + //write revisionslog entry revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_ATTRIBUTQUERY); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index a8e02c317..b8ced1198 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -46,11 +46,9 @@ import at.gv.egovernment.moa.logging.Logger; @Scope(value = BeanDefinition.SCOPE_PROTOTYPE) public class PVPTargetConfiguration extends RequestImpl { - public static final String DATAID_MOASESSION = "moasession"; 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_ATTRQUERYCONTAINERID = "attrQueryContainerID"; private static final long serialVersionUID = 4889919265919638188L; 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 c190ad779..316ca2177 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 @@ -832,9 +832,9 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } @Override - public InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(AuthenticationSession moaSession) { - MiscUtil.assertNotNull(moaSession, "MOASession"); - Logger.trace("Get interfederated IDP for AttributeQuery with sessionID " + moaSession.getSessionID() + " from database."); + public InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(String moaSessionID) { + MiscUtil.assertNotNull(moaSessionID, "MOASessionID"); + Logger.trace("Get interfederated IDP for AttributeQuery with sessionID " + moaSessionID + " from database."); Session session = MOASessionDBUtils.getCurrentSession(); List result; @@ -843,7 +843,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt synchronized (session) { tx = session.beginTransaction(); Query query = session.getNamedQuery("getInterfederatedIDPForAttributeQueryWithSessionID"); - query.setParameter("sessionID", moaSession.getSessionID()); + query.setParameter("sessionID", moaSessionID); result = query.list(); //send transaction 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 aaa54fbb9..666511425 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 @@ -253,10 +253,10 @@ public interface IAuthenticationSessionStoreage { /** * Search an active federation IDP which could be used for federated Single Sign-On by using an AttributeQuery * - * @param moaSession MOASession data object + * @param moaSessionID ID of a active MOASession * @return Information of the federated IDP, or null if no active federated IDP is found */ - public InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(AuthenticationSession moaSession); + public InterfederationSessionStore searchInterfederatedIDPFORAttributeQueryWithSessionID(String moaSessionID); /** * Remove an active federation IDP from MOASession -- cgit v1.2.3 From d6a3569addaf5a7db27dd3e79a4ba4bcd27c2486 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 8 Mar 2016 10:55:47 +0100 Subject: update mandate ReferenceValue generator. This was necessary to get a referencevalue, which is MIS conform and which could used as SAML2 RequestID --- .../moa/id/auth/data/AuthenticationSession.java | 22 ++--- .../java/at/gv/egovernment/moa/id/util/Random.java | 95 ++++++++++++++++++---- 2 files changed, 93 insertions(+), 24 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 196415ddc..7873fb96d 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 @@ -86,7 +86,7 @@ public class AuthenticationSession implements Serializable { /** * Use mandate */ - private boolean useMandate; + private boolean useMandates; private boolean isOW = false; @@ -371,19 +371,22 @@ public class AuthenticationSession implements Serializable { */ public void setUseMandate(String useMandate) { if (useMandate.compareToIgnoreCase("true") == 0) - this.useMandate = true; + this.useMandates = true; else - this.useMandate = false; + this.useMandates = false; + + } + + public void setUseMandates(boolean useMandates) { + this.useMandates = useMandates; } /** - * Returns if mandate is used or not - * * @return */ - public boolean getUseMandate() { - return this.useMandate; + public boolean isMandateUsed() { + return this.useMandates; } /** @@ -502,6 +505,7 @@ public class AuthenticationSession implements Serializable { return genericSessionDataStorate; } + /** * Returns a generic session-data object with is stored with a specific identifier * @@ -579,7 +583,5 @@ public class AuthenticationSession implements Serializable { Logger.trace("Add generic session-data with key:" + key + " to session."); genericSessionDataStorate.put(key, object); - } - - + } } 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 index 22a021d99..07679999b 100644 --- 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 @@ -47,10 +47,17 @@ package at.gv.egovernment.moa.id.util; -import iaik.security.random.SeedGenerator; - 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; /** @@ -60,37 +67,97 @@ import java.security.SecureRandom; */ 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; - + 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 + *
+ * 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 + return preFix + new String(Hex.encodeHex(Bytes.concat(now.getBytes(), randValue), true)); // 20 bytes = 160 bits + + } + + + + /** + * Creates a new random number [256bit], and encode it as hex value. + * + * @return random hex encoded value [256bit] + */ + public static String nextHexRandom() { + return new String(Hex.encodeHex(nextByteRandom(32), true)); // 32 bytes = 256 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 + * @return random long as a String [64bit] */ - public static String nextRandom() { - - byte[] b = new byte[32]; // 32 bytes = 256 bits - random.nextBytes(b); - - ByteBuffer bb = ByteBuffer.wrap(b); - long l = bb.getLong(); + @Deprecated + public static String nextRandom() { + long l = ByteBuffer.wrap(nextByteRandom(32)).getLong(); // 32 bytes = 256 bits return "" + Math.abs(l); - } + 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 bits + * @return + */ + private static byte[] nextByteRandom(int size) { + byte[] b = new byte[size]; + random.nextBytes(b); + return b; + } } -- cgit v1.2.3 From e2d27757411fdcba586cc162f362c72ca3ae689c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 8 Mar 2016 11:09:04 +0100 Subject: move SpingWebContextInitialisation into an appropriate jar to use moa-id-lib in other Spring based web applications --- .../moa/id/auth/MOAIDAuthInitializer.java | 282 --------------------- .../id/auth/MOAIDAuthSpringResourceProvider.java | 66 ----- 2 files changed, 348 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java deleted file mode 100644 index ce158d7fe..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java +++ /dev/null @@ -1,282 +0,0 @@ - - - -package at.gv.egovernment.moa.id.auth; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.security.Provider; -import java.security.Security; - -import javax.activation.CommandMap; -import javax.activation.MailcapCommandMap; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletRegistration; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.support.BeanDefinitionRegistry; -import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import org.springframework.context.support.GenericApplicationContext; -import org.springframework.web.WebApplicationInitializer; -import org.springframework.web.context.ContextLoaderListener; -import org.springframework.web.context.request.RequestContextListener; -import org.springframework.web.context.support.GenericWebApplicationContext; -import org.springframework.web.context.support.ServletContextResource; -import org.springframework.web.servlet.DispatcherServlet; - -import at.gv.egiz.components.spring.api.SpringLoader; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -import at.gv.egovernment.moa.id.util.SSLUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.logging.LoggingContext; -import at.gv.egovernment.moa.logging.LoggingContextManager; -import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; -import at.gv.egovernment.moa.spss.server.iaik.config.IaikConfigurator; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.MiscUtil; -import iaik.pki.PKIException; -import iaik.security.ecc.provider.ECCProvider; -import iaik.security.provider.IAIK; - -/** - * Web application initializer - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class MOAIDAuthInitializer implements WebApplicationInitializer { - - private String[] rootServletContexts = null; - - private String[] servletContexts = null; - - private String[] activeProfiles = null; - - public MOAIDAuthInitializer() { - this.rootServletContexts = null; - this.servletContexts = new String[] { - "/WEB-INF/applicationContext.xml", - - }; - this.activeProfiles = null; - } - - - /* (non-Javadoc) - * @see org.springframework.web.WebApplicationInitializer#onStartup(javax.servlet.ServletContext) - */ - @Override - public void onStartup(ServletContext servletContext) throws ServletException { - try { - Logger.info("=============== Loading Root Context! ==============="); - GenericWebApplicationContext rootContext = new GenericWebApplicationContext(); - rootContext.setServletContext(servletContext); - - Logger.info("=============== Setting active profiles! ==============="); - if (this.activeProfiles != null) { - for (String profile : this.activeProfiles) { - rootContext.getEnvironment().addActiveProfile(profile); - } - } - - Logger.info("=============== Loading Local Contexts! ==============="); - XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader( - rootContext); - if (rootServletContexts != null) { - for (String rootServletContext : rootServletContexts) { - Logger.debug("Loading: "+ rootServletContext); - xmlReader.loadBeanDefinitions(new ServletContextResource( - servletContext, rootServletContext)); - } - } - // Manage the lifecycle of the root application context - servletContext.addListener(new ContextLoaderListener(rootContext)); - - // logger.debug("Beans after logAMQP in {}", rootContext); - // dumpBeanDefinitions(rootContext); - - Logger.info("=============== Loading SPI Context! ==============="); - // logger.debug("Startup with context {}", rootContext); - if (rootContext instanceof BeanDefinitionRegistry) { - Logger.debug("Loading EGIZ components"); - SpringLoader - .loadSpringServices(rootContext); - } else { - Logger.warn("Failed to load external Spring since no BeanDefinitionRegistry"); - } - - Logger.trace("Beans after SPI in "+ rootContext); - dumpBeanDefinitions(rootContext); - - Logger.debug("Loading servlet config in "+ rootContext); - if (servletContexts != null) { - for (String servletContextString : servletContexts) { - xmlReader.loadBeanDefinitions(new ServletContextResource( - servletContext, servletContextString)); - } - } - Logger.debug("Refreshing context "+ rootContext); - rootContext.refresh(); - - Logger.info("=============== Register Dispatcher Servlet! ==============="); - - Logger.trace("Final Beans in "+ rootContext); - dumpBeanDefinitions(rootContext); - - - Logger.info("Registering dispatcher configuration"); - ServletRegistration.Dynamic dispatcher = servletContext.addServlet( - "dispatcher", new DispatcherServlet(rootContext)); - if (dispatcher != null) { - dispatcher.setLoadOnStartup(1); - dispatcher.addMapping("/"); - dispatcher.setAsyncSupported(true); - } else { - Logger.error("Failed to register dispatcher server in servlet context!"); - } - - Logger.info("=============== Register RequestContextListener! ==============="); - servletContext.addListener(new RequestContextListener()); - - Logger.info("Basic Context initalisation finished --> Start MOA-ID-Auth initialisation process ..."); - MOAIDAuthInitializer.initialize(rootContext); - Logger.info(MOAIDMessageProvider.getInstance().getMessage( - "init.00", null)); - Logger.info("MOA-ID-Auth initialization finished."); - - - } catch (Throwable e) { - Logger.fatal( - MOAIDMessageProvider.getInstance().getMessage("init.02", - null), e); - - } - - } - - - - /** - * Initializes the web application components which need initialization: - * logging, JSSE, MOA-ID Auth configuration, Axis, session cleaner. - * @param rootContext - */ - public static void initialize(GenericWebApplicationContext rootContext) throws ConfigurationException, - PKIException, IOException, GeneralSecurityException { - Logger.setHierarchy("moa.id.auth"); - Logger.info("Default java file.encoding: " - + System.getProperty("file.encoding")); - - - //JDK bug workaround according to: - // http://jce.iaik.tugraz.at/products/03_cms/faq/index.php#JarVerifier - // register content data handlers for S/MIME types - MailcapCommandMap mc = new MailcapCommandMap(); - CommandMap.setDefaultCommandMap(mc); - - if (MiscUtil.isEmpty(System.getProperty("https.cipherSuites"))) - System.setProperty( - "https.cipherSuites", - "TLS_DH_anon_WITH_AES_128_CBC_SHA" + - ",TLS_DHE_RSA_WITH_AES_128_CBC_SHA" + - ",TLS_DHE_DSS_WITH_AES_128_CBC_SHA" + - ",TLS_RSA_WITH_AES_128_CBC_SHA" + - ",TLS_RSA_WITH_AES_256_CBC_SHA" + - ",SSL_DH_anon_WITH_3DES_EDE_CBC_SHA" + - ",SSL_RSA_WITH_3DES_EDE_CBC_SHA" - ); - - - - // load some jsse classes so that the integrity of the jars can be - // verified - // before the iaik jce is installed as the security provider - // this workaround is only needed when sun jsse is used in conjunction - // with - // iaik-jce (on jdk1.3) - ClassLoader cl = MOAIDAuthInitializer.class.getClassLoader(); - try { - cl.loadClass("javax.security.cert.Certificate"); // from jcert.jar - } catch (ClassNotFoundException e) { - Logger.warn(MOAIDMessageProvider.getInstance().getMessage( - "init.01", null), e); - } - - Logger.info("Loading Java security providers."); - IAIK.addAsProvider(); - ECCProvider.addAsProvider(); - - // Initializes SSLSocketFactory store - SSLUtils.initialize(); - - // Initializes Namespace Map - Constants.nSMap.put(Constants.SAML_PREFIX, Constants.SAML_NS_URI); - Constants.nSMap.put(Constants.ECDSA_PREFIX, - "http://www.w3.org/2001/04/xmldsig-more#"); - Constants.nSMap.put(Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); - - - // Initialize configuration provider - AuthConfiguration authConf = AuthConfigurationProviderFactory.reload(rootContext); - - //test, if MOA-ID is already configured - authConf.getPublicURLPrefix(); - - - // Initialize MOA-SP - //MOA-SP is only use by API calls since MOA-ID 3.0.0 - try { - LoggingContextManager.getInstance().setLoggingContext( - new LoggingContext("startup")); - ConfigurationProvider config = ConfigurationProvider - .getInstance(); - new IaikConfigurator().configure(config); - - } catch (at.gv.egovernment.moa.spss.server.config.ConfigurationException ex) { - throw new ConfigurationException("config.10", new Object[] { ex - .toString() }, ex); - - } - - - //IAIK.addAsProvider(); - //ECCProvider.addAsProvider(); - - Security.insertProviderAt(IAIK.getInstance(), 0); - Security.addProvider(new ECCProvider()); - - if (Logger.isDebugEnabled()) { - Logger.debug("Loaded Security Provider:"); - Provider[] providerList = Security.getProviders(); - for (int i=0; i " + beanDefinition.getBeanClassName()); - - } - - Logger.trace("Registered Bean in context --"+ context); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.java deleted file mode 100644 index a82a958db..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthSpringResourceProvider.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.auth; - -import org.springframework.core.io.ClassPathResource; -import org.springframework.core.io.Resource; - -import at.gv.egiz.components.spring.api.SpringResourceProvider; - -/** - * @author tlenz - * - */ -public class MOAIDAuthSpringResourceProvider implements SpringResourceProvider { - - /* (non-Javadoc) - * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getResourcesToLoad() - */ - @Override - public Resource[] getResourcesToLoad() { - ClassPathResource moaidauthConfig = new ClassPathResource("/moaid.configuration.beans.xml", MOAIDAuthSpringResourceProvider.class); - ClassPathResource configurationDBConfig = new ClassPathResource("/configuration.beans.xml", MOAIDAuthSpringResourceProvider.class); - ClassPathResource moaIdAuthBeans = new ClassPathResource("/moaid.authentication.beans.xml", MOAIDAuthSpringResourceProvider.class); - - return new Resource[] {configurationDBConfig, moaidauthConfig, moaIdAuthBeans}; - - } - - /* (non-Javadoc) - * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getPackagesToScan() - */ - @Override - public String[] getPackagesToScan() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getName() - */ - @Override - public String getName() { - return "MOA-ID-Auth SpringResourceProvider"; - } - -} -- cgit v1.2.3 From b9937af42fdab6b85aa1121148bda474c70f5e75 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 8 Mar 2016 11:10:19 +0100 Subject: finish first beta-version of ELGA mandate-service client-module --- .../id/advancedlogging/MOAIDEventConstants.java | 6 +- .../moa/id/advancedlogging/StatisticLogger.java | 13 +- .../moa/id/auth/MOAIDAuthConstants.java | 4 + .../moa/id/auth/MOAIDAuthInitializer.java | 166 ++ .../id/auth/builder/AuthenticationDataBuilder.java | 1652 ++++++++++---------- .../moa/id/auth/builder/BPKBuilder.java | 97 +- .../AuthenticationSessionStorageConstants.java | 2 + .../StartAuthentificationParameterParser.java | 24 +- .../moa/id/data/AuthenticationData.java | 76 +- .../at/gv/egovernment/moa/id/data/IAuthData.java | 4 +- .../at/gv/egovernment/moa/id/data/MISMandate.java | 26 +- .../java/at/gv/egovernment/moa/id/data/Trible.java | 51 + .../moa/id/moduls/AuthenticationManager.java | 4 +- .../gv/egovernment/moa/id/moduls/RequestImpl.java | 5 +- .../attributes/BirthdateAttributeBuilder.java | 1 - .../protocols/builder/attributes/EIDSourcePIN.java | 1 - .../MandateFullMandateAttributeBuilder.java | 5 +- ...dateNaturalPersonGivenNameAttributeBuilder.java | 2 +- .../id/protocols/pvp2x/AttributQueryAction.java | 212 ++- .../id/protocols/pvp2x/AuthenticationAction.java | 15 +- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 22 +- .../moa/id/protocols/pvp2x/binding/IDecoder.java | 3 +- .../id/protocols/pvp2x/binding/PostBinding.java | 29 +- .../protocols/pvp2x/binding/RedirectBinding.java | 26 +- .../id/protocols/pvp2x/binding/SoapBinding.java | 3 +- .../pvp2x/builder/AuthResponseBuilder.java | 19 +- .../pvp2x/builder/PVPAttributeBuilder.java | 49 + .../pvp2x/builder/PVPAuthnRequestBuilder.java | 15 +- .../builder/assertion/PVP2AssertionBuilder.java | 167 +- .../IPVPAuthnRequestBuilderConfiguruation.java | 17 + .../protocols/pvp2x/config/PVPConfiguration.java | 21 +- .../metadata/IMOARefreshableMetadataProvider.java | 38 + .../pvp2x/metadata/MOAMetadataProvider.java | 3 +- .../pvp2x/utils/AssertionAttributeExtractor.java | 92 +- .../AbstractRequestSignedSecurityPolicyRule.java | 4 +- .../validation/MOAPVPSignedRequestPolicyRule.java | 17 +- .../pvp2x/verification/SAMLVerificationEngine.java | 129 +- .../verification/SAMLVerificationEngineSP.java | 161 ++ .../storage/DBAuthenticationSessionStoreage.java | 5 - 39 files changed, 1892 insertions(+), 1294 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java index d5d0a3ab1..eccd63e3d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java @@ -81,7 +81,7 @@ public interface MOAIDEventConstants extends EventConstants { public static final int AUTHPROCESS_PEPS_REQUESTED = 4400; public static final int AUTHPROCESS_PEPS_RECEIVED = 4401; public static final int AUTHPROCESS_PEPS_IDL_RECEIVED = 4402; - + //person information public static final int PERSONAL_INFORMATION_PROF_REPRESENTATIVE_BPK = 5000; public static final int PERSONAL_INFORMATION_PROF_REPRESENTATIVE = 5001; @@ -92,6 +92,10 @@ public interface MOAIDEventConstants extends EventConstants { public static final int PERSONAL_INFORMATION_MANDATE_MANDATOR_HASH = 5102; public static final int PERSONAL_INFORMATION_MANDATE_MANDATOR_BASEID = 5103; + //Attribute Provider [6000 --> 7900] + public static final int AUTHPROCESS_ELGA_MANDATE_SERVICE_REQUESTED = 6000; + public static final int AUTHPROCESS_ELGA_MANDATE_RECEIVED = 6001; + public static final int AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED = 6002; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java index 87b3bc9ca..8efdf6014 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/advancedlogging/StatisticLogger.java @@ -54,6 +54,7 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -106,12 +107,14 @@ public class StatisticLogger { boolean isbusinessservice = isBusinessService(dbOA); dblog.setBusinessservice(isbusinessservice); dblog.setOatarget(authData.getBPKType()); - - dblog.setInterfederatedSSOSession(authData.isInterfederatedSSOSession()); + + + boolean isFederatedAuthentication = protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE) != null; + dblog.setInterfederatedSSOSession(isFederatedAuthentication); - if (authData.isInterfederatedSSOSession()) { + if (isFederatedAuthentication) { dblog.setBkutype(IOAAuthParameters.INDERFEDERATEDIDP); - dblog.setBkuurl(authData.getInterfederatedIDP()); + dblog.setBkuurl(protocolRequest.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_ENTITYID, String.class)); } else { dblog.setBkuurl(authData.getBkuURL()); @@ -252,7 +255,7 @@ public class StatisticLogger { dblog.setBkutype(findBKUType(moasession.getBkuURL(), dbOA)); } - dblog.setMandatelogin(moasession.getUseMandate()); + dblog.setMandatelogin(moasession.isMandateUsed()); } } catch (MOADatabaseException e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index c7ef73b47..27c87ccbf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -25,6 +25,8 @@ public class MOAIDAuthConstants extends MOAIDConstants{ public static final String PARAM_TARGET = "Target"; /** servlet parameter "useMandate" */ public static final String PARAM_USEMANDATE = "useMandate"; + public static final String PARAM_USEMISMANDATE = "useMISMandate"; + public static final String PARAM_USEELGAMANDATE = "useELGAMandate"; /** servlet parameter "OA" */ public static final String PARAM_OA = "OA"; /** servlet parameter "bkuURI" */ @@ -166,6 +168,8 @@ public class MOAIDAuthConstants extends MOAIDConstants{ } }); + public static final String COUNTRYCODE_AUSTRIA = "AT"; + public static final String REGEX_PATTERN_TARGET = "^[A-Za-z]{2}(-.*)?$"; public static final String MDC_TRANSACTION_ID = "transactionId"; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java new file mode 100644 index 000000000..458f9afe6 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java @@ -0,0 +1,166 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.Provider; +import java.security.Security; + +import javax.activation.CommandMap; +import javax.activation.MailcapCommandMap; + +import org.springframework.web.context.support.GenericWebApplicationContext; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; +import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.id.util.SSLUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.logging.LoggingContext; +import at.gv.egovernment.moa.logging.LoggingContextManager; +import at.gv.egovernment.moa.spss.server.config.ConfigurationProvider; +import at.gv.egovernment.moa.spss.server.iaik.config.IaikConfigurator; +import at.gv.egovernment.moa.util.Constants; +import at.gv.egovernment.moa.util.MiscUtil; +import iaik.pki.PKIException; +import iaik.security.ecc.provider.ECCProvider; +import iaik.security.provider.IAIK; + +/** + * @author tlenz + * + */ +public class MOAIDAuthInitializer { + + /** + * Initializes the web application components which need initialization: + * logging, JSSE, MOA-ID Auth configuration, Axis, session cleaner. + * @param rootContext + */ + public static void initialize(GenericWebApplicationContext rootContext) throws ConfigurationException, + PKIException, IOException, GeneralSecurityException { + Logger.setHierarchy("moa.id.auth"); + Logger.info("Default java file.encoding: " + + System.getProperty("file.encoding")); + + + //JDK bug workaround according to: + // http://jce.iaik.tugraz.at/products/03_cms/faq/index.php#JarVerifier + // register content data handlers for S/MIME types + MailcapCommandMap mc = new MailcapCommandMap(); + CommandMap.setDefaultCommandMap(mc); + + if (MiscUtil.isEmpty(System.getProperty("https.cipherSuites"))) + System.setProperty( + "https.cipherSuites", + "TLS_DH_anon_WITH_AES_128_CBC_SHA" + + ",TLS_DHE_RSA_WITH_AES_128_CBC_SHA" + + ",TLS_DHE_DSS_WITH_AES_128_CBC_SHA" + + ",TLS_RSA_WITH_AES_128_CBC_SHA" + + ",TLS_RSA_WITH_AES_256_CBC_SHA" + + ",SSL_DH_anon_WITH_3DES_EDE_CBC_SHA" + + ",SSL_RSA_WITH_3DES_EDE_CBC_SHA" + ); + + + + // load some jsse classes so that the integrity of the jars can be + // verified + // before the iaik jce is installed as the security provider + // this workaround is only needed when sun jsse is used in conjunction + // with + // iaik-jce (on jdk1.3) + ClassLoader cl = MOAIDAuthInitializer.class.getClassLoader(); + try { + cl.loadClass("javax.security.cert.Certificate"); // from jcert.jar + } catch (ClassNotFoundException e) { + Logger.warn(MOAIDMessageProvider.getInstance().getMessage( + "init.01", null), e); + } + + Logger.info("Loading Java security providers."); + IAIK.addAsProvider(); + ECCProvider.addAsProvider(); + + // Initializes SSLSocketFactory store + SSLUtils.initialize(); + + // Initializes Namespace Map + Constants.nSMap.put(Constants.SAML_PREFIX, Constants.SAML_NS_URI); + Constants.nSMap.put(Constants.ECDSA_PREFIX, + "http://www.w3.org/2001/04/xmldsig-more#"); + Constants.nSMap.put(Constants.DSIG_PREFIX, Constants.DSIG_NS_URI); + + //seed the random number generator + Random.seedRandom(); + Logger.debug("Random-number generator is seeded."); + + // Initialize configuration provider + AuthConfiguration authConf = AuthConfigurationProviderFactory.reload(rootContext); + + //test, if MOA-ID is already configured + authConf.getPublicURLPrefix(); + + + // Initialize MOA-SP + //MOA-SP is only use by API calls since MOA-ID 3.0.0 + try { + LoggingContextManager.getInstance().setLoggingContext( + new LoggingContext("startup")); + ConfigurationProvider config = ConfigurationProvider + .getInstance(); + new IaikConfigurator().configure(config); + + } catch (at.gv.egovernment.moa.spss.server.config.ConfigurationException ex) { + throw new ConfigurationException("config.10", new Object[] { ex + .toString() }, ex); + + } + + + //IAIK.addAsProvider(); + //ECCProvider.addAsProvider(); + + Security.insertProviderAt(IAIK.getInstance(), 0); + Security.addProvider(new ECCProvider()); + + if (Logger.isDebugEnabled()) { + Logger.debug("Loaded Security Provider:"); + Provider[] providerList = Security.getProviders(); + for (int i=0; i reqAttributes, InterfederationSessionStore nextIDPInformation) throws MOAIDException { - AuthenticationData authdata = new AuthenticationData(); + + public IAuthData buildAuthenticationData(IRequest pendingReq, + AuthenticationSession session) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { + return buildAuthenticationData(pendingReq, session, pendingReq.getOnlineApplicationConfiguration()); + } + + public IAuthData buildAuthenticationData(IRequest pendingReq, + AuthenticationSession session, IOAAuthParameters oaParam) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { + AuthenticationData authdata = null; + + //only needed for SAML1 legacy support try { - //mark AttributeQuery as used if it exists - OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); - if (activeOA != null) { - //reuse some parameters if it is a Service-Provider reauthentication - authdata.setSessionIndex(activeOA.getAssertionSessionID()); - authdata.setNameID(activeOA.getUserNameID()); - authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); - - //mark - if ( pendingReq instanceof PVPTargetConfiguration && - ((PVPTargetConfiguration) pendingReq).getRequest() instanceof MOARequest && - ((PVPTargetConfiguration) pendingReq).getRequest().getInboundMessage() instanceof AttributeQuery) { - try { - activeOA.setAttributeQueryUsed(true); - MOASessionDBUtils.saveOrUpdate(activeOA); - - } catch (MOADatabaseException e) { - Logger.error("MOASession interfederation information can not stored to database.", e); + //check if SAML1 authentication module is in Classpath + Class saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); + IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); + if (saml1RequstTemplate != null && + saml1RequstTemplate.isInstance(pendingReq)) { + //request is SAML1 --> invoke SAML1 protocol specific methods + if (session.getExtendedSAMLAttributesOA() == null) { + saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, new ArrayList()); - } + } else { + saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, session.getExtendedSAMLAttributesOA()); } + + authdata = (AuthenticationData) saml1authdata; + + } else { + authdata = new AuthenticationData(); + } + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { + authdata = new AuthenticationData(); - //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) and configuration - IOAAuthParameters spConfig = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes); - - //search federated IDP information for this MOASession - if (nextIDPInformation != null) { - Logger.info("Find active federated IDP information." - + ". --> Request next IDP:" + nextIDPInformation.getIdpurlprefix() - + " for authentication information."); - - //load configuration of next IDP - OAAuthParameter idp = authConfig.getOnlineApplicationParameter(nextIDPInformation.getIdpurlprefix()); - if (idp == null) { - Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() - + "is not loadable."); - throw new MOAIDException("auth.32", new Object[]{nextIDPInformation.getIdpurlprefix()}); - - } - - //check if next IDP config allows inbound messages - if (!idp.isInboundSSOInterfederationAllowed()) { - Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() - + "disallow inbound authentication messages."); - throw new MOAIDException("auth.33", new Object[]{nextIDPInformation.getIdpurlprefix()}); - - } - - //check next IDP service area policy. BusinessService IDPs can only request wbPKs - if (!spConfig.getBusinessService() && !idp.isIDPPublicService()) { - Logger.error("Interfederated IDP " + idp.getPublicURLPrefix() - + " has a BusinessService-IDP but requests PublicService attributes."); - throw new MOAIDException("auth.34", new Object[]{nextIDPInformation.getIdpurlprefix()}); - - } + } - //validation complete --> start AttributeQuery Request - getAuthDataFromInterfederation(authdata, reqAttributes, nextIDPInformation, idp); - - } else { - Logger.debug("Build authData for AttributQuery from local MOASession."); - buildAuthDataFormMOASession(authdata, session, spConfig, pendingReq); + OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); + //reuse authentication information in case of service-provider reauthentication + if (activeOA != null) { + authdata.setSessionIndex(activeOA.getAssertionSessionID()); + authdata.setNameID(activeOA.getUserNameID()); + authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); + + } + + //TODO: move to eIDAS-Code in case of ISA1.18 action is enabled for eIDAS + //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway + if (oaParam.isSTORKPVPGateway()) + oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, pendingReq); - } - - return authdata; + Boolean isMinimalFrontChannelResp = pendingReq.getGenericData( + PVPTargetConfiguration.DATAID_INTERFEDERATION_MINIMAL_FRONTCHANNEL_RESP, Boolean.class); + if (isMinimalFrontChannelResp != null && isMinimalFrontChannelResp) { + //only set minimal response attributes + authdata.setQAALevel( + pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_QAALEVEL, String.class)); + authdata.setBPK( + pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_NAMEID, String.class)); - } catch (MOAIDException e) { - throw e; + } else { + //build AuthenticationData from MOASession + buildAuthDataFormMOASession(authdata, session, oaParam, pendingReq); + } + + return authdata; } - - private void getAuthDataFromInterfederation( - AuthenticationData authdata, List reqQueryAttr, - InterfederationSessionStore nextIDPInfo, OAAuthParameter nextIDPConfig ) throws MOAIDException{ - String idpEnityID = nextIDPConfig.getPublicURLPrefix(); + /** + * Get PVP authentication attributes by using a SAML2 AttributeQuery + * + * @param reqQueryAttr List of PVP attributes which are requested + * @param userNameID SAML2 UserNameID of the user for which attributes are requested + * @param idpConfig Configuration of the IDP, which is requested + * @return + * @return PVP attribute DAO, which contains all received information + * @throws MOAIDException + */ + public AssertionAttributeExtractor getAuthDataFromAttributeQuery(List reqQueryAttr, + String userNameID, IOAAuthParameters idpConfig ) throws MOAIDException{ + String idpEnityID = idpConfig.getPublicURLPrefix(); - AssertionAttributeExtractor extractor; try { Logger.debug("Starting AttributeQuery process ..."); //collect attributes by using BackChannel communication - String endpoint = nextIDPConfig.getIDPAttributQueryServiceURL(); + String endpoint = idpConfig.getIDPAttributQueryServiceURL(); if (MiscUtil.isEmpty(endpoint)) { Logger.error("No AttributeQueryURL for interfederationIDP " + idpEnityID); throw new ConfigurationException("config.26", new Object[]{idpEnityID}); @@ -226,7 +202,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } //build attributQuery request - AttributeQuery query = attributQueryBuilder.buildAttributQueryRequest(nextIDPInfo.getUserNameID(), endpoint, reqQueryAttr); + AttributeQuery query = attributQueryBuilder.buildAttributQueryRequest(userNameID, endpoint, reqQueryAttr); //build SOAP request List xmlObjects = MOASAMLSOAPClient.send(endpoint, query); @@ -249,17 +225,8 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { MOAMetadataProvider.getInstance())); //create assertion attribute extractor from AttributeQuery response - extractor = new AssertionAttributeExtractor(intfResp); - - //copy attributes into authData object - Set includedAttrNames = extractor.getAllIncludeAttributeNames(); - for (String el : includedAttrNames) { - authdata.setGenericData(el, extractor.getSingleAttributeValue(el)); - Logger.debug("Add PVP-attribute " + el + " into authData objext"); - - } - - + return new AssertionAttributeExtractor(intfResp); + } catch (Exception e) { Logger.warn("PVP 2.1 assertion validation FAILED.", e); throw new AssertionValidationExeption("auth.27", @@ -272,24 +239,7 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { new Object[]{idpEnityID, "Receive AttributeQuery response-body include no PVP 2.1 response"}); } - - try { - //mark attribute request as used - if (nextIDPInfo.isStoreSSOInformation()) { - nextIDPInfo.setAttributesRequested(true); - MOASessionDBUtils.saveOrUpdate(nextIDPInfo); - - //delete federated IDP from Session - } else { - MOASessionDBUtils.delete(nextIDPInfo); - - } - - } catch (MOADatabaseException e) { - Logger.error("MOASession interfederation information can not stored to database.", e); - - } - + } catch (SOAPException e) { throw new BuildException("builder.06", null, e); @@ -301,589 +251,588 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { } } - - - public IAuthData buildAuthenticationData(IRequest pendingReq, - AuthenticationSession session) throws ConfigurationException, BuildException, WrongParametersException, DynamicOABuildException { - AuthenticationData authdata = null; - //only needed for SAML1 legacy support - try { - //check if SAML1 authentication module is in Classpath - Class saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); - IAuthData saml1authdata = (IAuthData) Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1AuthenticationData").newInstance(); - if (saml1RequstTemplate != null && - saml1RequstTemplate.isInstance(pendingReq)) { - //request is SAML1 --> invoke SAML1 protocol specific methods - if (session.getExtendedSAMLAttributesOA() == null) { - saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, new ArrayList()); + private void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, + IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { + + Collection includedToGenericAuthData = null; + if (session.getGenericSessionDataStorage() != null && + !session.getGenericSessionDataStorage().isEmpty()) + includedToGenericAuthData = session.getGenericSessionDataStorage().keySet(); + else + includedToGenericAuthData = new ArrayList(); + + try { + //#################################################### + //set general authData info's + authData.setIssuer(protocolRequest.getAuthURL()); + authData.setSsoSession(protocolRequest.needSingleSignOnFunctionality()); + authData.setIsBusinessService(oaParam.getBusinessService()); + + + //#################################################### + //parse user info's from identityLink + IdentityLink idlFromPVPAttr = null; + IdentityLink identityLink = session.getIdentityLink(); + if (identityLink != null) { + parseBasicUserInfosFromIDL(authData, identityLink, includedToGenericAuthData); + + } else { + // identityLink is not direct in MOASession + String pvpAttrIDL = session.getGenericDataFromSession(PVPConstants.EID_IDENTITY_LINK_NAME, String.class); + //find PVP-Attr. which contains the IdentityLink + if (MiscUtil.isNotEmpty(pvpAttrIDL)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_IDENTITY_LINK_FRIENDLY_NAME + + " --> Parse basic user info's from that attribute."); + InputStream idlStream = null; + try { + idlStream = Base64Utils.decodeToStream(pvpAttrIDL, false); + idlFromPVPAttr = new IdentityLinkAssertionParser(idlStream).parseIdentityLink(); + parseBasicUserInfosFromIDL(authData, idlFromPVPAttr, includedToGenericAuthData); + + } catch (ParseException e) { + Logger.error("Received IdentityLink is not valid", e); + + } catch (Exception e) { + Logger.error("Received IdentityLink is not valid", e); + + } finally { + try { + includedToGenericAuthData.remove(PVPConstants.EID_IDENTITY_LINK_NAME); + if (idlStream != null) + idlStream.close(); + + } catch (IOException e) { + Logger.fatal("Close InputStream FAILED.", e); + + } + + } - } else { - saml1authdata.getClass().getMethod("setExtendedSAMLAttributesOA", List.class).invoke(saml1authdata, session.getExtendedSAMLAttributesOA()); } - authdata = (AuthenticationData) saml1authdata; - - } else { - authdata = new AuthenticationData(); - + //if no basic user info's are set yet, parse info's single PVP-Attributes + if (MiscUtil.isEmpty(authData.getFamilyName())) { + Logger.debug("No IdentityLink found or not parseable --> Parse basic user info's from single PVP-Attributes."); + authData.setFamilyName(session.getGenericDataFromSession(PVPConstants.PRINCIPAL_NAME_NAME, String.class)); + authData.setGivenName(session.getGenericDataFromSession(PVPConstants.GIVEN_NAME_NAME, String.class)); + authData.setDateOfBirth(session.getGenericDataFromSession(PVPConstants.BIRTHDATE_NAME, String.class)); + authData.setIdentificationValue(session.getGenericDataFromSession(PVPConstants.EID_SOURCE_PIN_NAME, String.class)); + authData.setIdentificationType(session.getGenericDataFromSession(PVPConstants.EID_SOURCE_PIN_TYPE_NAME, String.class)); + + //remove corresponding keys from genericSessionData if exists + includedToGenericAuthData.remove(PVPConstants.PRINCIPAL_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.GIVEN_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.BIRTHDATE_NAME); + includedToGenericAuthData.remove(PVPConstants.EID_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPConstants.EID_SOURCE_PIN_TYPE_NAME); + } + } - - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { - authdata = new AuthenticationData(); - } + if (authData.getIdentificationType() != null && + !authData.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + Logger.trace("IdentificationType is not a baseID --> clear it. "); + authData.setBPK(authData.getIdentificationValue()); + authData.setBPKType(authData.getIdentificationType()); - OASessionStore activeOA = authenticatedSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); - //reuse authentication information in case of service-provider reauthentication - if (activeOA != null) { - authdata.setSessionIndex(activeOA.getAssertionSessionID()); - authdata.setNameID(activeOA.getUserNameID()); - authdata.setNameIDFormat(activeOA.getUserNameIDFormat()); + authData.setIdentificationValue(null); + authData.setIdentificationType(null); + + } + + + //#################################################### + //set BKU URL + includedToGenericAuthData.remove(PVPConstants.EID_CCS_URL_NAME); + if (MiscUtil.isNotEmpty(session.getBkuURL())) + authData.setBkuURL(session.getBkuURL()); + else + authData.setBkuURL(session.getGenericDataFromSession(PVPConstants.EID_CCS_URL_NAME, String.class)); - } - - //get OnlineApplication from MOA-ID-Auth configuration - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - - //TODO: move to eIDAS-Code in case of ISA1.18 action is enabled for eIDAS - //build OA dynamically from STROK request if this OA is used as STORK<->PVP gateway - if (oaParam.isSTORKPVPGateway()) - oaParam = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oaParam, pendingReq); - - //check if minimal response is required - - //TODO check if really required - Boolean isMinimalFrontChannelResp = pendingReq.getGenericData( - PVPTargetConfiguration.DATAID_INTERFEDERATION_MINIMAL_FRONTCHANNEL_RESP, Boolean.class); - if (isMinimalFrontChannelResp != null && isMinimalFrontChannelResp) { - //only set minimal response attributes - authdata.setQAALevel( - pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_QAALEVEL, String.class)); - authdata.setBPK( - pendingReq.getGenericData(PVPTargetConfiguration.DATAID_INTERFEDERATION_NAMEID, String.class)); + + //#################################################### + //set QAA level + includedToGenericAuthData.remove(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME); + if (MiscUtil.isNotEmpty(session.getQAALevel())) + authData.setQAALevel(session.getQAALevel()); + + else { + String qaaLevel = session.getGenericDataFromSession(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME, String.class); + if (MiscUtil.isNotEmpty(qaaLevel)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_CITIZEN_QAA_LEVEL_FRIENDLY_NAME + + " --> Parse QAA-Level from that attribute."); - } else { - //build AuthenticationData from MOASession - buildAuthDataFormMOASession(authdata, session, oaParam, pendingReq); + if (qaaLevel.startsWith(PVPConstants.STORK_QAA_PREFIX)) { + authData.setQAALevel(qaaLevel); + + } else { + Logger.debug("Found PVP QAA level. QAA mapping process starts ... "); + String mappedQAA = PVPtoSTORKMapper.getInstance().mapToQAALevel(qaaLevel); + if (MiscUtil.isNotEmpty(mappedQAA)) + authData.setQAALevel(mappedQAA); + + } + } + } - } - - return authdata; - } + //if no QAA level is set in MOASession then set default QAA level + if (MiscUtil.isEmpty(authData.getQAALevel())) { + Logger.info("No QAA level found. Set to default level " + PVPConstants.STORK_QAA_PREFIX + "1"); + authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + "1"); + + } - private void buildAuthDataFormInterfederationResponse( - AuthenticationData authData, - AuthenticationSession session, - AssertionAttributeExtractor extractor, - IOAAuthParameters oaParam, - IRequest req) - throws BuildException, AssertionAttributeExtractorExeption { - - Logger.debug("Build AuthData from assertion starts ...."); - - authData.setIsBusinessService(oaParam.getBusinessService()); - - authData.setFamilyName(extractor.getSingleAttributeValue(PVPConstants.PRINCIPAL_NAME_NAME)); - authData.setGivenName(extractor.getSingleAttributeValue(PVPConstants.GIVEN_NAME_NAME)); - authData.setDateOfBirth(extractor.getSingleAttributeValue(PVPConstants.BIRTHDATE_NAME)); - authData.setCcc(extractor.getSingleAttributeValue(PVPConstants.EID_ISSUING_NATION_NAME)); - authData.setBkuURL(extractor.getSingleAttributeValue(PVPConstants.EID_CCS_URL_NAME)); - authData.setIdentificationValue(extractor.getSingleAttributeValue(PVPConstants.EID_SOURCE_PIN_NAME)); - authData.setIdentificationType(extractor.getSingleAttributeValue(PVPConstants.EID_SOURCE_PIN_TYPE_NAME)); - - - if (extractor.containsAttribute(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME)) { - String bpkType = extractor.getSingleAttributeValue(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME); - if (bpkType.startsWith(Constants.URN_PREFIX_CDID) && - !bpkType.substring(Constants.URN_PREFIX_CDID.length(), - Constants.URN_PREFIX_CDID.length() + 1).equals("+")) { - Logger.warn("Receive uncorrect encoded bBKType attribute " + bpkType + " Starting attribute value correction ... "); - bpkType = Constants.URN_PREFIX_CDID + "+" + bpkType.substring(Constants.URN_PREFIX_CDID.length() + 1); + + //#################################################### + //set signer certificate + includedToGenericAuthData.remove(PVPConstants.EID_SIGNER_CERTIFICATE_NAME); + if (session.getEncodedSignerCertificate() != null) + authData.setSignerCertificate(session.getEncodedSignerCertificate()); + + else { + String pvpAttrSignerCert = session.getGenericDataFromSession(PVPConstants.EID_SIGNER_CERTIFICATE_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrSignerCert)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_SIGNER_CERTIFICATE_FRIENDLY_NAME); + try { + authData.setSignerCertificate(Base64Utils.decode(pvpAttrSignerCert, false)); + + } catch (IOException e) { + Logger.error("SignerCertificate received via federated IDP is NOT valid", e); + + } + } else + Logger.info("NO SignerCertificate in MOASession."); } - - authData.setBPKType(bpkType); - } - - if (extractor.containsAttribute(PVPConstants.BPK_NAME)) { - String pvpbPK = extractor.getSingleAttributeValue(PVPConstants.BPK_NAME); - if (pvpbPK.startsWith("bPK:")) { - Logger.warn("Attribute " + PVPConstants.BPK_NAME - + " contains a not standardize prefix! Staring attribute value correction process ..."); - pvpbPK = pvpbPK.substring("bPK:".length()); + + //#################################################### + //set authBlock + includedToGenericAuthData.remove(PVPConstants.EID_AUTH_BLOCK_NAME); + if (MiscUtil.isNotEmpty(session.getAuthBlock())) { + authData.setAuthBlock(session.getAuthBlock()); + + } else { + String pvpAttrAuthBlock = session.getGenericDataFromSession(PVPConstants.EID_AUTH_BLOCK_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrAuthBlock)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_AUTH_BLOCK_FRIENDLY_NAME); + try { + byte[] authBlock = Base64Utils.decode(pvpAttrAuthBlock, false); + authData.setAuthBlock(new String(authBlock, "UTF-8")); + + } catch (IOException e) { + Logger.error("AuthBlock received via federated IDP is NOT valid", e); + + } + + } else + Logger.info("NO AuthBlock in MOASession."); } - String[] spitted = pvpbPK.split(":"); - authData.setBPK(spitted[1]); - if (MiscUtil.isEmpty(authData.getBPKType())) { - Logger.debug("PVP assertion contains NO bPK/wbPK target attribute. " + - "Starting target extraction from bPK/wbPK prefix ..."); - //exract bPK/wbPK type from bpk attribute value prefix if type is - //not transmitted as single attribute - Pattern pattern = Pattern.compile("[a-zA-Z]{2}(-[a-zA-Z]+)?"); - Matcher matcher = pattern.matcher(spitted[0]); - if (matcher.matches()) { - //find public service bPK - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + spitted[0]); - Logger.debug("Found bPK prefix. Set target to " + authData.getBPKType()); - - } else { - //find business service wbPK - authData.setBPKType(Constants.URN_PREFIX_WBPK+ "+" + spitted[0]); - Logger.debug("Found wbPK prefix. Set target to " + authData.getBPKType()); - - } + + //#################################################### + //set isForeigner flag + //TODO: change to new eIDAS-token attribute identifier + if (session.getGenericDataFromSession(PVPConstants.EID_STORK_TOKEN_NAME) != null) { + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_STORK_TOKEN_FRIENDLY_NAME + + " --> Set 'isForeigner' flag to TRUE"); + authData.setForeigner(true); + + } else { + authData.setForeigner(session.isForeigner()); + } - } - - boolean foundEncryptedbPKForOA = false; - if (extractor.containsAttribute(PVPConstants.ENC_BPK_LIST_NAME)) { - List encbPKList = Arrays.asList( - extractor.getSingleAttributeValue(PVPConstants.ENC_BPK_LIST_NAME).split(";")); - authData.setEncbPKList(encbPKList); - for (String fullEncbPK : encbPKList) { - int index = fullEncbPK.indexOf("|"); - if (index >= 0) { - String encbPK = fullEncbPK.substring(index+1); - String second = fullEncbPK.substring(0, index); - int secIndex = second.indexOf("+"); - if (secIndex >= 0) { - if (oaParam.getTarget().equals(second.substring(secIndex+1))) { - Logger.debug("Found encrypted bPK for online-application " - + oaParam.getPublicURLPrefix() - + " Start decryption process ..."); - PrivateKey privKey = oaParam.getBPKDecBpkDecryptionKey(); - foundEncryptedbPKForOA = true; - if (privKey != null) { - try { - String bPK = BPKBuilder.decryptBPK(encbPK, oaParam.getTarget(), privKey); - if (MiscUtil.isNotEmpty(bPK)) { - if (MiscUtil.isEmpty(authData.getBPK())) { - authData.setBPK(bPK); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget()); - Logger.info("bPK decryption process finished successfully."); - } - - } else { - Logger.error("bPK decryption FAILED."); - + + + //#################################################### + //set citizen country-code + includedToGenericAuthData.remove(PVPConstants.EID_ISSUING_NATION_NAME); + String pvpCCCAttr = session.getGenericDataFromSession(PVPConstants.EID_ISSUING_NATION_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpCCCAttr)) { + authData.setCcc(pvpCCCAttr); + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_ISSUING_NATION_FRIENDLY_NAME); + + } else { + if (authData.isForeigner()) { + try { + if (authData.getSignerCertificate() != null) { + //TODO: replace with TSL lookup when TSL is ready! + X509Certificate certificate = new X509Certificate(authData.getSignerCertificate()); + if (certificate != null) { + LdapName ln = new LdapName(certificate.getIssuerDN() + .getName()); + for (Rdn rdn : ln.getRdns()) { + if (rdn.getType().equalsIgnoreCase("C")) { + Logger.info("C is: " + rdn.getValue()); + authData.setCcc(rdn.getValue().toString()); + break; } - } catch (BuildException e) { - Logger.error("bPK decryption FAILED.", e); - } - - } else { - Logger.info("bPK decryption FAILED, because no valid decryption key is found."); - - } - - } else { - Logger.info("Found encrypted bPK but " + - "encrypted bPK target does not match to online-application target"); + } - } - } - } - } - } - - if (MiscUtil.isEmpty(authData.getIdentificationValue()) && - MiscUtil.isEmpty(authData.getBPK()) && - !foundEncryptedbPKForOA) { - Logger.info("Federated assertion include no bPK, encrypted bPK or baseID"); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME - + " or " + PVPConstants.ENC_BPK_LIST_NAME); - - } - - //check if received bPK matchs to online application configuration - //and no encrypted bPK is found for this oa - if (!matchsReceivedbPKToOnlineApplication(oaParam, authData) - && !foundEncryptedbPKForOA) { - Logger.info("Received bPK/wbPK does not match to online application"); - - if (MiscUtil.isEmpty(authData.getIdentificationValue())) { - Logger.info("No baseID found. Connect SZR to reveive baseID ..."); - try { - EgovUtilPropertiesConfiguration eGovClientsConfig = authConfig.geteGovUtilsConfig(); - if (eGovClientsConfig != null) { - SZRClient szrclient = new SZRClient(eGovClientsConfig); + } else + Logger.warn("NO PVP-Attr: " + PVPConstants.EID_ISSUING_NATION_NAME + + " and NO SignerCertificate in MOASession -->" + + " Can NOT extract citizen-country of foreign person."); - Logger.debug("Create SZR request to get baseID ... "); - PersonInfoType personInfo = new PersonInfoType(); - at.gv.util.xsd.szr.persondata.PhysicalPersonType person = new at.gv.util.xsd.szr.persondata.PhysicalPersonType(); - personInfo.setPerson(person); - at.gv.util.xsd.szr.persondata.PersonNameType name = new at.gv.util.xsd.szr.persondata.PersonNameType(); - person.setName(name); - at.gv.util.xsd.szr.persondata.IdentificationType idValue = new at.gv.util.xsd.szr.persondata.IdentificationType(); - person.setIdentification(idValue); - //set bPK or wbPK - idValue.setValue(authData.getBPK()); - idValue.setType(authData.getBPKType()); - - //set person information - name.setGivenName(authData.getGivenName()); - name.setFamilyName(authData.getFamilyName()); - if (authData.getDateOfBirth() != null) - person.setDateOfBirth(authData.getFormatedDateOfBirth()); - - //request szr and store baseID - authData.setIdentificationValue(szrclient.getStammzahl(personInfo)); - authData.setIdentificationType(Constants.URN_PREFIX_BASEID); - - } else { - Logger.warn("No SZR clieht configuration found. Interfederation SSO login not possible."); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); + } catch (Exception e) { + Logger.error("Failed to extract country code from certificate with message: " + e.getMessage()); } - - } catch (EgovUtilException e) { - Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); - - } catch (SZRException e) { - Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - throw new AssertionAttributeExtractorExeption("No " + PVPConstants.BPK_FRIENDLY_NAME - + " or " + PVPConstants.EID_SOURCE_PIN_NAME); + + } else { + authData.setCcc(COUNTRYCODE_AUSTRIA); - } + } } - //build OA specific bPK/wbPK information - buildOAspecificbPK(req, oaParam, authData, - authData.getIdentificationValue(), - authData.getIdentificationType()); - } - - if (MiscUtil.isEmpty(authData.getBPK())) { - Logger.debug("Calcutlate bPK from baseID"); - buildOAspecificbPK(req, oaParam, authData, - authData.getIdentificationValue(), - authData.getIdentificationType()); - - } - - - try { - String qaaLevel = extractor.getQAALevel(); - if (MiscUtil.isNotEmpty(qaaLevel) && - qaaLevel.startsWith(PVPConstants.STORK_QAA_PREFIX)) { - authData.setQAALevel(qaaLevel); - - } else { - Logger.debug("Found PVP QAA level. QAA mapping process starts ... "); - String mappedQAA = PVPtoSTORKMapper.getInstance().mapToQAALevel(qaaLevel); - if (MiscUtil.isNotEmpty(mappedQAA)) - authData.setQAALevel(mappedQAA); + //#################################################### + //set max. SSO session time + includedToGenericAuthData.remove(AuthenticationSessionStorageConstants.FEDERATION_RESPONSE_VALIDE_TO); + Date validToFromFederatedIDP = session.getGenericDataFromSession( + AuthenticationSessionStorageConstants.FEDERATION_RESPONSE_VALIDE_TO, Date.class); + if (validToFromFederatedIDP != null) { + authData.setSsoSessionValidTo(validToFromFederatedIDP); + Logger.debug("Use idToken validTo periode from federated IDP response."); - else - throw new AssertionAttributeExtractorExeption("PVP SecClass not mappable"); + } else { + if (authData.isSsoSession()) { + long maxSSOSessionTime = authConfig.getSSOCreatedTimeOut() * 1000; + Date ssoSessionValidTo = new Date(session.getSessionCreated().getTime() + maxSSOSessionTime); + authData.setSsoSessionValidTo(ssoSessionValidTo); - } - - } catch (AssertionAttributeExtractorExeption e) { - Logger.warn("No QAA level found in element of interfederated assertion. " + - "(ErrorHeader=" + e.getMessage() + ")"); - if (extractor.containsAttribute(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME)) { - authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + - extractor.getSingleAttributeValue(PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME)); - - } else { - Logger.info("No QAA level found. Set to default level " + - PVPConstants.STORK_QAA_PREFIX + "1"); - authData.setQAALevel(PVPConstants.STORK_QAA_PREFIX + "1"); + } else { + //set valid to 5 min + Date ssoSessionValidTo = new Date(new Date().getTime() + 5 * 60 * 1000); + authData.setSsoSessionValidTo(ssoSessionValidTo); + } } - - } - - if (extractor.containsAttribute(PVPConstants.EID_AUTH_BLOCK_NAME)) { - try { - byte[] authBlock = Base64Utils.decode(extractor.getSingleAttributeValue(PVPConstants.EID_AUTH_BLOCK_NAME), false); - authData.setAuthBlock(new String(authBlock, "UTF-8")); - } catch (IOException e) { - Logger.error("Received AuthBlock is not valid", e); + //mandate functionality + MISMandate misMandate = null; + if (session.isMandateUsed()) { + //#################################################### + //set Mandate reference value + includedToGenericAuthData.remove(PVPConstants.MANDATE_REFERENCE_VALUE_NAME); + if (MiscUtil.isNotEmpty(session.getMandateReferenceValue())) + authData.setMandateReferenceValue(session.getMandateReferenceValue()); - } - } - - if (extractor.containsAttribute(PVPConstants.EID_SIGNER_CERTIFICATE_NAME)) { - try { - authData.setSignerCertificate(Base64Utils.decode( - extractor.getSingleAttributeValue(PVPConstants.EID_SIGNER_CERTIFICATE_NAME), false)); + else { + String pvpMandateRefAttr = session.getGenericDataFromSession(PVPConstants.MANDATE_REFERENCE_VALUE_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpMandateRefAttr)) { + authData.setMandateReferenceValue(pvpMandateRefAttr); + Logger.debug("Find PVP-Attr: " + PVPConstants.MANDATE_REFERENCE_VALUE_FRIENDLY_NAME); + } + } - } catch (IOException e) { - Logger.error("Received SignerCertificate is not valid", e); - } - } + /* TODO: Support SSO Mandate MODE! + * Insert functionality to translate mandates in case of SSO + */ - if (extractor.containsAttribute(PVPConstants.EID_IDENTITY_LINK_NAME)) { - try { - InputStream idlStream = Base64Utils.decodeToStream(extractor.getSingleAttributeValue(PVPConstants.EID_IDENTITY_LINK_NAME), false); - IdentityLink idl = new IdentityLinkAssertionParser(idlStream).parseIdentityLink(); - idlStream.close(); - buildOAspecificIdentityLink(oaParam, authData, idl); + //#################################################### + //set Full-mandate + misMandate = session.getMISMandate(); + if (misMandate != null ) { + //set MIS mandate to authdata + authData.setMISMandate(misMandate); + authData.setUseMandate(session.isMandateUsed()); + + } else { + String pvpFullMandateAttr = session.getGenericDataFromSession( + PVPConstants.MANDATE_FULL_MANDATE_NAME, String.class); + //check if full-mandate is available as PVP attribute + if (MiscUtil.isNotEmpty(pvpFullMandateAttr)) { + Logger.debug("Find PVP-Attr: " + PVPConstants.MANDATE_FULL_MANDATE_FRIENDLY_NAME); + try { + byte[] mandate = Base64Utils.decode(pvpFullMandateAttr, false); + misMandate = new MISMandate(); + misMandate.setMandate(mandate); + + //read Organwalter OID + String pvpRepOIDAttr = session.getGenericDataFromSession(PVPConstants.MANDATE_PROF_REP_OID_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpRepOIDAttr)) { + misMandate.setProfRep(pvpRepOIDAttr); + Logger.debug("Find PVP-Attr: " + PVPConstants.MANDATE_PROF_REP_OID_NAME); - } catch (ParseException e) { - Logger.error("Received IdentityLink is not valid", e); - - } catch (Exception e) { - Logger.error("Received IdentityLink is not valid", e); + } + + //read Organwalter bPK from full-mandate + NodeList mandateElements = misMandate.getMandateDOM().getChildNodes(); + for (int i=0; i Use single PVP attributes for mandate information."); + //check if ELGA mandates exists + String mandateType = session.getGenericDataFromSession(PVPConstants.MANDATE_TYPE_NAME, String.class); + if (MiscUtil.isNotEmpty(mandateType)) { + //switch to mandate-mode for authdata generation, because mandate-information + // is directly included in MOA-Session as PVP attributes + Logger.info("AuthDataBuilder find directly included 'MandateType' PVP-attribute." + + " --> Switch to mandate-mode for authdata generation."); + authData.setUseMandate(true); + + } + } + } + //remove PVP attributes with mandate information, because full-mandate exists + if (authData.getMISMandate() != null) { + includedToGenericAuthData.remove(PVPConstants.MANDATE_FULL_MANDATE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_TYPE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_BPK_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_TYPE_NAME); + + includedToGenericAuthData.remove(PVPConstants.MANDATE_PROF_REP_DESC_NAME); + includedToGenericAuthData.remove(PVPConstants.MANDATE_PROF_REP_OID_NAME); + } } - } - // set mandate attributes - authData.setMandateReferenceValue(extractor.getSingleAttributeValue(PVPConstants.MANDATE_REFERENCE_VALUE_NAME)); - - if (extractor.containsAttribute(PVPConstants.MANDATE_FULL_MANDATE_NAME)) { - try { - byte[] mandate = Base64Utils.decode( - (extractor.getSingleAttributeValue(PVPConstants.MANDATE_FULL_MANDATE_NAME)), false); + + + + //#################################################### + // set bPK and IdentityLink for Organwalter --> + // Organwalter has a special bPK is received from MIS + if (authData.isUseMandate() && session.isOW() && misMandate != null + && MiscUtil.isNotEmpty(misMandate.getOWbPK())) { + //TODO: if full-mandate is removed in OPB --> OWbPK functionality needs an update!!! + authData.setBPK(misMandate.getOWbPK()); + authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); + Logger.trace("Authenticated User is OW: " + misMandate.getOWbPK()); - if (authData.getMISMandate() == null) - authData.setMISMandate(new MISMandate()); - authData.getMISMandate().setMandate(mandate); - authData.getMISMandate().setFullMandateIncluded(true); - authData.setUseMandate(true); - - } catch (Exception e) { - Logger.error("Received Mandate is not valid", e); - throw new AssertionAttributeExtractorExeption(PVPConstants.MANDATE_FULL_MANDATE_NAME); - } - } - - //TODO: build short mandate if full mandate is no included. - if (authData.getMISMandate() == null && - (extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME) - || extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_BPK_NAME) - || extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME)) ) { - Logger.info("Federated assertion contains no full mandate. Start short mandate generation process ... "); - - MISMandate misMandate = new MISMandate(); - misMandate.setFullMandateIncluded(false); - - Mandate mandateObject = new Mandate(); - Mandator mandator = new Mandator(); - mandateObject.setMandator(mandator); + //TODO: check in case of mandates for business services + if (identityLink != null) + authData.setIdentityLink(identityLink); - //build legal person short mandate - if (extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME)) { - Logger.debug("Build short mandate for legal person ..."); - CorporateBodyType legalperson = new CorporateBodyType(); - IdentificationType legalID = new IdentificationType(); - Value idvalue = new Value(); - legalID.setValue(idvalue ); - legalperson.getIdentification().add(legalID ); - mandator.setCorporateBody(legalperson ); - - legalperson.setFullName(extractor.getSingleAttributeValue(PVPConstants.MANDATE_LEG_PER_FULL_NAME_NAME)); - legalID.setType(extractor.getSingleAttributeValue(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_TYPE_NAME)); - idvalue.setValue(extractor.getSingleAttributeValue(PVPConstants.MANDATE_LEG_PER_SOURCE_PIN_NAME)); - - //build natural person short mandate - } else if ( (extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_SOURCE_PIN_NAME) || - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_BPK_NAME)) && - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_BIRTHDATE_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_FAMILY_NAME_NAME) && - extractor.containsAttribute(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME)) { - Logger.debug("Build short mandate for natural person ..."); - PhysicalPersonType physPerson = new PhysicalPersonType(); - PersonNameType persName = new PersonNameType(); - mandator.setPhysicalPerson(physPerson ); - physPerson.setName(persName ); - FamilyName familyName = new FamilyName(); - persName.getFamilyName().add(familyName ); - IdentificationType persID = new IdentificationType(); - physPerson.getIdentification().add(persID ); - Value idValue = new Value(); - persID.setValue(idValue ); - - String[] pvp2GivenName = extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_GIVEN_NAME_NAME).split(" "); - for(int i=0; i pvpEncbPKAttr = getEncryptedbPKFromPVPAttribute(session, authData, oaParam); + + //check if a unique ID for this citizen exists + if (MiscUtil.isEmpty(authData.getIdentificationValue()) && + MiscUtil.isEmpty(pvpbPKValue) && MiscUtil.isEmpty(authData.getBPK()) && + pvpEncbPKAttr == null) { + Logger.info("Can not build authData, because moaSession include no bPK, encrypted bPK or baseID"); + throw new MOAIDException("builder.08", new Object[]{"No " + PVPConstants.BPK_FRIENDLY_NAME + + " or " + PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME + + " or " + PVPConstants.ENC_BPK_LIST_FRIENDLY_NAME}); + + } + + // baseID is in MOASesson --> calculate bPK directly + if (MiscUtil.isNotEmpty(authData.getIdentificationValue())) { + Logger.debug("Citizen baseID is in MOASession --> calculate bPK from this."); + Pair result = buildOAspecificbPK(protocolRequest, oaParam, authData); + authData.setBPK(result.getFirst()); + authData.setBPKType(result.getSecond()); + + //check if bPK already added to AuthData matches OA + } else if (MiscUtil.isNotEmpty(authData.getBPK()) + && matchsReceivedbPKToOnlineApplication(oaParam, authData.getBPKType()) ) { + Logger.debug("Correct bPK is already included in AuthData."); + + //check if bPK received by PVP-Attribute matches OA + } else if (MiscUtil.isNotEmpty(pvpbPKValue) && + matchsReceivedbPKToOnlineApplication(oaParam, pvpbPKTypeAttr)) { + Logger.debug("Receive correct bPK from PVP-Attribute"); + authData.setBPK(pvpbPKValue); + authData.setBPKType(pvpbPKTypeAttr); + //check if decrypted bPK exists + } else if (pvpEncbPKAttr != null) { + Logger.debug("Receive bPK as encrypted bPK and decryption was possible."); + authData.setBPK(pvpEncbPKAttr.getFirst()); + authData.setBPKType(pvpEncbPKAttr.getSecond()); + + //ask SZR to get bPK } else { - String[] pvp2bPK = extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_BPK_NAME).split(":"); - if (pvp2bPK.length == 2) { - idValue.setValue(pvp2bPK[1]); + String notValidbPK = authData.getBPK(); + String notValidbPKType = authData.getBPKType(); + if (MiscUtil.isEmpty(notValidbPK) && + MiscUtil.isEmpty(notValidbPKType)) { + notValidbPK = pvpbPKValue; + notValidbPKType = pvpbPKTypeAttr; - Pattern pattern = Pattern.compile(MOAIDAuthConstants.REGEX_PATTERN_TARGET); - Matcher matcher = pattern.matcher(pvp2bPK[0]); - if (matcher.matches()) - persID.setType(Constants.URN_PREFIX_CDID + "+" + pvp2bPK[0]); - else - persID.setType(Constants.URN_PREFIX_WBPK + "+" + pvp2bPK[0]); + if (MiscUtil.isEmpty(notValidbPK) && + MiscUtil.isEmpty(notValidbPKType)) { + Logger.fatal("No bPK in MOASession. THIS error should not occur any more."); + throw new NullPointerException("No bPK in MOASession. THIS error should not occur any more."); + } + } + + Pair baseIDFromSZR = getbaseIDFromSZR(authData, notValidbPK, notValidbPKType); + if (baseIDFromSZR != null) { + Logger.info("Receive citizen baseID from SRZ. Authentication can be completed"); + authData.setIdentificationValue(baseIDFromSZR.getFirst()); + authData.setIdentificationType(baseIDFromSZR.getSecond()); + Pair result = buildOAspecificbPK(protocolRequest, oaParam, authData); + authData.setBPK(result.getFirst()); + authData.setBPKType(result.getSecond()); } else { - Logger.warn("Receive mandator bPK from federation with an unsupported format. " + extractor.getSingleAttributeValue(PVPConstants.MANDATE_NAT_PER_BPK_NAME)); - throw new AssertionAttributeExtractorExeption("Receive mandator bPK from federation with an unsupported format."); + Logger.warn("Can not build authData, because moaSession include no valid bPK, encrypted bPK or baseID"); + throw new MOAIDException("builder.08", new Object[]{"No valid " + PVPConstants.BPK_FRIENDLY_NAME + + " or " + PVPConstants.EID_SOURCE_PIN_FRIENDLY_NAME + + " or " + PVPConstants.ENC_BPK_LIST_FRIENDLY_NAME}); } } - - } else { - Logger.error("Short mandate could not generated. Assertion contains not all attributes which are necessary."); - throw new AssertionAttributeExtractorExeption("Assertion contains not all attributes which are necessary for mandate generation", null); - - } - - try { - JAXBContext jc = JAXBContext.newInstance("at.gv.e_government.reference.namespace.mandates._20040701_"); - Marshaller m = jc.createMarshaller(); - ByteArrayOutputStream stream = new ByteArrayOutputStream(); - m.marshal(mandateObject, stream); - misMandate.setMandate(Base64Utils.encode(stream.toByteArray()).getBytes()); - stream.close(); + + //build IdentityLink + if (identityLink != null) + authData.setIdentityLink(buildOAspecificIdentityLink(oaParam, identityLink, authData.getBPK(), authData.getBPKType())); - } catch (JAXBException e) { - Logger.error("Failed to parse short mandate", e); - throw new AssertionAttributeExtractorExeption(); + else if (idlFromPVPAttr != null) { + authData.setIdentityLink(buildOAspecificIdentityLink(oaParam, idlFromPVPAttr, authData.getBPK(), authData.getBPKType())); + Logger.debug("Set IdentityLink received from federated IDP"); - } catch (IOException e) { - Logger.error("Failed to parse short mandate", e); - throw new AssertionAttributeExtractorExeption(); - - } - authData.setUseMandate(true); + } else { + Logger.info("Can NOT set IdentityLink. Msg: No IdentityLink found"); + + } + } - } - - - if (extractor.containsAttribute(PVPConstants.MANDATE_PROF_REP_OID_NAME)) { - if (authData.getMISMandate() == null) - authData.setMISMandate(new MISMandate()); - authData.getMISMandate().setProfRep( - extractor.getSingleAttributeValue(PVPConstants.MANDATE_PROF_REP_OID_NAME)); - } - - //set PVP role attribute - if (extractor.containsAttribute(PVPConstants.ROLES_NAME)) { - String pvpRoles = extractor.getSingleAttributeValue(PVPConstants.ROLES_NAME); - if (MiscUtil.isNotEmpty(pvpRoles)) { - List roles = Arrays.asList(pvpRoles.split(";")); + //################################################################### + //set PVP role attribute (implemented for ISA 1.18 action) + includedToGenericAuthData.remove(PVPConstants.ROLES_NAME); + String pvpAttrRoles = session.getGenericDataFromSession(PVPConstants.ROLES_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrRoles)) { + List roles = Arrays.asList(pvpAttrRoles.split(";")); for (String role : roles) { authData.addAuthenticationRole(AuthenticationRoleFactory.buildFormPVPole(role)); - } - } - } - - //set PVP OU attribute - if (extractor.containsAttribute(PVPConstants.OU_NAME)) { - authData.setPvpAttribute_OU(extractor.getSingleAttributeValue(PVPConstants.OU_NAME)); - Logger.debug("Found PVP 'OU' attribute in response -> " + authData.getPvpAttribute_OU()); - - } - - //set STORK attributes - if (extractor.containsAttribute(PVPConstants.EID_STORK_TOKEN_NAME)) { - try { - authData.setGenericData(AuthenticationSessionStorageConstants.STORK_RESPONSE, - extractor.getSingleAttributeValue(PVPConstants.EID_STORK_TOKEN_NAME)); - authData.setForeigner(true); - } catch (SessionDataStorageException e) { - Logger.warn("STORK Response can not stored into generic authData.", e); + } + } + + + //################################################################### + //set PVP OU attribute (implemented for ISA 1.18 action) + includedToGenericAuthData.remove(PVPConstants.OU_NAME); + String pvpAttrOUName = session.getGenericDataFromSession(PVPConstants.OU_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpAttrOUName)) { + authData.setPvpAttribute_OU(pvpAttrOUName); + Logger.debug("Found PVP 'OU' attribute in response -> " + authData.getPvpAttribute_OU()); - } + } - } - -// if (!extractor.getSTORKAttributes().isEmpty()) { -// authData.setStorkAttributes(extractor.getSTORKAttributes()); -// authData.setForeigner(true); -// -// } + //#################################################################### + //parse AuthBlock signature-verification response + //INFO: this parameters are only required for SAML1 auth. protocol + VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); + if (verifyXMLSigResp != null) { + authData.setQualifiedCertificate(verifyXMLSigResp + .isQualifiedCertificate()); + authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); + authData.setPublicAuthorityCode(verifyXMLSigResp + .getPublicAuthorityCode()); - authData.setSsoSession(true); - authData.setInterfederatedSSOSession(true); - - if (extractor.getFullAssertion().getAuthnStatements() != null - && extractor.getFullAssertion().getAuthnStatements().size() > 0) { - for (AuthnStatement el : extractor.getFullAssertion().getAuthnStatements()) { - if (el.getSessionNotOnOrAfter() != null) { - authData.setSsoSessionValidTo(el.getSessionNotOnOrAfter().toDate()); - break; - } + } else { + //set parameters in respect to QAA level + Logger.info("No authBlock signature-verfication response found. Maybe IDP federation is in use."); + if (PVPConstants.STORK_QAA_1_4.equals(authData.getQAALevel())) + authData.setQualifiedCertificate(true); + else + authData.setQualifiedCertificate(false); + authData.setPublicAuthority(false); + + } + + //#################################################################### + //copy all generic authentication information, which are not processed before to authData + Iterator copyInterator = includedToGenericAuthData.iterator(); + while (copyInterator.hasNext()) { + String elementKey = copyInterator.next(); + try { + authData.setGenericData(elementKey, session.getGenericDataFromSession(elementKey)); + + } catch (SessionDataStorageException e) { + Logger.warn("Can not add generic authData with key:" + elementKey, e); + + } } - } else { - authData.setSsoSessionValidTo(extractor.getFullAssertion().getConditions().getNotOnOrAfter().toDate()); + } catch (BuildException e) { + throw e; - } + } catch (Throwable ex) { + throw new BuildException("builder.00", new Object[]{ + "AuthenticationData", ex.toString()}, ex); + } - //only for SAML1 - if (PVPConstants.STORK_QAA_1_4.equals(authData.getQAALevel())) - authData.setQualifiedCertificate(true); - else - authData.setQualifiedCertificate(false); - authData.setPublicAuthority(false); } - + /** - * @param oaParam - * @param authData - * @return + * Check a bPK-Type against a Service-Provider configuration
+ * If bPK-Type is null the result is false. + * + * @param oaParam Service-Provider configuration, never null + * @param bPKType bPK-Type to check + * @return true, if bPK-Type matchs to Service-Provider configuration, otherwise false */ - private boolean matchsReceivedbPKToOnlineApplication( - IOAAuthParameters oaParam, AuthenticationData authData) { - + private boolean matchsReceivedbPKToOnlineApplication(IOAAuthParameters oaParam, String bPKType) { String oaTarget = null; if (oaParam.getBusinessService()) { - if (oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_WBPK) || - oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_STORK)) - oaTarget = oaParam.getIdentityLinkDomainIdentifier(); - - else { - Logger.warn("BusinessIdentifier can not be clearly assigned, because it starts without a prefix."); - return false; - - } - + oaTarget = oaParam.getIdentityLinkDomainIdentifier(); + } else { oaTarget = Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget(); } - - - if (oaTarget.equals(authData.getBPKType())) + + if (oaTarget.equals(bPKType)) return true; else return false; } - private void buildAuthDataFormMOASession(AuthenticationData authData, AuthenticationSession session, - IOAAuthParameters oaParam, IRequest protocolRequest) throws BuildException, ConfigurationException { - - IdentityLink identityLink = session.getIdentityLink(); - - VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); - - authData.setIssuer(protocolRequest.getAuthURL()); - + private void parseBasicUserInfosFromIDL(AuthenticationData authData, IdentityLink identityLink, Collection includedGenericSessionData) { //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO authData.setIdentificationValue(identityLink.getIdentificationValue()); authData.setIdentificationType(identityLink.getIdentificationType()); @@ -892,173 +841,238 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { authData.setFamilyName(identityLink.getFamilyName()); authData.setDateOfBirth(identityLink.getDateOfBirth()); - if (verifyXMLSigResp != null) { - authData.setQualifiedCertificate(verifyXMLSigResp - .isQualifiedCertificate()); - authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); - authData.setPublicAuthorityCode(verifyXMLSigResp - .getPublicAuthorityCode()); - - } else { - Logger.warn("No signature verfication response found!"); - - } - - authData.setBkuURL(session.getBkuURL()); - - //copy all generic authentication information to authData - if (session.getGenericSessionDataStorage() != null && - !session.getGenericSessionDataStorage().isEmpty()) { - Iterator> copyInterator = session.getGenericSessionDataStorage().entrySet().iterator(); - while (copyInterator.hasNext()) { - Entry element = copyInterator.next(); - try { - authData.setGenericData(element.getKey(), element.getValue()); - - } catch (SessionDataStorageException e) { - Logger.warn("Can not add generic authData with key:" + element.getKey(), e); - - } - } - } - - authData.setSignerCertificate(session.getEncodedSignerCertificate()); - authData.setAuthBlock(session.getAuthBlock()); - - authData.setForeigner(session.isForeigner()); - authData.setQAALevel(session.getQAALevel()); - - authData.setIsBusinessService(oaParam.getBusinessService()); + //remove corresponding keys from genericSessionData if exists + includedGenericSessionData.remove(PVPConstants.PRINCIPAL_NAME_NAME); + includedGenericSessionData.remove(PVPConstants.GIVEN_NAME_NAME); + includedGenericSessionData.remove(PVPConstants.BIRTHDATE_NAME); + includedGenericSessionData.remove(PVPConstants.EID_SOURCE_PIN_NAME); + includedGenericSessionData.remove(PVPConstants.EID_SOURCE_PIN_TYPE_NAME); - if (session.isForeigner()) { - try { - //TODO: replace with TSL lookup when TSL is ready! - X509Certificate certificate = new X509Certificate(authData.getSignerCertificate()); - if (certificate != null) { - LdapName ln = new LdapName(certificate.getIssuerDN() - .getName()); - for (Rdn rdn : ln.getRdns()) { - if (rdn.getType().equalsIgnoreCase("C")) { - Logger.info("C is: " + rdn.getValue()); - authData.setCcc(rdn.getValue().toString()); - break; - } - } - } + } + + /** + * @param authData + * @param notValidbPK + * @param notValidbPKType + * @return + */ + private Pair getbaseIDFromSZR(AuthenticationData authData, String notValidbPK, + String notValidbPKType) { + try { + EgovUtilPropertiesConfiguration eGovClientsConfig = authConfig.geteGovUtilsConfig(); + if (eGovClientsConfig != null) { + Logger.info("bPK in MOASession (bPK-Type:" + notValidbPKType + + " does no match to Service-Provider configuration. --> Request SZR to get correct bPK."); - } catch (Exception e) { - Logger.error("Failed to extract country code from certificate with message: " + e.getMessage()); + SZRClient szrclient = new SZRClient(eGovClientsConfig); - } - - if (MiscUtil.isEmpty(authData.getCcc())) { - String storkCCC = authData.getGenericData( - AuthenticationSessionStorageConstants.STORK_CCC, String.class); + Logger.debug("Create SZR request to get baseID ... "); + PersonInfoType personInfo = new PersonInfoType(); + at.gv.util.xsd.szr.persondata.PhysicalPersonType person = new at.gv.util.xsd.szr.persondata.PhysicalPersonType(); + personInfo.setPerson(person); + at.gv.util.xsd.szr.persondata.PersonNameType name = new at.gv.util.xsd.szr.persondata.PersonNameType(); + person.setName(name); + at.gv.util.xsd.szr.persondata.IdentificationType idValue = new at.gv.util.xsd.szr.persondata.IdentificationType(); + person.setIdentification(idValue); + + //set bPK or wbPK + idValue.setValue(authData.getBPK()); + idValue.setType(authData.getBPKType()); + + //set person information + name.setGivenName(authData.getGivenName()); + name.setFamilyName(authData.getFamilyName()); + if (authData.getDateOfBirth() != null) + person.setDateOfBirth(authData.getFormatedDateOfBirth()); + + //request szr and store baseID + return Pair.newInstance(szrclient.getStammzahl(personInfo), + Constants.URN_PREFIX_BASEID); + + } else { + Logger.debug("No SZR clieht configuration found."); + return null; - if (MiscUtil.isNotEmpty(storkCCC)) { - authData.setCcc(storkCCC); - Logger.info("Can not extract country from certificate -> Use country:" + storkCCC + " from STORK request."); - - } - } + + } catch (SZRException e) { + Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); - } else { - authData.setCcc("AT"); + } catch (at.gv.util.ex.EgovUtilException e) { + Logger.warn("SZR connection FAILED. Interfederation SSO login not possible.", e); } - try { - authData.setSsoSession(protocolRequest.needSingleSignOnFunctionality()); + return null; + } + + /** + * Add encrypted bPKs from PVP Attribute 'ENC_BPK_LIST_NAME', which could be exist in + * MOASession as 'GenericData'
session.getGenericDataFromSession(PVPConstants.ENC_BPK_LIST_NAME, String.class)
+ * to authData + * + * @param session MOASession, but never null + * @param authData AuthenticationData DAO + * @param spConfig Service-Provider configuration + * + * @return Pair which was received by PVP-Attribute and could be decrypted for this Service Provider, + * or null if no attribute exists or can not decrypted + */ + private Pair getEncryptedbPKFromPVPAttribute(AuthenticationSession session, + AuthenticationData authData, IOAAuthParameters spConfig) { + //set List of encrypted bPKs to authData DAO + String pvpEncbPKListAttr = session.getGenericDataFromSession(PVPConstants.ENC_BPK_LIST_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpEncbPKListAttr)) { + List encbPKList = Arrays.asList(pvpEncbPKListAttr.split(";")); + authData.setEncbPKList(encbPKList); - //set max. SSO session time - if (authData.isSsoSession()) { - long maxSSOSessionTime = authConfig.getSSOCreatedTimeOut() * 1000; - Date ssoSessionValidTo = new Date(session.getSessionCreated().getTime() + maxSSOSessionTime); - authData.setSsoSessionValidTo(ssoSessionValidTo); - - } else { - //set valid to 5 min - Date ssoSessionValidTo = new Date(new Date().getTime() + 5 * 60 * 1000); - authData.setSsoSessionValidTo(ssoSessionValidTo); - + //check if one of this encrypted bPK could be decrypt for this Service-Provider + for (String fullEncbPK : encbPKList) { + int index = fullEncbPK.indexOf("|"); + if (index >= 0) { + String encbPK = fullEncbPK.substring(index+1); + String second = fullEncbPK.substring(0, index); + int secIndex = second.indexOf("+"); + if (secIndex >= 0) { + if (spConfig.getTarget().equals(second.substring(secIndex+1))) { + Logger.debug("Found encrypted bPK for online-application " + + spConfig.getPublicURLPrefix() + + " Start decryption process ..."); + PrivateKey privKey = spConfig.getBPKDecBpkDecryptionKey(); + if (privKey != null) { + try { + String bPK = BPKBuilder.decryptBPK(encbPK, spConfig.getTarget(), privKey); + if (MiscUtil.isNotEmpty(bPK)) { + Logger.info("bPK decryption process finished successfully."); + return Pair.newInstance(bPK, Constants.URN_PREFIX_CDID + "+" + spConfig.getTarget()); + + } else { + Logger.error("bPK decryption FAILED."); + + } + } catch (BuildException e) { + Logger.error("bPK decryption FAILED.", e); + + } + + } else { + Logger.info("bPK decryption FAILED, because no valid decryption key is found."); + + } + + } else { + Logger.info("Found encrypted bPK but " + + "encrypted bPK target does not match to online-application target"); + + } + } + } } - - - /* TODO: Support SSO Mandate MODE! - * Insert functionality to translate mandates in case of SSO - */ + } + + return null; + } + /** + * Get bPK from PVP Attribute 'BPK_NAME', which could be exist in + * MOASession as 'GenericData'
session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class)
+ * + * @param session MOASession, but never null + * @return bPK, which was received by PVP-Attribute, or null if no attribute exists + */ + private String getbPKValueFromPVPAttribute(AuthenticationSession session) { + String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpbPKValueAttr)) { - MISMandate mandate = session.getMISMandate(); - if (session.getUseMandate() && mandate == null) { - Logger.error("Mandate is requested but NO mandate-data is found!."); - throw new BuildException("builder.00", new Object[]{ - "Mandate", "Mandate is requested but NO mandate-data is found!"}); + //fix a wrong bPK-value prefix, which was used in some PVP Standardportal implementations + if (pvpbPKValueAttr.startsWith("bPK:")) { + Logger.warn("Attribute " + PVPConstants.BPK_NAME + + " contains a not standardize prefix! Staring attribute value correction process ..."); + pvpbPKValueAttr = pvpbPKValueAttr.substring("bPK:".length()); } - authData.setMandateReferenceValue(session.getMandateReferenceValue()); - - if (mandate != null) { - //set MIS mandate to authdata - authData.setMISMandate(mandate); - authData.setUseMandate(session.getUseMandate()); - - } else { - //check if ELGA mandates exists - String mandateType = session.getGenericDataFromSession( - PVPConstants.MANDATE_TYPE_NAME, String.class); - if (MiscUtil.isNotEmpty(mandateType)) { - //switch to mandate-mode for authdata generation, because mandate-information - // is directly included in MOA-Session as PVP attributes - Logger.debug("AuthDataBuilder find directly included 'MandateType' attribute." - + " --> Switch to mandate-mode for authdata generation."); - authData.setUseMandate(true); - - } - + String[] spitted = pvpbPKValueAttr.split(":"); + if (spitted.length != 2) { + Logger.warn("Attribute " + PVPConstants.BPK_NAME + " has a wrong encoding and can NOT be USED!" + + " Value:" + pvpbPKValueAttr); + return null; } - - if (session.getUseMandate() && session.isOW() - && mandate != null && MiscUtil.isNotEmpty(mandate.getOWbPK())) { - authData.setBPK(mandate.getOWbPK()); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); - - //TODO: check in case of mandates for business services - authData.setIdentityLink(identityLink); - Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); - - } else { - buildOAspecificbPK(protocolRequest, oaParam, authData, - identityLink.getIdentificationValue(), - identityLink.getIdentificationType()); - - buildOAspecificIdentityLink(oaParam, authData, identityLink); - - } + Logger.debug("Find PVP-Attr: " + PVPConstants.BPK_FRIENDLY_NAME); + return spitted[1]; - //TODO - } catch (BuildException e) { - throw e; + } + + return null; + } + + /** + * Get bPK-Type from PVP Attribute 'EID_SECTOR_FOR_IDENTIFIER_NAME', which could be exist in + * MOASession as 'GenericData'
session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class)
+ * + * @param session MOASession, but never null + * @return bPKType, which was received by PVP-Attribute, or null if no attribute exists + */ + private String getbPKTypeFromPVPAttribute(AuthenticationSession session) { + String pvpbPKTypeAttr = session.getGenericDataFromSession(PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, String.class); + if (MiscUtil.isNotEmpty(pvpbPKTypeAttr)) { - } catch (Throwable ex) { - throw new BuildException("builder.00", new Object[]{ - "AuthenticationData", ex.toString()}, ex); - } + //fix a wrong bPK-Type encoding, which was used in some PVP Standardportal implementations + if (pvpbPKTypeAttr.startsWith(Constants.URN_PREFIX_CDID) && + !pvpbPKTypeAttr.substring(Constants.URN_PREFIX_CDID.length(), + Constants.URN_PREFIX_CDID.length() + 1).equals("+")) { + Logger.warn("Receive uncorrect encoded bBKType attribute " + pvpbPKTypeAttr + " Starting attribute value correction ... "); + pvpbPKTypeAttr = Constants.URN_PREFIX_CDID + "+" + pvpbPKTypeAttr.substring(Constants.URN_PREFIX_CDID.length() + 1); + + } + Logger.debug("Find PVP-Attr: " + PVPConstants.EID_SECTOR_FOR_IDENTIFIER_FRIENDLY_NAME); + return pvpbPKTypeAttr; + } + + return null; + + + /* + * INFO: This code could be used to extract the bPKType from 'PVPConstants.BPK_NAME', + * because the prefix of BPK_NAME attribute contains the postfix of the bPKType + * + * Now, all PVP Standardportals should be able to send 'EID_SECTOR_FOR_IDENTIFIER' + * PVP attributes + */ +// String pvpbPKValueAttr = session.getGenericDataFromSession(PVPConstants.BPK_NAME, String.class); +// String[] spitted = pvpbPKValueAttr.split(":"); +// if (MiscUtil.isEmpty(authData.getBPKType())) { +// Logger.debug("PVP assertion contains NO bPK/wbPK target attribute. " + +// "Starting target extraction from bPK/wbPK prefix ..."); +// //exract bPK/wbPK type from bpk attribute value prefix if type is +// //not transmitted as single attribute +// Pattern pattern = Pattern.compile("[a-zA-Z]{2}(-[a-zA-Z]+)?"); +// Matcher matcher = pattern.matcher(spitted[0]); +// if (matcher.matches()) { +// //find public service bPK +// authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + spitted[0]); +// Logger.debug("Found bPK prefix. Set target to " + authData.getBPKType()); +// +// } else { +// //find business service wbPK +// authData.setBPKType(Constants.URN_PREFIX_WBPK+ "+" + spitted[0]); +// Logger.debug("Found wbPK prefix. Set target to " + authData.getBPKType()); +// +// } +// } } - - private void buildOAspecificIdentityLink(IOAAuthParameters oaParam, AuthenticationData authData, IdentityLink idl) throws MOAIDException { + + private IdentityLink buildOAspecificIdentityLink(IOAAuthParameters oaParam, IdentityLink idl, String bPK, String bPKType) throws MOAIDException { if (oaParam.getBusinessService()) { Element idlassertion = idl.getSamlAssertion(); //set bpk/wpbk; Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - prIdentification.getFirstChild().setNodeValue(authData.getBPK()); + prIdentification.getFirstChild().setNodeValue(bPK); //set bkp/wpbk type Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); - prIdentificationType.getFirstChild().setNodeValue(authData.getBPKType()); + prIdentificationType.getFirstChild().setNodeValue(bPKType); IdentityLinkAssertionParser idlparser = new IdentityLinkAssertionParser(idlassertion); IdentityLink businessServiceIdl = idlparser.parseIdentityLink(); @@ -1073,62 +1087,70 @@ public class AuthenticationDataBuilder extends MOAIDAuthConstants { resignedilAssertion = businessServiceIdl.getSamlAssertion(); } IdentityLinkAssertionParser resignedIDLParser = new IdentityLinkAssertionParser(resignedilAssertion); - IdentityLink resignedIDL = resignedIDLParser.parseIdentityLink(); + return resignedIDLParser.parseIdentityLink(); - authData.setIdentityLink(resignedIDL); - } else - authData.setIdentityLink(idl); + return idl; } - - private void buildOAspecificbPK(IRequest protocolRequest, IOAAuthParameters oaParam, AuthenticationData authData, String baseID, String baseIDType) throws BuildException { - - if (oaParam.getBusinessService()) { - //since we have foreigner, wbPK is not calculated in BKU - if (baseIDType.equals(Constants.URN_PREFIX_BASEID)) { - String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); - authData.setBPK(new BPKBuilder().buildbPKorwbPK(baseID, registerAndOrdNr)); - authData.setBPKType(registerAndOrdNr); - - } else { - authData.setBPK(baseID); - authData.setBPKType(baseIDType); - - } - Logger.trace("Authenticate user with wbPK " + authData.getBPK()); - - } else { - if (baseIDType.equals(Constants.URN_PREFIX_BASEID)) { - // only compute bPK if online application is a public service and we have the Stammzahl - String target = null; - Object saml1Requst = null; - try { - saml1Requst = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl").newInstance(); - - } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | java.lang.SecurityException ex) { - - - } - - if (saml1Requst != null && protocolRequest.getClass().isInstance(saml1Requst)) - target = protocolRequest.getGenericData( - MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, String.class); - else - target = oaParam.getTarget(); - - String bpkBase64 = new BPKBuilder().buildBPK(baseID, target); - authData.setBPK(bpkBase64); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + target); - } + private Pair buildOAspecificbPK(IRequest pendingReq, IOAAuthParameters oaParam, AuthenticationData authData) throws BuildException { + + String bPK; + String bPKType; - Logger.trace("Authenticate user with bPK " + authData.getBPK()); - } + String baseID = authData.getIdentificationValue(); + String baseIDType = authData.getIdentificationType(); + + String eIDASOutboundCountry = pendingReq.getGenericData(RequestImpl.eIDAS_GENERIC_REQ_DATA_COUNTRY, String.class); + if (Constants.URN_PREFIX_BASEID.equals(baseIDType)) { + if (MiscUtil.isNotEmpty(eIDASOutboundCountry) && !COUNTRYCODE_AUSTRIA.equals(eIDASOutboundCountry)) { + Pair eIDASID = new BPKBuilder().buildeIDASIdentifer(baseIDType, baseID, + COUNTRYCODE_AUSTRIA, eIDASOutboundCountry); + Logger.trace("Authenticate user with bPK:" + eIDASID.getFirst() + " Type:" + eIDASID.getSecond()); + return eIDASID; + + } else if (oaParam.getBusinessService()) { + //is Austrian private-service application + String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); + bPK = new BPKBuilder().buildbPKorwbPK(baseID, registerAndOrdNr); + bPKType = registerAndOrdNr; + + } else { + // only compute bPK if online application is a public service and we have the Stammzahl + String target = null; + Class saml1RequstTemplate = null; + try { + saml1RequstTemplate = Class.forName("at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl"); + if (saml1RequstTemplate != null && + saml1RequstTemplate.isInstance(pendingReq)) { + target = (String) pendingReq.getClass().getMethod("getTarget").invoke(pendingReq); + + } + + } catch (ClassNotFoundException | IllegalAccessException | IllegalArgumentException | java.lang.SecurityException | InvocationTargetException | NoSuchMethodException ex) { } + + if (MiscUtil.isEmpty(target)) + target = oaParam.getTarget(); + + bPK = new BPKBuilder().buildBPK(baseID, target); + bPKType = Constants.URN_PREFIX_CDID + "+" + target; + + } + + } else { + Logger.warn("!!!baseID-element does not include a baseID. This should not be happen any more!!!"); + bPK = baseID; + bPKType = baseIDType; + + } + Logger.trace("Authenticate user with bPK:" + bPK + " Type:" + bPKType); + return Pair.newInstance(bPK, bPKType); + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java index 1cf6929e6..9e4e36fec 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java @@ -46,13 +46,6 @@ package at.gv.egovernment.moa.id.auth.builder; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Base64Utils; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.MiscUtil; - import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -66,6 +59,13 @@ import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; +import at.gv.egovernment.moa.id.auth.exception.BuildException; +import at.gv.egovernment.moa.id.data.Pair; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.Base64Utils; +import at.gv.egovernment.moa.util.Constants; +import at.gv.egovernment.moa.util.MiscUtil; + /** * Builder for the bPK, as defined in * "Ableitung f¨r die bereichsspezifische Personenkennzeichnung" @@ -203,73 +203,42 @@ public class BPKBuilder { /** * Builds the storkeid from the given parameters. * - * @param identityLink identity link - * @param destinationCountry destination country code (2 chars) - * @return storkid in a BASE64 encoding - * @throws BuildException if an error occurs on building the wbPK - */ - public String buildStorkeIdentifier(IdentityLink identityLink, String destinationCountry) - throws BuildException { - return buildStorkbPK(identityLink.getIdentificationValue(), - identityLink.getIdentificationType(), "AT", destinationCountry); - } - - /** - * Builds the storkeid from the given parameters. - * - * @param identityLink identity link - * @param destinationCountry destination country code (2 chars) - * @return storkid in a BASE64 encoding - * @throws BuildException if an error occurs on building the wbPK - */ - public String buildStorkeIdentifier(String identificationType, String identificationValue, String destinationCountry) - throws BuildException { - return buildStorkbPK(identificationValue, identificationType, "AT", destinationCountry); - } - - /** - * Builds the storkeid from the given parameters. - * - * @param identityLink identity link - * @param sourceCountry source country code (2 chars) - * @param destinationCountry destination country code (2 chars) - * @return storkid in a BASE64 encoding + * @param baseID baseID of the citizen + * @param baseIDType Type of the baseID + * @param sourceCountry CountryCode of that country, which build the eIDAs ID + * @param destinationCountry CountryCode of that country, which receives the eIDAs ID + * + * @return Pair in a BASE64 encoding * @throws BuildException if an error occurs on building the wbPK */ - public String buildStorkbPK(String baseID, String baseIDType, String sourceCountry, String destinationCountry) - throws BuildException { - String identificationValue = null; - + public Pair buildeIDASIdentifer(String baseID, String baseIDType, String sourceCountry, String destinationCountry) + throws BuildException { + String bPK = null; + String bPKType = null; + // check if we have been called by public sector application - if (baseIDType.startsWith(Constants.URN_PREFIX_BASEID)) { - identificationValue = calculateStorkeIdentifierBase(baseID, sourceCountry, destinationCountry); + if (baseIDType.startsWith(Constants.URN_PREFIX_BASEID)) { + bPKType = Constants.URN_PREFIX_EIDAS + "+" + sourceCountry + "+" + destinationCountry; + Logger.debug("Building eIDAS identification from: [identValue]+" + bPKType); + bPK = calculatebPKwbPK(baseID + "+" + bPKType); } else { // if not, sector identification value is already calculated by BKU - Logger.debug("STORK eIdentifier already provided by BKU"); - identificationValue = baseID; + Logger.debug("eIDAS eIdentifier already provided by BKU"); + bPK = baseID; } - if ((identificationValue == null || - identificationValue.length() == 0 || - destinationCountry == null || - destinationCountry.length() == 0 || - sourceCountry == null || - sourceCountry.length() == 0)) { + if ((MiscUtil.isEmpty(bPK) || + MiscUtil.isEmpty(sourceCountry) || + MiscUtil.isEmpty(destinationCountry))) { throw new BuildException("builder.00", - new Object[]{"storkid", "Unvollständige Parameterangaben: identificationValue=" + - identificationValue + ", Zielland=" + destinationCountry + ", Ursprungsland=" + sourceCountry}); + new Object[]{"eIDAS-ID", "Unvollständige Parameterangaben: identificationValue=" + + bPK + ", Zielland=" + destinationCountry + ", Ursprungsland=" + sourceCountry}); } - Logger.info("Building STORK identification from: " + sourceCountry+"/"+destinationCountry+"/" + "[identValue]"); - String eIdentifier = sourceCountry+"/"+destinationCountry+"/"+identificationValue; - - return eIdentifier; - } - - private String calculateStorkeIdentifierBase(String baseID, String sourceCountry, String destinationCountry) throws BuildException { - String basisbegriff = baseID + "+" + Constants.URN_PREFIX_STORK + "+" + sourceCountry + "+" + destinationCountry; - Logger.debug("Building STORK identification from: [identValue]+" + Constants.URN_PREFIX_STORK + "+" + sourceCountry + "+" + destinationCountry); - return calculatebPKwbPK(basisbegriff); + Logger.debug("Building eIDAS identification from: " + sourceCountry+"/"+destinationCountry+"/" + "[identValue]"); + String eIdentifier = sourceCountry + "/" + destinationCountry + "/" + bPK; + + return Pair.newInstance(eIdentifier, baseIDType); } private String calculatebPKwbPK(String basisbegriff) throws BuildException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java index 648dcf6f1..4a764e362 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSessionStorageConstants.java @@ -38,5 +38,7 @@ public class AuthenticationSessionStorageConstants { public static final String eIDAS_ATTRIBUTELIST = PREFIX_eIDAS + "attributeList"; public static final String eIDAS_RESPONSE = PREFIX_eIDAS + "response"; + + public static final String FEDERATION_RESPONSE_VALIDE_TO = "federationRespValidTo"; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java index b7e95785b..a4abbbcfa 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java @@ -78,20 +78,20 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ //check UseMandate flag - String useMandateString = null; - boolean useMandateBoolean = false; + String useMISMandateString = null; + boolean useMISMandateBoolean = false; if ((useMandate != null) && (useMandate.compareTo("") != 0)) { - useMandateString = useMandate; + useMISMandateString = useMandate; } else { - useMandateString = "false"; + useMISMandateString = "false"; } - if (useMandateString.compareToIgnoreCase("true") == 0) - useMandateBoolean = true; + if (useMISMandateString.compareToIgnoreCase("true") == 0) + useMISMandateBoolean = true; else - useMandateBoolean = false; + useMISMandateBoolean = false; - moasession.setUseMandate(useMandateString); + moasession.setUseMandate(useMISMandateString); //load OnlineApplication configuration @@ -155,7 +155,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ } else { Logger.debug("Service-Provider is of type 'PrivateService' with DomainIdentifier:" + oaParam.getIdentityLinkDomainIdentifier()); - if (useMandateBoolean) { + if (useMISMandateBoolean) { Logger.error("Online-Mandate Mode for business application not supported."); throw new AuthenticationException("auth.17", null); } @@ -213,6 +213,12 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ protocolReq.setNeedSingleSignOnFunctionality(false); } + if (protocolReq.needSingleSignOnFunctionality() && useMISMandateBoolean) { + Logger.info("Usage of MIS-MandateService does not allow Single Sign-On. --> SSO is disabled for this request."); + protocolReq.setNeedSingleSignOnFunctionality(false); + + } + } public void parse(ExecutionContext ec, HttpServletRequest req, diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java index 53be0881b..aa9a0824d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java @@ -147,8 +147,8 @@ public class AuthenticationData implements IAuthData, Serializable { private boolean ssoSession = false; private Date ssoSessionValidTo = null; - private boolean interfederatedSSOSession = false; - private String interfederatedIDP = null; +// private boolean interfederatedSSOSession = false; +// private String interfederatedIDP = null; private String sessionIndex = null; private String nameID = null; @@ -255,16 +255,18 @@ public class AuthenticationData implements IAuthData, Serializable { } /** - * Returns the identificationValue. - * @return String + * Holds the baseID of a citizen + * + * @return baseID */ public String getIdentificationValue() { return identificationValue; } /** - * Returns the identificationType - * @return String + * Holds the type of the baseID + * + * @return baseID-Type */ public String getIdentificationType() { return identificationType; @@ -439,6 +441,10 @@ public class AuthenticationData implements IAuthData, Serializable { } public Element getMandate() { + if (mandate == null) + return null; + + //parse Element from mandate XML try { byte[] byteMandate = mandate.getMandate(); String stringMandate = new String(byteMandate); @@ -579,7 +585,9 @@ public class AuthenticationData implements IAuthData, Serializable { } /** - * @return the ccc + * CountryCode of the citizen which is identified and authenticated + * + * @return the CountryCode
like. AT, SI, ...
*/ public String getCcc() { return ccc; @@ -635,33 +643,33 @@ public class AuthenticationData implements IAuthData, Serializable { this.nameIDFormat = nameIDFormat; } - /** - * @return the interfederatedSSOSession - */ - public boolean isInterfederatedSSOSession() { - return interfederatedSSOSession; - } - - /** - * @param interfederatedSSOSession the interfederatedSSOSession to set - */ - public void setInterfederatedSSOSession(boolean interfederatedSSOSession) { - this.interfederatedSSOSession = interfederatedSSOSession; - } - - /** - * @return the interfederatedIDP - */ - public String getInterfederatedIDP() { - return interfederatedIDP; - } - - /** - * @param interfederatedIDP the interfederatedIDP to set - */ - public void setInterfederatedIDP(String interfederatedIDP) { - this.interfederatedIDP = interfederatedIDP; - } +// /** +// * @return the interfederatedSSOSession +// */ +// public boolean isInterfederatedSSOSession() { +// return interfederatedSSOSession; +// } +// +// /** +// * @param interfederatedSSOSession the interfederatedSSOSession to set +// */ +// public void setInterfederatedSSOSession(boolean interfederatedSSOSession) { +// this.interfederatedSSOSession = interfederatedSSOSession; +// } +// +// /** +// * @return the interfederatedIDP +// */ +// public String getInterfederatedIDP() { +// return interfederatedIDP; +// } +// +// /** +// * @param interfederatedIDP the interfederatedIDP to set +// */ +// public void setInterfederatedIDP(String interfederatedIDP) { +// this.interfederatedIDP = interfederatedIDP; +// } /** * @return the ssoSessionValidTo diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java index 91d40fcc3..c32564679 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/IAuthData.java @@ -40,7 +40,7 @@ public interface IAuthData { boolean isBusinessService(); boolean isSsoSession(); - boolean isInterfederatedSSOSession(); + //boolean isInterfederatedSSOSession(); boolean isUseMandate(); String getFamilyName(); @@ -53,7 +53,7 @@ public interface IAuthData { Date getSsoSessionValidTo(); - String getInterfederatedIDP(); + //String getInterfederatedIDP(); String getIdentificationValue(); String getIdentificationType(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java index 12fe3c948..81157994e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/MISMandate.java @@ -79,7 +79,7 @@ public class MISMandate implements Serializable{ private String oid = null; private byte[] mandate = null; private String owBPK = null; - private boolean isFullMandateIncluded = false; +// private boolean isFullMandateIncluded = false; public String getProfRep() { return oid; @@ -144,18 +144,18 @@ public class MISMandate implements Serializable{ } } - /** - * @return the isFullMandateIncluded - */ - public boolean isFullMandateIncluded() { - return isFullMandateIncluded; - } - /** - * @param isFullMandateIncluded the isFullMandateIncluded to set - */ - public void setFullMandateIncluded(boolean isFullMandateIncluded) { - this.isFullMandateIncluded = isFullMandateIncluded; - } +// /** +// * @return the isFullMandateIncluded +// */ +// public boolean isFullMandateIncluded() { +// return isFullMandateIncluded; +// } +// /** +// * @param isFullMandateIncluded the isFullMandateIncluded to set +// */ +// public void setFullMandateIncluded(boolean isFullMandateIncluded) { +// this.isFullMandateIncluded = isFullMandateIncluded; +// } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java new file mode 100644 index 000000000..78e8be452 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/Trible.java @@ -0,0 +1,51 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.data; + +public class Trible { + private final P1 first; + private final P2 second; + private final P3 third; + + private Trible(final P1 newFirst, final P2 newSecond, final P3 newThird) { + this.first = newFirst; + this.second = newSecond; + this.third = newThird; + } + + public P1 getFirst() { + return this.first; + } + + public P2 getSecond() { + return this.second; + } + + public P3 getThird() { + return this.third; + } + + public static Trible newInstance(final P1 newFirst, final P2 newSecond, final P3 newThird) { + return new Trible(newFirst, newSecond, newThird); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 21ef38732..f065bbc56 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -72,7 +72,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.SingleLogOutBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.MOASAMLSOAPClient; -import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngineSP; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.storage.ITransactionStorage; @@ -100,7 +100,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { @Autowired private MOAReversionLogger revisionsLogger; @Autowired protected AuthConfiguration authConfig; @Autowired private SingleLogOutBuilder sloBuilder; - @Autowired private SAMLVerificationEngine samlVerificationEngine; + @Autowired private SAMLVerificationEngineSP samlVerificationEngine; public void performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index e05bedac8..aec5ad124 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -48,7 +48,10 @@ public abstract class RequestImpl implements IRequest, Serializable{ public static final String DATAID_INTERFEDERATIOIDP_URL = "interIDPURL"; public static final String DATAID_INTERFEDERATIOIDP_RESPONSE = "interIDPResponse"; - public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; + public static final String DATAID_REQUESTED_ATTRIBUTES = "requestedAttributes"; + public static final String DATAID_INTERFEDERATIOIDP_ENTITYID = "interIDPEntityID"; + + public static final String eIDAS_GENERIC_REQ_DATA_COUNTRY = "country"; private static final long serialVersionUID = 1L; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java index 7cbdeca66..0e6dc1838 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java @@ -26,7 +26,6 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java index 0437cd687..69f0c3088 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java @@ -23,7 +23,6 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributePolicyException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java index 27d3845ff..ca66700a2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java @@ -26,10 +26,7 @@ import java.io.IOException; import javax.xml.transform.TransformerException; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.NoMandateDataAttributeException; @@ -48,7 +45,7 @@ public class MandateFullMandateAttributeBuilder implements IPVPAttributeBuilder if (authData.isUseMandate()) { //only provide full mandate if it is included. //In case of federation only a short mandate could be include - if (authData.getMandate() != null && authData.getMISMandate().isFullMandateIncluded()) { + if (authData.getMandate() != null) { String fullMandate; try { fullMandate = DOMUtils.serializeNode(authData diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java index 8948f1227..55c864335 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateNaturalPersonGivenNameAttributeBuilder.java @@ -46,7 +46,7 @@ public class MandateNaturalPersonGivenNameAttributeBuilder implements IPVPAttrib IAttributeGenerator g) throws AttributeException { if (authData.isUseMandate()) { //get PVP attribute directly, if exists - String givenName = authData.getGenericData(MANDATE_NAT_PER_BPK_NAME, String.class); + String givenName = authData.getGenericData(MANDATE_NAT_PER_GIVEN_NAME_NAME, String.class); if (MiscUtil.isEmpty(givenName)) { Element mandate = authData.getMandate(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java index 042eeeed8..142810d45 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AttributQueryAction.java @@ -25,6 +25,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x; import java.util.ArrayList; import java.util.Arrays; +import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; @@ -44,23 +45,28 @@ import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; import at.gv.egovernment.moa.id.auth.builder.DynamicOAAuthParameterBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.data.FederatedAuthenticatenContainer; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; +import at.gv.egovernment.moa.id.data.Trible; import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.SoapBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz @@ -72,7 +78,7 @@ public class AttributQueryAction implements IAction { @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; @Autowired private AuthenticationDataBuilder authDataBuilder; @Autowired private IDPCredentialProvider pvpCredentials; - @Autowired private ITransactionStorage transactionStorage; + @Autowired private AuthConfiguration authConfig; private final static List DEFAULTSTORKATTRIBUTES = Arrays.asList( new String[]{PVPConstants.EID_STORK_TOKEN_NAME}); @@ -98,34 +104,44 @@ public class AttributQueryAction implements IAction { //set time reference DateTime date = new DateTime(); - //get Single Sign-On information for the Service-Provider - // which sends the Attribute-Query request - AuthenticationSession moaSession = authenticationSessionStorage.getSession(pendingReq.getMOASessionIdentifier()); - if (moaSession == null) { - Logger.warn("No MOASession with ID:" + pendingReq.getMOASessionIdentifier() + " FOUND."); - throw new MOAIDException("auth.02", new Object[]{pendingReq.getMOASessionIdentifier()}); - } - - InterfederationSessionStore nextIDPInformation = - authenticationSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(moaSession.getSessionID()); - - AttributeQuery attrQuery = - (AttributeQuery)((MOARequest)((PVPTargetConfiguration) pendingReq).getRequest()).getSamlRequest(); + try { + //get Single Sign-On information for the Service-Provider + // which sends the Attribute-Query request + AuthenticationSession moaSession = authenticationSessionStorage.getSession(pendingReq.getMOASessionIdentifier()); + if (moaSession == null) { + Logger.warn("No MOASession with ID:" + pendingReq.getMOASessionIdentifier() + " FOUND."); + throw new MOAIDException("auth.02", new Object[]{pendingReq.getMOASessionIdentifier()}); + } - //generate authData for AttributQueryRequest - authData = authDataBuilder.buildAuthenticationDataForAttributQuery(pendingReq, moaSession, attrQuery.getAttributes(), nextIDPInformation); - + InterfederationSessionStore nextIDPInformation = + authenticationSessionStorage.searchInterfederatedIDPFORAttributeQueryWithSessionID(moaSession.getSessionID()); - //add default attributes in case of mandates or STORK is in use - List attrList = addDefaultAttributes(attrQuery, authData); + AttributeQuery attrQuery = + (AttributeQuery)((MOARequest)((PVPTargetConfiguration) pendingReq).getRequest()).getSamlRequest(); + + //build PVP 2.1 response-attribute information for this AttributQueryRequest + Trible, Date, String> responseInfo = + buildResponseInformationForAttributQuery(pendingReq, moaSession, attrQuery.getAttributes(), nextIDPInformation); - //build PVP 2.1 assertion - Assertion assertion = PVP2AssertionBuilder.buildAssertion(req, attrQuery, attrList, authData, date, authData.getSessionIndex()); - - //build PVP 2.1 response - Response authResponse = AuthResponseBuilder.buildResponse(req.getAuthURL(), attrQuery, date, assertion); - - try { + Logger.debug("AttributQuery return " + responseInfo.getFirst().size() + + " attributes with QAA-Level:" + responseInfo.getThird() + + " validTo:" + responseInfo.getSecond().toString()); + + //build PVP 2.1 assertion + + String issuerEntityID = pendingReq.getAuthURL(); + if (issuerEntityID.endsWith("/")) + issuerEntityID = issuerEntityID.substring(0, issuerEntityID.length()-1); + + Assertion assertion = PVP2AssertionBuilder.buildAssertion(issuerEntityID, + attrQuery, responseInfo.getFirst(), date, new DateTime(responseInfo.getSecond().getTime()), + responseInfo.getThird(), authData.getSessionIndex()); + + //build PVP 2.1 response + Response authResponse = AuthResponseBuilder.buildResponse( + MOAMetadataProvider.getInstance(), issuerEntityID, attrQuery, date, + assertion, authConfig.isPVP2AssertionEncryptionActive()); + SoapBinding decoder = new SoapBinding(); decoder.encodeRespone(httpReq, httpResp, authResponse, null, null, pvpCredentials.getIDPAssertionSigningCredential()); @@ -139,6 +155,11 @@ public class AttributQueryAction implements IAction { Logger.error("Security exception", e); throw new MOAIDException("pvp2.01", null, e); + } catch (MOADatabaseException e) { + Logger.error("MOASession with SessionID=" + pendingReq.getMOASessionIdentifier() + + " is not found in Database", e); + throw new MOAIDException("init.04", new Object[] { pendingReq.getMOASessionIdentifier() }); + } } else { @@ -164,32 +185,143 @@ public class AttributQueryAction implements IAction { public String getDefaultActionName() { return PVP2XProtocol.ATTRIBUTEQUERY; } + + private Trible, Date, String> buildResponseInformationForAttributQuery(IRequest pendingReq, + AuthenticationSession session, List reqAttributes, InterfederationSessionStore nextIDPInformation) throws MOAIDException { + try { + //mark AttributeQuery as used if it exists + OASessionStore activeOA = authenticationSessionStorage.searchActiveOASSOSession(session, pendingReq.getOAURL(), pendingReq.requestedModule()); + if (activeOA != null) { + //mark + if ( pendingReq instanceof PVPTargetConfiguration && + ((PVPTargetConfiguration) pendingReq).getRequest() instanceof MOARequest && + ((PVPTargetConfiguration) pendingReq).getRequest().getInboundMessage() instanceof AttributeQuery) { + try { + activeOA.setAttributeQueryUsed(true); + MOASessionDBUtils.saveOrUpdate(activeOA); + + } catch (MOADatabaseException e) { + Logger.error("MOASession interfederation information can not stored to database.", e); + + } + } + } + + //build OnlineApplication dynamic from requested attributes (AttributeQuerry Request) and configuration + IOAAuthParameters spConfig = DynamicOAAuthParameterBuilder.buildFromAttributeQuery(reqAttributes); + + //search federated IDP information for this MOASession + if (nextIDPInformation != null) { + Logger.info("Find active federated IDP information." + + ". --> Request next IDP:" + nextIDPInformation.getIdpurlprefix() + + " for authentication information."); + + //load configuration of next IDP + OAAuthParameter idp = authConfig.getOnlineApplicationParameter(nextIDPInformation.getIdpurlprefix()); + if (idp == null) { + Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() + + "is not loadable."); + throw new MOAIDException("auth.32", new Object[]{nextIDPInformation.getIdpurlprefix()}); + + } + + //check if next IDP config allows inbound messages + if (!idp.isInboundSSOInterfederationAllowed()) { + Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() + + "disallow inbound authentication messages."); + throw new MOAIDException("auth.33", new Object[]{nextIDPInformation.getIdpurlprefix()}); + + } + + //check next IDP service area policy. BusinessService IDPs can only request wbPKs + if (!spConfig.getBusinessService() && !idp.isIDPPublicService()) { + Logger.error("Interfederated IDP " + idp.getPublicURLPrefix() + + " has a BusinessService-IDP but requests PublicService attributes."); + throw new MOAIDException("auth.34", new Object[]{nextIDPInformation.getIdpurlprefix()}); + + } + + //validation complete --> start AttributeQuery Request + AssertionAttributeExtractor extractor = authDataBuilder.getAuthDataFromAttributeQuery(reqAttributes, + nextIDPInformation.getUserNameID(), idp); + + try { + //mark attribute request as used + if (nextIDPInformation.isStoreSSOInformation()) { + nextIDPInformation.setAttributesRequested(true); + MOASessionDBUtils.saveOrUpdate(nextIDPInformation); - private List addDefaultAttributes(AttributeQuery query, IAuthData authData) { + //delete federated IDP from Session + } else { + MOASessionDBUtils.delete(nextIDPInformation); + + } + + } catch (MOADatabaseException e) { + Logger.error("MOASession interfederation information can not stored to database.", e); + + } + + return Trible.newInstance( + extractor.getAllResponseAttributesFromFirstAttributeStatement(), + extractor.getAssertionNotOnOrAfter(), + extractor.getQAALevel()); + + } else { + Logger.debug("Build authData for AttributQuery from local MOASession."); + IAuthData authData = authDataBuilder.buildAuthenticationData(pendingReq, session, spConfig); + + //add default attributes in case of mandates or STORK is in use + List attrList = addDefaultAttributes(reqAttributes, authData); + + //build Set of response attributes + List respAttr = PVPAttributeBuilder.buildSetOfResponseAttributes(authData, attrList); + + return Trible.newInstance(respAttr, authData.getSsoSessionValidTo(), authData.getQAALevel()); + + } + + } catch (MOAIDException e) { + throw e; + } + } + + /** + * Add additional PVP Attribute-Names in respect to current MOASession. + *

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

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

+ * Like: 'urn:publicid:gv.at:cdid+BF' + * + * @return qualifier, or null if no qualifier should be set + */ + public String getSubjectNameIDQualifier(); + /** * Define the format of the subjectNameID, which is included in authn-request * @@ -125,5 +134,13 @@ public interface IPVPAuthnRequestBuilderConfiguruation { * @return nameIDFormat, of SAML2 'transient' if nothing is defined */ public String getSubjectNameIDFormat(); + + /** + * Define a SP specific SAMK2 requestID + * + * @return requestID, or null if the requestID should be generated automatically + */ + public String getRequestID(); + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java index bbf395a6f..58210a72c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/PVPConfiguration.java @@ -28,7 +28,6 @@ import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.Properties; import java.util.jar.Attributes; import java.util.jar.Manifest; @@ -92,18 +91,18 @@ public class PVPConfiguration { private static String moaIDVersion = null; //PVP2 generalpvpconfigdb; - Properties props; - String rootDir = null; + //Properties props; + //String rootDir = null; private PVPConfiguration() { - try { - //generalpvpconfigdb = AuthConfigurationProvider.getInstance().getGeneralPVP2DBConfig(); - props = AuthConfigurationProviderFactory.getInstance().getGeneralPVP2ProperiesConfig(); - rootDir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); - - } catch (ConfigurationException e) { - e.printStackTrace(); - } +// try { +// //generalpvpconfigdb = AuthConfigurationProvider.getInstance().getGeneralPVP2DBConfig(); +// //props = AuthConfigurationProviderFactory.getInstance().getGeneralPVP2ProperiesConfig(); +// //rootDir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); +// +// } catch (ConfigurationException e) { +// e.printStackTrace(); +// } } public List getIDPPublicPath() throws ConfigurationException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java new file mode 100644 index 000000000..3da4dc18a --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/IMOARefreshableMetadataProvider.java @@ -0,0 +1,38 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.pvp2x.metadata; + +/** + * @author tlenz + * + */ +public interface IMOARefreshableMetadataProvider { + + /** + * Refresh a entity or load a entity in a metadata provider + * + * @param entityID + * @return true, if refresh is success, otherwise false + */ + public boolean refreshMetadataProvider(String entityID); +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java index 6e87abb06..618346485 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/MOAMetadataProvider.java @@ -59,7 +59,7 @@ import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; public class MOAMetadataProvider extends SimpleMOAMetadataProvider - implements ObservableMetadataProvider, IGarbageCollectorProcessing { + implements ObservableMetadataProvider, IGarbageCollectorProcessing, IMOARefreshableMetadataProvider { private static MOAMetadataProvider instance = null; private static Object mutex = new Object(); @@ -118,6 +118,7 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider MetadataProvider internalProvider; + @Override public boolean refreshMetadataProvider(String entityID) { try { OAAuthParameter oaParam = diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java index 8787df82d..106be8a09 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/utils/AssertionAttributeExtractor.java @@ -25,6 +25,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.utils; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -53,9 +54,18 @@ public class AssertionAttributeExtractor { private final List minimalAttributeNameList = Arrays.asList( PVPConstants.PRINCIPAL_NAME_NAME, - PVPConstants.GIVEN_NAME_NAME); - - + PVPConstants.GIVEN_NAME_NAME, + PVPConstants.ENC_BPK_LIST_NAME, + PVPConstants.BPK_NAME); + + /** + * Parse the SAML2 Response element and extracts included information + *

+ * INFO: Actually, only the first SAML2 Assertion of the SAML2 Response is used! + * + * @param samlResponse SAML2 Response + * @throws AssertionAttributeExtractorExeption + */ public AssertionAttributeExtractor(StatusResponseType samlResponse) throws AssertionAttributeExtractorExeption { if (samlResponse != null && samlResponse instanceof Response) { List assertions = ((Response) samlResponse).getAssertions(); @@ -96,6 +106,27 @@ public class AssertionAttributeExtractor { throw new AssertionAttributeExtractorExeption(); } + /** + * Get all SAML2 attributes from first SAML2 AttributeStatement element + * + * @return List of SAML2 Attributes + */ + public List getAllResponseAttributesFromFirstAttributeStatement() { + return assertion.getAttributeStatements().get(0).getAttributes(); + + } + + /** + * Get all SAML2 attributes of specific SAML2 AttributeStatement element + * + * @param attrStatementID List ID of the AttributeStatement element + * @return List of SAML2 Attributes + */ + public List getAllResponseAttributes(int attrStatementID) { + return assertion.getAttributeStatements().get(attrStatementID).getAttributes(); + + } + /** * check attributes from assertion with minimal required attribute list * @return @@ -107,7 +138,7 @@ public class AssertionAttributeExtractor { /** * check attributes from assertion with attributeNameList - * bPK or enc_bPK is always needed + * bPK or enc_bPK are always needed * * @param List of attributes which are required * @@ -116,24 +147,24 @@ public class AssertionAttributeExtractor { public boolean containsAllRequiredAttributes(Collection attributeNameList) { //first check if a bPK or an encrypted bPK is available - if (attributs.containsKey(PVPConstants.ENC_BPK_LIST_NAME) || - (attributs.containsKey(PVPConstants.BPK_NAME))) { - boolean flag = true; - for (String attr : attributeNameList) { - if (!attributs.containsKey(attr)) { - flag = false; - Logger.debug("Assertion contains no Attribute " + attr); - - } - + boolean flag = true; + for (String attr : attributeNameList) { + if (!attributs.containsKey(attr)) { + flag = false; + Logger.debug("Assertion contains no Attribute " + attr); + } - - return flag; - + } - Logger.debug("Assertion contains no bPK or encryptedbPK."); - return false; + if (flag) + return flag; + + else { + Logger.debug("Assertion contains no bPK or encryptedbPK."); + return false; + + } } public boolean containsAttribute(String attributeName) { @@ -218,6 +249,29 @@ public class AssertionAttributeExtractor { return assertion; } + + /** + * Get the Assertion validTo period + * + * Primarily, the 'SessionNotOnOrAfter' attribute in the SAML2 'AuthnStatment' element is used. + * If this is empty, this method returns value of SAML 'Conditions' element. + * + * @return Date, until this SAML2 assertion is valid + */ + public Date getAssertionNotOnOrAfter() { + if (getFullAssertion().getAuthnStatements() != null + && getFullAssertion().getAuthnStatements().size() > 0) { + for (AuthnStatement el : getFullAssertion().getAuthnStatements()) { + if (el.getSessionNotOnOrAfter() != null) + return (el.getSessionNotOnOrAfter().toDate()); + } + + } + + return getFullAssertion().getConditions().getNotOnOrAfter().toDate(); + + } + private AuthnStatement getAuthnStatement() throws AssertionAttributeExtractorExeption { List authnList = assertion.getAuthnStatements(); if (authnList.size() == 0) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java index f62410656..86ca591ee 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AbstractRequestSignedSecurityPolicyRule.java @@ -139,7 +139,7 @@ public abstract class AbstractRequestSignedSecurityPolicyRule implements Securit throw new SecurityPolicyException("Signature validation FAILED."); } - Logger.debug("PVP AuthnRequest signature valid."); + Logger.debug("PVP message signature valid."); } catch (org.opensaml.xml.security.SecurityException e) { Logger.info("PVP2x message signature validation FAILED. Message:" + e.getMessage()); @@ -148,7 +148,7 @@ public abstract class AbstractRequestSignedSecurityPolicyRule implements Securit } } else { - throw new SecurityPolicyException("Request is not signed."); + throw new SecurityPolicyException("PVP Message is not signed."); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java index 932f3b818..7b3f890e9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/MOAPVPSignedRequestPolicyRule.java @@ -25,10 +25,12 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.validation; import javax.xml.namespace.QName; import org.opensaml.common.SignableSAMLObject; +import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.xml.XMLObject; import org.opensaml.xml.signature.SignatureTrustEngine; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IMOARefreshableMetadataProvider; +import at.gv.egovernment.moa.logging.Logger; /** * @author tlenz @@ -37,13 +39,19 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; public class MOAPVPSignedRequestPolicyRule extends AbstractRequestSignedSecurityPolicyRule { + private IMOARefreshableMetadataProvider metadataProvider = null; + /** + * @param metadataProvider * @param trustEngine * @param peerEntityRole */ - public MOAPVPSignedRequestPolicyRule(SignatureTrustEngine trustEngine, + public MOAPVPSignedRequestPolicyRule(MetadataProvider metadataProvider, SignatureTrustEngine trustEngine, QName peerEntityRole) { super(trustEngine, peerEntityRole); + if (metadataProvider instanceof IMOARefreshableMetadataProvider) + this.metadataProvider = (IMOARefreshableMetadataProvider) metadataProvider; + } /* (non-Javadoc) @@ -51,7 +59,10 @@ public class MOAPVPSignedRequestPolicyRule extends */ @Override protected boolean refreshMetadataProvider(String entityID) { - return MOAMetadataProvider.getInstance().refreshMetadataProvider(entityID); + if (metadataProvider != null) + return metadataProvider.refreshMetadataProvider(entityID); + + return false; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java index 5e44c9057..f384dd511 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngine.java @@ -22,50 +22,30 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.verification; -import java.util.ArrayList; -import java.util.List; - import javax.xml.namespace.QName; import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; -import org.joda.time.DateTime; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.common.xml.SAMLSchemaBuilder; -import org.opensaml.saml2.core.Conditions; -import org.opensaml.saml2.core.EncryptedAssertion; import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.Response; -import org.opensaml.saml2.core.StatusCode; import org.opensaml.saml2.core.StatusResponseType; -import org.opensaml.saml2.encryption.Decrypter; -import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; import org.opensaml.saml2.metadata.IDPSSODescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; import org.opensaml.security.MetadataCriteria; import org.opensaml.security.SAMLSignatureProfileValidator; -import org.opensaml.xml.encryption.ChainingEncryptedKeyResolver; -import org.opensaml.xml.encryption.DecryptionException; -import org.opensaml.xml.encryption.InlineEncryptedKeyResolver; -import org.opensaml.xml.encryption.SimpleRetrievalMethodEncryptedKeyResolver; import org.opensaml.xml.security.CriteriaSet; -import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.credential.UsageType; import org.opensaml.xml.security.criteria.EntityIDCriteria; import org.opensaml.xml.security.criteria.UsageCriteria; -import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver; import org.opensaml.xml.signature.SignatureTrustEngine; import org.opensaml.xml.validation.ValidationException; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Element; import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; @@ -77,8 +57,6 @@ import at.gv.egovernment.moa.util.MiscUtil; @Service("SAMLVerificationEngine") public class SAMLVerificationEngine { - @Autowired AuthConfiguration authConfig; - public void verify(InboundMessage msg, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { try { if (msg instanceof MOARequest && @@ -181,111 +159,8 @@ public class SAMLVerificationEngine { throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); } } - - public void validateAssertion(Response samlResp, boolean validateDestination, Credential assertionDecryption) throws AssertionValidationExeption { - try { - if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { - List saml2assertions = new ArrayList(); - - //validate destination URL - List allowedPublicURLPrefix = authConfig.getPublicURLPrefix(); - boolean isValidDestination = false; - for (String allowedPreFix : allowedPublicURLPrefix) { - if (validateDestination && samlResp.getDestination().startsWith( - allowedPreFix)) { - isValidDestination = true; - break; - - } - } - if (!isValidDestination && validateDestination) { - Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); - throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); - - } - - //check encrypted Assertion - List encryAssertionList = samlResp.getEncryptedAssertions(); - if (encryAssertionList != null && encryAssertionList.size() > 0) { - //decrypt assertions - - Logger.debug("Found encryped assertion. Start decryption ..."); - - StaticKeyInfoCredentialResolver skicr = - new StaticKeyInfoCredentialResolver(assertionDecryption); - - ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); - encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); - encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); - encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); - - Decrypter samlDecrypter = - new Decrypter(null, skicr, encryptedKeyResolver); - - for (EncryptedAssertion encAssertion : encryAssertionList) { - saml2assertions.add(samlDecrypter.decrypt(encAssertion)); - - } - - Logger.debug("Assertion decryption finished. "); - - } else { - saml2assertions.addAll(samlResp.getAssertions()); - - } - - List validatedassertions = new ArrayList(); - for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { - - try { - performSchemaValidation(saml2assertion.getDOM()); - - Conditions conditions = saml2assertion.getConditions(); - DateTime notbefore = conditions.getNotBefore().minusMinutes(5); - DateTime notafter = conditions.getNotOnOrAfter(); - if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { - Logger.warn("PVP2 Assertion is out of Date. " - + "{ Current : " + new DateTime() - + " NotBefore: " + notbefore - + " NotAfter : " + notafter - + " }");; - - } else { - validatedassertions.add(saml2assertion); - - } - - } catch (SchemaValidationException e) { - - } - } - - if (validatedassertions.isEmpty()) { - Logger.info("No valid PVP 2.1 assertion received."); - throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); - } - - samlResp.getAssertions().clear(); - samlResp.getEncryptedAssertions().clear(); - samlResp.getAssertions().addAll(validatedassertions); - - } else { - Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " - + samlResp.getStatus().getStatusCode().getValue()); - throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " - + samlResp.getStatus().getStatusCode().getValue(), null); - } - - } catch (DecryptionException e) { - Logger.warn("Assertion decrypt FAILED.", e); - throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); - - } catch (ConfigurationException e) { - throw new AssertionValidationExeption("pvp.12", null, e); - } - } - - private void performSchemaValidation(Element source) throws SchemaValidationException { + + protected void performSchemaValidation(Element source) throws SchemaValidationException { String err = null; try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java new file mode 100644 index 000000000..cd80d8c24 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/SAMLVerificationEngineSP.java @@ -0,0 +1,161 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.pvp2x.verification; + +import java.util.ArrayList; +import java.util.List; + +import org.joda.time.DateTime; +import org.opensaml.saml2.core.Conditions; +import org.opensaml.saml2.core.EncryptedAssertion; +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.saml2.encryption.Decrypter; +import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; +import org.opensaml.xml.encryption.ChainingEncryptedKeyResolver; +import org.opensaml.xml.encryption.DecryptionException; +import org.opensaml.xml.encryption.InlineEncryptedKeyResolver; +import org.opensaml.xml.encryption.SimpleRetrievalMethodEncryptedKeyResolver; +import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationException; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +@Service("SAMLVerificationEngineSP") +public class SAMLVerificationEngineSP extends SAMLVerificationEngine { + + @Autowired AuthConfiguration authConfig; + + public void validateAssertion(Response samlResp, boolean validateDestination, Credential assertionDecryption) throws AssertionValidationExeption { + try { + if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { + List saml2assertions = new ArrayList(); + + //validate destination URL + List allowedPublicURLPrefix = authConfig.getPublicURLPrefix(); + boolean isValidDestination = false; + for (String allowedPreFix : allowedPublicURLPrefix) { + if (validateDestination && samlResp.getDestination().startsWith( + allowedPreFix)) { + isValidDestination = true; + break; + + } + } + if (!isValidDestination && validateDestination) { + Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); + throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); + + } + + //check encrypted Assertion + List encryAssertionList = samlResp.getEncryptedAssertions(); + if (encryAssertionList != null && encryAssertionList.size() > 0) { + //decrypt assertions + + Logger.debug("Found encryped assertion. Start decryption ..."); + + StaticKeyInfoCredentialResolver skicr = + new StaticKeyInfoCredentialResolver(assertionDecryption); + + ChainingEncryptedKeyResolver encryptedKeyResolver = new ChainingEncryptedKeyResolver(); + encryptedKeyResolver.getResolverChain().add( new InlineEncryptedKeyResolver() ); + encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); + encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); + + Decrypter samlDecrypter = + new Decrypter(null, skicr, encryptedKeyResolver); + + for (EncryptedAssertion encAssertion : encryAssertionList) { + saml2assertions.add(samlDecrypter.decrypt(encAssertion)); + + } + + Logger.debug("Assertion decryption finished. "); + + } else { + saml2assertions.addAll(samlResp.getAssertions()); + + } + + List validatedassertions = new ArrayList(); + for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { + + try { + performSchemaValidation(saml2assertion.getDOM()); + + Conditions conditions = saml2assertion.getConditions(); + DateTime notbefore = conditions.getNotBefore().minusMinutes(5); + DateTime notafter = conditions.getNotOnOrAfter(); + if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { + Logger.warn("PVP2 Assertion is out of Date. " + + "{ Current : " + new DateTime() + + " NotBefore: " + notbefore + + " NotAfter : " + notafter + + " }");; + + } else { + validatedassertions.add(saml2assertion); + + } + + } catch (SchemaValidationException e) { + + } + } + + if (validatedassertions.isEmpty()) { + Logger.info("No valid PVP 2.1 assertion received."); + throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); + } + + samlResp.getAssertions().clear(); + samlResp.getEncryptedAssertions().clear(); + samlResp.getAssertions().addAll(validatedassertions); + + } else { + Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " + + samlResp.getStatus().getStatusCode().getValue()); + throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " + + samlResp.getStatus().getStatusCode().getValue(), null); + } + + } catch (DecryptionException e) { + Logger.warn("Assertion decrypt FAILED.", e); + throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); + + } catch (ConfigurationException e) { + throw new AssertionValidationExeption("pvp.12", null, e); + } + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java index 316ca2177..10594d6fc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/DBAuthenticationSessionStoreage.java @@ -53,7 +53,6 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.EncryptedData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.util.Random; @@ -440,10 +439,6 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } - //set additional information for AttributeQuery - activeOA.setAttQueryContainerID(protocolRequest.getGenericData( - PVPTargetConfiguration.DATAID_INTERFEDERATION_ATTRQUERYCONTAINERID, String.class)); - List activeOAs = dbsession.getActiveOAsessions(); activeOAs.add(activeOA); dbsession.setActiveOAsessions(activeOAs); -- cgit v1.2.3 From f66ed1831a4877d6c7cb3c55bbc3fd84024a1523 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 9 Mar 2016 09:14:38 +0100 Subject: move main frontend GUI to seperate package --- .../servlet/SAML2InterfederationSignalServlet.java | 38 ---------------------- 1 file changed, 38 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.java deleted file mode 100644 index 1d18ccb2c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/SAML2InterfederationSignalServlet.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.auth.servlet; - -/** - * @author tlenz - * - */ - -public class SAML2InterfederationSignalServlet extends - AbstractProcessEngineSignalController { - - - //TODO: getMOASessionID from SAML2 relayState - //TODO: add WebService EndPoints for pvp2/sp/post and redirect - //TODO: implement SAML2 preprocessing - -} -- cgit v1.2.3 From f9020f47b60bc1cff6c671461924ba606ce87853 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 9 Mar 2016 09:15:03 +0100 Subject: fix some problems in ELGA-mandate module --- .../src/main/java/at/gv/egovernment/moa/id/util/Random.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 index 07679999b..47f784c33 100644 --- 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 @@ -99,7 +99,7 @@ public class Random { char preFix = allowedPreFix[Math.abs(random.nextInt() % allowedPreFix.length)]; //generate ID - return preFix + new String(Hex.encodeHex(Bytes.concat(now.getBytes(), randValue), true)); // 20 bytes = 160 bits + return preFix + new String(Hex.encodeHex(Bytes.concat(now.getBytes(), randValue))); // 20 bytes = 160 bits } @@ -111,7 +111,7 @@ public class Random { * @return random hex encoded value [256bit] */ public static String nextHexRandom() { - return new String(Hex.encodeHex(nextByteRandom(32), true)); // 32 bytes = 256 bits + return new String(Hex.encodeHex(nextByteRandom(32))); // 32 bytes = 256 bits } -- cgit v1.2.3 From 02e6fdd42a17a857b463d61ecea5b72e6d5e5074 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 9 Mar 2016 15:59:45 +0100 Subject: remove unused code --- .../id/config/legacy/BuildFromLegacyConfig.java | 570 --------- .../gv/egovernment/moa/id/config/legacy/CPEPS.java | 120 -- .../moa/id/config/legacy/ConfigurationBuilder.java | 1253 -------------------- .../moa/id/config/legacy/ConnectionParameter.java | 154 --- .../moa/id/config/legacy/OAAuthParameter.java | 464 -------- .../moa/id/config/legacy/OAParameter.java | 186 --- .../moa/id/config/legacy/STORKConfig.java | 112 -- .../config/legacy/SignatureCreationParameter.java | 134 --- .../legacy/SignatureVerificationParameter.java | 57 - .../id/config/legacy/VerifyInfoboxParameter.java | 433 ------- .../id/config/legacy/VerifyInfoboxParameters.java | 181 --- 11 files changed, 3664 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/CPEPS.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/ConfigurationBuilder.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/ConnectionParameter.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/OAAuthParameter.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/OAParameter.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/STORKConfig.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/SignatureCreationParameter.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/SignatureVerificationParameter.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/VerifyInfoboxParameter.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/VerifyInfoboxParameters.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java deleted file mode 100644 index 887a7e40f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java +++ /dev/null @@ -1,570 +0,0 @@ -///******************************************************************************* -// * Copyright 2014 Federal Chancellery Austria -// * MOA-ID has been developed in a cooperation between BRZ, the Federal -// * Chancellery Austria - ICT staff unit, and Graz University of Technology. -// * -// * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by -// * the European Commission - subsequent versions of the EUPL (the "Licence"); -// * You may not use this work except in compliance with the Licence. -// * You may obtain a copy of the Licence at: -// * http://www.osor.eu/eupl/ -// * -// * Unless required by applicable law or agreed to in writing, software -// * distributed under the Licence is distributed on an "AS IS" basis, -// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// * See the Licence for the specific language governing permissions and -// * limitations under the Licence. -// * -// * This product combines work with different licenses. See the "NOTICE" text -// * file for details on the various modules and licenses. -// * The "NOTICE" text file is part of the distribution. Any derivative works -// * that you distribute must include a readable copy of the "NOTICE" text file. -// *******************************************************************************/ -//package at.gv.egovernment.moa.id.config.legacy; -// -//import java.io.BufferedInputStream; -//import java.io.File; -//import java.io.FileInputStream; -//import java.io.IOException; -//import java.io.InputStream; -//import java.math.BigInteger; -//import java.net.URI; -//import java.nio.file.Path; -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.Collections; -//import java.util.List; -//import java.util.Map; -//import java.util.Properties; -//import java.util.Set; -// -//import org.w3c.dom.Element; -// -//import at.gv.egovernment.moa.id.commons.db.dao.config.AuthComponentGeneral; -//import at.gv.egovernment.moa.id.commons.db.dao.config.AuthComponentOA; -//import at.gv.egovernment.moa.id.commons.db.dao.config.BKUURLS; -//import at.gv.egovernment.moa.id.commons.db.dao.config.ChainingModeType; -//import at.gv.egovernment.moa.id.commons.db.dao.config.ChainingModes; -//import at.gv.egovernment.moa.id.commons.db.dao.config.ConnectionParameterClientAuthType; -//import at.gv.egovernment.moa.id.commons.db.dao.config.Contact; -//import at.gv.egovernment.moa.id.commons.db.dao.config.DefaultBKUs; -//import at.gv.egovernment.moa.id.commons.db.dao.config.ForeignIdentities; -//import at.gv.egovernment.moa.id.commons.db.dao.config.GeneralConfiguration; -//import at.gv.egovernment.moa.id.commons.db.dao.config.IdentificationNumber; -//import at.gv.egovernment.moa.id.commons.db.dao.config.IdentityLinkSigners; -//import at.gv.egovernment.moa.id.commons.db.dao.config.LegacyAllowed; -//import at.gv.egovernment.moa.id.commons.db.dao.config.MOAIDConfiguration; -//import at.gv.egovernment.moa.id.commons.db.dao.config.MOAKeyBoxSelector; -//import at.gv.egovernment.moa.id.commons.db.dao.config.MOASP; -//import at.gv.egovernment.moa.id.commons.db.dao.config.Mandates; -//import at.gv.egovernment.moa.id.commons.db.dao.config.MandatesProfileNameItem; -//import at.gv.egovernment.moa.id.commons.db.dao.config.OAPVP2; -//import at.gv.egovernment.moa.id.commons.db.dao.config.OASAML1; -//import at.gv.egovernment.moa.id.commons.db.dao.config.OASSO; -//import at.gv.egovernment.moa.id.commons.db.dao.config.OAuth; -//import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; -//import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineMandates; -//import at.gv.egovernment.moa.id.commons.db.dao.config.Organization; -//import at.gv.egovernment.moa.id.commons.db.dao.config.PVP2; -//import at.gv.egovernment.moa.id.commons.db.dao.config.Protocols; -//import at.gv.egovernment.moa.id.commons.db.dao.config.SAML1; -//import at.gv.egovernment.moa.id.commons.db.dao.config.SLRequestTemplates; -//import at.gv.egovernment.moa.id.commons.db.dao.config.SSO; -//import at.gv.egovernment.moa.id.commons.db.dao.config.SecurityLayer; -//import at.gv.egovernment.moa.id.commons.db.dao.config.TemplateType; -//import at.gv.egovernment.moa.id.commons.db.dao.config.TemplatesType; -//import at.gv.egovernment.moa.id.commons.db.dao.config.TimeOuts; -//import at.gv.egovernment.moa.id.commons.db.dao.config.TransformsInfoType; -//import at.gv.egovernment.moa.id.commons.db.dao.config.TrustAnchor; -//import at.gv.egovernment.moa.id.commons.db.dao.config.VerifyAuthBlock; -//import at.gv.egovernment.moa.id.commons.db.dao.config.VerifyIdentityLink; -//import at.gv.egovernment.moa.id.config.ConfigurationException; -//import at.gv.egovernment.moa.id.config.ConfigurationProvider; -// -//import at.gv.egovernment.moa.id.data.IssuerAndSerial; -//import at.gv.egovernment.moa.logging.Logger; -//import at.gv.egovernment.moa.util.Base64Utils; -//import at.gv.egovernment.moa.util.DOMUtils; -//import at.gv.egovernment.moa.util.FileUtils; -//import at.gv.egovernment.moa.util.MiscUtil; -// -//public class BuildFromLegacyConfig { -// -// private static final String GENERIC_CONFIG_PARAM_SOURCEID = "AuthenticationServer.SourceID"; -// -// private static final String SEARCHBKUTEMPLATE_LOCAL = "https://127.0.0.1:3496/"; -// private static final String SEARCHBKUTEMPLATE_HANDY = "https://www.handy-signatur.at"; -// private static final String SEARCHBKUTEMPLATE_ONLINE = "bkuonline/http-security-layer-request"; -// -// public static final String AUTH_SESSION_TIMEOUT_PROPERTY = -// "AuthenticationSession.TimeOut"; -// /** -// * The name of the generic configuration property giving the authentication data time out. -// */ -// public static final String AUTH_DATA_TIMEOUT_PROPERTY = -// "AuthenticationData.TimeOut"; -// -// -// public static MOAIDConfiguration build(File fileName, String rootConfigFileDir, MOAIDConfiguration oldconfig) throws ConfigurationException { -// InputStream stream = null; -// Element configElem; -// ConfigurationBuilder builder; -// -// Logger.info("Load Legacy-Configuration from file=" + fileName); -// -// try { -// // load the main config file -// stream = new BufferedInputStream(new FileInputStream(fileName)); -// configElem = DOMUtils.parseXmlValidating(stream); -// -// } catch (Throwable t) { -// throw new ConfigurationException("config.03", null, t); -// } -// -// finally { -// try { -// if (stream != null) { -// stream.close(); -// } -// } catch (IOException e) { -// -// } -// } -// -// try { -// String oldbkuonline = ""; -// String oldbkulocal = ""; -// String oldbkuhandy = ""; -// -// // build the internal datastructures -// builder = new ConfigurationBuilder(configElem, rootConfigFileDir); -// -// -// MOAIDConfiguration moaIDConfig = new MOAIDConfiguration(); -// -// AuthComponentGeneral generalAuth = new AuthComponentGeneral(); -// moaIDConfig.setAuthComponentGeneral(generalAuth); -// -// -// //not supported by MOA-ID 2.0 -// //ConnectionParameter bKUConnectionParameter = builder.buildAuthBKUConnectionParameter(); -// //bKUSelectable = (bKUConnectionParameter!=null); -// //bKUSelectionType = builder.buildAuthBKUSelectionType(); -// -// -// //Load generic Config -// Map genericConfiguration = builder.buildGenericConfiguration(); -// GeneralConfiguration authGeneral = new GeneralConfiguration(); -// -// if (genericConfiguration.containsKey(ConfigurationProvider.TRUST_MANAGER_REVOCATION_CHECKING)) -// authGeneral.setTrustManagerRevocationChecking( -// Boolean.valueOf((String)genericConfiguration.get(ConfigurationProvider.TRUST_MANAGER_REVOCATION_CHECKING))); -// else -// authGeneral.setTrustManagerRevocationChecking(true); -// -// if (genericConfiguration.containsKey(ConfigurationProvider.DIRECTORY_CERTSTORE_PARAMETER_PROPERTY)) -// authGeneral.setCertStoreDirectory( -// (String)genericConfiguration.get(ConfigurationProvider.DIRECTORY_CERTSTORE_PARAMETER_PROPERTY)); -// else -// authGeneral.setTrustManagerRevocationChecking(true); -// -// -// //Load Assertion and Session timeouts -// TimeOuts timeOuts = new TimeOuts(); -// if (genericConfiguration.containsKey(AUTH_DATA_TIMEOUT_PROPERTY)) -// timeOuts.setAssertion(BigInteger.valueOf(Long.valueOf((String)genericConfiguration.get(AUTH_DATA_TIMEOUT_PROPERTY)))); -// else -// timeOuts.setAssertion(BigInteger.valueOf(2*60)); //default 2min -// -// if (genericConfiguration.containsKey(AUTH_SESSION_TIMEOUT_PROPERTY)) -// timeOuts.setAssertion(BigInteger.valueOf(Long.valueOf((String)genericConfiguration.get(AUTH_SESSION_TIMEOUT_PROPERTY)))); -// else -// timeOuts.setAssertion(BigInteger.valueOf(30*60)); //default 30min -// -// timeOuts.setMOASessionUpdated(BigInteger.valueOf(15*60)); //default 15min -// authGeneral.setTimeOuts(timeOuts); -// generalAuth.setGeneralConfiguration(authGeneral); -// -// Protocols auth_protocols = new Protocols(); -// generalAuth.setProtocols(auth_protocols); -// -// LegacyAllowed prot_legacy = new LegacyAllowed(); -// auth_protocols.setLegacyAllowed(prot_legacy); -// final List PROTOCOLS_LEGACY_ALLOWED = Arrays.asList("id_saml1","id_pvp2x"); -// prot_legacy.setProtocolName(PROTOCOLS_LEGACY_ALLOWED); -// -// //set SAML1 config -// SAML1 saml1 = new SAML1(); -// saml1.setIsActive(true); -// if (genericConfiguration.containsKey(GENERIC_CONFIG_PARAM_SOURCEID)) -// saml1.setSourceID((String)genericConfiguration.get(GENERIC_CONFIG_PARAM_SOURCEID)); -// auth_protocols.setSAML1(saml1); -// -// //set OAuth config -// OAuth oauth = new OAuth(); -// oauth.setIsActive(true); -// auth_protocols.setOAuth(oauth); -// -// //set PVP2.1 config -// PVP2 prot_pvp2 = new PVP2(); -// auth_protocols.setPVP2(prot_pvp2); -// prot_pvp2.setPublicURLPrefix("https://...."); -// prot_pvp2.setIssuerName("MOA-ID 2.x IDP"); -// -// Organization pvp2_org = new Organization(); -// prot_pvp2.setOrganization(pvp2_org); -// pvp2_org.setDisplayName("OrganisationDisplayName"); -// pvp2_org.setName("OrganisatioName"); -// pvp2_org.setURL("http://testorganisation.at"); -// -// List pvp2_contacts = new ArrayList(); -// prot_pvp2.setContact(pvp2_contacts); -// -// Contact pvp2_contact = new Contact(); -// pvp2_contact.setCompany("OrganisationDisplayName"); -// pvp2_contact.setGivenName("Max"); -// -// -// List mails = new ArrayList(); -// pvp2_contact.setMail(mails); -// mails.add("max@muster.mann"); -// -// List phones = new ArrayList(); -// pvp2_contact.setPhone(phones); -// phones.add("01 5555 5555"); -// -// pvp2_contact.setSurName("Mustermann"); -// pvp2_contact.setType("technical"); -// pvp2_contacts.add(pvp2_contact); -// -// //SSO -// SSO auth_sso = new SSO(); -// generalAuth.setSSO(auth_sso); -// auth_sso.setTarget(""); -// auth_sso.setFriendlyName(""); -// -// -// //set SecurityLayer Transformations -// String[] transformsInfoFileNames = builder.buildTransformsInfoFileNames(builder.getConfigElem(), ConfigurationBuilder.AUTH_SECLAYER_TRANSFORMS_INFO_FILENAME_XPATH); -// String[] transformsInfos = builder.loadTransformsInfos(transformsInfoFileNames); -// -// List auth_transformInfos = new ArrayList(); -// if (transformsInfos != null && transformsInfos.length > 0) { -// for (int i=0; i transformlist = new ArrayList(); -// Collections.addAll(transformlist, moaSpAuthBlockVerifyTransformsInfoIDs); -// auth_moaSP_verifyAuthBlock.setVerifyTransformsInfoProfileID(transformlist); -// auth_moaSP.setVerifyAuthBlock(auth_moaSP_verifyAuthBlock); -// -// -// //set IdentityLinkSigners -// IdentityLinkSigners auth_idsigners = new IdentityLinkSigners(); -// generalAuth.setIdentityLinkSigners(auth_idsigners); -// List identityLinkX509SubjectNames = builder.getIdentityLink_X509SubjectNames(); -// auth_idsigners.setX509SubjectName(identityLinkX509SubjectNames); -// -// -// //not supported by MOA-ID 2.0 -// VerifyInfoboxParameters defaultVerifyInfoboxParameters = null; -//// Node defaultVerifyInfoboxParamtersElem = XPathUtils.selectSingleNode(configElem, ConfigurationBuilder.AUTH_VERIFY_INFOBOXES_XPATH); -//// if (defaultVerifyInfoboxParamtersElem != null) { -//// defaultVerifyInfoboxParameters = -//// builder.buildVerifyInfoboxParameters((Element)defaultVerifyInfoboxParamtersElem, null, moaSpIdentityLinkTrustProfileID); -//// } -// -// -// //Set ForeignIdentities -// ForeignIdentities auth_foreign = new ForeignIdentities(); -// generalAuth.setForeignIdentities(auth_foreign); -// -// //set Connection parameters -// ConnectionParameter foreignIDConnectionParameter = builder.buildForeignIDConnectionParameter(); -// ConnectionParameterClientAuthType auth_foreign_connection = -// parseConnectionParameterClientAuth(foreignIDConnectionParameter); -// auth_foreign.setConnectionParameter(auth_foreign_connection); -// -// //set OnlineMandates config -// ConnectionParameter onlineMandatesConnectionParameter = builder.buildOnlineMandatesConnectionParameter(); -// if (onlineMandatesConnectionParameter != null) { -// OnlineMandates auth_mandates = new OnlineMandates(); -// generalAuth.setOnlineMandates(auth_mandates); -// auth_mandates.setConnectionParameter( -// parseConnectionParameterClientAuth(onlineMandatesConnectionParameter)); -// } -// -// -// //TODO: add auth template configuration!!! -// -// -// if (oldconfig != null) { -// if (oldconfig.getDefaultBKUs() != null) { -// oldbkuhandy = oldconfig.getDefaultBKUs().getHandyBKU(); -// oldbkulocal = oldconfig.getDefaultBKUs().getLocalBKU(); -// oldbkuonline = oldconfig.getDefaultBKUs().getOnlineBKU(); -// } -// } else { -// List trustbkus = builder.getTrustedBKUs(); -// for (String trustbku : trustbkus) { -// if (MiscUtil.isEmpty(oldbkuonline) && trustbku.endsWith(SEARCHBKUTEMPLATE_ONLINE)) -// oldbkuonline = trustbku; -// -// if (MiscUtil.isEmpty(oldbkuhandy) && trustbku.startsWith(SEARCHBKUTEMPLATE_HANDY)) -// oldbkuhandy = trustbku; -// -// if (MiscUtil.isEmpty(oldbkulocal) && trustbku.startsWith(SEARCHBKUTEMPLATE_LOCAL)) -// oldbkulocal = trustbku; -// } -// -// } -// -// -// //set OnlineApplications -// OAAuthParameter[] onlineApplicationAuthParameters = builder.buildOnlineApplicationAuthParameters(defaultVerifyInfoboxParameters, moaSpIdentityLinkTrustProfileID); -// -// ArrayList moa_oas = new ArrayList(); -// moaIDConfig.setOnlineApplication(moa_oas); -// -// for (OAAuthParameter oa : onlineApplicationAuthParameters) { -// OnlineApplication moa_oa = new OnlineApplication(); -// -// //set general OA configuration -// moa_oa.setCalculateHPI(false); //TODO: Bernd fragen warum das nicht direkt über den Bereichsidentifyer definert wird -// moa_oa.setFriendlyName(oa.getFriendlyName()); -// moa_oa.setKeyBoxIdentifier(MOAKeyBoxSelector.fromValue(oa.getKeyBoxIdentifier())); -// moa_oa.setPublicURLPrefix(oa.getPublicURLPrefix()); -// moa_oa.setTarget(oa.getTarget()); -// moa_oa.setTargetFriendlyName(oa.getTargetFriendlyName()); -// moa_oa.setType(oa.getOaType()); -// moa_oa.setIsActive(true); -// -// -// AuthComponentOA oa_auth = new AuthComponentOA(); -// moa_oa.setAuthComponentOA(oa_auth); -// -// //SLLayer Version / useIframe -//// oa_auth.setSlVersion(oa.getSlVersion()); -//// oa_auth.setUseIFrame(false); -//// oa_auth.setUseUTC(oa.getUseUTC()); -// -// //BKUURLs -// BKUURLS bkuurls = new BKUURLS(); -// bkuurls.setOnlineBKU(oldbkuonline); -// bkuurls.setHandyBKU(oldbkuhandy); -// bkuurls.setLocalBKU(oldbkulocal); -// oa_auth.setBKUURLS(bkuurls); -// -// //IdentificationNumber -// IdentificationNumber idnumber = new IdentificationNumber(); -// idnumber.setValue(oa.getIdentityLinkDomainIdentifier()); -// idnumber.setType(oa.getIdentityLinkDomainIdentifierType()); -// oa_auth.setIdentificationNumber(idnumber); -// -// //set Templates -// TemplatesType templates = new TemplatesType(); -// oa_auth.setTemplates(templates); -// templates.setAditionalAuthBlockText(""); -// TemplateType template = new TemplateType(); -// template.setURL(oa.getTemplateURL()); -// ArrayList template_list = new ArrayList(); -// template_list.add(template); -// templates.setTemplate(template_list); -// -// -// //TransformsInfo not supported by MOAID 2.0 -// String[] transforminfos = oa.getTransformsInfos(); -// for (String e1 : transforminfos) { -// if (MiscUtil.isNotEmpty(e1)) { -// Logger.warn("OA specific transformation for OA " + oa.getPublicURLPrefix() -// + " are not supported. USE AdditionalAuthBlock text!"); -// } -// } -// -// //VerifyInfoBoxes not supported by MOAID 2.0 -// -// //set Mandates -// Mandates oa_mandates = new Mandates(); -// oa_auth.setMandates(oa_mandates); -// List profileList = new ArrayList(); -// -// String oldProfiles = oa.getMandateProfiles(); -// if (MiscUtil.isNotEmpty(oldProfiles)) { -// String[] oldprofileList = oldProfiles.split(","); -// for (int i=0; i chainingModes = builder.buildChainingModes(); -// List chaining_anchor = new ArrayList(); -// Set chaining_anchor_map = chainingModes.keySet(); -// for (IssuerAndSerial e1 : chaining_anchor_map) { -// TrustAnchor trustanchor = new TrustAnchor(); -// -// ChainingModeType type1 = ChainingModeType.fromValue(chainingModes.get(e1)); -// trustanchor.setMode(type1); -// -// trustanchor.setX509IssuerName(e1.getIssuerDN()); -// trustanchor.setX509SerialNumber(e1.getSerial()); -// chaining_anchor.add(trustanchor); -// } -// moa_chainingModes.setTrustAnchor(chaining_anchor); -// -// -// //set trustedCACertificate path -// moaIDConfig.setTrustedCACertificates(builder.getTrustedCACertificates()); -// -// -// //Not required in MOAID 2.0 config (DefaultBKUs & SLRequestTemplates) -// //trustedBKUs = builder.getTrustedBKUs(); -// //trustedTemplateURLs = builder.getTrustedTemplateURLs(); -// -// -// //set DefaultBKUs -// DefaultBKUs moa_defaultbkus = new DefaultBKUs(); -// moaIDConfig.setDefaultBKUs(moa_defaultbkus); -// moa_defaultbkus.setOnlineBKU(oldbkuonline); -// moa_defaultbkus.setHandyBKU(oldbkuhandy); -// moa_defaultbkus.setLocalBKU(oldbkulocal); -// -// -// //set SLRequest Templates -// SLRequestTemplates moa_slrequesttemp = new SLRequestTemplates(); -// moaIDConfig.setSLRequestTemplates(moa_slrequesttemp); -// moa_slrequesttemp.setOnlineBKU("http://localhost:8080/moa-id-auth/template_onlineBKU.html"); -// moa_slrequesttemp.setHandyBKU("http://localhost:8080/moa-id-auth/template_handyBKU.html"); -// moa_slrequesttemp.setLocalBKU("http://127.0.0.1:8080/moa-id-auth/template_localBKU.html"); -// -// return moaIDConfig; -// -// } catch (Throwable t) { -// throw new ConfigurationException("config.02", null, t); -// } -// } -// -// private static ConnectionParameterClientAuthType parseConnectionParameterClientAuth( -// ConnectionParameter old) { -// ConnectionParameterClientAuthType auth_moaSP_connection = new ConnectionParameterClientAuthType(); -// auth_moaSP_connection.setURL(old.getUrl()); -// -// //TODO: remove from Database config!!!!! -//// auth_moaSP_connection.setAcceptedServerCertificates(old.getAcceptedServerCertificates()); -//// ClientKeyStore auth_moaSP_connection_keyStore = new ClientKeyStore(); -//// auth_moaSP_connection_keyStore.setValue(old.getClientKeyStore()); -//// auth_moaSP_connection_keyStore.setPassword(old.getClientKeyStorePassword()); -//// auth_moaSP_connection.setClientKeyStore(auth_moaSP_connection_keyStore); -// return auth_moaSP_connection; -// } -// -// private static Properties getGeneralPVP2ProperiesConfig(Properties props) { -// Properties configProp = new Properties(); -// for (Object key : props.keySet()) { -// String propPrefix = "protocols.pvp2."; -// if (key.toString().startsWith(propPrefix)) { -// String propertyName = key.toString().substring(propPrefix.length()); -// configProp.put(propertyName, props.get(key.toString())); -// } -// } -// return configProp; -// } -//} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/CPEPS.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/CPEPS.java deleted file mode 100644 index 1d9f738be..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/CPEPS.java +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/** - * - */ -package at.gv.egovernment.moa.id.config.legacy; - -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import org.opensaml.saml2.metadata.RequestedAttribute; - -/** - * Encpasulates C-PEPS information according MOA configuration - * - * @author bzwattendorfer - * - */ -public class CPEPS { - - /** Country Code of C-PEPS */ - private String countryCode; - - /** URL of C-PEPS */ - private URL pepsURL; - - /** Specific attributes to be requested for this C-PEPS */ - private List countrySpecificRequestedAttributes = new ArrayList(); - - /** - * Constructs a C-PEPS - * @param countryCode ISO Country Code of C-PEPS - * @param pepsURL URL of C-PEPS - */ - public CPEPS(String countryCode, URL pepsURL) { - super(); - this.countryCode = countryCode; - this.pepsURL = pepsURL; - } - - /** - * Gets the country code of this C-PEPS - * @return ISO country code - */ - public String getCountryCode() { - return countryCode; - } - - /** - * Sets the country code of this C-PEPS - * @param countryCode ISO country code - */ - public void setCountryCode(String countryCode) { - this.countryCode = countryCode; - } - - /** - * Gets the URL of this C-PEPS - * @return C-PEPS URL - */ - public URL getPepsURL() { - return pepsURL; - } - - /** - * Sets the C-PEPS URL - * @param pepsURL C-PEPS URL - */ - public void setPepsURL(URL pepsURL) { - this.pepsURL = pepsURL; - } - - /** - * Gets the country specific attributes of this C-PEPS - * @return List of country specific attributes - */ - public List getCountrySpecificRequestedAttributes() { - return countrySpecificRequestedAttributes; - } - - /** - * Sets the country specific attributes - * @param countrySpecificRequestedAttributes List of country specific requested attributes - */ - public void setCountrySpecificRequestedAttributes( - List countrySpecificRequestedAttributes) { - this.countrySpecificRequestedAttributes = countrySpecificRequestedAttributes; - } - - /** - * Adds a Requested attribute to the country specific attribute List - * @param countrySpecificRequestedAttribute Additional country specific requested attribute to add - */ - public void addCountrySpecificRequestedAttribute(RequestedAttribute countrySpecificRequestedAttribute) { - this.countrySpecificRequestedAttributes.add(countrySpecificRequestedAttribute); - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/ConfigurationBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/ConfigurationBuilder.java deleted file mode 100644 index 6ad45d8c9..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/ConfigurationBuilder.java +++ /dev/null @@ -1,1253 +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.config.legacy; - -import iaik.pki.pathvalidation.ChainingModes; -import iaik.utils.RFC2253NameParser; -import iaik.utils.RFC2253NameParserException; - -import java.io.IOException; -import java.math.BigInteger; -import java.security.Principal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Vector; - -import org.w3c.dom.Attr; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.traversal.NodeIterator; - -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.data.Schema; -import at.gv.egovernment.moa.id.auth.data.SchemaImpl; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.legacy.OAAuthParameter; -import at.gv.egovernment.moa.id.config.legacy.VerifyInfoboxParameter; -import at.gv.egovernment.moa.id.config.legacy.VerifyInfoboxParameters; -import at.gv.egovernment.moa.id.config.legacy.SignatureCreationParameter; -import at.gv.egovernment.moa.id.data.IssuerAndSerial; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.BoolUtils; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.egovernment.moa.util.FileUtils; -import at.gv.egovernment.moa.util.StringUtils; -import at.gv.egovernment.moa.util.XPathException; -import at.gv.egovernment.moa.util.XPathUtils; - -/** - * A class that builds configuration data from a DOM based representation. - * - * @author Patrick Peck - * @author Stefan Knirsch - * @version $Id$ - */ -public class ConfigurationBuilder { - - // - // XPath namespace prefix shortcuts - // - /** an XPATH-Expression */ - protected static final String CONF = Constants.MOA_ID_CONFIG_PREFIX + ":"; - /** an XPATH-Expression */ - protected static final String DSIG = Constants.DSIG_PREFIX + ":"; - - /** an XPATH-Expression */ - protected static final String STORK = Constants.STORK_PREFIX + ":"; - - /** an XPATH-Expression */ - protected static final String STORKP= Constants.STORKP_PREFIX + ":"; - - // - // chaining mode constants appearing in the configuration file - // - /** an XPATH-Expression */ - protected static final String CM_CHAINING = "chaining"; - /** an XPATH-Expression */ - protected static final String CM_PKIX = "pkix"; - /** an XPATH-Expression */ - protected static final String DEFAULT_ENCODING = "UTF-8"; - - // - // XPath expressions to select certain parts of the configuration - // - /** an XPATH-Expression */ - protected static final String ROOT = "/" + CONF + "MOA-IDConfiguration/"; - - /** an XPATH-Expression */ - protected static final String AUTH_BKU_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "BKUSelection"; - /** an XPATH-Expression */ - protected static final String AUTH_BKUSELECT_TEMPLATE_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "Templates/" + CONF + "BKUSelectionTemplate/@URL"; - /** an XPATH-Expression */ - protected static final String AUTH_TEMPLATE_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "Templates/" + CONF + "Template/@URL"; - /** an XPATH-Expression */ - public static final String AUTH_TEMPLATE_ONLINEMANDATES_BKU_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "Templates/" + CONF + "OnlineMandates/" + CONF + "BKU"; - - - //protected static final String AUTH_MANDATE_TEMPLATE_XPATH = -// ROOT + CONF + "AuthComponent/" + CONF + "Templates/" + CONF + "MandateTemplate/@URL"; - /** an XPATH-Expression */ - protected static final String INPUT_PROCESSOR_TEMPLATE_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "Templates/" + CONF + "InputProcessorSignTemplate/@URL"; - /** an XPATH-Expression */ - public static final String AUTH_SECLAYER_TRANSFORMS_INFO_FILENAME_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "SecurityLayer/" + CONF + "TransformsInfo/@filename"; - /** an XPATH-Expression */ - protected static final String AUTH_MOA_SP_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "MOA-SP"; - /** an XPATH-Expression */ - protected static final String AUTH_MOA_SP_VERIFY_IDENTITY_TRUST_ID_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "MOA-SP/" + CONF + "VerifyIdentityLink/" + CONF + "TrustProfileID"; - /** an XPATH-Expression */ - protected static final String AUTH_MOA_SP_VERIFY_AUTH_TRUST_ID_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "MOA-SP/" + CONF + "VerifyAuthBlock/" + CONF + "TrustProfileID"; - /** an XPATH-Expression */ - protected static final String AUTH_MOA_SP_VERIFY_AUTH_VERIFY_ID_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "MOA-SP/" + CONF + "VerifyAuthBlock/" + CONF + "VerifyTransformsInfoProfileID"; - - /** an XPATH-Expression */ - protected static final String AUTH_IDENTITY_LINK_X509SUBJECTNAME_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "IdentityLinkSigners/" + CONF + "X509SubjectName"; - - /** an XPATH-Expression */ - public static final String AUTH_VERIFY_INFOBOXES_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "VerifyInfoboxes"; - - /** an XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "ForeignIdentities"; - - /** an XPATH-Expression */ - public static final String AUTH_ONLINEMANDATES_XPATH = - ROOT + CONF + "AuthComponent/" + CONF + "OnlineMandates"; - - - - /** an XPATH-Expression */ - protected static final String OA_XPATH = ROOT + CONF + "OnlineApplication"; - /** an XPATH-Expression */ - protected static final String OA_LOGIN_XPATH = ROOT + CONF + "OnlineApplication/@loginURL"; - /** an XPATH-Expression */ - protected static final String OA_AUTH_COMPONENT_XPATH = CONF + "AuthComponent"; - /** an XPATH-Expression */ - protected static final String OA_AUTH_COMPONENT_IDENT_NUMBER_XPATH = CONF + "IdentificationNumber"; - /** an XPATH-Expression */ - protected static final String OA_AUTH_COMPONENT_BKUSELECT_TEMPLATE_XPATH = - CONF + "Templates/" + CONF + "BKUSelectionTemplate/@URL"; - /** an XPATH-Expression */ - protected static final String OA_AUTH_COMPONENT_TEMPLATE_XPATH = - CONF + "Templates/" + CONF + "Template/@URL"; - /** an XPATH-Expression */ - public static final String OA_AUTH_COMPONENT_TEMPLATE_ONLINEMANDATES_BKU_XPATH = - CONF + "Templates/" + CONF + "OnlineMandates/" + CONF + "BKU"; - //protected static final String OA_AUTH_COMPONENT_MANDATE_TEMPLATE_XPATH = - //CONF + "Templates/" + CONF + "MandateTemplate/@URL"; - /** an XPATH-Expression */ - protected static final String OA_AUTH_COMPONENT_TRANSFORMS_INFO_FILENAME_XPATH = CONF + "TransformsInfo/@filename"; - /** an XPATH-Expression */ - protected static final String OA_AUTH_COMPONENT_VERIFY_INFOBOXES_XPATH = CONF + "VerifyInfoboxes"; - /** an XPATH-Expression */ - protected static final String OA_AUTH_COMPONENT_MANDATES_PROFILES_XPATH = CONF + "Mandates" + "/" + CONF + "Profiles"; - /** an XPATH-Expression */ - protected static final String CONNECTION_PARAMETER_URL_XPATH = - CONF + "ConnectionParameter/@URL"; - /** an XPATH-Expression */ - protected static final String CONNECTION_PARAMETER_ACCEPTED_CERTS_XPATH = - CONF + "ConnectionParameter/" + CONF + "AcceptedServerCertificates"; - /** an XPATH-Expression */ - protected static final String CONNECTION_PARAMETERN_KEYSTORE_XPATH = - CONF + "ConnectionParameter/" + CONF + "ClientKeyStore"; - /** an XPATH-Expression */ - protected static final String CONNECTION_PARAMETER_KEYSTORE_PASS_XPATH = - CONNECTION_PARAMETERN_KEYSTORE_XPATH + "/@password"; - /** an XPATH-Expression */ - protected static final String GENERIC_CONFIGURATION_XPATH = - ROOT + CONF + "GenericConfiguration"; - - /** an XPATH-Expression */ - protected static final String TRUSTED_BKUS = - ROOT + CONF + "TrustedBKUs/" + CONF + "BKUURL"; - - protected static final String TRUSTED_TEMPLATEURLS = - ROOT + CONF + "TrustedTemplateURLs/" + CONF + "TemplateURL"; - - - /** an XPATH-Expression */ - protected static final String CHAINING_MODES_XPATH = - ROOT + CONF + "ChainingModes"; - /** an XPATH-Expression */ - protected static final String CHAINING_MODES_DEFAULT_XPATH = - CHAINING_MODES_XPATH + "/@systemDefaultMode"; - /** an XPATH-Expression */ - protected static final String TRUST_ANCHOR_XPATH = - ROOT + CONF + "ChainingModes/" + CONF + "TrustAnchor"; - /** an XPATH-Expression */ - protected static final String ISSUER_XPATH = DSIG + "X509IssuerName"; - /** an XPATH-Expression */ - protected static final String SERIAL_XPATH = DSIG + "X509SerialNumber"; - /** an XPATH-Expression */ - protected static final String TRUSTED_CA_CERTIFICATES_XPATH = - ROOT + CONF + "TrustedCACertificates"; - - /** an XPATH-Expression */ - protected static final String VERIFY_INFOBOXES_DEFAULT_TRUST_PROFILE_XPATH = CONF + "DefaultTrustProfile"; - /** an XPATH-Expression */ - protected static final String VERIFY_INFOBOXES_TRUST_PROFILE_ID_XPATH = CONF + "TrustProfileID"; - /** an XPATH-Expression */ - protected static final String VERIFY_INFOBOXES_INFOBOX_XPATH = CONF + "Infobox"; - - - /** STORK Config XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_CPEPS = - ROOT + CONF + "AuthComponent/" + CONF + "ForeignIdentities/" + CONF + "STORK/" + CONF + "C-PEPS"; - - /** STORK Config AttributeName */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_CPEPS_COUNTRY_CODE = "countryCode"; - - /** STORK Config AttributeName */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_CPEPS_URL = "URL"; - - /** STORK Config XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_SIGNATURE_CREATION_PARAMETER = - ROOT + CONF + "AuthComponent/" + CONF + "ForeignIdentities/" + CONF + "STORK/" + CONF + "SAMLSigningParameter/" + - CONF + "SignatureCreationParameter" ; - - /** STORK Config XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_CPEPS_REQUESTED_ATTRIBUTES = - STORK + "RequestedAttribute"; - - /** STORK Config XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_SIGNATURE_VERIFICATION_PARAMETER = - ROOT + CONF + "AuthComponent/" + CONF + "ForeignIdentities/" + CONF + "STORK/" + CONF + "SAMLSigningParameter/" + - CONF + "SignatureVerificationParameter"; - - /** STORK Config XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_KEYSTORE = - CONF + "KeyStore"; - - /** STORK Config XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_KEYNAME = - CONF + "KeyName"; - - /** STORK Config XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_KEYSTORE_PASSWORD = - CONF + "KeyStore/@password"; - - /** STORK Config XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_KEYNAME_PASSWORD = - CONF + "KeyName/@password"; - - /** STORK Config XPATH-Expression */ - public static final String AUTH_FOREIGN_IDENTITIES_STORK_TRUSTPROFILE_ID = - CONF + "TrustProfileID"; - - /** STORK Config XPATH-Expression */ - public static final String OA_AUTH_COMPONENT_STORK_QAA = - CONF + "STORK/" + STORK + "QualityAuthenticationAssuranceLevel"; - - /** STORK Config XPATH-Expression */ - public static final String OA_AUTH_COMPONENT_STORK_REQUESTED_ATTRIBUTE = - CONF + "STORK/" + STORKP + "RequestedAttributes/" + STORK + "RequestedAttribute"; - - /** - * main configuration file directory name used to configure MOA-ID - */ - protected String rootConfigFileDir_; - - /** The root element of the MOA-ID configuration */ - protected Element configElem_; - - /** - * Creates a new MOAConfigurationProvider. - * - * @param configElem The root element of the MOA-ID configuration. - */ - public ConfigurationBuilder(Element configElem, String rootConfigDir) { - configElem_ = configElem; - rootConfigFileDir_ = rootConfigDir; - } - - /** - * Returns the root element of the MOA-ID configuration. - * - * @return The root element of the MOA-ID configuration. - */ - public Element getConfigElem() { - return configElem_; - } - - /** - * Build a ConnectionParameter object containing all information - * of the moa-sp element in the authentication component - * @return ConnectionParameter of the authentication component moa-sp element - */ - public ConnectionParameter buildAuthBKUConnectionParameter() { - - Element authBKU = (Element) XPathUtils.selectSingleNode(configElem_, AUTH_BKU_XPATH); - if (authBKU==null) return null; - return buildConnectionParameter(authBKU); - } - - /** - * Build a ConnectionParameter containing all information - * of the foreignid element in the authentication component - * @return ConnectionParameter of the authentication component foreignid element - */ - public ConnectionParameter buildForeignIDConnectionParameter() { - Element foreignid = (Element)XPathUtils.selectSingleNode(configElem_, AUTH_FOREIGN_IDENTITIES_XPATH); - if (foreignid==null) return null; - return buildConnectionParameter(foreignid); - - } - - /** - * Build a ConnectionParameter containing all information - * of the OnlineMandates element in the authentication component - * @return ConnectionParameter of the authentication component OnlineMandates element - */ - public ConnectionParameter buildOnlineMandatesConnectionParameter() { - Element onlinemandates = (Element)XPathUtils.selectSingleNode(configElem_, AUTH_ONLINEMANDATES_XPATH); - if (onlinemandates==null) return null; - return buildConnectionParameter(onlinemandates); - - } - - /** - * Method buildAuthBKUSelectionType. - * - * Build a string with the configuration value of BKUSelectionAlternative - * - * @return String - */ - public String buildAuthBKUSelectionType() { - - Element authBKU = (Element) XPathUtils.selectSingleNode(configElem_, AUTH_BKU_XPATH); - if (authBKU==null) return null; - return (authBKU).getAttribute("BKUSelectionAlternative"); - } - - /** - * Build a string array with all filenames leading - * to the Transforms Information for the Security Layer - * @param contextNode The node from which should be searched - * @param xpathExpr The XPATH expression for the search - * @return String[] of filenames to the Security Layer Transforms Information - * or null if no transforms are included - */ - public String[] buildTransformsInfoFileNames(Node contextNode, String xpathExpr) { - - List transformsInfoFileNames = new ArrayList(); - - try { - NodeIterator tiIter = XPathUtils.selectNodeIterator(contextNode, xpathExpr); - - Attr tiElem; - while ((tiElem = (Attr) tiIter.nextNode()) != null) { - String tiFileName = tiElem.getNodeValue(); - transformsInfoFileNames.add(tiFileName); - } - - String[] result = new String[transformsInfoFileNames.size()]; - transformsInfoFileNames.toArray(result); - - return result; - } catch (XPathException xpe) { - return new String[0]; - } - } - - - /** - * Loads the transformsInfos from files. - * @throws Exception on any exception thrown - */ - public String[] loadTransformsInfos(String[] transformsInfoFileNames) throws Exception { - - String[] transformsInfos; - - transformsInfos = new String[transformsInfoFileNames.length]; - for (int i = 0; i < transformsInfoFileNames.length; i++) { - - String fileURL = transformsInfoFileNames[i]; - try { - // if fileURL is relative to rootConfigFileDir make it absolute - fileURL = FileUtils.makeAbsoluteURL(fileURL, rootConfigFileDir_); - - String transformsInfo = FileUtils.readURL(fileURL, DEFAULT_ENCODING); - transformsInfos[i] = transformsInfo; - - } catch (IOException e) { - Logger.info("Transformation with URL " + fileURL + " can not be loaded"); - } - } - - return transformsInfos; - } - - /** - * Build a ConnectionParameter bean containing all information - * of the authentication component moa-sp element - * @return ConnectionParameter of the authentication component moa-sp element - */ - public ConnectionParameter buildMoaSpConnectionParameter() { - - Element connectionParameter = (Element) XPathUtils.selectSingleNode(configElem_, AUTH_MOA_SP_XPATH); - if (connectionParameter==null) return null; - return buildConnectionParameter(connectionParameter); - } - - /** - * Return a string with a url-reference to the VerifyIdentityLink trust - * profile id within the moa-sp part of the authentication component - * @return String with a url-reference to the VerifyIdentityLink trust profile ID - */ - public String getMoaSpIdentityLinkTrustProfileID() { - return XPathUtils.getElementValue( - configElem_, - AUTH_MOA_SP_VERIFY_IDENTITY_TRUST_ID_XPATH, - ""); - } - /** - * Return a string representation of an URL pointing to trusted CA Certificates - * @return String representation of an URL pointing to trusted CA Certificates - */ - public String getTrustedCACertificates() { - return XPathUtils.getElementValue( - configElem_, - TRUSTED_CA_CERTIFICATES_XPATH,null); - } - - /** - * Return a string with a url-reference to the VerifyAuthBlock trust - * profile id within the moa-sp part of the authentication component - * @return String with a url-reference to the VerifyAuthBlock trust profile ID - */ - public String getMoaSpAuthBlockTrustProfileID() { - return XPathUtils.getElementValue( - configElem_, - AUTH_MOA_SP_VERIFY_AUTH_TRUST_ID_XPATH, - ""); - } - /** - * Build a string array with references to all verify transform info - * IDs within the moa-sp part of the authentication component - * @return A string array containing all urls to the - * verify transform info IDs - */ - public String[] buildMoaSpAuthBlockVerifyTransformsInfoIDs() { - - List verifyTransformsInfoIDs = new ArrayList(); - NodeIterator vtIter = - XPathUtils.selectNodeIterator( - configElem_, - AUTH_MOA_SP_VERIFY_AUTH_VERIFY_ID_XPATH); - Element vtElem; - - while ((vtElem = (Element) vtIter.nextNode()) != null) { - - String vtInfoIDs = DOMUtils.getText(vtElem); - verifyTransformsInfoIDs.add(vtInfoIDs); - } - String[] result = new String[verifyTransformsInfoIDs.size()]; - verifyTransformsInfoIDs.toArray(result); - - return result; - } - - public List getTrustedBKUs() { - - List trustedBKUs = new ArrayList(); - - NodeIterator bkuIter = XPathUtils.selectNodeIterator(configElem_, TRUSTED_BKUS); - - Element vtElem; - - while ((vtElem = (Element) bkuIter.nextNode()) != null) { - String bkuURL = DOMUtils.getText(vtElem); - trustedBKUs.add(bkuURL); - } - - return trustedBKUs; - - } - -public List getTrustedTemplateURLs() { - - List trustedTemplateURLs = new ArrayList(); - - NodeIterator bkuIter = XPathUtils.selectNodeIterator(configElem_, TRUSTED_TEMPLATEURLS); - - Element vtElem; - - while ((vtElem = (Element) bkuIter.nextNode()) != null) { - String bkuURL = DOMUtils.getText(vtElem); - trustedTemplateURLs.add(bkuURL); - } - - return trustedTemplateURLs; - - } - - /** - * Returns a list containing all X509 Subject Names - * of the Identity Link Signers - * @return a list containing the configured identity-link signer X509 subject names - */ - public List getIdentityLink_X509SubjectNames() { - - Vector x509SubjectNameList = new Vector(); - NodeIterator x509Iter = - XPathUtils.selectNodeIterator( - configElem_, - AUTH_IDENTITY_LINK_X509SUBJECTNAME_XPATH); - Element x509Elem; - - while ((x509Elem = (Element) x509Iter.nextNode()) != null) { - String vtInfoIDs = DOMUtils.getText(x509Elem); - x509SubjectNameList.add(vtInfoIDs); - } - - // now add the default identity link signers - String[] identityLinkSignersWithoutOID = MOAIDAuthConstants.IDENTITY_LINK_SIGNERS_WITHOUT_OID; - for (int i=0; inull. - * @param moaSpIdentityLinkTrustProfileID The ID of the trust profile used for validating - * the identity link signer certificate. Needed for - * checking if this ID is not used for validating other - * infoboxes. - * - * @return An OAProxyParameter array containing beans - * with all relevant information for the authentication component of the online - * application - */ - public OAAuthParameter[] buildOnlineApplicationAuthParameters( - VerifyInfoboxParameters defaultVerifyInfoboxParameters, String moaSpIdentityLinkTrustProfileID) - throws ConfigurationException - { - - String bkuSelectionTemplateURL = - XPathUtils.getAttributeValue(configElem_, AUTH_BKUSELECT_TEMPLATE_XPATH, null); - String templateURL = - XPathUtils.getAttributeValue(configElem_, AUTH_TEMPLATE_XPATH, null); - String inputProcessorSignTemplateURL = - XPathUtils.getAttributeValue(configElem_, INPUT_PROCESSOR_TEMPLATE_XPATH, null); - - - List OA_set = new ArrayList(); - NodeList OAIter = XPathUtils.selectNodeList(configElem_, OA_XPATH); - - for (int i = 0; i < OAIter.getLength(); i++) { - Element oAElem = (Element) OAIter.item(i); - Element authComponent = - (Element) XPathUtils.selectSingleNode(oAElem, OA_AUTH_COMPONENT_XPATH); - - OAAuthParameter oap = new OAAuthParameter(); - String publicURLPrefix = oAElem.getAttribute("publicURLPrefix"); - oap.setPublicURLPrefix(publicURLPrefix); - oap.setKeyBoxIdentier(oAElem.getAttribute("keyBoxIdentifier")); - oap.setFriendlyName(oAElem.getAttribute("friendlyName")); - String targetConfig = oAElem.getAttribute("target"); - String targetFriendlyNameConfig = oAElem.getAttribute("targetFriendlyName"); - - // get the type of the online application - String oaType = oAElem.getAttribute("type"); - oap.setOaType(oaType); - String slVersion = "1.1"; - if ("businessService".equalsIgnoreCase(oaType)) { - if (authComponent==null) { - Logger.error("Missing \"AuthComponent\" for OA of type \"businessService\""); - throw new ConfigurationException("config.02", null); - } - Element identificationNumberElem = - (Element) XPathUtils.selectSingleNode(authComponent, OA_AUTH_COMPONENT_IDENT_NUMBER_XPATH); - if (identificationNumberElem==null) { - Logger.error("Missing \"IdentificationNumber\" for OA of type \"businessService\""); - throw new ConfigurationException("config.02", null); - } - Element identificationNumberChild = DOMUtils.getElementFromNodeList(identificationNumberElem.getChildNodes()); - if (identificationNumberChild == null) { - Logger.error("Missing \"IdentificationNumber\" for OA of type \"businessService\""); - throw new ConfigurationException("config.02", null); - } - - if (!StringUtils.isEmpty(targetConfig)) { - Logger.error("Target attribute can not be set for OA of type \"businessService\""); - throw new ConfigurationException("config.02", null); - } - if (!StringUtils.isEmpty(targetFriendlyNameConfig)) { - Logger.error("Target friendly name attribute can not be set for OA of type \"businessService\""); - throw new ConfigurationException("config.02", null); - } - - - if ("false".equalsIgnoreCase(oAElem.getAttribute("calculateHPI"))) { - oap.setIdentityLinkDomainIdentifier(buildIdentityLinkDomainIdentifier(identificationNumberChild)); - //BZ.., setting type of IdLinkDomainIdentifier - oap.setIdentityLinkDomainIdentifierType(identificationNumberChild.getLocalName()); - //..BZ - } else { - // If we have business service and want to dealt with GDA, the security layer can be advised to calulate - // the Health Professional Identifier HPI instead of the wbPK - Logger.info("OA uses HPI for Identification"); - oap.setIdentityLinkDomainIdentifier(Constants.URN_PREFIX_HPI); - } - - // if OA type is "businessSErvice" set slVersion to 1.2 and ignore parameter in config file - Logger.info("OA type is \"businessService\"; setting Security Layer version to 1.2"); - slVersion = "1.2"; - - } else { - - if (StringUtils.isEmpty(targetConfig) && !StringUtils.isEmpty(targetFriendlyNameConfig)) { - Logger.error("Target friendly name attribute can not be set alone for OA of type \"businessService\""); - throw new ConfigurationException("config.02", null); - } - oap.setTarget(targetConfig); - oap.setTargetFriendlyName(targetFriendlyNameConfig); - - if (authComponent!=null) { - slVersion = authComponent.getAttribute("slVersion"); - } - - - } - oap.setSlVersion(slVersion); - //Check if there is an Auth-Block to read from configuration - - if (authComponent!=null) - { - oap.setProvideStammzahl(BoolUtils.valueOf(authComponent.getAttribute("provideStammzahl"))); - oap.setProvideAuthBlock(BoolUtils.valueOf(authComponent.getAttribute("provideAUTHBlock"))); - oap.setProvideIdentityLink(BoolUtils.valueOf(authComponent.getAttribute("provideIdentityLink"))); - oap.setProvideCertificate(BoolUtils.valueOf(authComponent.getAttribute("provideCertificate"))); - oap.setProvideFullMandatorData(BoolUtils.valueOf(authComponent.getAttribute("provideFullMandatorData"))); - oap.setUseUTC(BoolUtils.valueOf(authComponent.getAttribute("useUTC"))); - oap.setUseCondition(BoolUtils.valueOf(authComponent.getAttribute("useCondition"))); - oap.setConditionLength(buildConditionLength(authComponent.getAttribute("conditionLength"))); - oap.setBkuSelectionTemplateURL(buildTemplateURL(authComponent, OA_AUTH_COMPONENT_BKUSELECT_TEMPLATE_XPATH, bkuSelectionTemplateURL)); - oap.setTemplateURL(buildTemplateURL(authComponent, OA_AUTH_COMPONENT_TEMPLATE_XPATH, templateURL)); - -// System.out.println(publicURLPrefix); -// System.out.println("useCondition: " + oap.getUseCondition()); -// System.out.println("conditionLength: " + oap.getConditionLength()); - - oap.setInputProcessorSignTemplateURL(buildTemplateURL(authComponent, INPUT_PROCESSOR_TEMPLATE_XPATH, inputProcessorSignTemplateURL)); - // load OA specific transforms if present - String[] transformsInfoFileNames = buildTransformsInfoFileNames(authComponent, OA_AUTH_COMPONENT_TRANSFORMS_INFO_FILENAME_XPATH); - try { - oap.setTransformsInfos(loadTransformsInfos(transformsInfoFileNames)); - } catch (Exception ex) { - Logger.error("Error loading transforms specified for OA \"" + publicURLPrefix + "\"; using default transforms."); - } - Node verifyInfoboxParamtersNode = XPathUtils.selectSingleNode(authComponent, OA_AUTH_COMPONENT_VERIFY_INFOBOXES_XPATH); - oap.setVerifyInfoboxParameters(buildVerifyInfoboxParameters( - verifyInfoboxParamtersNode, defaultVerifyInfoboxParameters, moaSpIdentityLinkTrustProfileID)); - - Node mandateProfilesNode = XPathUtils.selectSingleNode(authComponent, OA_AUTH_COMPONENT_MANDATES_PROFILES_XPATH); - if (mandateProfilesNode != null) { - if ("businessService".equalsIgnoreCase(oaType)) { - Logger.error("No Online Mandate Modus for OA of type \"businessService\" allowed."); - throw new ConfigurationException("config.02", null); - } - else { - String profiles = DOMUtils.getText(mandateProfilesNode); - oap.setMandateProfiles(profiles); - } - } - - //add STORK Configuration specific to OA (RequestedAttributes, QAALevel) - //QualityAuthenticationAssuranceLevel qaaLevel = buildOaSTORKQAALevel(authComponent); - //if (qaaLevel != null) { - // oap.setQaaLevel(qaaLevel); - // Logger.debug("Using non-MOA-default STORK QAALevel for this OA " + "(" + oap.getPublicURLPrefix() + "): " + qaaLevel.getValue()); - //} - - //RequestedAttributes additionalRequestedAttributes = buildOaSTORKRequestedAttributes(authComponent); - // - //if(!additionalRequestedAttributes.getRequestedAttributes().isEmpty()) { - // //we have additional STORK attributes to request for this OA - // Logger.debug("Using non-MOA-default STORK RequestedAttributes for this OA " + "(" + oap.getPublicURLPrefix() + "): "); - // for (RequestedAttribute addReqAttr : additionalRequestedAttributes.getRequestedAttributes()) { - // if (!SAMLUtil.containsAttribute(oap.getRequestedAttributes().getRequestedAttributes(),addReqAttr.getName())) { - /// addReqAttr.detach(); - // oap.getRequestedAttributes().getRequestedAttributes().add(addReqAttr); - // Logger.debug("Requesting additional attribute: " + addReqAttr.getName() + ", isRequired: " + addReqAttr.isRequired()); - // } - // } - - //} else { - // //do nothing, only request default attributes - //} - - - } - OA_set.add(oap); - } - OAAuthParameter[] result = - new OAAuthParameter[OA_set.size()]; - OA_set.toArray(result); - - return result; - - } - - /** - * Returns the condition length as int - * @param length the condition length as int - * @return - */ - private int buildConditionLength(String length) { - - if (StringUtils.isEmpty(length)) - return -1; - else - return new Integer(length).intValue(); - } - - /** - * Builds the URL for a BKUSelectionTemplate or a Template. The method selects - * the uri string from the MOA ID configuration file via the given xpath expression - * and returns either this string or the default value. - * - * @param oaAuthComponent The AuthComponent element to get the template from. - * @param xpathExpr The xpath expression for selecting the template uri. - * @param defaultURL The default template url. - * @return The template url. This may either the via xpath selected uri - * or, if no template is specified within the online appliacation, - * the default url. Both may be null. - */ - protected String buildTemplateURL(Element oaAuthComponent, String xpathExpr, String defaultURL) { - String templateURL = XPathUtils.getAttributeValue(oaAuthComponent, xpathExpr, defaultURL); - if (templateURL != null) { - templateURL = FileUtils.makeAbsoluteURL(templateURL, rootConfigFileDir_); - } - return templateURL; - } - - - - - - - /** - * Method buildConnectionParameter: internal Method for creating a - * ConnectionParameter object with all data found in the incoming element - * @param root This Element contains the ConnectionParameter - * @return ConnectionParameter - */ - protected ConnectionParameter buildConnectionParameter(Element root) - { - ConnectionParameter result = new ConnectionParameter(); - result.setAcceptedServerCertificates( - XPathUtils.getElementValue(root,CONNECTION_PARAMETER_ACCEPTED_CERTS_XPATH,null)); - - result.setAcceptedServerCertificates(FileUtils.makeAbsoluteURL( - result.getAcceptedServerCertificates(), rootConfigFileDir_)); - - result.setUrl( - XPathUtils.getAttributeValue(root, CONNECTION_PARAMETER_URL_XPATH, "")); - result.setClientKeyStore( - XPathUtils.getElementValue(root,CONNECTION_PARAMETERN_KEYSTORE_XPATH,null)); - - result.setClientKeyStore(FileUtils.makeAbsoluteURL( - result.getClientKeyStore(), rootConfigFileDir_)); - - result.setClientKeyStorePassword( - XPathUtils.getAttributeValue(root,CONNECTION_PARAMETER_KEYSTORE_PASS_XPATH,"")); - - if ((result.getAcceptedServerCertificates()==null) - && (result.getUrl()=="") - && (result.getClientKeyStore()==null) - && (result.getClientKeyStorePassword()=="")) - return null; - - return result; - } - - - /** - * Build the mapping of generic configuration properties. - * - * @return a {@link Map} of generic configuration properties (a name to value - * mapping) from the configuration. - */ - public Map buildGenericConfiguration() { - - Map genericConfiguration = new HashMap(); - NodeIterator gcIter = - XPathUtils.selectNodeIterator( - configElem_, - GENERIC_CONFIGURATION_XPATH); - Element gcElem; - - while ((gcElem = (Element) gcIter.nextNode()) != null) { - String gcName = gcElem.getAttribute("name"); - String gcValue = gcElem.getAttribute("value"); - - genericConfiguration.put(gcName, gcValue); - } - - return genericConfiguration; - } - - - /** - * Returns the default chaining mode from the configuration. - * - * @return The default chaining mode. - */ - public String getDefaultChainingMode() { - String defaultChaining = - XPathUtils.getAttributeValue( - configElem_, - CHAINING_MODES_DEFAULT_XPATH, - CM_CHAINING); - - return translateChainingMode(defaultChaining); - - } - /** - * Build the chaining modes for all configured trust anchors. - * - * @return The mapping from trust anchors to chaining modes. - */ - public Map buildChainingModes() { - Map chainingModes = new HashMap(); - NodeIterator trustIter = - XPathUtils.selectNodeIterator(configElem_, TRUST_ANCHOR_XPATH); - Element trustAnchorElem; - - while ((trustAnchorElem = (Element) trustIter.nextNode()) != null) { - IssuerAndSerial issuerAndSerial = buildIssuerAndSerial(trustAnchorElem); - String mode = trustAnchorElem.getAttribute("mode"); - - if (issuerAndSerial != null) { - chainingModes.put(issuerAndSerial, translateChainingMode(mode)); - } - } - - return chainingModes; - } - - /** - * Build an IssuerAndSerial from the DOM representation. - * - * @param root The root element (being of type dsig: - * X509IssuerSerialType. - * @return The issuer and serial number contained in the root - * element or null if could not be built for any reason. - */ - protected IssuerAndSerial buildIssuerAndSerial(Element root) { - String issuer = XPathUtils.getElementValue(root, ISSUER_XPATH, null); - String serial = XPathUtils.getElementValue(root, SERIAL_XPATH, null); - - if (issuer != null && serial != null) { - try { - RFC2253NameParser nameParser = new RFC2253NameParser(issuer); - Principal issuerDN = nameParser.parse(); - - return new IssuerAndSerial(issuerDN, new BigInteger(serial)); - } catch (RFC2253NameParserException e) { - warn("config.09", new Object[] { issuer, serial }, e); - return null; - } catch (NumberFormatException e) { - warn("config.09", new Object[] { issuer, serial }, e); - return null; - } - } - return null; - } - - /** - * Translate the chaining mode from the configuration file to one used in the - * IAIK MOA API. - * - * @param chainingMode The chaining mode from the configuration. - * @return The chaining mode as provided by the ChainingModes - * interface. - * @see iaik.pki.pathvalidation.ChainingModes - */ - protected String translateChainingMode(String chainingMode) { - if (chainingMode.equals(CM_CHAINING)) { - return ChainingModes.CHAIN_MODE; - } else if (chainingMode.equals(CM_PKIX)) { - return ChainingModes.PKIX_MODE; - } else { - return ChainingModes.CHAIN_MODE; - } - } - - /** - * Builds the IdentityLinkDomainIdentifier as needed for providing it to the - * SecurityLayer for computation of the wbPK. - *

e.g.:
- * input element: - *
- * <pr:Firmenbuchnummer Identifier="FN">000468 i</pr:Firmenbuchnummer> - *

- * return value: urn:publicid:gv.at+wbpk+FN468i - * - * @param number The element holding the identification number of the business - * company. - * @return The domain identifier - */ - protected String buildIdentityLinkDomainIdentifier(Element number) { - if (number == null) { - return null; - } - String identificationNumber = number.getFirstChild().getNodeValue(); - String identifier = number.getAttribute("Identifier"); - // remove all blanks - identificationNumber = StringUtils.removeBlanks(identificationNumber); - if (number.getLocalName().equals("Firmenbuchnummer") || identifier.equalsIgnoreCase("fn") || identifier.equalsIgnoreCase("xfn")) { - // delete zeros from the beginning of the number - identificationNumber = StringUtils.deleteLeadingZeros(identificationNumber); - // remove hyphens - identificationNumber = StringUtils.removeToken(identificationNumber, "-"); - } - StringBuffer identityLinkDomainIdentifier = new StringBuffer(Constants.URN_PREFIX_WBPK); - identityLinkDomainIdentifier.append("+"); - if (!identificationNumber.startsWith(identifier)) { - identityLinkDomainIdentifier.append(identifier); - } - identityLinkDomainIdentifier.append("+"); - identityLinkDomainIdentifier.append(identificationNumber); - return identityLinkDomainIdentifier.toString(); - } - - /** - * Builds the parameters for verifying additional infoboxes (additional to the - * IdentityLink infobox). - * - * @param verifyInfoboxesElem The VerifyInfoboxes element from the - * config file. This maybe the global element or the - * elment from an Online application. - * @param defaultVerifyInfoboxParameters Default parameters to be used, if no - * VerifyInfoboxes element is present. - * This only applies to parameters - * of an specific online application and is set to - * null when building the global parameters. - * @param moaSpIdentityLinkTrustProfileID The ID of the trust profile used for validating - * the identity link signer certificate. Needed for - * checking if this ID is not used for validating other - * infoboxes. - * - * @return A {@link at.gv.egovernment.moa.id.config.auth.VerifyInfoboxParameters VerifyInfoboxParameters} - * object needed for verifying additional infoboxes. - * - * @throws ConfigurationException If the trust profile for validating the identity link - * signer certificate is used for validating another infobox. - */ - public VerifyInfoboxParameters buildVerifyInfoboxParameters( - Node verifyInfoboxesElem, - VerifyInfoboxParameters defaultVerifyInfoboxParameters, - String moaSpIdentityLinkTrustProfileID) - throws ConfigurationException - { - - if ((verifyInfoboxesElem == null) && (defaultVerifyInfoboxParameters == null)) { - return null; - } - Vector identifiers = new Vector(); - List defaultIdentifiers = null; - Map defaultInfoboxParameters = null; - if (defaultVerifyInfoboxParameters != null) { - defaultIdentifiers = defaultVerifyInfoboxParameters.getIdentifiers(); - defaultInfoboxParameters = defaultVerifyInfoboxParameters.getInfoboxParameters(); - } - Hashtable infoboxParameters = new Hashtable(); - if (verifyInfoboxesElem != null) { - // get the DefaultTrustProfileID - String defaultTrustProfileID = null; - Node defaultTrustProfileNode = - XPathUtils.selectSingleNode(verifyInfoboxesElem, VERIFY_INFOBOXES_DEFAULT_TRUST_PROFILE_XPATH); - if (defaultTrustProfileNode != null) { - Node trustProfileIDNode = - XPathUtils.selectSingleNode(defaultTrustProfileNode, VERIFY_INFOBOXES_TRUST_PROFILE_ID_XPATH); - defaultTrustProfileID = trustProfileIDNode.getFirstChild().getNodeValue(); - if (defaultTrustProfileID.equals(moaSpIdentityLinkTrustProfileID)) { - throw new ConfigurationException("config.15", new Object[] {moaSpIdentityLinkTrustProfileID}); - } - } - // get the Infoboxes - NodeList infoboxes = - XPathUtils.selectNodeList(verifyInfoboxesElem, VERIFY_INFOBOXES_INFOBOX_XPATH); - for (int i=0; iTrustManager. - * This field will only be used in case of an HTTPS URL. - */ - private String acceptedServerCertificates; - /** - * File URL of a X509 key store containing the private key to be used - * for an HTTPS connection when the server requires client authentication. - * This field will only be used in case of an HTTPS URL. - */ - private String clientKeyStore; - /** - * Password protecting the client key store. - */ - private String clientKeyStorePassword; - - /** - * Checks whether the URL scheme is "https". - * @return true in case of an URL starting with "https" - */ - public boolean isHTTPSURL() { - return getUrl().indexOf("https") == 0; - } - - /** - * Returns the url. - * @return String - */ - public String getUrl() { - return url; - } - - /** - * Returns the acceptedServerCertificates. - * @return String - */ - public String getAcceptedServerCertificates() { - return acceptedServerCertificates; - } - - /** - * Sets the acceptedServerCertificates. - * @param acceptedServerCertificates The acceptedServerCertificates to set - */ - public void setAcceptedServerCertificates(String acceptedServerCertificates) { - this.acceptedServerCertificates = acceptedServerCertificates; - } - - /** - * Sets the url. - * @param url The url to set - */ - public void setUrl(String url) { - this.url = url; - } - - /** - * Returns the clientKeyStore. - * @return String - */ - public String getClientKeyStore() { - return clientKeyStore; - } - - /** - * Returns the clientKeyStorePassword. - * @return String - */ - public String getClientKeyStorePassword() { - return clientKeyStorePassword; - } - - /** - * Sets the clientKeyStore. - * @param clientKeyStore The clientKeyStore to set - */ - public void setClientKeyStore(String clientKeyStore) { - this.clientKeyStore = clientKeyStore; - } - - /** - * Sets the clientKeyStorePassword. - * @param clientKeyStorePassword The clientKeyStorePassword to set - */ - public void setClientKeyStorePassword(String clientKeyStorePassword) { - this.clientKeyStorePassword = clientKeyStorePassword; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/OAAuthParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/OAAuthParameter.java deleted file mode 100644 index 6bdbd38d8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/OAAuthParameter.java +++ /dev/null @@ -1,464 +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.config.legacy; - -/** - * Configuration parameters belonging to an online application, - * to use with the MOA ID Auth component. - * - * @author Stefan Knirsch - * @version $Id$ - */ -/** - * - * - * @author Harald Bratko - */ -public class OAAuthParameter extends OAParameter { - /** - * Sercurity Layer version - */ - private String slVersion; - /** - * true, if the Security Layer version is version 1.2, otherwise false - */ - private boolean slVersion12; - /** - * identityLinkDomainIdentifier - * (e.g urn:publicid:gv.at+wbpk+FN468i for a "Firmenbuchnummer") - *
- * only used within a business application context for providing it to the - * security layer as input for wbPK computation - */ - private String identityLinkDomainIdentifier; - /** - * key box Identifier (e.g. CertifiedKeypair, SecureSignatureKeypair) - */ - private String keyBoxIdentifier; - /** - * transformations for rendering in the secure viewer of the security layer - * implementation; multiple transformation can be given for different mime types - */ - private String[] transformsInfos; - /** - * determines whether "Stammzahl" is to be included in the authentication data - */ - private boolean provideStammzahl; - /** - * determines whether AUTH block is to be included in the authentication data - */ - private boolean provideAuthBlock; - /** - * determines whether identity link is to be included in the authentication data - */ - private boolean provideIdentityLink; - /** - * determines whether the certificate is to be included in the authentication data - */ - private boolean provideCertificate; - /** - * determines whether the full mandator data (i.e. the mandate) is to be included in the authentication data - */ - private boolean provideFullMandatorData; - - /** determines wheter the IssueInstant of the SAML assertion is in UTC or not*/ - private boolean useUTC; - - /** determines wheter a saml:Condition is added to the SAML assertion or not */ - private boolean useCondition; - - /** determines the validity time of the SAML assertion (if useCondition is true) in seconds */ - private int conditionLength; - /** - * url to a template for web page "Auswahl der Bürgerkartenumgebung" - */ - private String bkuSelectionTemplateURL; - /** - * template for web page "Anmeldung mit Bürgerkarte" - */ - private String templateURL; - - /** - * template for web page "Signatur der Anmeldedaten" - */ - private String inputProcessorSignTemplateURL; - /** - * Parameters for verifying infoboxes. - */ - private VerifyInfoboxParameters verifyInfoboxParameters; - - /** - * Parameter for Mandate profiles - */ - private String mandateProfiles; - - /** - * - * Type for authentication number (e.g. Firmenbuchnummer) - */ - private String identityLinkDomainIdentifierType; - -/** - * Returns true if the Security Layer version is version 1.2, - * otherwise false. - * @return true if the Security Layer version is version 1.2, - * otherwise false - */ - public boolean getSlVersion12() { - return slVersion12; - } - - /** - * Returns the security layer version. - * @return the security layer version. - */ - public String getSlVersion() { - return slVersion; - } - - /** - * Returns the identityLinkDomainIdentifier. - * @return the identityLinkDomainIdentifier. - */ - public String getIdentityLinkDomainIdentifier() { - return identityLinkDomainIdentifier; - } - - /** - * Returns the transformsInfos. - * @return the transformsInfos. - */ - public String[] getTransformsInfos() { - return transformsInfos; - } - - /** - * Returns the provideAuthBlock. - * @return String - */ - public boolean getProvideAuthBlock() { - return provideAuthBlock; - } - - /** - * Returns the provideIdentityLink. - * @return String - */ - public boolean getProvideIdentityLink() { - return provideIdentityLink; - } - - /** - * Returns the provideStammzahl. - * @return String - */ - public boolean getProvideStammzahl() { - return provideStammzahl; - } - - /** - * Returns true if the certificate should be provided within the - * authentication data, otherwise false. - * @return true if the certificate should be provided, - * otherwise false - */ - public boolean getProvideCertifcate() { - return provideCertificate; - } - - /** - * Returns true if the full mandator data should be provided within the - * authentication data, otherwise false. - * @return true if the full mandator data should be provided, - * otherwise false - */ - public boolean getProvideFullMandatorData() { - return provideFullMandatorData; - } - - /** - * Returns true if the IssueInstant should be given in UTC, otherwise false. - * @return true if the IssueInstant should be given in UTC, otherwise false. - */ - public boolean getUseUTC() { - return useUTC; - } - - /** - * Returns true if the SAML assertion should contain a saml:Condition, otherwise false. - * @return true if the SAML assertion should contain a saml:Condition, otherwise false. - */ - public boolean getUseCondition() { - return useCondition; - } - - /** - * Returns the validity time of the SAML assertion (if useCondition is true) in seconds - * @return the validity time of the SAML assertion (if useCondition is true) in seconds - */ - public int getConditionLength() { - return conditionLength; - } - - -/** - * Returns the key box identifier. - * @return String - */ - public String getKeyBoxIdentifier() { - return keyBoxIdentifier; - } - - /** - * Returns the BkuSelectionTemplate url. - * @return The BkuSelectionTemplate url or null if no url for - * a BkuSelectionTemplate is set. - */ - public String getBkuSelectionTemplateURL() { - return bkuSelectionTemplateURL; - } - - /** - * Returns the TemplateURL url. - * @return The TemplateURL url or null if no url for - * a Template is set. - */ - public String getTemplateURL() { - return templateURL; - } - - - /** - * Returns the inputProcessorSignTemplateURL url. - * @return The inputProcessorSignTemplateURL url or null if no url for - * a input processor sign template is set. - */ - public String getInputProcessorSignTemplateURL() { - return inputProcessorSignTemplateURL; - } - - /** - * Returns the parameters for verifying additional infoboxes. - * - * @return The parameters for verifying additional infoboxes. - * Maybe null. - */ - public VerifyInfoboxParameters getVerifyInfoboxParameters() { - return verifyInfoboxParameters; - } - - /** - * Sets the security layer version. - * Also sets slVersion12 ({@link #getSlVersion12()}) - * to true if the Security Layer version is 1.2. - * @param slVersion The security layer version to be used. - */ - public void setSlVersion(String slVersion) { - this.slVersion = slVersion; - if ("1.2".equals(slVersion)) { - this.slVersion12 = true; - } - } - /** - * Sets the IdentityLinkDomainIdentifier. - * @param identityLinkDomainIdentifier The IdentityLinkDomainIdentifiern number of the online application. - */ - public void setIdentityLinkDomainIdentifier(String identityLinkDomainIdentifier) { - this.identityLinkDomainIdentifier = identityLinkDomainIdentifier; - } - /** - * Sets the transformsInfos. - * @param transformsInfos The transformsInfos to be used. - */ - public void setTransformsInfos(String[] transformsInfos) { - this.transformsInfos = transformsInfos; - } - - -/** - * Sets the provideAuthBlock. - * @param provideAuthBlock The provideAuthBlock to set - */ - public void setProvideAuthBlock(boolean provideAuthBlock) { - this.provideAuthBlock = provideAuthBlock; - } - - /** - * Sets the provideIdentityLink. - * @param provideIdentityLink The provideIdentityLink to set - */ - public void setProvideIdentityLink(boolean provideIdentityLink) { - this.provideIdentityLink = provideIdentityLink; - } - - /** - * Sets the provideStammzahl. - * @param provideStammzahl The provideStammzahl to set - */ - public void setProvideStammzahl(boolean provideStammzahl) { - this.provideStammzahl = provideStammzahl; - } - - /** - * Sets the provideCertificate variable. - * @param provideCertificate The provideCertificate value to set - */ - public void setProvideCertificate(boolean provideCertificate) { - this.provideCertificate = provideCertificate; - } - - /** - * Sets the provideFullMandatorData variable. - * @param provideFullMandatorData The provideFullMandatorData value to set - */ - public void setProvideFullMandatorData(boolean provideFullMandatorData) { - this.provideFullMandatorData = provideFullMandatorData; - } - - /** - * Sets the useUTC variable. - * @param useUTC The useUTC value to set - */ - public void setUseUTC(boolean useUTC) { - this.useUTC = useUTC; - } - - /** - * Sets the useCondition variable - * @param useCondition The useCondition value to set - */ - public void setUseCondition(boolean useCondition) { - this.useCondition = useCondition; - } - - /** - * Sets the conditionLength variable - * @param conditionLength the conditionLength value to set - */ - public void setConditionLength(int conditionLength) { - this.conditionLength = conditionLength; - } - - - /** - * Sets the key box identifier. - * @param keyBoxIdentifier to set - */ - public void setKeyBoxIdentier(String keyBoxIdentifier) { - this.keyBoxIdentifier = keyBoxIdentifier; - } - - /** - * Sets the BkuSelectionTemplate url. - * @param bkuSelectionTemplateURL The url string specifying the location - * of a BkuSelectionTemplate. - */ - public void setBkuSelectionTemplateURL(String bkuSelectionTemplateURL) { - this.bkuSelectionTemplateURL = bkuSelectionTemplateURL; - } - - /** - * Sets the Template url. - * @param templateURL The url string specifying the location - * of a Template. - */ - public void setTemplateURL(String templateURL) { - this.templateURL = templateURL; - } - - /** - * Sets the input processor sign form template url. - * - * @param inputProcessorSignTemplateURL The url string specifying the - * location of the input processor sign form - */ - public void setInputProcessorSignTemplateURL(String inputProcessorSignTemplateURL) { - this.inputProcessorSignTemplateURL = inputProcessorSignTemplateURL; - } - - /** - * Sets the parameters for verifying additonal (to the identitylink infobox) infoboxes. - * - * @param verifyInfoboxParameters The verifyInfoboxParameters to set. - */ - public void setVerifyInfoboxParameters(VerifyInfoboxParameters verifyInfoboxParameters) { - this.verifyInfoboxParameters = verifyInfoboxParameters; - } - - /** - * Gets the IdentityLinkDomainIdentifier (e.g. Firmenbuchnummer) - * @return IdentityLinkDomainIdentifier (e.g. Firmenbuchnummer) - */ - public String getIdentityLinkDomainIdentifierType() { - return identityLinkDomainIdentifierType; - } - - /** - * Sets the IdentityLinkDomainIdentifier (e.g. Firmenbuchnummer) - * @param identityLinkDomainIdentifierType The IdentityLinkDomainIdentifier to set (e.g. Firmenbuchnummer) - */ - public void setIdentityLinkDomainIdentifierType(String identityLinkDomainIdentifierType) { - this.identityLinkDomainIdentifierType = identityLinkDomainIdentifierType; - } - - /** - * Sets the Mandate/Profiles - * @param profiles - */ - public void setMandateProfiles(String profiles) { - this.mandateProfiles = profiles; - } - - /** - * Returns the Mandates/Profiles - * @return - */ - public String getMandateProfiles() { - return this.mandateProfiles; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/OAParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/OAParameter.java deleted file mode 100644 index 2a4d68726..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/OAParameter.java +++ /dev/null @@ -1,186 +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.config.legacy; - -/** - * Configuration parameters belonging to an online application, - * to be used within both, the MOA ID Auth and the - * MOA ID PROXY component. - * - * @author Harald Bratko - */ -public class OAParameter { - - /** - * type of the online application (maybe "PublicService" or "BusinessService") - */ - private String oaType; - - /** - * specifies whether the online application is a business application or not - * (true if value of {@link #oaType} is "businessService" - */ - private boolean businessService; - - /** - * public URL prefix of the online application - */ - private String publicURLPrefix; - - /** - * specifies a human readable name of the Online Application - */ - private String friendlyName; - - /** - * specified a specific target for the Online Application (overwrites the target in der request) - */ - private String target; - /** - * specifies a friendly name for the target - */ - private String targetFriendlyName; - - /** - * Returns the type of the online application. - * @return the type of the online application. - */ - public String getOaType() { - return oaType; - } - - /** - * Returns true is the OA is a businss application, otherwise - * false. - * @return true is the OA is a businss application, otherwise - * false - */ - public boolean getBusinessService() { - return this.businessService; - } - - /** - * Returns the publicURLPrefix. - * @return String - */ - public String getPublicURLPrefix() { - return publicURLPrefix; - } - - /** - * - * Sets the type of the online application. - * If the type is "businessService" the value of businessService - * ({@link #getBusinessService()}) is also set to true - * @param oaType The type of the online application. - */ - public void setOaType(String oaType) { - this.oaType = oaType; - if ("businessService".equalsIgnoreCase(oaType)) { - this.businessService = true; - } - } - - /** - * Sets the publicURLPrefix. - * @param publicURLPrefix The publicURLPrefix to set - */ - public void setPublicURLPrefix(String publicURLPrefix) { - this.publicURLPrefix = publicURLPrefix; - } - - - /** - * Gets the friendly name of the OA - * @return Friendly Name of the OA - */ - public String getFriendlyName() { - return friendlyName; - } - - /** - * Sets the friendly name of the OA - * @param friendlyName - */ - public void setFriendlyName(String friendlyName) { - this.friendlyName = friendlyName; - } - - /** - * Gets the target of the OA - * @return target of the OA - */ - public String getTarget() { - return target; - } - - /** - * Sets the target of the OA - * @param target - */ - public void setTarget(String target) { - this.target = target; - } - - /** - * Gets the target friendly name of the OA - * @return target Friendly Name of the OA - */ - public String getTargetFriendlyName() { - return targetFriendlyName; - } - - /** - * Sets the target friendly name of the OA - * @param targetFriendlyName - */ - public void setTargetFriendlyName(String targetFriendlyName) { - this.targetFriendlyName = targetFriendlyName; - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/STORKConfig.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/STORKConfig.java deleted file mode 100644 index 4666122d2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/STORKConfig.java +++ /dev/null @@ -1,112 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/** - * - */ -package at.gv.egovernment.moa.id.config.legacy; - -import java.util.HashMap; -import java.util.Map; - -import at.gv.egovernment.moa.util.StringUtils; - -/** - * Encapsulates several STORK configuration parameters according MOA configuration - * - * @author bzwattendorfer - * - */ -public class STORKConfig { - - /** STORK SAML signature creation parameters */ - private SignatureCreationParameter signatureCreationParameter; - - /** STORK SAML signature verification parameters */ - private SignatureVerificationParameter signatureVerificationParameter; - - /** Map of supported C-PEPSs */ - private Map cpepsMap = new HashMap(); - - - /** - * Constructs a STORK Config object - * @param signatureCreationParameter STORK SAML Signature creation parameters - * @param signatureVerificationParameter STORK SAML Signature verification parameters - * @param cpepsMap Map of supported C-PEPS - */ - public STORKConfig(SignatureCreationParameter signatureCreationParameter, - SignatureVerificationParameter signatureVerificationParameter, - Map cpepsMap) { - super(); - this.signatureCreationParameter = signatureCreationParameter; - this.signatureVerificationParameter = signatureVerificationParameter; - this.cpepsMap = cpepsMap; - } - - public SignatureCreationParameter getSignatureCreationParameter() { - return signatureCreationParameter; - } - - public void setSignatureCreationParameter( - SignatureCreationParameter signatureCreationParameter) { - this.signatureCreationParameter = signatureCreationParameter; - } - - public SignatureVerificationParameter getSignatureVerificationParameter() { - return signatureVerificationParameter; - } - - public void setSignatureVerificationParameter( - SignatureVerificationParameter signatureVerificationParameter) { - this.signatureVerificationParameter = signatureVerificationParameter; - } - - public Map getCpepsMap() { - return cpepsMap; - } - - public void setCpepsMap(Map cpepsMap) { - this.cpepsMap = cpepsMap; - } - - public boolean isSTORKAuthentication(String ccc) { - - if (StringUtils.isEmpty(ccc) || this.cpepsMap.isEmpty()) - return false; - - if (this.cpepsMap.containsKey(ccc.toUpperCase())) - return true; - else - return false; - - } - - public CPEPS getCPEPS(String ccc) { - if (isSTORKAuthentication(ccc)) - return this.cpepsMap.get(ccc); - else - return null; - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/SignatureCreationParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/SignatureCreationParameter.java deleted file mode 100644 index 69d4889af..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/SignatureCreationParameter.java +++ /dev/null @@ -1,134 +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.config.legacy; - -/** - * Encapsulates signature creation parameters according MOA configuration - * - * @author bzwattendorfer - * - */ -public class SignatureCreationParameter { - - /** KeyStore Path */ - private String keyStorePath; - - /** KeyStore Password */ - private String keyStorePassword; - - /** Signing Key Name */ - private String keyName; - - /** Signing Key Password */ - private String keyPassword; - - /** - * Gets the KeyStore Path - * @return File Path to KeyStore - */ - public String getKeyStorePath() { - return keyStorePath; - } - - /** - * Sets the KeyStore Path - * @param keyStorePath Path to KeyStore - */ - public void setKeyStorePath(String keyStorePath) { - this.keyStorePath = keyStorePath; - } - - /** - * Gets the KeyStore Password - * @return Password to KeyStore - */ - public String getKeyStorePassword() { - return keyStorePassword; - } - - /** - * Sets the KeyStore Password - * @param keyStorePassword Password to KeyStore - */ - public void setKeyStorePassword(String keyStorePassword) { - this.keyStorePassword = keyStorePassword; - } - - /** - * Gets the Signing Key Name - * @return Siging Key Name - */ - public String getKeyName() { - return keyName; - } - - /** - * Sets the Signing Key Name - * @param keyName Signing Key Name - */ - public void setKeyName(String keyName) { - this.keyName = keyName; - } - - /** - * Gets the Signing Key Password - * @return Signing Key Password - */ - public String getKeyPassword() { - return keyPassword; - } - - /** - * Sets the Signing Key Password - * @param keyPassword Signing Key Password - */ - public void setKeyPassword(String keyPassword) { - this.keyPassword = keyPassword; - } - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/SignatureVerificationParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/SignatureVerificationParameter.java deleted file mode 100644 index 9358d763f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/SignatureVerificationParameter.java +++ /dev/null @@ -1,57 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/** - * - */ -package at.gv.egovernment.moa.id.config.legacy; - -/** - * Encapsulates Signature Verification data for STORK according MOA configuration - * - * @author bzwattendorfer - * - */ -public class SignatureVerificationParameter { - - /** ID of the MOA-SP TrustProfile to be used for STORK SAML signature verification */ - private String trustProfileID; - - /** - * Gets the MOA-SP TrustProfileID - * @return TrustProfileID of MOA-SP for STORK signature verification - */ - public String getTrustProfileID() { - return trustProfileID; - } - - /** - * Sets the MOA-SP TrustProfileID - * @param trustProfileID TrustProfileID of MOA-SP for STORK signature verification - */ - public void setTrustProfileID(String trustProfileID) { - this.trustProfileID = trustProfileID; - } - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/VerifyInfoboxParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/VerifyInfoboxParameter.java deleted file mode 100644 index 6f00a7b9c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/VerifyInfoboxParameter.java +++ /dev/null @@ -1,433 +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.config.legacy; - -import java.io.IOException; -import java.util.Iterator; -import java.util.List; - -import javax.xml.transform.TransformerException; - -import org.apache.xpath.XPathAPI; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import at.gv.egovernment.moa.id.auth.data.Schema; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.egovernment.moa.util.StringUtils; - -/** - * This class is a container for parameters that maybe needed for verifying an infobox. - * - * @author Harald Bratko - */ -public class VerifyInfoboxParameter { - - /** - * The default package name (first part) of a infobox validator class. - */ - public static final String DEFAULT_PACKAGE_TRUNK = "at.gv.egovernment.moa.id.auth.validator."; - - /** - * The identifier of the infobox to be verified. This identifier must exactly the - * identifier of the infobox returned by BKU. - */ - protected String identifier_; - - /** - * The friendly name of the infobox. - * This name is used within browser messages, thus it should be the german equivalent of - * the {@link #identifier_ infobox identifier} (e.g. "Stellvertretungen" - * for "Mandates" or "GDAToken" for - * "EHSPToken". - *
If not specified within the config file the {@link #identifier_ infobox identifier} - * will be used. - */ - protected String friendlyName_; - - /** - * The Id of the TrustProfile to be used for validating certificates. - */ - protected String trustProfileID_; - - /** - * The full name of the class to be used for verifying the infobox. - */ - protected String validatorClassName_; - - /** - * Schema location URIs that may be needed by the - * validator to parse infobox tokens. - * Each entry in the list is a {@link at.gv.egovernment.moa.id.auth.data.Schema Schema} - * specifying the location of an XML schema. - */ - protected List schemaLocations_; - - /** - * Application specific parameters that may be needed for verifying an infobox. - */ - protected Element applicationSpecificParams_; - - /** - * Specifies if the infobox is be required to be returned by the BKU. - */ - protected boolean required_; - - /** - * Specifies whether the Stammzahl should be passed to the verifying - * application or not. - */ - protected boolean provideStammzahl_; - - /** - * Specifies whether the identity link should be passed to the verifying - * application or not. - */ - protected boolean provideIdentityLink_; - - /** - * Initializes this VerifiyInfoboxParamater with the given identifier and a default - * validator class name. - * - * @param identifier The identifier of the infobox to be verified. - */ - public VerifyInfoboxParameter(String identifier) { - identifier_ = identifier; - StringBuffer sb = new StringBuffer(DEFAULT_PACKAGE_TRUNK); - sb.append(identifier.toLowerCase()); - sb.append("."); - sb.append(identifier.substring(0, 1).toUpperCase()); - sb.append(identifier.substring(1)); - sb.append("Validator"); - validatorClassName_ = sb.toString(); - } - - /** - * Returns application specific parameters. - * Each child element of this element contains a verifying application specific parameter. {@link #applicationSpecificParams_} - * - * @see #applicationSpecificParams_ - * - * @return Application specific parameters. - */ - public Element getApplicationSpecificParams() { - return applicationSpecificParams_; - } - - /** - * Sets the application specific parameters. - * - * @see #applicationSpecificParams_ - * - * @param applicationSpecificParams The application specific parameters to set. - */ - public void setApplicationSpecificParams(Element applicationSpecificParams) { - applicationSpecificParams_ = applicationSpecificParams; - } - - /** - * Appends special application specific parameters for party representation. - * - * @param applicationSpecificParams The application specific parameters for party representation to set. - */ - public void appendParepSpecificParams(Element applicationSpecificParams) { - try { - if (applicationSpecificParams_==null) { - applicationSpecificParams_ = applicationSpecificParams.getOwnerDocument().createElement("ApplicationSpecificParameters"); - } - Element nameSpaceNode = applicationSpecificParams.getOwnerDocument().createElement("NameSpaceNode"); - nameSpaceNode.setAttribute("xmlns:" + Constants.MOA_ID_CONFIG_PREFIX, Constants.MOA_ID_CONFIG_NS_URI); - NodeList nodeList = XPathAPI.selectNodeList(applicationSpecificParams, "*", nameSpaceNode); - if (null!=nodeList) { - for (int i=0; iTrue if the identity link should be passed to the verifying - * application, otherwise false. - */ - public boolean getProvideIdentityLink() { - return provideIdentityLink_; - } - - /** - * Sets the {@link #provideIdentityLink_} parameter. - * - * @param provideIdentityLink True if the identity link should be passed to - * the verifying application, otherwise false. - */ - public void setProvideIdentityLink(boolean provideIdentityLink) { - provideIdentityLink_ = provideIdentityLink; - } - - /** - * Specifies whether the Stammzahl should be passed to the verifying - * application or not. - * - * @return True if the Stammzahl should be passed to the - * verifying application, otherwise false. - */ - public boolean getProvideStammzahl() { - return provideStammzahl_; - } - - /** - * Sets the {@link #provideStammzahl_} parameter. - * - * @param provideStammzahl True if the Stammzahl should be - * passed to the verifying application, otherwise false. - */ - public void setProvideStammzahl(boolean provideStammzahl) { - provideStammzahl_ = provideStammzahl; - } - - /** - * Specifies whether the infobox is required or not. - * - * @return True if the infobox is required to be returned by the BKU, - * otherwise false. - */ - public boolean isRequired() { - return required_; - } - - /** - * Sets the {@link #required_} parameter. - * - * @param required True if the infobox is required to be returned by the - * BKU, otherwise false. - */ - public void setRequired(boolean required) { - required_ = required; - } - - /** - * Schema location URIs that may be needed by the - * validator to parse infobox tokens. - * Each entry in the list is a {@link at.gv.egovernment.moa.id.auth.data.Schema Schema} - * specifying the location of an XML schema. - * - * @return A list of {@link at.gv.egovernment.moa.id.auth.data.Schema Schema} objects - * each of them specifying the location of an XML schema. - */ - public List getSchemaLocations() { - return schemaLocations_; - } - - /** - * Sets the schema locations. - * - * @see #schemaLocations_ - * - * @param schemaLocations The schema location list to be set. - */ - public void setSchemaLocations(List schemaLocations) { - schemaLocations_ = schemaLocations; - } - - /** - * Returns the ID of the trust profile to be used for verifying certificates. - * - * @return The ID of the trust profile to be used for verifying certificates. - * Maybe null. - */ - public String getTrustProfileID() { - return trustProfileID_; - } - - /** - * Sets the ID of the trust profile to be used for verifying certificates. - * - * @param trustProfileID The ID of the trust profile to be used for verifying certificates. - */ - public void setTrustProfileID(String trustProfileID) { - trustProfileID_ = trustProfileID; - } - - /** - * Returns the name of the class to be used for verifying this infobox. - * - * @return The name of the class to be used for verifying this infobox. - */ - public String getValidatorClassName() { - return validatorClassName_; - } - - /** - * Sets the name of the class to be used for verifying this infobox. - * - * @param validatorClassName The name of the class to be used for verifying this infobox. - */ - public void setValidatorClassName(String validatorClassName) { - validatorClassName_ = validatorClassName; - } - - /** - * Get a string representation of this object. - * This method is for debugging purposes only. - * - * @return A string representation of this object. - */ - public String toString() { - - StringBuffer buffer = new StringBuffer(1024); - - buffer.append(" "); - buffer.append("\n"); - if (friendlyName_ != null) { - buffer.append(" "); - buffer.append(friendlyName_); - buffer.append(""); - buffer.append("\n"); - } - if (trustProfileID_ != null) { - buffer.append(" "); - buffer.append(trustProfileID_); - buffer.append(""); - buffer.append("\n"); - } - if (validatorClassName_ != null) { - buffer.append(" "); - buffer.append(validatorClassName_); - buffer.append(""); - buffer.append("\n"); - } - if (schemaLocations_ != null) { - buffer.append(" "); - buffer.append("\n"); - Iterator it = schemaLocations_.iterator(); - while (it.hasNext()) { - buffer.append(" \n"); - } - buffer.append(" "); - buffer.append("\n"); - } - if (applicationSpecificParams_ != null) { - try { - String applicationSpecificParams = DOMUtils.serializeNode(applicationSpecificParams_); - buffer.append(" "); - buffer.append(StringUtils.removeXMLDeclaration(applicationSpecificParams)); - buffer.append("\n"); - } catch (TransformerException e) { - // do nothing - } catch (IOException e) { - // do nothing - } - } - buffer.append(" "); - - - return buffer.toString() ; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/VerifyInfoboxParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/VerifyInfoboxParameters.java deleted file mode 100644 index b7a6b42be..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/VerifyInfoboxParameters.java +++ /dev/null @@ -1,181 +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.config.legacy; - -import java.util.Hashtable; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * This class contains the parameters for verifying all the infoboxes configured for an - * online application. - * - * @author Harald Bratko - */ -public class VerifyInfoboxParameters { - - /** - * A map of {@link VerifyInfoboxParameter} objects. - * Each of these objects contains parameters that maybe needed for validating an - * infobox. - */ - protected Map infoboxParameters_; - - /** - * A list of the identifiers of the infoboxes supported by this - * VerifyInfoboxParameters; - */ - protected List identifiers_; - - /** - * Holds the (comma separated) identifiers of those infoboxes MOA-IF is able to validate - * in the context of the actual online application. - * The string will be added as value of the PushInfobox parameter in the - * HTML form used for reading the infoboxes from the BKU. - */ - protected String pushInfobox_; - - /** - * Initializes this VerifyInfoboxParameters with an empty {@link #infoboxParameters_} - * map. - */ - public VerifyInfoboxParameters() { - infoboxParameters_ = new Hashtable(); - pushInfobox_ = ""; - } - - /** - * Initializes this VerifyInfoboxParameters with the given - * infoboxParameters map and builds the {@link #pushInfobox_} string - * from the keys of the given map. - */ - public VerifyInfoboxParameters(List identifiers, Map infoboxParameters) { - identifiers_ = identifiers; - infoboxParameters_ = infoboxParameters; - // build the pushInfobox string - if ((identifiers != null) && (!identifiers.isEmpty())) { - StringBuffer identifiersSB = new StringBuffer(); - int identifiersNum = identifiers.size(); - int i = 1; - Iterator it = identifiers.iterator(); - while (it.hasNext()) { - identifiersSB.append((String)it.next()); - if (i != identifiersNum) { - identifiersSB.append(","); - } - i++; - } - pushInfobox_ = identifiersSB.toString(); - } else { - pushInfobox_ = ""; - } - } - - /** - * Returns the (comma separated) identifiers of the infoboxes configured for the actual - * online application. - * - * @see #pushInfobox_ - * - * @return The (comma separated) identifiers of the infoboxes configured for the actual - * online application. - */ - public String getPushInfobox() { - return pushInfobox_; - } - - /** - * Sets the {@link #pushInfobox_} string. - * - * @param pushInfobox The pushInfobox string to be set. - */ - public void setPushInfobox(String pushInfobox) { - pushInfobox_ = pushInfobox; - } - - /** - * Returns map of {@link VerifyInfoboxParameter} objects. - * Each of these objects contains parameters that maybe needed for validating an - * infobox. - * - * @return The map of {@link VerifyInfoboxParameter} objects. - */ - public Map getInfoboxParameters() { - return infoboxParameters_; - } - - /** - * Sets the map of {@link VerifyInfoboxParameter} objects. - * - * @see #infoboxParameters_ - * - * @param infoboxParameters The infoboxParameters to set. - */ - public void setInfoboxParameters(Map infoboxParameters) { - infoboxParameters_ = infoboxParameters; - } - - /** - * Returns the identifiers of the supported infoboxes. - * - * @return The identifiers. - */ - public List getIdentifiers() { - return identifiers_; - } - - /** - * Sets the identifiers. - * - * @param identifiers The identifiers to set. - */ - public void setIdentifiers(List identifiers) { - identifiers_ = identifiers; - } - -} -- cgit v1.2.3 From 124d1fbe79b017b1159b254faea4bba98d86b8d6 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 9 Mar 2016 16:00:17 +0100 Subject: fix bug in TaskException extractor --- .../at/gv/egovernment/moa/id/auth/servlet/AbstractController.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index d5fc90023..04e4e7bdb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -336,7 +336,9 @@ public abstract class AbstractController extends MOAIDAuthConstants { taskExc = (TaskExecutionException) procExc.getCause(); exholder = taskExc.getOriginalException(); - } + } else + break; + } if (taskExc == null) -- cgit v1.2.3 From 95a13bba7fc04b13a666442bbe9ef89d3822068e Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 9 Mar 2016 16:00:54 +0100 Subject: fix problem in ELGA MandateService client --- .../at/gv/egovernment/moa/id/advancedlogging/MOAIDEventConstants.java | 3 +++ 1 file changed, 3 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') 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 eccd63e3d..054543c3e 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 @@ -96,6 +96,9 @@ public interface MOAIDEventConstants extends EventConstants { public static final int AUTHPROCESS_ELGA_MANDATE_SERVICE_REQUESTED = 6000; public static final int AUTHPROCESS_ELGA_MANDATE_RECEIVED = 6001; public static final int AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED = 6002; + public static final int AUTHPROCESS_ELGA_MANDATE_RECEIVED_IP = 6003; + + } -- cgit v1.2.3 From e34d8e8a2292a0ea049ab3b3aa6e649aa215e82b Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 10 Mar 2016 10:53:25 +0100 Subject: fix bug in PVP RedirectBinding decoder --- .../protocols/pvp2x/binding/RedirectBinding.java | 29 ++++++++++++++-------- 1 file changed, 18 insertions(+), 11 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 1d13cbd07..7278c9c6c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -57,7 +57,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessageInterface; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; -import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.IMOARefreshableMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -180,20 +180,27 @@ public class RedirectBinding implements IDecoder, IEncoder { if (MiscUtil.isEmpty(messageContext.getInboundMessageIssuer())) { throw e; - } - Logger.debug("PVP2X message validation FAILED. Relead metadata for entityID: " + messageContext.getPeerEntityId()); - if (!MOAMetadataProvider.getInstance().refreshMetadataProvider(messageContext.getInboundMessageIssuer())) - throw e; + } - else { - Logger.trace("PVP2X metadata reload finished. Check validate message again."); - decode.decode(messageContext); + if (metadataProvider instanceof IMOARefreshableMetadataProvider) { + Logger.debug("PVP2X message validation FAILED. Relead metadata for entityID: " + messageContext.getPeerEntityId()); + 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); + //check signature + signatureRule.evaluate(messageContext); + } + Logger.trace("Second PVP2X message validation finished"); + + } else { + throw e; + } - Logger.trace("Second PVP2X message validation finished"); } InboundMessage msg = null; -- cgit v1.2.3 From a6cadad81df2b44a99ca452ea1737abf1fa7d3e8 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 10 Mar 2016 12:31:38 +0100 Subject: add additional PVP response validation --- .../id/protocols/pvp2x/PVPTargetConfiguration.java | 3 + .../builder/assertion/PVP2AssertionBuilder.java | 1 + .../verification/SAMLVerificationEngineSP.java | 142 +++++++++++++++++---- 3 files changed, 121 insertions(+), 25 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index b8ced1198..e7f2a7d4b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -50,8 +50,11 @@ public class PVPTargetConfiguration extends RequestImpl { 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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index 7a7044ebf..3aa05bb2d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -435,6 +435,7 @@ public class PVP2AssertionBuilder implements PVPConstants { .createSAMLObject(SubjectConfirmationData.class); subjectConfirmationData.setInResponseTo(authnRequest.getID()); subjectConfirmationData.setNotOnOrAfter(new DateTime(authData.getSsoSessionValidTo().getTime())); + subjectConfirmationData.setNotBefore(date); subjectConfirmationData.setRecipient(assertionConsumerService.getLocation()); 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 cd80d8c24..1e13da179 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 @@ -26,10 +26,15 @@ import java.util.ArrayList; import java.util.List; import org.joda.time.DateTime; +import org.opensaml.common.binding.decoding.BasicURLComparator; +import org.opensaml.saml2.core.Audience; +import org.opensaml.saml2.core.AudienceRestriction; import org.opensaml.saml2.core.Conditions; import org.opensaml.saml2.core.EncryptedAssertion; import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.StatusCode; +import org.opensaml.saml2.core.validator.AudienceRestrictionSchemaValidator; +import org.opensaml.saml2.core.validator.AudienceSchemaValidator; import org.opensaml.saml2.encryption.Decrypter; import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; import org.opensaml.xml.encryption.ChainingEncryptedKeyResolver; @@ -38,9 +43,11 @@ import org.opensaml.xml.encryption.InlineEncryptedKeyResolver; import org.opensaml.xml.encryption.SimpleRetrievalMethodEncryptedKeyResolver; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver; +import org.opensaml.xml.validation.ValidationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; @@ -56,7 +63,17 @@ public class SAMLVerificationEngineSP extends SAMLVerificationEngine { @Autowired AuthConfiguration authConfig; - public void validateAssertion(Response samlResp, boolean validateDestination, Credential assertionDecryption) throws AssertionValidationExeption { + /** + * Validate a PVP response and all included assertions + * + * @param samlResp + * @param validateDestination + * @param assertionDecryption + * @param spEntityID + * @param loggerSPName + * @throws AssertionValidationExeption + */ + public void validateAssertion(Response samlResp, boolean validateDestination, Credential assertionDecryption, String spEntityID, String loggerSPName) throws AssertionValidationExeption { try { if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { List saml2assertions = new ArrayList(); @@ -74,15 +91,28 @@ public class SAMLVerificationEngineSP extends SAMLVerificationEngine { } if (!isValidDestination && validateDestination) { Logger.warn("PVP 2.1 assertion destination does not match to IDP URL"); - throw new AssertionValidationExeption("PVP 2.1 assertion destination does not match to IDP URL", null); + throw new AssertionValidationExeption("sp.pvp2.07", new Object[]{loggerSPName, "'Destination' attribute is not valid"}); } - //check encrypted Assertion + //validate response issueInstant + DateTime issueInstant = samlResp.getIssueInstant(); + if (issueInstant == null) { + Logger.warn("PVP response does not include a 'IssueInstant' attribute"); + throw new AssertionValidationExeption("sp.pvp2.07", new Object[]{loggerSPName, "'IssueInstant' attribute is not included"}); + + } + if (issueInstant.minusMinutes(MOAIDAuthConstants.TIME_JITTER).isAfterNow()) { + Logger.warn("PVP response: IssueInstant DateTime is not valid anymore."); + throw new AssertionValidationExeption("sp.pvp2.07", new Object[]{loggerSPName, "'IssueInstant' Time is not valid any more"}); + + } + + + //check encrypted Assertions List encryAssertionList = samlResp.getEncryptedAssertions(); if (encryAssertionList != null && encryAssertionList.size() > 0) { - //decrypt assertions - + //decrypt assertions Logger.debug("Found encryped assertion. Start decryption ..."); StaticKeyInfoCredentialResolver skicr = @@ -93,13 +123,10 @@ public class SAMLVerificationEngineSP extends SAMLVerificationEngine { encryptedKeyResolver.getResolverChain().add( new EncryptedElementTypeEncryptedKeyResolver() ); encryptedKeyResolver.getResolverChain().add( new SimpleRetrievalMethodEncryptedKeyResolver() ); - Decrypter samlDecrypter = - new Decrypter(null, skicr, encryptedKeyResolver); + Decrypter samlDecrypter = new Decrypter(null, skicr, encryptedKeyResolver); - for (EncryptedAssertion encAssertion : encryAssertionList) { + for (EncryptedAssertion encAssertion : encryAssertionList) saml2assertions.add(samlDecrypter.decrypt(encAssertion)); - - } Logger.debug("Assertion decryption finished. "); @@ -108,35 +135,90 @@ public class SAMLVerificationEngineSP extends SAMLVerificationEngine { } + //validate all assertions List validatedassertions = new ArrayList(); for (org.opensaml.saml2.core.Assertion saml2assertion : saml2assertions) { - + + boolean isAssertionValid = true; try { + //schema validation performSchemaValidation(saml2assertion.getDOM()); - + + + //validate DateTime conditions Conditions conditions = saml2assertion.getConditions(); - DateTime notbefore = conditions.getNotBefore().minusMinutes(5); - DateTime notafter = conditions.getNotOnOrAfter(); - if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { - Logger.warn("PVP2 Assertion is out of Date. " - + "{ Current : " + new DateTime() - + " NotBefore: " + notbefore - + " NotAfter : " + notafter - + " }");; + if (conditions != null) { + DateTime notbefore = conditions.getNotBefore().minusMinutes(5); + DateTime notafter = conditions.getNotOnOrAfter(); + if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { + isAssertionValid = false; + Logger.info("Assertion:" + saml2assertion.getID() + + " is out of Date. " + + "{ Current : " + new DateTime() + + " NotBefore: " + notbefore + + " NotAfter : " + notafter + + " }");; + + } + + //validate audienceRestrictions are valid for this SP + List audienceRest = conditions.getAudienceRestrictions(); + if (audienceRest == null || audienceRest.size() == 0) { + Logger.info("Assertion:" + saml2assertion.getID() + + " has not 'AudienceRestriction' element"); + isAssertionValid = false; + + } else { + for (AudienceRestriction el : audienceRest) { + el.registerValidator(new AudienceRestrictionSchemaValidator()); + el.validate(false); + + for (Audience audience : el.getAudiences()) { + audience.registerValidator(new AudienceSchemaValidator()); + audience.validate(false); + + if (!urlCompare(spEntityID, audience.getAudienceURI())) { + Logger.info("Assertion:" + saml2assertion.getID() + + " 'AudienceRestriction' is not valid."); + isAssertionValid = false; + } + } + } + } + } else { + Logger.info("Assertion:" + saml2assertion.getID() + + " contains not 'Conditions' element"); + isAssertionValid = false; + + } + + //add assertion if it is valid + if (isAssertionValid) { + Logger.debug("Add valid Assertion:" + saml2assertion.getID()); validatedassertions.add(saml2assertion); - } + } else + Logger.warn("Remove non-valid Assertion:" + saml2assertion.getID()); } catch (SchemaValidationException e) { + isAssertionValid = false; + Logger.info("Assertion:" + saml2assertion.getID() + + " Schema validation FAILED. Msg:" + e.getMessage()); + + } catch (ValidationException e) { + isAssertionValid = false; + Logger.info("Assertion:" + saml2assertion.getID() + + " AudienceRestriction schema-validation FAILED. Msg:" + e.getMessage()); } } if (validatedassertions.isEmpty()) { Logger.info("No valid PVP 2.1 assertion received."); - throw new AssertionValidationExeption("No valid PVP 2.1 assertion received.", null); + throw new AssertionValidationExeption("sp.pvp2.10", new Object[]{loggerSPName}); + } samlResp.getAssertions().clear(); @@ -146,16 +228,26 @@ public class SAMLVerificationEngineSP extends SAMLVerificationEngine { } else { Logger.info("PVP 2.1 assertion includes an error. Receive errorcode " + samlResp.getStatus().getStatusCode().getValue()); - throw new AssertionValidationExeption("PVP 2.1 assertion includes an error. Receive errorcode " - + samlResp.getStatus().getStatusCode().getValue(), null); + throw new AssertionValidationExeption("sp.pvp2.05", + new Object[]{loggerSPName, + samlResp.getIssuer().getValue(), + samlResp.getStatus().getStatusCode().getValue(), + samlResp.getStatus().getStatusMessage().getMessage()}); + } } catch (DecryptionException e) { Logger.warn("Assertion decrypt FAILED.", e); - throw new AssertionValidationExeption("Assertion decrypt FAILED.", null, e); + throw new AssertionValidationExeption("sp.pvp2.11", null, e); } catch (ConfigurationException e) { throw new AssertionValidationExeption("pvp.12", null, e); } } + + protected static boolean urlCompare(String url1, String url2) { + BasicURLComparator comparator = new BasicURLComparator(); + comparator.setCaseInsensitive(false); + return comparator.compare(url1, url2); + } } -- cgit v1.2.3 From 0fe2bed17c674587a60e63fac211a0354ab4ef03 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 10 Mar 2016 16:07:58 +0100 Subject: remove axis 1 implementation completely --- .../auth/builder/SignatureVerificationUtils.java | 2 +- .../auth/invoke/SignatureVerificationInvoker.java | 77 +++++++++++++++------- 2 files changed, 53 insertions(+), 26 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 e321c9d05..f2e4da818 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 @@ -81,7 +81,7 @@ public class SignatureVerificationUtils { Element domVerifyXMLSignatureRequest = build(signature, trustProfileID); //send signature-verification to MOA-SP - Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() + Element domVerifyXMLSignatureResponse = SignatureVerificationInvoker.getInstance() .verifyXMLSignature(domVerifyXMLSignatureRequest); // parses the 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 72a7d3ba1..5c96f6ad2 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 @@ -46,22 +46,16 @@ package at.gv.egovernment.moa.id.auth.invoke; -import java.util.Vector; - import javax.xml.namespace.QName; -import javax.xml.rpc.Call; -import javax.xml.rpc.Service; -import javax.xml.rpc.ServiceFactory; -import org.apache.axis.message.SOAPBodyElement; 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.config.ConfigurationException; import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.spss.api.SignatureVerificationService; import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureRequestParser; import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureResponseBuilder; @@ -77,9 +71,43 @@ import at.gv.egovernment.moa.util.MiscUtil; * @version $Id$ */ public class SignatureVerificationInvoker { - /** This QName Object identifies the SignatureVerification endpoint of the web service */ + + private static SignatureVerificationInvoker instance = null; + private SignatureVerificationService svs = null; + + /** This QName Object identifies the SignatureVerification endpoint of the web service */ private static final QName SERVICE_QNAME = new QName("SignatureVerification"); + + public static SignatureVerificationInvoker getInstance() { + if (instance == null) { + instance = new SignatureVerificationInvoker(); + + } + + return instance; + } + + private SignatureVerificationInvoker() { + try { + AuthConfiguration authConfigProvider = AuthConfigurationProviderFactory.getInstance(); + ConnectionParameter authConnParam = authConfigProvider.getMoaSpConnectionParameter(); + + if (authConnParam != null && MiscUtil.isNotEmpty(authConnParam.getUrl())) { + + + } else { + svs = SignatureVerificationService.getInstance(); + + } + + } catch (ConfigurationException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + /** * Method verifyXMLSignature. * @param request to be sent @@ -99,29 +127,28 @@ public class SignatureVerificationInvoker { */ protected Element doCall(QName serviceName, Element request) throws ServiceException { ConnectionParameter authConnParam = null; - try { - Service service = ServiceFactory.newInstance().createService(serviceName); - Call call = service.createCall(); - SOAPBodyElement body = new SOAPBodyElement(request); - SOAPBodyElement[] params = new SOAPBodyElement[] { body }; - Vector responses; - SOAPBodyElement response; - - String endPoint; + 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())) { - Logger.debug("Connecting using auth url: " + authConnParam.getUrl() + ", service " + serviceName.getNamespaceURI() + " : " + serviceName.getLocalPart() + " : "+ serviceName.getPrefix()); - endPoint = authConnParam.getUrl(); - call.setTargetEndpointAddress(endPoint); - 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(); + + 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 { - SignatureVerificationService svs = SignatureVerificationService.getInstance(); VerifyXMLSignatureRequest vsrequest = new VerifyXMLSignatureRequestParser().parse(request); VerifyXMLSignatureResponse vsresponse = svs.verifyXMLSignature(vsrequest); -- cgit v1.2.3 From f67427831d1f8c49ce6c474691b880d90a42b584 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 14 Mar 2016 09:17:57 +0100 Subject: refactor the GUI generation for user interaction --- .../moa/id/advancedlogging/MOAReversionLogger.java | 6 +- .../moa/id/advancedlogging/StatisticLogger.java | 10 +- .../moa/id/advancedlogging/TransactionIDUtils.java | 2 +- .../moa/id/auth/AuthenticationSessionCleaner.java | 4 +- .../moa/id/auth/BaseAuthenticationServer.java | 3 +- .../moa/id/auth/MOAIDAuthConstants.java | 194 --------------- .../moa/id/auth/MOAIDAuthInitializer.java | 6 +- .../id/auth/builder/AuthenticationDataBuilder.java | 14 +- .../builder/CreateXMLSignatureRequestBuilder.java | 6 +- .../moa/id/auth/builder/DataURLBuilder.java | 2 +- .../builder/DynamicOAAuthParameterBuilder.java | 6 +- .../moa/id/auth/builder/GUILayoutBuilder.java | 157 ------------ .../moa/id/auth/builder/LoginFormBuilder.java | 171 ------------- .../moa/id/auth/builder/RedirectFormBuilder.java | 65 ----- .../id/auth/builder/SendAssertionFormBuilder.java | 147 ----------- .../auth/builder/SignatureVerificationUtils.java | 2 +- .../moa/id/auth/data/AuthenticationSession.java | 2 +- .../id/auth/exception/AuthenticationException.java | 1 + .../moa/id/auth/exception/BKUException.java | 2 + .../moa/id/auth/exception/BuildException.java | 1 + .../exception/DatabaseEncryptionException.java | 2 + .../id/auth/exception/DynamicOABuildException.java | 2 + .../id/auth/exception/ECDSAConverterException.java | 1 + .../exception/InvalidProtocolRequestException.java | 2 + .../auth/exception/MISSimpleClientException.java | 1 + .../moa/id/auth/exception/MOAIDException.java | 222 ----------------- .../moa/id/auth/exception/MOASPException.java | 2 + .../moa/id/auth/exception/ParseException.java | 1 + .../auth/exception/ProtocolNotActiveException.java | 2 + .../moa/id/auth/exception/ServiceException.java | 1 + .../exception/SessionDataStorageException.java | 45 ---- .../moa/id/auth/exception/ValidateException.java | 1 + .../auth/exception/WrongParametersException.java | 1 + .../auth/invoke/SignatureVerificationInvoker.java | 10 +- .../id/auth/modules/AbstractAuthServletTask.java | 6 +- .../id/auth/modules/BKUSelectionModuleImpl.java | 2 +- .../id/auth/modules/TaskExecutionException.java | 2 +- .../internal/tasks/EvaluateBKUSelectionTask.java | 2 +- .../tasks/EvaluateSSOConsentsTaskImpl.java | 2 +- .../internal/tasks/FinalizeAuthenticationTask.java | 4 +- .../tasks/GenerateBKUSelectionFrameTask.java | 43 ++-- .../GenerateSSOConsentEvaluatorFrameTask.java | 37 +-- .../tasks/RestartAuthProzessManagement.java | 2 +- .../StartAuthentificationParameterParser.java | 10 +- .../moa/id/auth/servlet/AbstractController.java | 128 +++------- .../AbstractProcessEngineSignalController.java | 6 +- .../id/auth/servlet/GUILayoutBuilderServlet.java | 128 ---------- .../GeneralProcessEngineSignalController.java | 6 +- .../id/auth/servlet/IDPSingleLogOutServlet.java | 66 +++-- .../moa/id/auth/servlet/LogOutServlet.java | 4 +- .../moa/id/auth/servlet/RedirectServlet.java | 48 ++-- .../WebFrontEndSecurityInterceptor.java | 6 +- .../gv/egovernment/moa/id/client/SZRGWClient.java | 25 +- .../moa/id/client/SZRGWClientException.java | 2 +- .../moa/id/client/utils/SZRGWClientUtils.java | 12 +- .../moa/id/config/ConfigurationException.java | 82 ------ .../moa/id/config/ConfigurationProvider.java | 66 ----- .../moa/id/config/ConfigurationProviderImpl.java | 2 + .../moa/id/config/ConnectionParameter.java | 1 + .../id/config/ConnectionParameterInterface.java | 35 --- .../moa/id/config/auth/AuthConfiguration.java | 165 ------------ .../auth/AuthConfigurationProviderFactory.java | 3 +- .../moa/id/config/auth/IOAAuthParameters.java | 224 ----------------- .../moa/id/config/auth/OAAuthParameter.java | 64 +---- .../PropertyBasedAuthConfigurationProvider.java | 15 +- .../config/auth/data/BPKDecryptionParameters.java | 137 ---------- .../config/auth/data/DynamicOAAuthParameters.java | 18 +- .../moa/id/config/auth/data/ProtocolAllowed.java | 91 ------- .../auth/data/SAML1ConfigurationParameters.java | 276 --------------------- .../gv/egovernment/moa/id/config/stork/CPEPS.java | 138 ----------- .../moa/id/config/stork/STORKConfig.java | 33 ++- .../config/stork/SignatureCreationParameter.java | 103 -------- .../stork/SignatureVerificationParameter.java | 53 ---- .../moa/id/config/stork/StorkAttribute.java | 27 -- .../config/stork/StorkAttributeProviderPlugin.java | 81 ------ .../moa/id/data/AuthenticationData.java | 2 +- .../moa/id/moduls/AuthenticationManager.java | 67 +++-- .../at/gv/egovernment/moa/id/moduls/IAction.java | 3 +- .../gv/egovernment/moa/id/moduls/IModulInfo.java | 2 + .../at/gv/egovernment/moa/id/moduls/IRequest.java | 202 --------------- .../egovernment/moa/id/moduls/IRequestStorage.java | 3 +- .../id/moduls/NoPassivAuthenticationException.java | 2 +- .../gv/egovernment/moa/id/moduls/RequestImpl.java | 9 +- .../egovernment/moa/id/moduls/RequestStorage.java | 3 +- .../gv/egovernment/moa/id/moduls/SSOManager.java | 82 +----- .../egovernment/moa/id/process/ProcessEngine.java | 2 +- .../moa/id/process/ProcessEngineImpl.java | 4 +- .../at/gv/egovernment/moa/id/process/api/Task.java | 2 +- .../moa/id/process/springweb/MoaIdTask.java | 2 +- .../AbstractAuthProtocolModulController.java | 4 +- .../protocols/ProtocolFinalizationController.java | 6 +- .../builder/attributes/BPKAttributeBuilder.java | 2 +- .../attributes/BirthdateAttributeBuilder.java | 2 +- .../protocols/builder/attributes/EIDAuthBlock.java | 2 +- .../id/protocols/builder/attributes/EIDCcsURL.java | 2 +- .../EIDCitizenQAALevelAttributeBuilder.java | 2 +- .../builder/attributes/EIDIdentityLinkBuilder.java | 2 +- .../EIDIssuingNationAttributeBuilder.java | 2 +- .../builder/attributes/EIDSTORKTOKEN.java | 2 +- .../attributes/EIDSectorForIDAttributeBuilder.java | 2 +- .../builder/attributes/EIDSignerCertificate.java | 2 +- .../protocols/builder/attributes/EIDSourcePIN.java | 2 +- .../builder/attributes/EIDSourcePINType.java | 2 +- .../attributes/EncryptedBPKAttributeBuilder.java | 2 +- .../attributes/GivenNameAttributeBuilder.java | 2 +- .../protocols/builder/attributes/HolderOfKey.java | 4 +- .../builder/attributes/IAttributeBuilder.java | 2 +- .../MandateFullMandateAttributeBuilder.java | 2 +- ...MandateLegalPersonFullNameAttributeBuilder.java | 2 +- ...andateLegalPersonSourcePinAttributeBuilder.java | 2 +- ...teLegalPersonSourcePinTypeAttributeBuilder.java | 2 +- .../MandateNaturalPersonBPKAttributeBuilder.java | 2 +- ...dateNaturalPersonBirthDateAttributeBuilder.java | 2 +- ...ateNaturalPersonFamilyNameAttributeBuilder.java | 2 +- ...dateNaturalPersonGivenNameAttributeBuilder.java | 2 +- ...dateNaturalPersonSourcePinAttributeBuilder.java | 2 +- ...NaturalPersonSourcePinTypeAttributeBuilder.java | 2 +- .../MandateProfRepDescAttributeBuilder.java | 2 +- .../MandateProfRepOIDAttributeBuilder.java | 2 +- .../MandateReferenceValueAttributeBuilder.java | 2 +- .../attributes/MandateTypeAttributeBuilder.java | 2 +- .../attributes/PVPVersionAttributeBuilder.java | 2 +- .../attributes/PrincipalNameAttributeBuilder.java | 2 +- .../id/protocols/pvp2x/AttributQueryAction.java | 14 +- .../id/protocols/pvp2x/AuthenticationAction.java | 6 +- .../moa/id/protocols/pvp2x/MetadataAction.java | 4 +- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 16 +- .../moa/id/protocols/pvp2x/SingleLogOutAction.java | 6 +- .../id/protocols/pvp2x/binding/PostBinding.java | 2 +- .../pvp2x/builder/AttributQueryBuilder.java | 4 +- .../pvp2x/builder/AuthResponseBuilder.java | 2 +- .../pvp2x/builder/PVPAttributeBuilder.java | 2 +- .../pvp2x/builder/PVPAuthnRequestBuilder.java | 2 +- .../pvp2x/builder/PVPMetadataBuilder.java | 2 +- .../pvp2x/builder/SingleLogOutBuilder.java | 6 +- .../builder/assertion/PVP2AssertionBuilder.java | 6 +- .../pvp2x/config/IDPPVPMetadataConfiguration.java | 2 +- .../protocols/pvp2x/config/PVPConfiguration.java | 4 +- .../exceptions/AssertionValidationExeption.java | 2 +- .../exceptions/AuthnRequestValidatorException.java | 2 +- .../protocols/pvp2x/exceptions/PVP2Exception.java | 2 +- .../pvp2x/metadata/MOAMetadataProvider.java | 12 +- .../pvp2x/metadata/SimpleMOAMetadataProvider.java | 2 +- .../signer/CredentialsNotAvailableException.java | 2 +- .../pvp2x/signer/IDPCredentialProvider.java | 2 +- .../protocols/pvp2x/utils/MOASAMLSOAPClient.java | 2 +- .../pvp2x/validation/ChainSAMLValidator.java | 2 +- .../protocols/pvp2x/validation/ISAMLValidator.java | 2 +- .../pvp2x/validation/SAMLSignatureValidator.java | 2 +- .../pvp2x/verification/ChainSAMLVerifier.java | 2 +- .../pvp2x/verification/EntityVerifier.java | 8 +- .../pvp2x/verification/ISAMLVerifier.java | 2 +- .../verification/SAMLVerificationEngineSP.java | 6 +- .../metadata/MOASPMetadataSignatureFilter.java | 2 +- .../metadata/MetadataSignatureFilter.java | 3 +- .../metadata/SchemaValidationFilter.java | 2 +- .../storage/DBAuthenticationSessionStoreage.java | 8 +- .../id/storage/IAuthenticationSessionStoreage.java | 2 +- .../moa/id/util/ErrorResponseUtils.java | 2 +- .../gv/egovernment/moa/id/util/FormBuildUtils.java | 136 ---------- .../moa/id/util/IdentityLinkReSigner.java | 4 +- .../moa/id/util/MOAIDMessageProvider.java | 104 -------- .../moa/id/util/ParamValidatorUtils.java | 6 +- .../at/gv/egovernment/moa/id/util/SSLUtils.java | 6 +- .../moa/id/util/VelocityLogAdapter.java | 99 -------- .../egovernment/moa/id/util/VelocityProvider.java | 112 --------- .../moa/id/util/legacy/LegacyHelper.java | 2 +- 167 files changed, 504 insertions(+), 3822 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GUILayoutBuilder.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/RedirectFormBuilder.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIDException.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/SessionDataStorageException.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationException.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProvider.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConnectionParameterInterface.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/BPKDecryptionParameters.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/ProtocolAllowed.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/SAML1ConfigurationParameters.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/CPEPS.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/SignatureCreationParameter.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/SignatureVerificationParameter.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/StorkAttribute.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/StorkAttributeProviderPlugin.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/FormBuildUtils.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/MOAIDMessageProvider.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/VelocityLogAdapter.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/VelocityProvider.java (limited to 'id/server/idserverlib/src/main/java/at') 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 17e39f766..4620a5c6b 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 @@ -32,10 +32,10 @@ import org.springframework.stereotype.Service; import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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.data.MISMandate; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; 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 8efdf6014..0171f9d90 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 @@ -41,19 +41,19 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBod import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.BKUException; import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; 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.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.commons.db.StatisticLogDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.statistic.StatisticLog; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; 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 index 7f6f2c6b3..6d53fd510 100644 --- 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 @@ -25,7 +25,7 @@ package at.gv.egovernment.moa.id.advancedlogging; import java.util.Date; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.util.MiscUtil; /** 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 a1ba00e02..94138e0fc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java @@ -8,10 +8,10 @@ import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.storage.ITransactionStorage; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java index 1ce6fa1e9..20f2029cb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/BaseAuthenticationServer.java @@ -5,8 +5,9 @@ import org.springframework.beans.factory.annotation.Autowired; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java deleted file mode 100644 index 27c87ccbf..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ /dev/null @@ -1,194 +0,0 @@ - - - -package at.gv.egovernment.moa.id.auth; - -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import at.gv.egovernment.moa.id.commons.MOAIDConstants; -import iaik.asn1.ObjectID; - - -/** - * Constants used throughout moa-id-auth component. - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class MOAIDAuthConstants extends MOAIDConstants{ - - /** servlet parameter "Target" */ - public static final String PARAM_TARGET = "Target"; - /** servlet parameter "useMandate" */ - public static final String PARAM_USEMANDATE = "useMandate"; - public static final String PARAM_USEMISMANDATE = "useMISMandate"; - public static final String PARAM_USEELGAMANDATE = "useELGAMandate"; - /** servlet parameter "OA" */ - public static final String PARAM_OA = "OA"; - /** servlet parameter "bkuURI" */ - public static final String PARAM_BKU = "bkuURI"; - public static final String PARAM_MODUL = "MODUL"; - public static final String PARAM_ACTION = "ACTION"; - public static final String PARAM_SSO = "SSO"; - public static final String INTERFEDERATION_IDP = "interIDP"; - public static final String PARAM_TARGET_PENDINGREQUESTID = "pendingid"; - - public static final String PARAM_SLOSTATUS = "status"; - public static final String PARAM_SLORESTART = "restart"; - public static final String SLOSTATUS_SUCCESS = "success"; - public static final String SLOSTATUS_ERROR = "error"; - - /** servlet parameter "sourceID" */ - public static final String PARAM_SOURCEID = "sourceID"; - /** servlet parameter "BKUSelectionTemplate" */ - public static final String PARAM_BKUTEMPLATE = "BKUSelectionTemplate"; - /** servlet parameter "CCC (Citizen Country Code)" */ - public static final String PARAM_CCC = "CCC"; - /** servlet parameter "BKUSelectionTemplate" */ - public static final String PARAM_INPUT_PROCESSOR_SIGN_TEMPLATE = "InputProcessorSignTemplate"; - /** default BKU URL */ - public static final String DEFAULT_BKU = "http://localhost:3495/http-security-layer-request"; - /** default BKU URL for https connections*/ - public static final String DEFAULT_BKU_HTTPS = "https://127.0.0.1:3496/https-security-layer-request"; - /** servlet parameter "returnURI" */ - public static final String PARAM_RETURN = "returnURI"; - /** servlet parameter "Template" */ - public static final String PARAM_TEMPLATE = "Template"; - /** servlet parameter "MOASessionID" */ - public static final String PARAM_SESSIONID = "MOASessionID"; - /** servlet parameter "XMLResponse" */ - public static final String PARAM_XMLRESPONSE = "XMLResponse"; - /** servlet parameter "SAMLArtifact" */ - public static final String PARAM_SAMLARTIFACT = "SAMLArtifact"; - /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.StartAuthenticationServlet} is mapped to */ - public static final String REQ_START_AUTHENTICATION = "StartAuthentication"; - /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet} is mapped to */ - public static final String REQ_VERIFY_IDENTITY_LINK = "VerifyIdentityLink"; - /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.GetForeignIDServlet} is mapped to */ - public static final String REQ_GET_FOREIGN_ID = "GetForeignID"; - /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet} is mapped to */ - public static final String REQ_VERIFY_CERTIFICATE = "VerifyCertificate"; - /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.GetMISSessionIDServlet} is mapped to */ - public static final String GET_MIS_SESSIONID = "GetMISSessionID"; - /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.ProcessValidatorInputServlet} is mapped to */ - public static final String REQ_PROCESS_VALIDATOR_INPUT = "ProcessInput"; - /** Request name {@link at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet} is mapped to */ - public static final String REQ_VERIFY_AUTH_BLOCK = "VerifyAuthBlock"; - /** Logging hierarchy used for controlling debug output of XML structures to files */ - public static final String DEBUG_OUTPUT_HIERARCHY = "moa.id.auth"; - /** Header Name for controlling the caching mechanism of the browser */ - public static final String HEADER_EXPIRES = "Expires"; - /** Header Value for controlling the caching mechanism of the browser */ - public static final String HEADER_VALUE_EXPIRES = "Sat, 6 May 1995 12:00:00 GMT"; - /** Header Name for controlling the caching mechanism of the browser */ - public static final String HEADER_PRAGMA = "Pragma"; - /** Header Value for controlling the caching mechanism of the browser */ - public static final String HEADER_VALUE_PRAGMA = "no-cache"; - /** Header Name for controlling the caching mechanism of the browser */ - public static final String HEADER_CACHE_CONTROL = "Cache-control"; - /** Header Value for controlling the caching mechanism of the browser */ - public static final String HEADER_VALUE_CACHE_CONTROL = "no-store, no-cache, must-revalidate"; - /** Header Value for controlling the caching mechanism of the browser */ - public static final String HEADER_VALUE_CACHE_CONTROL_IE = "post-check=0, pre-check=0"; - /** - * the identity link signer X509Subject names of those identity link signer certificates - * not including the identity link signer OID. The authorisation for signing the identity - * link must be checked by using their issuer names. After february 19th 2007 the OID of - * the certificate will be used fo checking the authorisation for signing identity links. - */ - public static final String[] IDENTITY_LINK_SIGNERS_WITHOUT_OID = - new String[] {"T=Dr.,CN=Nikolaus Schwab,O=BM f. Inneres i.A. des gf. Mitgieds der Datenschutzkommission", - "T=Dr.,CN=Nikolaus Schwab,O=BM f. Inneres i.A. des gf. Mitglieds der Datenschutzkommission"}; - - /** the number of the certifcate extension "Eigenschaft zur Ausstellung von Personenbindungen" */ - public static final String IDENTITY_LINK_SIGNER_OID_NUMBER = "1.2.40.0.10.1.7.1"; - /** - * the OID of the identity link signer certificate (Eigenschaft zur Ausstellung von Personenbindungen); - * used for checking the authorisation for signing the identity link for identity links signed after february 19th 2007 - */ - public static final ObjectID IDENTITY_LINK_SIGNER_OID = new ObjectID(IDENTITY_LINK_SIGNER_OID_NUMBER); - - /** the number of the certifcate extension for party representatives */ - public static final String PARTY_REPRESENTATION_OID_NUMBER = "1.2.40.0.10.3"; - -// /** the number of the certifcate extension for party organ representatives */ -// public static final String PARTY_ORGAN_REPRESENTATION_OID_NUMBER = PARTY_REPRESENTATION_OID_NUMBER + ".10"; - - /** OW */ - public static final String OW_ORGANWALTER = PARTY_REPRESENTATION_OID_NUMBER + ".4"; - - /** List of OWs */ - public static final List OW_LIST = Arrays.asList( - new ObjectID(OW_ORGANWALTER)); - - /**BKU type identifiers to use bkuURI from configuration*/ - public static final String REQ_BKU_TYPE_LOCAL = "local"; - public static final String REQ_BKU_TYPE_ONLINE = "online"; - public static final String REQ_BKU_TYPE_HANDY = "handy"; - public static final List REQ_BKU_TYPES = Arrays.asList(REQ_BKU_TYPE_LOCAL, REQ_BKU_TYPE_ONLINE, REQ_BKU_TYPE_HANDY); - - public static final List LEGACYPARAMETERWHITELIST - = Arrays.asList(PARAM_TARGET, PARAM_BKU, PARAM_OA, PARAM_TEMPLATE, PARAM_USEMANDATE, PARAM_CCC, PARAM_SOURCEID); - - public final static String EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION = "OIDTextualDescription"; - public final static String EXT_SAML_MANDATE_OID = "OID"; - public final static String EXT_SAML_MANDATE_RAW = "Mandate"; - public final static String EXT_SAML_MANDATE_NAME = "MandatorName"; - public final static String EXT_SAML_MANDATE_DOB = "MandatorDateOfBirth"; - public final static String EXT_SAML_MANDATE_WBPK = "MandatorWbpk"; - public final static String EXT_SAML_MANDATE_REPRESENTATIONTYPE = "RepresentationType"; - public final static String EXT_SAML_MANDATE_REPRESENTATIONTEXT = "Vollmachtsvertreter"; - public final static String EXT_SAML_MANDATE_CB_BASE_ID = "MandatorDomainIdentifier"; - - public static final String PARAM_APPLET_HEIGTH = "heigth"; - public static final String PARAM_APPLET_WIDTH = "width"; - - public static final Map COUNTRYCODE_XX_TO_NAME = - Collections.unmodifiableMap(new HashMap() { - private static final long serialVersionUID = 1L; - { - put("AT", "Other Countries");//"Workaround for PEPS Simulator" - put("BE", "België/Belgique"); - //put("CH", "Schweiz"); - put("EE", "Eesti"); - put("ES", "España"); - put("FI", "Suomi"); - put("IS", "Ísland"); - put("IT", "Italia"); - put("LI", "Liechtenstein"); - put("LT", "Lithuania"); - put("LU", "Luxemburg"); - put("PT", "Portugal"); - put("SE", "Sverige"); - put("SI", "Slovenija"); - } - }); - - public static final String COUNTRYCODE_AUSTRIA = "AT"; - - public static final String REGEX_PATTERN_TARGET = "^[A-Za-z]{2}(-.*)?$"; - - public static final String MDC_TRANSACTION_ID = "transactionId"; - public static final String MDC_SESSION_ID = "sessionId"; - - //AuthnRequest IssueInstant validation - public static final int TIME_JITTER = 5; //all 5 minutes time jitter - - public static final String PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH = "interfederationAuthentication"; - public static final String PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION = "requireLocalAuthentication"; - public static final String PROCESSCONTEXT_PERFORM_BKUSELECTION = "performBKUSelection"; - public static final String PROCESSCONTEXT_ISLEGACYREQUEST = "isLegacyRequest"; - - //General protocol-request data-store keys - public static final String AUTHPROCESS_DATA_TARGET = "authProces_Target"; - public static final String AUTHPROCESS_DATA_TARGETFRIENDLYNAME = "authProces_TargetFriendlyName"; - public static final String AUTHPROCESS_DATA_SECURITYLAYERTEMPLATE = "authProces_SecurityLayerTemplate"; - - //General MOASession data-store keys - public static final String MOASESSION_DATA_HOLDEROFKEY_CERTIFICATE = "holderofkey_cert"; - -} 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 458f9afe6..a8b9509bc 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,11 +32,11 @@ import javax.activation.MailcapCommandMap; import org.springframework.web.context.support.GenericWebApplicationContext; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; +import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.id.util.SSLUtils; import at.gv.egovernment.moa.logging.Logger; 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 32fabc3f4..4c83d0ea4 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 @@ -47,7 +47,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; @@ -55,21 +54,22 @@ import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; 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.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; -import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; 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.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.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.AuthenticationData; 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.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; 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 e763c5355..73fe961eb 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,10 +50,10 @@ import java.text.MessageFormat; import java.util.Calendar; import java.util.List; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +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.config.TargetToSectorNameMapper; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DateTimeUtils; import at.gv.egovernment.moa.util.StringUtils; 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 index 9a2baf873..8334780ba 100644 --- 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 @@ -46,7 +46,7 @@ package at.gv.egovernment.moa.id.auth.builder; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; /** * Builds a DataURL parameter meant for the security layer implementation 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 8c0de1121..f4f6e82ba 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 @@ -28,13 +28,13 @@ import java.util.List; import org.opensaml.saml2.core.Attribute; 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.commons.db.dao.session.InterfederationSessionStore; -import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.config.auth.data.DynamicOAAuthParameters; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GUILayoutBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GUILayoutBuilder.java deleted file mode 100644 index b95cbbc16..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GUILayoutBuilder.java +++ /dev/null @@ -1,157 +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.builder; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.net.URI; - -import org.apache.commons.io.IOUtils; - -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.util.FormBuildUtils; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -public class GUILayoutBuilder { - private static final String CSS_LAYOUTTEMPLATE = "css_template.css"; - private static final String JS_LAYOUTTEMPLATE = "javascript_tempalte.js"; - private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; - - private static String CONTEXTPATH = "#CONTEXTPATH#"; - private static String MOASESSIONID = "#SESSIONID#"; - private static String AUTH_URL = "#AUTH_URL#"; - private static String BKU_ONLINE = "#ONLINE#"; - private static String BKU_HANDY = "#HANDY#"; - private static String BKU_LOCAL = "#LOCAL#"; - - - public static String buildCSS(IRequest pendingReq, String authURL) { - return buildForm(pendingReq, authURL, CSS_LAYOUTTEMPLATE); - - } - - public static String buildJS(IRequest pendingReq, String authURL) { - return buildForm(pendingReq, authURL, JS_LAYOUTTEMPLATE); - - } - - - - private static String getTemplate(String templateName) { - String pathLocation; - InputStream input = null; - try { - String rootconfigdir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); - pathLocation = rootconfigdir + HTMLTEMPLATESDIR + templateName; - - try { - File file = new File(new URI(pathLocation)); - input = new FileInputStream(file); - - } catch (FileNotFoundException e) { - Logger.warn("No LoginFormTempaltes found. Use Generic Templates from package."); - pathLocation = "resources/templates/" + templateName; - input = Thread.currentThread() - .getContextClassLoader() - .getResourceAsStream(pathLocation); - - } - - return getTemplate(input); - - } catch (Exception e) { - return null; - - } finally { - try { - if (input != null) - input.close(); - - } catch (IOException e) { - Logger.warn("SendAssertionTemplate inputstream can not be closed.", e); - - } - } - } - - private static String getTemplate(InputStream input) { - String template = null; - try { - - StringWriter writer = new StringWriter(); - IOUtils.copy(input, writer); - template = writer.toString(); - - } catch (Exception e) { - Logger.error("Failed to read template", e); - - } - return template; - } - - private static String buildForm(IRequest pendingReq, String authURL, String templateName) { - //load default GUI-Layout template template - String value = getTemplate(templateName); - - if (pendingReq != null) { - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - - if(value != null) { - //only for BKU-Selection step and JavaScript generation - value = value.replace(AUTH_URL, LoginFormBuilder.SERVLET); - - value = value.replace(CONTEXTPATH, pendingReq.getAuthURL()); - value = value.replace(MOASESSIONID, pendingReq.getRequestID()); - - value = value.replace(BKU_ONLINE, IOAAuthParameters.ONLINEBKU); - value = value.replace(BKU_HANDY, IOAAuthParameters.HANDYBKU); - value = value.replace(BKU_LOCAL, IOAAuthParameters.LOCALBKU); - - - value = FormBuildUtils.customiceLayoutBKUSelection(value, - oaParam.isShowMandateCheckBox(), - oaParam.isOnlyMandateAllowed(), - oaParam.getFormCustomizaten(), - oaParam.isShowStorkLogin()); - } - - } else { - value = FormBuildUtils.defaultLayoutBKUSelection(value); - value = value.replace(CONTEXTPATH, authURL); - - } - - return value; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java deleted file mode 100644 index e1aa41ce2..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.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.auth.builder; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.net.URI; - -import org.apache.commons.io.IOUtils; - -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.stork.CPEPS; -import at.gv.egovernment.moa.id.util.FormBuildUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; - -public class LoginFormBuilder { - - private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; - private static final String HTMLTEMPLATEFULL = "loginFormFull.html"; - - private static String AUTH_URL = "#AUTH_URL#"; - private static String OANAME = "#OAName#"; - private static String BKU_ONLINE = "#ONLINE#"; - private static String BKU_HANDY = "#HANDY#"; - private static String BKU_LOCAL = "#LOCAL#"; - public static String CONTEXTPATH = "#CONTEXTPATH#"; - private static String MOASESSIONID = "#SESSIONID#"; - private static String PEPSLIST = "#PEPSLIST#"; - - public static String SERVLET = CONTEXTPATH+"/GenerateIframeTemplate"; - - private static String getTemplate() { - String pathLocation =""; - InputStream input = null; - - try { - String rootconfigdir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); - pathLocation = rootconfigdir + HTMLTEMPLATESDIR + HTMLTEMPLATEFULL; - File file = new File(new URI(pathLocation)); - input = new FileInputStream(file); - - } catch (ConfigurationException e) { - Logger.warn("MOA-ID configuration can not be loaded."); - - } catch (Exception e) { - - } - - return getTemplate(input); - - } - - public static String getTemplate(InputStream input) { - - String template = null; - - try { - if (input == null) { - - Logger.warn("No LoginFormTempaltes found. Use Generic Templates from package."); - - String pathLocation = "resources/templates/" + HTMLTEMPLATEFULL; - input = Thread.currentThread() - .getContextClassLoader() - .getResourceAsStream(pathLocation); - - } - - StringWriter writer = new StringWriter(); - IOUtils.copy(input, writer); - template = writer.toString(); - template = template.replace(AUTH_URL, SERVLET); - template = template.replace(BKU_ONLINE, IOAAuthParameters.ONLINEBKU); - template = template.replace(BKU_HANDY, IOAAuthParameters.HANDYBKU); - template = template.replace(BKU_LOCAL, IOAAuthParameters.LOCALBKU); - - } catch (Exception e) { - Logger.error("Failed to read template", e); - - } finally { - try { - input.close(); - - } catch (IOException e) { - Logger.warn("SendAssertionTemplate inputstream can not be closed.", e); - } - } - return template; - } - - public static String buildLoginForm(String modul, String action, IOAAuthParameters oaParam, String contextpath, String moaSessionID) { - - String value = null; - - byte[] oatemplate = oaParam.getBKUSelectionTemplate(); - // OA specific template requires a size of 8 bits minimum - if (oatemplate != null && oatemplate.length > 7) { - InputStream is = new ByteArrayInputStream(oatemplate); - value = getTemplate(is); - - } else { - //load default BKU-selection template - value = getTemplate(); - - } - - if(value != null) { - value = value.replace(OANAME, oaParam.getFriendlyName()); - value = value.replace(CONTEXTPATH, contextpath); - value = value.replace(MOASESSIONID, moaSessionID); - - if (oaParam.isShowStorkLogin()) { - String pepslist = ""; - try { - for (CPEPS current : oaParam.getPepsList()) { - String countryName = null; - if (MiscUtil.isNotEmpty(MOAIDAuthConstants.COUNTRYCODE_XX_TO_NAME.get(current.getCountryCode().toUpperCase()))) - countryName = MOAIDAuthConstants.COUNTRYCODE_XX_TO_NAME.get(current.getCountryCode().toUpperCase()); - else - countryName = current.getCountryCode().toUpperCase(); - - pepslist += "\n"; - - } - value = value.replace(PEPSLIST, pepslist); - - } catch (NullPointerException e) { - - } - } - - value = FormBuildUtils.customiceLayoutBKUSelection(value, - oaParam.isShowMandateCheckBox(), - oaParam.isOnlyMandateAllowed(), - oaParam.getFormCustomizaten(), - oaParam.isShowStorkLogin()); - - } - return value; - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/RedirectFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/RedirectFormBuilder.java deleted file mode 100644 index 2a5c8d418..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/RedirectFormBuilder.java +++ /dev/null @@ -1,65 +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.builder; - -import java.io.InputStream; -import java.io.StringWriter; - -import org.apache.commons.io.IOUtils; - -import at.gv.egovernment.moa.logging.Logger; - -public class RedirectFormBuilder { - - private static String URL = "#URL#"; - private static String TARGET = "#TARGET#"; - private static String template; - - private static String getTemplate() { - - if (template == null) { - try { - String classpathLocation = "resources/templates/redirectForm.html"; - InputStream input = Thread.currentThread() - .getContextClassLoader() - .getResourceAsStream(classpathLocation); - StringWriter writer = new StringWriter(); - IOUtils.copy(input, writer); - template = writer.toString(); - } catch (Exception e) { - Logger.error("Failed to read template", e); - } - } - - return template; - } - - public static String buildLoginForm(String url, String redirectTarget) { - String value = getTemplate(); - value = value.replace(URL, url); - value = value.replace(TARGET, redirectTarget); - - return value; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.java deleted file mode 100644 index 7121935b0..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/SendAssertionFormBuilder.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.auth.builder; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.net.URI; - -import org.apache.commons.io.IOUtils; - -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.util.FormBuildUtils; -import at.gv.egovernment.moa.logging.Logger; - -public class SendAssertionFormBuilder { - - private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; - private static final String HTMLTEMPLATEFULL = "sendAssertionFormFull.html"; - - private static final String TEMPLATEBGCOLOR = "style=\"background-color: #COLOR#\""; - - private static String URL = "#URL#"; - private static String ID = "#ID#"; - private static String OANAME = "#OAName#"; - private static String CONTEXTPATH = "#CONTEXTPATH#"; - private static String BACKGROUNDCOLOR = "#BACKGROUNDCOLOR#"; - private static String COLOR = "#COLOR#"; - - private static String SERVLET = CONTEXTPATH+"/SSOSendAssertionServlet"; - - private static String getTemplate() { - String pathLocation; - InputStream input = null; - try { - String rootconfigdir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); - pathLocation = rootconfigdir + HTMLTEMPLATESDIR + HTMLTEMPLATEFULL; - - try { - File file = new File(new URI(pathLocation)); - input = new FileInputStream(file); - - } catch (FileNotFoundException e) { - Logger.warn("No LoginFormTempaltes found. Use Generic Templates from package."); - pathLocation = "resources/templates/" + HTMLTEMPLATEFULL; - input = Thread.currentThread() - .getContextClassLoader() - .getResourceAsStream(pathLocation); - - } - - return getTemplate(input); - - } catch (Exception e) { - return null; - - } finally { - try { - if (input != null) - input.close(); - - } catch (IOException e) { - Logger.warn("SendAssertionTemplate inputstream can not be closed.", e); - - } - } - } - - private static String getTemplate(InputStream input) { - String template = null; - try { - - StringWriter writer = new StringWriter(); - IOUtils.copy(input, writer); - template = writer.toString(); - template = template.replace(URL, SERVLET); - - } catch (Exception e) { - Logger.error("Failed to read template", e); - - } - return template; - } - - public static String buildForm(IRequest pendingReq) { - String value = null; - - String contextpath = pendingReq.getAuthURL(); - IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - - byte[] oatemplate = oaParam.getSendAssertionTemplate(); - // OA specific template requires a size of 8 bits minimum - if (oatemplate != null && oatemplate.length > 7) { - InputStream is = new ByteArrayInputStream(oatemplate); - value = getTemplate(is); - - } else { - //load default BKU-selection template - value = getTemplate(); - - } - - if(value != null) { - value = value.replace(ID, pendingReq.getRequestID()); - value = value.replace(OANAME, oaParam.getFriendlyName()); - - if (contextpath.endsWith("/")) - contextpath = contextpath.substring(0, contextpath.length() - 1); - value = value.replace(CONTEXTPATH, contextpath); - - value = FormBuildUtils.customiceLayoutBKUSelection(value, - oaParam.isShowMandateCheckBox(), - oaParam.isOnlyMandateAllowed(), - oaParam.getFormCustomizaten(), - oaParam.isShowStorkLogin()); - - } - return value; - } - -} 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 f2e4da818..ec94101d1 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 @@ -31,11 +31,11 @@ import org.w3c.dom.Node; import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.ServiceException; import at.gv.egovernment.moa.id.auth.invoke.SignatureVerificationInvoker; import at.gv.egovernment.moa.id.auth.parser.VerifyXMLSignatureResponseParser; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; 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 7873fb96d..a72f6c2ea 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 @@ -46,7 +46,7 @@ import java.util.Map; import org.apache.commons.collections4.map.HashedMap; -import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; +import at.gv.egovernment.moa.id.commons.api.exceptions.SessionDataStorageException; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/AuthenticationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/AuthenticationException.java index 31a3e38dc..8fc6368fc 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/AuthenticationException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/AuthenticationException.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; /** * Exception thrown during handling of AuthenticationSession 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 index 9c2960c4c..ffbb6a19e 100644 --- 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 @@ -22,6 +22,8 @@ ******************************************************************************/ 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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/BuildException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/BuildException.java index 155a18f15..b31354927 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/BuildException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/BuildException.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; /** * Exception thrown while building an XML or HTML structure. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/DatabaseEncryptionException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/DatabaseEncryptionException.java index 69802d7e6..f62bbc4bd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/DatabaseEncryptionException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/DatabaseEncryptionException.java @@ -22,6 +22,8 @@ */ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; + /** * @author tlenz * diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/DynamicOABuildException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/DynamicOABuildException.java index 554cf7370..f43471f0a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/DynamicOABuildException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/DynamicOABuildException.java @@ -22,6 +22,8 @@ */ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; + /** * @author tlenz * diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ECDSAConverterException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ECDSAConverterException.java index 2b277736d..20e544330 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ECDSAConverterException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ECDSAConverterException.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; /** * Exception thrown while converting ECDSAKeys from/to an XML structure. 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 index 4f68bbac0..712d90fd8 100644 --- 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 @@ -22,6 +22,8 @@ */ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; + /** * @author tlenz * diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MISSimpleClientException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MISSimpleClientException.java index c80cbea26..718c35df3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MISSimpleClientException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MISSimpleClientException.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; public class MISSimpleClientException extends MOAIDException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIDException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIDException.java deleted file mode 100644 index ef6aaa75c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIDException.java +++ /dev/null @@ -1,222 +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 java.io.PrintStream; -import java.io.PrintWriter; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; - -import org.w3c.dom.DOMImplementation; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; -import at.gv.egovernment.moa.util.Constants; - -/** - * Base class of technical MOA exceptions. - * - * Technical exceptions are exceptions that originate from system failure (e.g., - * a database connection fails, a component is not available, etc.) - * - * @author Patrick Peck, Ivancsics Paul - * @version $Id$ - */ -public class MOAIDException extends Exception { - /** - * - */ - private static final long serialVersionUID = -1507246171708083912L; -/** message ID */ - private String messageId; - /** wrapped exception */ - private Throwable wrapped; - - private Object[] parameters; - - /** - * Create a new MOAIDException. - * - * @param messageId The identifier of the message associated with this - * exception. - * @param parameters Additional message parameters. - */ - public MOAIDException(String messageId, Object[] parameters) { - super(MOAIDMessageProvider.getInstance().getMessage(messageId, parameters)); - this.messageId = messageId; - this.parameters = parameters; - } - - /** - * Create a new MOAIDException. - * - * @param messageId The identifier of the message associated with this - * MOAIDException. - * @param parameters Additional message parameters. - * @param wrapped The exception wrapped by this - * MOAIDException. - */ - public MOAIDException( - String messageId, - Object[] parameters, - Throwable wrapped) { - - super(MOAIDMessageProvider.getInstance().getMessage(messageId, parameters)); - this.messageId = messageId; - this.wrapped = wrapped; - this.parameters = parameters; - } - - /** - * Print a stack trace of this exception to System.err. - * - * @see java.lang.Throwable#printStackTrace() - */ - public void printStackTrace() { - printStackTrace(System.err); - } - - /** - * Print a stack trace of this exception, including the wrapped exception. - * - * @param s The stream to write the stack trace to. - * @see java.lang.Throwable#printStackTrace(java.io.PrintStream) - */ - public void printStackTrace(PrintStream s) { - if (getWrapped() == null) - super.printStackTrace(s); - else { - s.print("Root exception: "); - getWrapped().printStackTrace(s); - } - } - - /** - * Print a stack trace of this exception, including the wrapped exception. - * - * @param s The stream to write the stacktrace to. - * @see java.lang.Throwable#printStackTrace(java.io.PrintWriter) - */ - public void printStackTrace(PrintWriter s) { - if (getWrapped() == null) - super.printStackTrace(s); - else { - s.print("Root exception: "); - getWrapped().printStackTrace(s); - } - } - - /** - * @return message ID - */ - public String getMessageId() { - return messageId; - } - - /** - * @return wrapped exception - */ - public Throwable getWrapped() { - return wrapped; - } - - - - /** - * @return the parameters - */ -public Object[] getParameters() { - return parameters; -} - -/** - * Convert this MOAIDException to an ErrorResponse - * element from the MOA namespace. - * - * @return An ErrorResponse element, containing the subelements - * ErrorCode and Info required by the MOA schema. - */ - public Element toErrorResponse() { - DocumentBuilder builder; - DOMImplementation impl; - Document doc; - Element errorResponse; - Element errorCode; - Element info; - - // create a new document - try { - builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - impl = builder.getDOMImplementation(); - } catch (ParserConfigurationException e) { - return null; - } - - // build the ErrorResponse element - doc = impl.createDocument(Constants.MOA_NS_URI, "ErrorResponse", null); - errorResponse = doc.getDocumentElement(); - - // add MOA namespace declaration - errorResponse.setAttributeNS( - Constants.XMLNS_NS_URI, - "xmlns", - Constants.MOA_NS_URI); - - // build the child elements - errorCode = doc.createElementNS(Constants.MOA_NS_URI, "ErrorCode"); - errorCode.appendChild(doc.createTextNode(messageId)); - info = doc.createElementNS(Constants.MOA_NS_URI, "Info"); - info.appendChild(doc.createTextNode(toString())); - errorResponse.appendChild(errorCode); - errorResponse.appendChild(info); - return errorResponse; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOASPException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOASPException.java index 42fa5c6a7..d498c3209 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOASPException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOASPException.java @@ -22,6 +22,8 @@ ******************************************************************************/ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; + public class MOASPException extends MOAIDException { private static final long serialVersionUID = -4646544256490397419L; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ParseException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ParseException.java index 83d0a398b..aac5fcddb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ParseException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ParseException.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; /** * Exception thrown while parsing an XML structure. 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 index fe2bcedca..2d09384a3 100644 --- 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 @@ -22,6 +22,8 @@ */ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; + /** * @author tlenz * diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ServiceException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ServiceException.java index 3bdf8f743..b892424d9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ServiceException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ServiceException.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; /** * Exception thrown while calling the MOA-SPSS web service. diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/SessionDataStorageException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/SessionDataStorageException.java deleted file mode 100644 index 203be784e..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/SessionDataStorageException.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.auth.exception; - -/** - * @author tlenz - * - */ -public class SessionDataStorageException extends MOAIDException { - - /** - * - */ - private static final long serialVersionUID = 5743057708136365929L; - - /** - * @param messageId - * @param parameters - */ - public SessionDataStorageException(String messageId, Object[] parameters) { - super(messageId, parameters); - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ValidateException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ValidateException.java index 0385352d2..124ae771a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ValidateException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/ValidateException.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; /** * Exception thrown while validating an incoming XML structure diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/WrongParametersException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/WrongParametersException.java index 895a2aeef..c83d1580b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/WrongParametersException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/WrongParametersException.java @@ -46,6 +46,7 @@ package at.gv.egovernment.moa.id.auth.exception; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; /** * Exception thrown when the AuthenticationServer API is 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 5c96f6ad2..a82ba501c 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,9 +52,9 @@ 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.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +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.api.SignatureVerificationService; import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureRequestParser; @@ -91,7 +91,7 @@ public class SignatureVerificationInvoker { private SignatureVerificationInvoker() { try { AuthConfiguration authConfigProvider = AuthConfigurationProviderFactory.getInstance(); - ConnectionParameter authConnParam = authConfigProvider.getMoaSpConnectionParameter(); + ConnectionParameterInterface authConnParam = authConfigProvider.getMoaSpConnectionParameter(); if (authConnParam != null && MiscUtil.isNotEmpty(authConnParam.getUrl())) { @@ -126,7 +126,7 @@ public class SignatureVerificationInvoker { * @throws ServiceException if an error occurs */ protected Element doCall(QName serviceName, Element request) throws ServiceException { - ConnectionParameter authConnParam = null; + ConnectionParameterInterface authConnParam = null; try { AuthConfiguration authConfigProvider = AuthConfigurationProviderFactory.getInstance(); authConnParam = authConfigProvider.getMoaSpConnectionParameter(); 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 index 8c7583855..84ca9fa05 100644 --- 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 @@ -23,10 +23,10 @@ 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.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +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.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.moduls.IRequest; 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; 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 c96167e71..90795a416 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,7 +22,7 @@ */ package at.gv.egovernment.moa.id.auth.modules; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.process.api.ExecutionContext; /** 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 index 932019d2c..1128cbab3 100644 --- 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 @@ -22,7 +22,7 @@ */ package at.gv.egovernment.moa.id.auth.modules; -import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.commons.api.IRequest; import at.gv.egovernment.moa.id.process.ProcessExecutionException; import at.gv.egovernment.moa.util.MiscUtil; 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 bd8dd709f..42789d01d 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,9 +30,9 @@ import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; import org.springframework.stereotype.Component; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; 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.process.api.ExecutionContext; 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/modules/internal/tasks/EvaluateSSOConsentsTaskImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/EvaluateSSOConsentsTaskImpl.java index 5b53a43bd..dfb90da3a 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 @@ -31,10 +31,10 @@ import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.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.util.ParamValidatorUtils; 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 index c8e379bc1..6a1ed7203 100644 --- 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 @@ -27,10 +27,10 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Component; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.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.moduls.RequestImpl; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.logging.Logger; 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 2cf2bfd9b..c582050ad 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 @@ -22,20 +22,23 @@ */ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import java.io.PrintWriter; - 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.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.auth.builder.LoginFormBuilder; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIBuilderConfiguration; +import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; +import at.gv.egovernment.moa.id.auth.frontend.builder.ServiceProviderSpecificGUIFormBuilderConfiguration; +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.config.auth.IOAAuthParameters; +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; @@ -45,7 +48,9 @@ import at.gv.egovernment.moa.logging.Logger; */ @Component("GenerateBKUSelectionFrameTask") public class GenerateBKUSelectionFrameTask extends AbstractAuthServletTask { - + + @Autowired IGUIFormBuilder guiBuilder; + /* (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) */ @@ -63,20 +68,20 @@ public class GenerateBKUSelectionFrameTask extends AbstractAuthServletTask { throw new AuthenticationException("auth.00", new Object[] { pendingReq.getOAURL() }); } - - //Build authentication form - String publicURLPreFix = pendingReq.getAuthURL(); - if (publicURLPreFix.endsWith("/")) - publicURLPreFix = publicURLPreFix.substring(0, publicURLPreFix.length() - 1); - String loginForm = LoginFormBuilder.buildLoginForm(pendingReq.requestedModule(), - pendingReq.requestedAction(), oaParam, publicURLPreFix, pendingReq.getRequestID()); - - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(loginForm); - out.flush(); + + IGUIBuilderConfiguration config = new ServiceProviderSpecificGUIFormBuilderConfiguration( + pendingReq, + ServiceProviderSpecificGUIFormBuilderConfiguration.VIEW_BKUSELECTION, + GeneralProcessEngineSignalController.ENDPOINT_BKUSELECTION_EVALUATION); + + guiBuilder.build(response, config, "BKU-Selection form"); + + } catch (GUIBuildException e) { + Logger.warn("Can not build GUI:'BKU-Selection'. Msg:" + e.getMessage()); + throw new TaskExecutionException(pendingReq, + "Can not build GUI. Msg:" + e.getMessage(), + new MOAIDException("builder.09", new Object[]{e.getMessage()}, e)); - } catch (MOAIDException 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/GenerateSSOConsentEvaluatorFrameTask.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GenerateSSOConsentEvaluatorFrameTask.java index 47afe5795..ca99e9ba3 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 @@ -22,18 +22,21 @@ */ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import java.io.PrintWriter; - 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.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.auth.builder.SendAssertionFormBuilder; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +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.ServiceProviderSpecificGUIFormBuilderConfiguration; +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; @@ -46,6 +49,8 @@ import at.gv.egovernment.moa.logging.Logger; @Component("GenerateSSOConsentEvaluatorFrameTask") public class GenerateSSOConsentEvaluatorFrameTask extends AbstractAuthServletTask { + @Autowired IGUIFormBuilder guiBuilder; + /* (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) */ @@ -59,22 +64,26 @@ public class GenerateSSOConsentEvaluatorFrameTask extends AbstractAuthServletTas //set authenticated flag to false, because user consents is required pendingReq.setAuthenticated(false); - //build consents evaluator form - String form = SendAssertionFormBuilder.buildForm(pendingReq); - //store pending request requestStoreage.storePendingRequest(pendingReq); + + //build consents evaluator form + IGUIBuilderConfiguration config = new ServiceProviderSpecificGUIFormBuilderConfiguration( + pendingReq, + ServiceProviderSpecificGUIFormBuilderConfiguration.VIEW_SENDASSERTION, + GeneralProcessEngineSignalController.ENDPOINT_SENDASSERTION_EVALUATION); + guiBuilder.build(response, config, "SendAssertion-Evaluation"); + //Log consents evaluator event to revisionslog revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_START); - - //write form to response object - response.setContentType("text/html;charset=UTF-8"); - PrintWriter out = new PrintWriter(response.getOutputStream()); - out.print(form); - out.flush(); - + + } catch (GUIBuildException e) { + Logger.warn("Can not build GUI:'SendAssertion-Evaluation'. Msg:" + e.getMessage()); + throw new TaskExecutionException(pendingReq, + "Can not build GUI. Msg:" + e.getMessage(), + new MOAIDException("builder.09", new Object[]{e.getMessage()}, e)); } catch (MOAIDException 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/RestartAuthProzessManagement.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java index ddda86ecc..c1d02a029 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/RestartAuthProzessManagement.java @@ -30,10 +30,10 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; 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; 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 a4abbbcfa..f91dc6d3e 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,15 +30,15 @@ import org.apache.commons.lang.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; 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.MOAIDException; 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.exceptions.MOAIDException; import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index 04e4e7bdb..1a029a9fa 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -22,34 +22,30 @@ */ package at.gv.egovernment.moa.id.auth.servlet; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.StringWriter; -import java.net.URI; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ExceptionHandler; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; +import at.gv.egovernment.moa.id.auth.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.exceptions.ConfigurationException; +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.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.moduls.IRequestStorage; import at.gv.egovernment.moa.id.process.ProcessExecutionException; import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; @@ -57,10 +53,8 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidator 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.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -72,16 +66,13 @@ public abstract class AbstractController extends MOAIDAuthConstants { public static final String ERROR_CODE_PARAM = "errorid"; - private static final String HTMLTEMPLATESDIR = "htmlTemplates/"; - private static final String HTMLTEMPLATEFULL = "error_message.html"; - private static String CONTEXTPATH = "contextPath"; - @Autowired protected StatisticLogger 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); @@ -227,89 +218,40 @@ public abstract class AbstractController extends MOAIDAuthConstants { } private void writeHTMLErrorResponse(HttpServletRequest req, HttpServletResponse httpResp, String msg, String errorCode, Exception error) throws IOException { - VelocityContext context = new VelocityContext(); - - //add errorcode and errormessage - context.put("errorMsg", msg); - context.put("errorCode", errorCode); + + 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()) { - context.put("stacktrace", getStacktraceFromException(error)); + //add stacktrace if debug is enabled + if (Logger.isTraceEnabled()) { + config.putCustomParameter("stacktrace", getStacktraceFromException(error)); - } - - writeHTMLErrorResponse(req, httpResp, context); - - } - - private void writeHTMLErrorResponse(HttpServletRequest req, HttpServletResponse httpResp, Exception error) throws IOException { - VelocityContext context = new VelocityContext(); - - //add errorcode and errormessage - context.put("errorMsg", error.getMessage()); - context.put("errorCode", ErrorResponseUtils.getInstance().getResponseErrorCode(error)); - - //add stacktrace if debug is enabled - if (Logger.isTraceEnabled()) { - context.put("stacktrace", getStacktraceFromException(error)); + } + + guiBuilder.build(httpResp, config, "Error-Message"); + + } catch (GUIBuildException e) { + Logger.warn("Can not build error-message GUI.", e); + GenericExceptionHandler(httpResp, e); } - writeHTMLErrorResponse(req, httpResp, context); } - private void writeHTMLErrorResponse(HttpServletRequest req, HttpServletResponse httpResp, VelocityContext context) throws IOException { - try { - String authURL = HTTPUtils.extractAuthURLFromRequest(req); - context.put(CONTEXTPATH, authURL); - - InputStream is = null; - String pathLocation = null; - try { - String rootconfigdir = authConfig.getRootConfigFileDir(); - pathLocation = rootconfigdir + HTMLTEMPLATESDIR + HTMLTEMPLATEFULL; - File file = new File(new URI(pathLocation)); - is = new FileInputStream(file); - evaluateErrorTemplate(context, httpResp, is); - - } catch (Exception e) { - Logger.warn("SLO Template is not found in configuration directory (" + - pathLocation + "). Load template from project library ... "); - - try { - pathLocation = "resources/templates/" + HTMLTEMPLATEFULL; - is = Thread.currentThread() - .getContextClassLoader() - .getResourceAsStream(pathLocation); - evaluateErrorTemplate(context, httpResp, is); - - } catch (Exception e1) { - Logger.error("Single LogOut form can not created.", e); - throw new MOAIDException("Create Single LogOut information FAILED.", null, e); - } - - } finally { - if (is != null) - is.close(); - - } - } catch (Exception e) { - Logger.error("Error-message form can not created.", e); - IOExceptionHandler(httpResp, e); - - } + private void writeHTMLErrorResponse(HttpServletRequest req, HttpServletResponse httpResp, Exception error) throws IOException { + writeHTMLErrorResponse(req, httpResp, + error.getMessage(), + ErrorResponseUtils.getInstance().getResponseErrorCode(error), + error); } - private void evaluateErrorTemplate(VelocityContext context, HttpServletResponse httpResp, InputStream is) throws Exception { - VelocityEngine engine = VelocityProvider.getClassPathVelocityEngine(); - BufferedReader reader = new BufferedReader(new InputStreamReader(is )); - StringWriter writer = new StringWriter(); - engine.evaluate(context, writer, "Error Template", reader); - httpResp.setContentType("text/html;charset=UTF-8"); - httpResp.getOutputStream().write(writer.toString().getBytes("UTF-8")); - - } private String getStacktraceFromException(Exception ex) { StringWriter errors = new StringWriter(); 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 index 6be0fce90..a23938f97 100644 --- 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 @@ -9,9 +9,9 @@ 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.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.moduls.IRequest; +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; 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 deleted file mode 100644 index 3f9093a21..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java +++ /dev/null @@ -1,128 +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 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.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.GUILayoutBuilder; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.moduls.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; - -/** - * @author tlenz - * - */ -@Controller -public class GUILayoutBuilderServlet extends AbstractController { - - public static final String ENDPOINT_CSS = "/css/buildCSS"; - public static final String ENDPOINT_JS = "/js/buildJS"; - - @Autowired AuthConfiguration authConfig; - @Autowired IRequestStorage requestStoreage; - - public GUILayoutBuilderServlet() { - super(); - Logger.debug("Registering servlet " + getClass().getName() - + " with mappings '" + ENDPOINT_CSS - + "' and '" + ENDPOINT_JS + "'."); - - } - - @RequestMapping(value = "/css/buildCSS", method = {RequestMethod.GET}) - public void buildCSS(HttpServletRequest req, HttpServletResponse resp) throws IOException { - IRequest pendingReq = extractPendingRequest(req); - - //build Service-Provider specific CSS - String css = GUILayoutBuilder.buildCSS(pendingReq, HTTPUtils.extractAuthURLFromRequest(req)); - - resp.setContentType("text/css;charset=UTF-8"); - writeResponse(resp, css, "CSS"); - - } - - @RequestMapping(value = "/js/buildJS", method = {RequestMethod.GET}) - public void buildJavaScript(HttpServletRequest req, HttpServletResponse resp) throws IOException { - IRequest pendingReq = extractPendingRequest(req); - - //build Service-Provider specific CSS - String js = GUILayoutBuilder.buildJS(pendingReq, HTTPUtils.extractAuthURLFromRequest(req)); - - resp.setContentType("text/javascript;charset=UTF-8"); - writeResponse(resp, js, "JavaScript"); - - } - - private void writeResponse(HttpServletResponse resp, String value, String ressourceID) throws IOException { - if (MiscUtil.isNotEmpty(value)) { - PrintWriter out = new PrintWriter(resp.getOutputStream()); - out.print(value); - out.flush(); - - } else { - Logger.warn("GUI ressource: " + ressourceID + " generation FAILED."); - resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Created resource failed"); - - } - - } - - private IRequest extractPendingRequest(HttpServletRequest req) { - try { - String pendingReqID = StringEscapeUtils.escapeHtml( - req.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); - - if (MiscUtil.isNotEmpty(pendingReqID)) { - IRequest pendingReq = requestStorage.getPendingRequest(pendingReqID); - if (pendingReq != null) { - Logger.trace("GUI-Layout builder: Pending-request:" - + pendingReqID + " found -> Build specific template"); - return pendingReq; - - } - } - - Logger.trace("GUI-Layout builder: No pending-request found -> Use default templates"); - - } catch (Exception e) { - Logger.warn("GUI-Layout builder-servlet has an error during request-preprocessing.", e); - } - - return null; - } -} 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 26a0488ca..dfa923558 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 @@ -39,9 +39,11 @@ import org.springframework.web.bind.annotation.RequestMethod; public class GeneralProcessEngineSignalController extends AbstractProcessEngineSignalController { + public static final String ENDPOINT_BKUSELECTION_EVALUATION = "/EvaluateBKUSelection"; + public static final String ENDPOINT_SENDASSERTION_EVALUATION = "/SSOSendAssertionServlet"; + public static final String ENDPOINT_GENERIC = "/signalProcess"; - - @RequestMapping(value = {"/GenerateIframeTemplate", + @RequestMapping(value = {"/EvaluateBKUSelection", "/SSOSendAssertionServlet", "/signalProcess" }, 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 9397f1132..66e8757ad 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 @@ -28,7 +28,6 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.velocity.VelocityContext; import org.opensaml.saml2.core.LogoutResponse; import org.opensaml.saml2.metadata.SingleLogoutService; import org.springframework.beans.factory.annotation.Autowired; @@ -36,10 +35,13 @@ 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.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +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; @@ -50,7 +52,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NOSLOServiceDescripto 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.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -68,6 +69,7 @@ public class IDPSingleLogOutServlet extends AbstractController { @Autowired IAuthenticationSessionStoreage authenicationStorage; @Autowired SingleLogOutBuilder sloBuilder; + @RequestMapping(value = "/idpSingleLogout", method = {RequestMethod.GET}) public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { @@ -104,18 +106,22 @@ public class IDPSingleLogOutServlet extends AbstractController { transactionStorage.remove(tokken); } - VelocityContext context = new VelocityContext(); + + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + if (MOAIDAuthConstants.SLOSTATUS_SUCCESS.equals(status)) - context.put("successMsg", + config.putCustomParameter("successMsg", MOAIDMessageProvider.getInstance().getMessage("slo.00", null)); else - context.put("errorMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - - ssoManager.printSingleLogOutInfo(context, resp, authURL); - - } catch (MOAIDException e) { - handleErrorNoRedirect(e, req, resp, false); + config.putCustomParameter("errorMsg", + MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); + guiBuilder.build(resp, config, "Single-LogOut GUI"); + + } catch (GUIBuildException e) { + handleErrorNoRedirect(e, req, resp, false); } catch (MOADatabaseException e) { handleErrorNoRedirect(e, req, resp, false); @@ -202,28 +208,36 @@ public class IDPSingleLogOutServlet extends AbstractController { } - VelocityContext context = new VelocityContext(); - context.put("errorMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - try { - ssoManager.printSingleLogOutInfo(context, resp, authURL); + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); - } catch (MOAIDException e) { + config.putCustomParameter("errorMsg", + MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); + + guiBuilder.build(resp, config, "Single-LogOut GUI"); + + } catch (GUIBuildException e) { e.printStackTrace(); } return; } } - - VelocityContext context = new VelocityContext(); - context.put("successMsg", - MOAIDMessageProvider.getInstance().getMessage("slo.02", null)); - try { - ssoManager.printSingleLogOutInfo(context, resp, authURL); + try { + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + + config.putCustomParameter("successMsg", + MOAIDMessageProvider.getInstance().getMessage("slo.02", null)); + + guiBuilder.build(resp, config, "Single-LogOut GUI"); - } catch (MOAIDException e) { + } catch (GUIBuildException e) { e.printStackTrace(); } 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 4fcf166c9..15333a933 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,8 +56,8 @@ 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.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.AuthenticationManager; import at.gv.egovernment.moa.id.moduls.SSOManager; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; @@ -91,7 +91,7 @@ public class LogOutServlet { } else { //return an error if RedirectURL is not a active Online-Applikation - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(redirectUrl); + IOAAuthParameters oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(redirectUrl); if (oa == null) { Logger.info("RedirctURL does not match to OA configuration. Set default RedirectURL back to MOA-ID-Auth"); redirectUrl = HTTPUtils.extractAuthURLFromRequest(req); 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 ba8ace6c9..f39421a21 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,7 +23,6 @@ package at.gv.egovernment.moa.id.auth.servlet; import java.io.IOException; -import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -33,12 +32,13 @@ 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.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.RedirectFormBuilder; +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.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.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.SSOManager; -import at.gv.egovernment.moa.id.util.FormBuildUtils; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -51,7 +51,11 @@ public class RedirectServlet { public static final String REDIRCT_PARAM_URL = "redirecturl"; private static final String DEFAULT_REDIRECTTARGET = "_parent"; + private static final String URL = "URL"; + private static final String TARGET = "TARGET"; + @Autowired SSOManager ssoManager; + @Autowired IGUIFormBuilder guiBuilder; @RequestMapping(value = "/RedirectServlet", method = RequestMethod.GET) public void performLogOut(HttpServletRequest req, HttpServletResponse resp) throws IOException { @@ -63,7 +67,7 @@ public class RedirectServlet { String interIDP = req.getParameter(MOAIDAuthConstants.INTERFEDERATION_IDP); Logger.debug("Check URL against online-applications"); - OAAuthParameter oa = null; + IOAAuthParameters oa = null; String redirectTarget = DEFAULT_REDIRECTTARGET; try { oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(url); @@ -77,7 +81,7 @@ public class RedirectServlet { //Redirect is a SAML1 send Artifact redirct if (MiscUtil.isNotEmpty(artifact)) { try { - String test = oa.getFormCustomizaten().get(FormBuildUtils.REDIRECTTARGET); + String test = oa.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_APPLETREDIRECTTARGET); if (MiscUtil.isNotEmpty(test)) redirectTarget = test; @@ -99,14 +103,15 @@ public class RedirectServlet { URLEncoder.encode(artifact, "UTF-8")); url = resp.encodeRedirectURL(url); - String redirect_form = RedirectFormBuilder.buildLoginForm(url, redirectTarget); - - resp.setContentType("text/html;charset=UTF-8"); - resp.setStatus(HttpServletResponse.SC_OK); - PrintWriter out = new PrintWriter(resp.getOutputStream()); - out.write(redirect_form); - out.flush(); - + + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_REDIRECT, + null); + config.putCustomParameter(URL, url); + config.putCustomParameter(TARGET, redirectTarget); + guiBuilder.build(resp, config, "RedirectForm"); + } else if (MiscUtil.isNotEmpty(interIDP)) { //store IDP identifier and redirect to generate AuthRequst service Logger.info("Receive an interfederation redirect request for IDP " + interIDP); @@ -121,13 +126,12 @@ public class RedirectServlet { } else { Logger.debug("Redirect to " + url); - String redirect_form = RedirectFormBuilder.buildLoginForm(url, DEFAULT_REDIRECTTARGET); - - resp.setContentType("text/html;charset=UTF-8"); - resp.setStatus(HttpServletResponse.SC_OK); - PrintWriter out = new PrintWriter(resp.getOutputStream()); - out.write(redirect_form); - out.flush(); + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_REDIRECT, + null); + config.putCustomParameter(URL, url); + guiBuilder.build(resp, config, "RedirectForm"); } 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 ce384d1a0..87804ea6c 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 @@ -29,10 +29,10 @@ 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.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +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.id.util.MOAIDMessageProvider; 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/client/SZRGWClient.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClient.java index 672d2a35e..1548f11b3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClient.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClient.java @@ -27,8 +27,15 @@ import java.util.Map; import javax.net.ssl.SSLSocketFactory; import javax.xml.namespace.QName; +import javax.xml.ws.BindingProvider; + +import org.apache.cxf.configuration.jsse.TLSClientParameters; +import org.apache.cxf.endpoint.Client; +import org.apache.cxf.frontend.ClientProxy; +import org.apache.cxf.transport.http.HTTPConduit; +import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; -import at.gv.egovernment.moa.id.config.ConnectionParameter; +import at.gv.egovernment.moa.id.commons.api.ConnectionParameterInterface; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.util.SSLUtils; import at.gv.egovernment.moa.logging.Logger; @@ -38,20 +45,12 @@ import at.gv.util.wsdl.szrgw.SZRGWType; import at.gv.util.xsd.srzgw.CreateIdentityLinkRequest; import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; -import javax.xml.ws.BindingProvider; - -import org.apache.cxf.configuration.jsse.TLSClientParameters; -import org.apache.cxf.endpoint.Client; -import org.apache.cxf.frontend.ClientProxy; -import org.apache.cxf.transport.http.HTTPConduit; -import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; - public class SZRGWClient { private SSLSocketFactory sslContext = null; - public SZRGWClient(ConnectionParameter szrgwconnection) throws SZRGWClientException { - initial(szrgwconnection); + public SZRGWClient(ConnectionParameterInterface connectionParameters) throws SZRGWClientException { + initial(connectionParameters); } public CreateIdentityLinkResponse sentCreateIDLRequest(CreateIdentityLinkRequest request, String serviceUrl) throws SZRGWClientException { @@ -101,11 +100,11 @@ public class SZRGWClient { } - private void initial(ConnectionParameter szrgwconnection) throws at.gv.egovernment.moa.id.client.SZRGWClientException{ + private void initial(ConnectionParameterInterface connectionParameters) throws at.gv.egovernment.moa.id.client.SZRGWClientException{ try { sslContext = SSLUtils.getSSLSocketFactory( AuthConfigurationProviderFactory.getInstance(), - szrgwconnection); + connectionParameters); } catch (Exception e) { Logger.warn("SZRGW Client initialization FAILED.", e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClientException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClientException.java index 2038e3f18..991e748de 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClientException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/client/SZRGWClientException.java @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.client; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; public class SZRGWClientException extends MOAIDException{ 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 b0b2029ec..622eca0a5 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 @@ -31,19 +31,19 @@ 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.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +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.commons.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; 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.CreateIdentityLinkRequest.PEPSData; import at.gv.util.xsd.srzgw.MISType.Filters; /** @@ -127,7 +127,7 @@ public class SZRGWClientUtils { try { AuthConfiguration authConf = AuthConfigurationProviderFactory.getInstance(); - ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); + ConnectionParameterInterface connectionParameters = authConf.getForeignIDConnectionParameter(); String requestID = UUID.randomUUID().toString(); SZRGWClient client = new SZRGWClient(connectionParameters); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationException.java deleted file mode 100644 index a0223853a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationException.java +++ /dev/null @@ -1,82 +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.config; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; - -/** - * Exception signalling an error in the configuration. - * - * @author Patrick Peck - * @version $Id$ - */ -public class ConfigurationException extends MOAIDException { - - /** - * - */ - private static final long serialVersionUID = -7199539463319751278L; - -/** - * Create a MOAConfigurationException. - */ - public ConfigurationException(String messageId, Object[] parameters) { - super(messageId, parameters); - } - - /** - * Create a MOAConfigurationException. - */ - public ConfigurationException( - String messageId, - Object[] parameters, - Throwable wrapped) { - - super(messageId, parameters, wrapped); - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProvider.java deleted file mode 100644 index 5ec0a5bc6..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationProvider.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.config; - -/** - * @author tlenz - * - */ -public interface ConfigurationProvider { - - /** - * The name of the system property which contains the file name of the - * configuration file. - */ - public static final String CONFIG_PROPERTY_NAME = - "moa.id.configuration"; - - /** - * The name of the system property which contains the file name of the - * configuration file. - */ - public static final String PROXY_CONFIG_PROPERTY_NAME = - "moa.id.proxy.configuration"; - - /** - * The name of the generic configuration property giving the certstore directory path. - */ - public static final String DIRECTORY_CERTSTORE_PARAMETER_PROPERTY = - "DirectoryCertStoreParameters.RootDir"; - - /** - * The name of the generic configuration property switching the ssl revocation checking on/off - */ - public static final String TRUST_MANAGER_REVOCATION_CHECKING = - "TrustManager.RevocationChecking"; - - public String getRootConfigFileDir(); - - public String getDefaultChainingMode(); - - public String getTrustedCACertificates(); - - public String getCertstoreDirectory(); - - public boolean isTrustmanagerrevoationchecking(); -} 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 60d676868..db6ff8d9b 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 @@ -51,6 +51,8 @@ import java.util.Properties; import org.hibernate.cfg.Configuration; +import at.gv.egovernment.moa.id.commons.api.ConfigurationProvider; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.StatisticLogDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConnectionParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConnectionParameter.java index e38a4f360..9d78c348b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConnectionParameter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConnectionParameter.java @@ -24,6 +24,7 @@ package at.gv.egovernment.moa.id.config; import java.util.Properties; +import at.gv.egovernment.moa.id.commons.api.ConnectionParameterInterface; import at.gv.egovernment.moa.util.MiscUtil; public abstract class ConnectionParameter implements ConnectionParameterInterface{ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConnectionParameterInterface.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConnectionParameterInterface.java deleted file mode 100644 index 8e95c106d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConnectionParameterInterface.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.config; - -public interface ConnectionParameterInterface { - - - public boolean isHTTPSURL(); - public String getUrl(); - public String getAcceptedServerCertificates(); - - public String getClientKeyStore(); - public String getClientKeyStorePassword(); - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java deleted file mode 100644 index 1f9259696..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java +++ /dev/null @@ -1,165 +0,0 @@ -package at.gv.egovernment.moa.id.config.auth; - -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.ConfigurationProvider; -import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.data.ProtocolAllowed; -import at.gv.egovernment.moa.id.config.stork.STORKConfig; -import at.gv.util.config.EgovUtilPropertiesConfiguration; - -public interface AuthConfiguration extends ConfigurationProvider{ - - public static final String DEFAULT_X509_CHAININGMODE = "pkix"; - - public Properties getGeneralPVP2ProperiesConfig(); - - public Properties getGeneralOAuth20ProperiesConfig(); - - public ProtocolAllowed getAllowedProtocols(); - - public Map getConfigurationWithPrefix(final String Prefix); - - public String getConfigurationWithKey(final String key); - - /** - * Get a configuration value from basic file based MOA-ID configuration - * - * @param key configuration key - * @return configuration value - */ - public String getBasicMOAIDConfiguration(final String key); - - public int getTransactionTimeOut(); - public int getSSOCreatedTimeOut(); - public int getSSOUpdatedTimeOut(); - - public String getAlternativeSourceID() throws ConfigurationException; - - public List getLegacyAllowedProtocols(); - - public OAAuthParameter getOnlineApplicationParameter(String oaURL); - - public String getMoaSpAuthBlockTrustProfileID(boolean useTestTrustStore) throws ConfigurationException; - - public List getMoaSpAuthBlockVerifyTransformsInfoIDs() throws ConfigurationException; - - public ConnectionParameter getMoaSpConnectionParameter() throws ConfigurationException; - - public ConnectionParameter getForeignIDConnectionParameter() throws ConfigurationException; - - public ConnectionParameter getOnlineMandatesConnectionParameter() throws ConfigurationException; - - public String getMoaSpIdentityLinkTrustProfileID(boolean useTestTrustStore) throws ConfigurationException; - - public List getTransformsInfos() throws ConfigurationException; - - public List getIdentityLinkX509SubjectNames() throws ConfigurationException; - - public List getSLRequestTemplates() throws ConfigurationException; - - public String getSLRequestTemplates(String type) throws ConfigurationException; - - public List getDefaultBKUURLs() throws ConfigurationException; - - public String getDefaultBKUURL(String type) throws ConfigurationException; - - public String getSSOTagetIdentifier() throws ConfigurationException; - - public String getSSOFriendlyName(); - - public String getSSOSpecialText(); - - public String getMOASessionEncryptionKey(); - - public String getMOAConfigurationEncryptionKey(); - - public boolean isIdentityLinkResigning(); - - public String getIdentityLinkResigningKey(); - - public boolean isMonitoringActive(); - - public String getMonitoringTestIdentityLinkURL(); - - public String getMonitoringMessageSuccess(); - - public boolean isAdvancedLoggingActive(); - - /** - * Returns the PublicURLPrefix. - * - * @return the PublicURLPrefix (one or more) of this IDP instance. All publicURLPrefix URLs are ends without / - * @throws ConfigurationException if no PublicURLPrefix is found. - */ - public List getPublicURLPrefix() throws ConfigurationException; - - public boolean isVirtualIDPsEnabled(); - - public boolean isPVP2AssertionEncryptionActive(); - - public boolean isCertifiacteQCActive(); - - public STORKConfig getStorkConfig() throws ConfigurationException; - - public EgovUtilPropertiesConfiguration geteGovUtilsConfig(); - - public String getDocumentServiceUrl(); - - /** - * Notify, if the STORK fake IdentityLink functionality is active - * - * @return true/false - */ - public boolean isStorkFakeIdLActive(); - - /** - * Get a list of all STORK countries for which a faked IdentityLink should be created - * - * @return {List} of country codes - */ - public List getStorkFakeIdLCountries(); - - /** - * Get a list of all STORK countries for which no signature is required - * - * @return {List} of country codes - */ - public List getStorkNoSignatureCountries(); - - /** - * Get the MOA-SS key-group identifier for fake IdentityLink signing - * - * @return MOA-SS key-group identifier {String} - */ - public String getStorkFakeIdLResigningKey(); - - - /** - * Notify, if the PVP2x metadata schema validation is active - * - * @return true/false - */ - public boolean isPVPSchemaValidationActive(); - - /** - * Get all configuration values with prefix and wildcard - * - * @param key: Search key. * and % can be used as wildcards - * @return Key/Value pairs {Map}, which key maps the search key - */ - Map getConfigurationWithWildCard(String key); - - /** - * Get configured default revisions-log event codes which should be logged - * - * @return {List} if event codes or null - */ - List getDefaultRevisionsLogEventCodes(); - - @Deprecated - public boolean isHTTPAuthAllowed(); -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProviderFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProviderFactory.java index a00d3d313..94bcae672 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProviderFactory.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProviderFactory.java @@ -24,7 +24,8 @@ package at.gv.egovernment.moa.id.config.auth; import org.springframework.context.ApplicationContext; -import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.logging.Logger; /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java deleted file mode 100644 index 58034cc7b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/IOAAuthParameters.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.config.auth; - -import java.security.PrivateKey; -import java.util.Collection; -import java.util.List; -import java.util.Map; - -import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters; -import at.gv.egovernment.moa.id.config.stork.CPEPS; -import at.gv.egovernment.moa.id.config.stork.StorkAttribute; -import at.gv.egovernment.moa.id.config.stork.StorkAttributeProviderPlugin; - -/** - * @author tlenz - * - */ -public interface IOAAuthParameters { - - public static final String ONLINEBKU = "online"; - public static final String HANDYBKU = "handy"; - public static final String LOCALBKU = "local"; - public static final String INDERFEDERATEDIDP = "interfederated"; - - /** - * Get the full key/value configuration for this online application - * - * @return an unmodifiable map of key/value pairs - */ - public Map getFullConfiguration(); - - /** - * Get a configuration value from online application key/value configuration - * - * @param key: The key identifier of a configuration value * - * @return The configuration value {String} or null if the key does not exist - */ - public String getConfigurationValue(String key); - - public String getFriendlyName(); - - public String getPublicURLPrefix(); - - public String getOaType(); - - public boolean getBusinessService(); - - /** - * Get target of a public service-provider - * - * @return target identifier without prefix - */ - public String getTarget(); - - public String getTargetFriendlyName(); - - public boolean isInderfederationIDP(); - - public boolean isSTORKPVPGateway(); - - public boolean isRemovePBKFromAuthBlock(); - - /** - * Return the private-service domain-identifier with PreFix - * - * @return the identityLinkDomainIdentifier - */ - public String getIdentityLinkDomainIdentifier(); - - /** - * @return the keyBoxIdentifier - */ - public String getKeyBoxIdentifier(); - - public SAML1ConfigurationParameters getSAML1Parameter(); - - /** - * Get a list of online application specific trusted security layer templates - * - * @return a {List} with template URLs, maybe empty but never null - */ - public List getTemplateURL(); - - - /** - * Return the additional AuthBlock text for this online application - * - * @return authblock text {String} or null if no text is configured - */ - public String getAditionalAuthBlockText(); - - /** - * Return an online application specific BKU URL for a requested BKU type - * - * @param bkutype: defines the type of BKU - * @return BKU URL {String} or null if no BKU URL is configured - */ - public String getBKUURL(String bkutype); - - /** - * Return a list of all configured BKU URLs for this online application - * - * @return List of BKU URLs or an empty list if no BKU is configured - */ - public List getBKUURL(); - - public boolean useSSO(); - - public boolean useSSOQuestion(); - - /** - * Return all mandate-profile types configured for this online application - * - * @return the mandateProfiles {List} or null if no profile is defined - */ - public List getMandateProfiles(); - - /** - * @return the identityLinkDomainIdentifierType - */ - public String getIdentityLinkDomainIdentifierType(); - - public boolean isShowMandateCheckBox(); - - public boolean isOnlyMandateAllowed(); - - /** - * Shall we show the stork login in the bku selection frontend? - * - * @return true, if is we should show stork login - */ - public boolean isShowStorkLogin(); - - public Map getFormCustomizaten(); - - public Integer getQaaLevel(); - - public boolean isRequireConsentForStorkAttributes(); - - /** - * Return a {Collection} of requested STORK attributes - * - * @return {Collection} maybe empty but never null - */ - public Collection getRequestedSTORKAttributes(); - - public byte[] getBKUSelectionTemplate(); - - public byte[] getSendAssertionTemplate(); - - /** - * Return a {Collection} of configured STORK CPEPS - * - * @return {Collection} maybe empty but never null - */ - public Collection getPepsList(); - - public String getIDPAttributQueryServiceURL(); - - /** - * @return - */ - boolean isInboundSSOInterfederationAllowed(); - - /** - * @return - */ - boolean isInterfederationSSOStorageAllowed(); - - /** - * @return - */ - boolean isOutboundSSOInterfederationAllowed(); - - boolean isTestCredentialEnabled(); - - List getTestCredentialOIDs(); - - boolean isUseIDLTestTrustStore(); - boolean isUseAuthBlockTestTestStore(); - - PrivateKey getBPKDecBpkDecryptionKey(); - - /** - * @return - */ - boolean isPassivRequestUsedForInterfederation(); - - /** - * @return - */ - boolean isPerformLocalAuthenticationOnInterfederationError(); - - /** - * Get a {Collection} of configured STORK attribute provider plug-ins - * - * @return {Collection} maybe empty but never null - */ - public Collection getStorkAPs(); - - public List getReversionsLoggingEventCodes(); - -} \ No newline at end of file diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java index fdd125156..b1bba6c17 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java @@ -61,19 +61,19 @@ import org.apache.commons.lang.SerializationUtils; import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.id.commons.MOAIDConstants; +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; +import at.gv.egovernment.moa.id.commons.api.data.CPEPS; +import at.gv.egovernment.moa.id.commons.api.data.SAML1ConfigurationParameters; +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.commons.validation.TargetValidator; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.data.BPKDecryptionParameters; -import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters; -import at.gv.egovernment.moa.id.config.stork.CPEPS; -import at.gv.egovernment.moa.id.config.stork.STORKConfig; -import at.gv.egovernment.moa.id.config.stork.StorkAttribute; -import at.gv.egovernment.moa.id.config.stork.StorkAttributeProviderPlugin; import at.gv.egovernment.moa.id.data.EncryptedData; import at.gv.egovernment.moa.id.util.ConfigurationEncrytionUtil; -import at.gv.egovernment.moa.id.util.FormBuildUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.MiscUtil; @@ -390,52 +390,6 @@ public boolean isOnlyMandateAllowed() { } } -/* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getFormCustomizaten() - */ -@Override -public Map getFormCustomizaten() { - Map map = new HashMap(); - map.putAll(FormBuildUtils.getDefaultMap()); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_BACKGROUNDCOLOR))) - map.put(FormBuildUtils.MAIN_BACKGROUNDCOLOR, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_BACKGROUNDCOLOR)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_BUTTONBACKGROUNDCOLOR))) - map.put(FormBuildUtils.BUTTON_BACKGROUNDCOLOR, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_BUTTONBACKGROUNDCOLOR)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_BUTTONBACLGROUNDCOLORFOCUS))) - map.put(FormBuildUtils.BUTTON_BACKGROUNDCOLOR_FOCUS, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_BUTTONBACLGROUNDCOLORFOCUS)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_BUTTONFRONTCOLOR))) - map.put(FormBuildUtils.BUTTON_COLOR, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_BUTTONFRONTCOLOR)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_FONTTYPE))) - map.put(FormBuildUtils.FONTFAMILY, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_FONTTYPE)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_FRONTCOLOR))) - map.put(FormBuildUtils.MAIN_COLOR, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_FRONTCOLOR)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_HEADERBACKGROUNDCOLOR))) - map.put(FormBuildUtils.HEADER_BACKGROUNDCOLOR, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_HEADERBACKGROUNDCOLOR)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_HEADERFRONTCOLOR))) - map.put(FormBuildUtils.HEADER_COLOR, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_HEADERFRONTCOLOR)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_HEADERTEXT))) - map.put(FormBuildUtils.HEADER_TEXT, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_HEADERTEXT)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_APPLETREDIRECTTARGET))) - map.put(FormBuildUtils.REDIRECTTARGET, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_APPLETREDIRECTTARGET)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_APPLETHEIGHT))) - map.put(FormBuildUtils.APPLET_HEIGHT, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_APPLETHEIGHT)); - - if (MiscUtil.isNotEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_APPLETWIDTH))) - map.put(FormBuildUtils.APPLET_WIDTH, oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_CUSTOMIZATION_APPLETWIDTH)); - - return map; -} /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getQaaLevel() @@ -615,7 +569,7 @@ public byte[] getSendAssertionTemplate() { public Collection getPepsList() { Map cPEPSMap = new HashMap(); try { - STORKConfig availableSTORKConfig = AuthConfigurationProviderFactory.getInstance().getStorkConfig(); + IStorkConfig availableSTORKConfig = AuthConfigurationProviderFactory.getInstance().getStorkConfig(); if (availableSTORKConfig != null) { Set configKeys = oaConfiguration.keySet(); 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 ed2f4d96b..210bda3e6 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 @@ -19,8 +19,14 @@ import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +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.ConfigurationProvider; +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.ProtocolAllowed; +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.config.persistence.MOAIDConfiguration; import at.gv.egovernment.moa.id.commons.db.dao.config.deprecated.AuthComponentGeneral; @@ -29,15 +35,12 @@ import at.gv.egovernment.moa.id.commons.db.dao.config.deprecated.OnlineApplicati 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.ConfigurationException; -import at.gv.egovernment.moa.id.config.ConfigurationProvider; import at.gv.egovernment.moa.id.config.ConfigurationProviderImpl; import at.gv.egovernment.moa.id.config.ConfigurationUtils; import at.gv.egovernment.moa.id.config.ConnectionParameter; import at.gv.egovernment.moa.id.config.ConnectionParameterForeign; import at.gv.egovernment.moa.id.config.ConnectionParameterMOASP; import at.gv.egovernment.moa.id.config.ConnectionParameterMandate; -import at.gv.egovernment.moa.id.config.auth.data.ProtocolAllowed; import at.gv.egovernment.moa.id.config.stork.STORKConfig; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; import at.gv.egovernment.moa.logging.Logger; @@ -916,8 +919,8 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return a new STORK Configuration or {@code null} * @throws ConfigurationException is thrown in case of missing {@link AuthComponentGeneral} */ - public STORKConfig getStorkConfig() throws ConfigurationException { - STORKConfig result = null; + public IStorkConfig getStorkConfig() throws ConfigurationException { + IStorkConfig result = null; try { Map storkProps = configuration.getPropertySubset( MOAIDConfigurationConstants.GENERAL_AUTH_STORK + "."); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/BPKDecryptionParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/BPKDecryptionParameters.java deleted file mode 100644 index b7d5ebed5..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/BPKDecryptionParameters.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.config.auth.data; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; - -import org.apache.commons.lang.SerializationUtils; - -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Base64Utils; -import at.gv.egovernment.moa.util.KeyStoreUtils; - - -/** - * @author tlenz - * - */ -public class BPKDecryptionParameters implements Serializable{ - - private static final long serialVersionUID = 1L; - - private byte[] keyStore = null; - private String keyStorePassword = null; - private String keyAlias = null; - private String keyPassword = null; - - /** - * @return - * @throws IOException - */ - public PrivateKey getPrivateKey() { - InputStream in = null; - try { - in = new ByteArrayInputStream(keyStore); - KeyStore store = KeyStoreUtils.loadKeyStore(in , keyStorePassword); - - char[] chPassword = " ".toCharArray(); - if (keyPassword != null) - chPassword = keyPassword.toCharArray(); - -// Certificate test = store.getCertificate(keyAlias); -// Base64Utils.encode(test.getPublicKey().getEncoded()); - - return (PrivateKey) store.getKey(keyAlias, chPassword); - - - } catch (KeyStoreException e) { - Logger.error("Can not load private key from keystore.", e); - - } catch (IOException e) { - Logger.error("Can not load private key from keystore.", e); - - } catch (UnrecoverableKeyException e) { - Logger.error("Can not load private key from keystore.", e); - - } catch (NoSuchAlgorithmException e) { - Logger.error("Can not load private key from keystore.", e); - - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - Logger.warn("Close InputStream failed." , e); - } - } - } - - return null; - } - - public byte[] serialize() { - return SerializationUtils.serialize(this); - - } - - /** - * @param keyStore the keyStore to set - */ - public void setKeyStore(byte[] keyStore) { - this.keyStore = keyStore; - } - - /** - * @param keyStorePassword the keyStorePassword to set - */ - public void setKeyStorePassword(String keyStorePassword) { - this.keyStorePassword = keyStorePassword; - } - - /** - * @param keyAlias the keyAlias to set - */ - public void setKeyAlias(String keyAlias) { - this.keyAlias = keyAlias; - } - - /** - * @param keyPassword the keyPassword to set - */ - public void setKeyPassword(String keyPassword) { - this.keyPassword = keyPassword; - } - - - - -} 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 171940063..8d70b1444 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 @@ -28,9 +28,10 @@ import java.util.Collection; import java.util.List; import java.util.Map; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.stork.StorkAttribute; -import at.gv.egovernment.moa.id.config.stork.StorkAttributeProviderPlugin; +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; +import at.gv.egovernment.moa.id.commons.api.data.StorkAttributeProviderPlugin; /** * @author tlenz @@ -196,15 +197,6 @@ public class DynamicOAAuthParameters implements IOAAuthParameters, Serializable{ return false; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getFormCustomizaten() - */ - @Override - public Map getFormCustomizaten() { - // TODO Auto-generated method stub - return null; - } - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getQaaLevel() */ @@ -254,7 +246,7 @@ public class DynamicOAAuthParameters implements IOAAuthParameters, Serializable{ * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getPepsList() */ @Override - public Collection getPepsList() { + public Collection getPepsList() { // TODO Auto-generated method stub return null; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/ProtocolAllowed.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/ProtocolAllowed.java deleted file mode 100644 index a04fb1626..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/ProtocolAllowed.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.config.auth.data; - -/** - * @author tlenz - * - */ -public class ProtocolAllowed { - - private boolean isSAML1Active = false; - private boolean isPVP21Active = true; - private boolean isOAUTHActive = true; - - /** - * - */ - public ProtocolAllowed() { - - } - - /** - * - */ - public ProtocolAllowed(boolean saml1, boolean pvp21, boolean oauth) { - this.isOAUTHActive = oauth; - this.isPVP21Active = pvp21; - this.isSAML1Active = saml1; - - } - - /** - * @return the isSAML1Active - */ - public boolean isSAML1Active() { - return isSAML1Active; - } - /** - * @param isSAML1Active the isSAML1Active to set - */ - public void setSAML1Active(boolean isSAML1Active) { - this.isSAML1Active = isSAML1Active; - } - /** - * @return the isPVP21Active - */ - public boolean isPVP21Active() { - return isPVP21Active; - } - /** - * @param isPVP21Active the isPVP21Active to set - */ - public void setPVP21Active(boolean isPVP21Active) { - this.isPVP21Active = isPVP21Active; - } - /** - * @return the isOAUTHActive - */ - public boolean isOAUTHActive() { - return isOAUTHActive; - } - /** - * @param isOAUTHActive the isOAUTHActive to set - */ - public void setOAUTHActive(boolean isOAUTHActive) { - this.isOAUTHActive = isOAUTHActive; - } - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/SAML1ConfigurationParameters.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/SAML1ConfigurationParameters.java deleted file mode 100644 index 8ff64f188..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/data/SAML1ConfigurationParameters.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.config.auth.data; - -/** - * @author tlenz - * - */ -public class SAML1ConfigurationParameters { - - private boolean isActive = false; - private boolean provideBaseId = false; - private boolean provideAuthBlock = false; - private boolean provideIdl = false; - private boolean provideCertificate = false; - private boolean provideMandate = false; - private boolean provideAllErrors = true; - private boolean useCondition = false; - private String sourceID = null; - private String condition = new String(); - - - /** - * - */ - public SAML1ConfigurationParameters(boolean isActive, - boolean provideBaseId, boolean provideAuthBlock, - boolean provideIdl, boolean provideCertificate, - boolean provideMandate, boolean provideAllErrors, - boolean useCondition, String condition, - String sourceID) { - this.condition = condition; - this.isActive = isActive; - this.provideAllErrors = provideAllErrors; - this.provideAuthBlock = provideAuthBlock; - this.provideBaseId = provideBaseId; - this.provideCertificate = provideCertificate; - this.provideIdl = provideIdl; - this.provideMandate = provideMandate; - this.useCondition = useCondition; - this.sourceID = sourceID; - - } - - - /** - * - */ - public SAML1ConfigurationParameters() { - - } - - - /** - * Gets the value of the isActive property. - * - * @return - * possible object is - * {@link String } - * - */ - public Boolean isIsActive() { - return this.isActive; - } - - /** - * @param isActive the isActive to set - */ - public void setActive(boolean isActive) { - this.isActive = isActive; - } - - - /** - * @param provideBaseId the provideBaseId to set - */ - public void setProvideBaseId(boolean provideBaseId) { - this.provideBaseId = provideBaseId; - } - - - /** - * @param provideAuthBlock the provideAuthBlock to set - */ - public void setProvideAuthBlock(boolean provideAuthBlock) { - this.provideAuthBlock = provideAuthBlock; - } - - - /** - * @param provideIdl the provideIdl to set - */ - public void setProvideIdl(boolean provideIdl) { - this.provideIdl = provideIdl; - } - - - /** - * @param provideCertificate the provideCertificate to set - */ - public void setProvideCertificate(boolean provideCertificate) { - this.provideCertificate = provideCertificate; - } - - - /** - * @param provideMandate the provideMandate to set - */ - public void setProvideMandate(boolean provideMandate) { - this.provideMandate = provideMandate; - } - - - /** - * @param provideAllErrors the provideAllErrors to set - */ - public void setProvideAllErrors(boolean provideAllErrors) { - this.provideAllErrors = provideAllErrors; - } - - - /** - * @param useCondition the useCondition to set - */ - public void setUseCondition(boolean useCondition) { - this.useCondition = useCondition; - } - - - /** - * @param sourceID the sourceID to set - */ - public void setSourceID(String sourceID) { - this.sourceID = sourceID; - } - - - /** - * @param condition the condition to set - */ - public void setCondition(String condition) { - this.condition = condition; - } - - - /** - * Gets the value of the provideStammzahl property. - * - * @return - * possible object is - * {@link String } - * - */ - public Boolean isProvideStammzahl() { - return this.provideBaseId; - } - - /** - * Gets the value of the provideAUTHBlock property. - * - * @return - * possible object is - * {@link String } - * - */ - public Boolean isProvideAUTHBlock() { - return this.provideAuthBlock; - } - - /** - * Gets the value of the provideIdentityLink property. - * - * @return - * possible object is - * {@link String } - * - */ - public Boolean isProvideIdentityLink() { - return this.provideIdl; - } - - /** - * Gets the value of the provideCertificate property. - * - * @return - * possible object is - * {@link String } - * - */ - public Boolean isProvideCertificate() { - return this.provideCertificate; - } - - /** - * Gets the value of the provideFullMandatorData property. - * - * @return - * possible object is - * {@link String } - * - */ - public Boolean isProvideFullMandatorData() { - return this.provideMandate; - } - - /** - * Gets the value of the useCondition property. - * - * @return - * possible object is - * {@link String } - * - */ - public Boolean isUseCondition() { - return this.useCondition; - } - - /** - * Gets the value of the conditionLength property. - * - * @return - * possible object is - * {@link BigInteger } - * - */ - - public int getConditionLength() { - return condition.length(); - } - - /** - * Gets the value of the sourceID property. - * - * @return - * possible object is - * {@link String } - * - */ - public String getSourceID() { - return this.sourceID; - } - - /** - * Gets the value of the provideAllErrors property. - * - * @return - * possible object is - * {@link String } - * - */ - public Boolean isProvideAllErrors() { - return this.provideAllErrors; - } - -} - diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/CPEPS.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/CPEPS.java deleted file mode 100644 index 3f4be5093..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/CPEPS.java +++ /dev/null @@ -1,138 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -/** - * - */ -package at.gv.egovernment.moa.id.config.stork; - -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import org.opensaml.saml2.metadata.RequestedAttribute; - -/** - * Encpasulates C-PEPS information according MOA configuration - * - * @author bzwattendorfer - * - */ -public class CPEPS { - - /** Country Code of C-PEPS */ - private String countryCode; - - /** URL of C-PEPS */ - private URL pepsURL; - - private Boolean isXMLSignatureSupported; - - /** Specific attributes to be requested for this C-PEPS */ - private List countrySpecificRequestedAttributes = new ArrayList(); - - /** - * Constructs a C-PEPS - * @param countryCode ISO Country Code of C-PEPS - * @param pepsURL URL of C-PEPS - */ - public CPEPS(String countryCode, URL pepsURL, Boolean isXMLSignatureSupported) { - super(); - this.countryCode = countryCode; - this.pepsURL = pepsURL; - this.isXMLSignatureSupported = isXMLSignatureSupported; - } - - /** - * Gets the country code of this C-PEPS - * @return ISO country code - */ - public String getCountryCode() { - return countryCode; - } - - /** - * Sets the country code of this C-PEPS - * @param countryCode ISO country code - */ - public void setCountryCode(String countryCode) { - this.countryCode = countryCode; - } - - /** - * Gets the URL of this C-PEPS - * @return C-PEPS URL - */ - public URL getPepsURL() { - return pepsURL; - } - - /** - * Sets the C-PEPS URL - * @param pepsURL C-PEPS URL - */ - public void setPepsURL(URL pepsURL) { - this.pepsURL = pepsURL; - } - - /** - * Returns weather the C-PEPS supports XMl Signatures or not (important for ERnB) - */ - public Boolean isXMLSignatureSupported() { - return isXMLSignatureSupported; - } - - /** - * Sets weather the C-PEPS supports XMl Signatures or not (important for ERnB) - * @param isXMLSignatureSupported C-PEPS XML Signature support - */ - public void setXMLSignatureSupported(boolean isXMLSignatureSupported) { - this.isXMLSignatureSupported = isXMLSignatureSupported; - } - - /** - * Gets the country specific attributes of this C-PEPS - * @return List of country specific attributes - */ - public List getCountrySpecificRequestedAttributes() { - return countrySpecificRequestedAttributes; - } - - /** - * Sets the country specific attributes - * @param countrySpecificRequestedAttributes List of country specific requested attributes - */ - public void setCountrySpecificRequestedAttributes( - List countrySpecificRequestedAttributes) { - this.countrySpecificRequestedAttributes = countrySpecificRequestedAttributes; - } - - /** - * Adds a Requested attribute to the country specific attribute List - * @param countrySpecificRequestedAttribute Additional country specific requested attribute to add - */ - public void addCountrySpecificRequestedAttribute(RequestedAttribute countrySpecificRequestedAttribute) { - this.countrySpecificRequestedAttributes.add(countrySpecificRequestedAttribute); - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/STORKConfig.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/STORKConfig.java index 9532aa9ab..8f6dff849 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/STORKConfig.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/STORKConfig.java @@ -34,8 +34,13 @@ import java.util.Map; import java.util.Properties; import java.util.Set; +import at.gv.egovernment.moa.id.commons.api.IStorkConfig; +import at.gv.egovernment.moa.id.commons.api.data.CPEPS; +import at.gv.egovernment.moa.id.commons.api.data.SignatureCreationParameter; +import at.gv.egovernment.moa.id.commons.api.data.SignatureVerificationParameter; +import at.gv.egovernment.moa.id.commons.api.data.StorkAttribute; +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.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -47,7 +52,7 @@ import at.gv.egovernment.moa.util.StringUtils; * @author bzwattendorfer * */ -public class STORKConfig { +public class STORKConfig implements IStorkConfig { /** STORK SAML signature creation parameters */ private Properties props = null; @@ -118,20 +123,36 @@ public class STORKConfig { } } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.stork.IStorkConfig#getSignatureCreationParameter() + */ + @Override public SignatureCreationParameter getSignatureCreationParameter() { return new SignatureCreationParameter(props, basedirectory); } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.stork.IStorkConfig#getSignatureVerificationParameter() + */ + @Override public SignatureVerificationParameter getSignatureVerificationParameter() { return sigverifyparam; } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.stork.IStorkConfig#getCpepsMap() + */ + @Override public Map getCpepsMap() { return cpepsMap; } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.stork.IStorkConfig#isSTORKAuthentication(java.lang.String) + */ + @Override public boolean isSTORKAuthentication(String ccc) { if (StringUtils.isEmpty(ccc) || this.cpepsMap.isEmpty()) @@ -144,6 +165,10 @@ public class STORKConfig { } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.stork.IStorkConfig#getCPEPS(java.lang.String) + */ + @Override public CPEPS getCPEPS(String ccc) { if (isSTORKAuthentication(ccc)) return this.cpepsMap.get(ccc); @@ -151,6 +176,10 @@ public class STORKConfig { return null; } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.stork.IStorkConfig#getStorkAttributes() + */ + @Override public List getStorkAttributes() { return attr; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/SignatureCreationParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/SignatureCreationParameter.java deleted file mode 100644 index f188daf0d..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/SignatureCreationParameter.java +++ /dev/null @@ -1,103 +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.config.stork; - -import java.util.Properties; - -/** - * Encapsulates signature creation parameters according MOA configuration - * - * @author bzwattendorfer - * - */ -public class SignatureCreationParameter { - - private static final String PROPS_PREFIX = "stork.samlsigningparameter.signaturecreation."; - private static final String PROPS_KEYSTORE_FILE = "keystore.file"; - private static final String PROPS_KEYSTORE_PASS = "keystore.password"; - private static final String PROPS_KEYNAME_NAME = "keyname.name"; - private static final String PROPS_KEYNAME_PASS = "keyname.password"; - - private Properties props; - private String basedirectory; - - SignatureCreationParameter(Properties props, String basedirectory) { - this.props = props; - this.basedirectory = basedirectory; - } - - /** - * Gets the KeyStore Path - * @return File Path to KeyStore - */ - public String getKeyStorePath() { - return basedirectory + props.getProperty(PROPS_PREFIX+PROPS_KEYSTORE_FILE); - } - - /** - * Gets the KeyStore Password - * @return Password to KeyStore - */ - public String getKeyStorePassword() { - return props.getProperty(PROPS_PREFIX+PROPS_KEYSTORE_PASS); - } - - /** - * Gets the Signing Key Name - * @return Siging Key Name - */ - public String getKeyName() { - return props.getProperty(PROPS_PREFIX+PROPS_KEYNAME_NAME); - } - - /** - * Gets the Signing Key Password - * @return Signing Key Password - */ - public String getKeyPassword() { - return props.getProperty(PROPS_PREFIX+PROPS_KEYNAME_PASS); - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/SignatureVerificationParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/SignatureVerificationParameter.java deleted file mode 100644 index 9b3e24c46..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/SignatureVerificationParameter.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.config.stork; - -/** - * Encapsulates Signature Verification data for STORK according MOA configuration - * - * @author bzwattendorfer - * - */ -public class SignatureVerificationParameter { - - /** ID of the MOA-SP TrustProfile to be used for STORK SAML signature verification */ - private String trustProfileID; - - public SignatureVerificationParameter(String trustProfileID2) { - this.trustProfileID = trustProfileID2; - } - - /** - * Gets the MOA-SP TrustProfileID - * @return TrustProfileID of MOA-SP for STORK signature verification - */ - public String getTrustProfileID() { - return trustProfileID; - } - - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/StorkAttribute.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/StorkAttribute.java deleted file mode 100644 index 87ec7fb0c..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/StorkAttribute.java +++ /dev/null @@ -1,27 +0,0 @@ -package at.gv.egovernment.moa.id.config.stork; - -public class StorkAttribute { - - protected Boolean mandatory; - protected String name; - - public StorkAttribute(String name, boolean mandatory) { - this.name = name; - this.mandatory = mandatory; - } - - public Boolean getMandatory() { - return mandatory; - } - public void setMandatory(Boolean mandatory) { - this.mandatory = mandatory; - } - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/StorkAttributeProviderPlugin.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/StorkAttributeProviderPlugin.java deleted file mode 100644 index 619af2358..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/StorkAttributeProviderPlugin.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.config.stork; - -/** - * @author tlenz - * - */ -public class StorkAttributeProviderPlugin { - private String name = null; - private String url = null; - private String attributes = null; - - /** - * - */ - public StorkAttributeProviderPlugin(String name, String url, String attributes) { - this.name = name; - this.url = url; - this.attributes = attributes; - } - - /** - * @return the name - */ - public String getName() { - return name; - } - /** - * @param name the name to set - */ - public void setName(String name) { - this.name = name; - } - /** - * @return the url - */ - public String getUrl() { - return url; - } - /** - * @param url the url to set - */ - public void setUrl(String url) { - this.url = url; - } - /** - * @return the attributes - */ - public String getAttributes() { - return attributes; - } - /** - * @param attributes the attributes to set - */ - public void setAttributes(String attributes) { - this.attributes = attributes; - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java index aa9a0824d..d306ec005 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/AuthenticationData.java @@ -35,7 +35,7 @@ import org.apache.commons.collections4.map.HashedMap; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; +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; 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 f065bbc56..5aceb8eec 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 @@ -35,7 +35,6 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; -import org.apache.velocity.VelocityContext; import org.opensaml.saml2.core.LogoutRequest; import org.opensaml.saml2.core.LogoutResponse; import org.opensaml.saml2.core.StatusCode; @@ -48,19 +47,23 @@ import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; 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.exception.MOAIDException; +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.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.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; @@ -76,7 +79,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEng 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.MOAIDMessageProvider; 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; @@ -101,6 +103,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { @Autowired protected AuthConfiguration authConfig; @Autowired private SingleLogOutBuilder sloBuilder; @Autowired private SAMLVerificationEngineSP samlVerificationEngine; + @Autowired private IGUIFormBuilder guiBuilder; public void performSingleLogOut(HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq) throws MOAIDException { @@ -551,12 +554,17 @@ public class AuthenticationManager extends MOAIDAuthConstants { + "/idpSingleLogout" + "?restart=" + relayState; - VelocityContext context = new VelocityContext(); - context.put("redirectURLs", sloReqList); - context.put("timeoutURL", timeOutURL); - context.put("timeout", SLOTIMEOUT); - ssoManager.printSingleLogOutInfo(context, httpResp, authURL); + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + config.putCustomParameter("redirectURLs", sloReqList); + config.putCustomParameter("timeoutURL", timeOutURL); + config.putCustomParameter("timeout", SLOTIMEOUT); + + guiBuilder.build(httpResp, config, "Single-LogOut GUI"); + } else { if (pvpReq != null) { @@ -567,20 +575,29 @@ public class AuthenticationManager extends MOAIDAuthConstants { } else { //print SLO information directly - VelocityContext context = new VelocityContext(); + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + if (sloContainer.getSloFailedOAs() == null || sloContainer.getSloFailedOAs().size() == 0) - context.put("successMsg", + config.putCustomParameter("successMsg", MOAIDMessageProvider.getInstance().getMessage("slo.00", null)); else - context.put("errorMsg", + config.putCustomParameter("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssoManager.printSingleLogOutInfo(context, httpResp, authURL); + + 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) { @@ -590,10 +607,22 @@ public class AuthenticationManager extends MOAIDAuthConstants { }else { //print SLO information directly - VelocityContext context = new VelocityContext(); - context.put("errorMsg", + DefaultGUIFormBuilderConfiguration config = new DefaultGUIFormBuilderConfiguration( + authURL, + DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, + null); + + config.putCustomParameter("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - ssoManager.printSingleLogOutInfo(context, httpResp, authURL); + + 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); + + } } 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 index 7833e795e..ae2771427 100644 --- 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 @@ -25,7 +25,8 @@ package at.gv.egovernment.moa.id.moduls; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +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; 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 index 79e52f6e1..b9b161bb6 100644 --- 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 @@ -25,6 +25,8 @@ 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 getServlets(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java deleted file mode 100644 index d5d0e6c48..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/IRequest.java +++ /dev/null @@ -1,202 +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.util.Collection; - -import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; - -public interface IRequest { - - /** - * Indicates the module, which implements this authentication protocol. - * The class, which is referenced, had to implement the 'IModulInfo' interface. - * - * @return Full-qualified name of the class which implements this protocol - */ - public String requestedModule(); - - /** - * Indicates the protocol specific action, which should executed if the request is processed. - * The class, which is referenced, had to implement the 'IAction' interface. - * - * @return Full-qualified name of the class which implements the action - */ - public String requestedAction(); - - /** - * Unique identifier, which indicates the service provider. - * In case of SAML1 protocol, it is the OA http-GET parameter - * - * @return Unique identifier for the service provider - */ - public String getOAURL(); - - /** - * Indicates the passive flag in authentication requests. - * If the passive flag is set, the identification and authentication process - * failed if no active SSO session is found. - * - * @return true, if the is passive flag is set in authentication request, otherwise false - */ - public boolean isPassiv(); - - /** - * Indicates the force authentication flag in authentication request - * If this flag is set, a new identification and authentication process - * is carried out in any case. - * - * @return true, if the force authentication flag is set, otherwise false - */ - public boolean forceAuth(); - - - /** - * Returns a generic request-data object with is stored with a specific identifier - * - * @param key The specific identifier of the request-data object - * @return The request-data object or null if no data is found with this key - */ - public Object getGenericData(String key); - - /** - * Returns a generic request-data object with is stored with a specific identifier - * - * @param key The specific identifier of the request-data object - * @param clazz The class type which is stored with this key - * @return The request-data object or null if no data is found with this key - */ - public T getGenericData(String key, final Class clazz); - - /** - * Store a generic data-object to request 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 request-data storage - */ - public void setGenericDataToSession(String key, Object object) throws SessionDataStorageException; - - /** - * Hold the identifier of this request object. - * This identifier can be used to load the request from request storage - * - * @return Request identifier - */ - public String getRequestID(); - - - /** - * Hold the identifier of the MOASession which is associated with this request - * - * @return MOASession identifier if a associated session exists, otherwise null - */ - public String getMOASessionIdentifier(); - - - /** - * Holds a unique transaction identifier, which could be used for looging - * This transaction identifier is unique for a single identification and authentication process - * - * @return Unique transaction identifier. - */ - public String getUniqueTransactionIdentifier(); - - /** - * Holds a unique session identifier, which could be used for logging - * This session identifier is unique for the full Single Sign-On session time - * - * @return Unique session identifier - */ - public String getUniqueSessionIdentifier(); - - - /** - * Hold the identifier if the process instance, which is associated with this request - * - * @return ProcessInstanceID if this request is associated with a authentication process, otherwise null - */ - public String getProcessInstanceId(); - - - /** - * get the IDP URL PreFix, which was used for authentication request - * - * @return IDP URL PreFix . The URL prefix always ends without / - */ - public String getAuthURL(); - public String getAuthURLWithOutSlash(); - - /** - * Indicates if this pending request needs authentication - * - * @return true if this request needs authentication, otherwise false - */ - public boolean isNeedAuthentication(); - - /** - * Indicates, if this pending request needs Single Sign-On (SSO) functionality - * - * @return true if this request needs SSO, otherwise false - */ - public boolean needSingleSignOnFunctionality(); - public void setNeedSingleSignOnFunctionality(boolean needSSO); - - /** - * Indicates, if this pending request is already authenticated - * - * @return true if this request is already authenticated, otherwise false - */ - public boolean isAuthenticated(); - public void setAuthenticated(boolean isAuthenticated); - - /** - * Get get Service-Provider configuration which is associated with this request. - * - * @return Service-Provider configuration - */ - public IOAAuthParameters getOnlineApplicationConfiguration(); - - /** - * Indicates, if this pending-request is aborted by the user - * - * @return true, if it is aborted, otherwise false - */ - public boolean isAbortedByUser(); - - /** - * Set the 'isAboredByUser' flag of this pending-request - * - * @param b true, if the user has abort the authentication process, otherwise false - */ - public void setAbortedByUser(boolean isAborted); - - /** - * This method get a Set of PVP 2.1 attribute, which are request by this pending-request. - * - * @return A set of PVP attribute names or null if no attributes are requested - * or the Service Provider, which sends this request needs no attributes - */ - public Collection getRequestedAttributes(); -} 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 index d26af89a2..987d92e16 100644 --- 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 @@ -22,7 +22,8 @@ */ package at.gv.egovernment.moa.id.moduls; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +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; /** 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 index 6551b88a3..f1db466e9 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; public class NoPassivAuthenticationException extends MOAIDException { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java index aec5ad124..85e4dc99b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestImpl.java @@ -33,12 +33,13 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; import at.gv.egovernment.moa.id.commons.MOAIDConstants; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +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.SessionDataStorageException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java index c49df43fa..1b550881e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java @@ -26,7 +26,8 @@ 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.auth.exception.MOAIDException; +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; 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 db4022cdc..bc7dd272b 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 @@ -22,13 +22,6 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringWriter; -import java.net.URI; import java.util.Date; import java.util.List; @@ -36,27 +29,24 @@ import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; import org.hibernate.Query; import org.hibernate.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionExtensions; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.SessionDataStorageException; +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.SessionDataStorageException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; 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.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.Random; -import at.gv.egovernment.moa.id.util.VelocityProvider; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -312,69 +302,7 @@ public class SSOManager { return false; } - - public void printSingleLogOutInfo(VelocityContext context, HttpServletResponse httpResp, String authURL) throws MOAIDException { - try { - Logger.trace("Initialize VelocityEngine..."); - context.put(CONTEXTPATH, authURL); - - InputStream is = null; - String pathLocation = null; - try { - String rootconfigdir = authConfig.getRootConfigFileDir(); - pathLocation = rootconfigdir + HTMLTEMPLATESDIR + HTMLTEMPLATEFULL; - File file = new File(new URI(pathLocation)); - is = new FileInputStream(file); - evaluateSLOTemplate(context, httpResp, is); - - } catch (Exception e) { - Logger.warn("SLO Template is not found in configuration directory (" + - pathLocation + "). Load template from project library ... "); - - try { - pathLocation = "resources/templates/" + HTMLTEMPLATEFULL; - is = Thread.currentThread() - .getContextClassLoader() - .getResourceAsStream(pathLocation); - evaluateSLOTemplate(context, httpResp, is); - - } catch (Exception e1) { - Logger.error("Single LogOut form can not created.", e); - throw new MOAIDException("Create Single LogOut information FAILED.", null, e); - } - - } finally { - if (is != null) - is.close(); - - } - - } catch (Exception e) { - Logger.error("Single LogOut form can not created.", e); - throw new MOAIDException("Create Single LogOut information FAILED.", null, e); - } - } - - private void evaluateSLOTemplate(VelocityContext context, HttpServletResponse httpResp, InputStream is) throws Exception { - - VelocityEngine engine = VelocityProvider.getClassPathVelocityEngine(); - - BufferedReader reader = new BufferedReader(new InputStreamReader(is )); - - //set default elements to velocity context - //context.put(CONTEXTPATH, authConfig.getPublicURLPrefix()); - - StringWriter writer = new StringWriter(); - //velocityEngine.evaluate(context, writer, "SLO_Template", reader); - engine.evaluate(context, writer, "SLO Template", reader); - - - httpResp.setContentType("text/html;charset=UTF-8"); - httpResp.getOutputStream().write(writer.toString().getBytes("UTF-8")); - - } - private String getValueFromCookie(HttpServletRequest httpReq, String cookieName) { Cookie[] cookies = httpReq.getCookies(); 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 index b68f170c8..44f622fa0 100644 --- 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 @@ -3,7 +3,7 @@ package at.gv.egovernment.moa.id.process; import java.io.InputStream; -import at.gv.egovernment.moa.id.moduls.IRequest; +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; 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 index 437eee63c..f9986dccb 100644 --- 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 @@ -15,9 +15,9 @@ import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +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.moduls.IRequest; 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; 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 index 88048d23e..cff85ad60 100644 --- 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 @@ -1,7 +1,7 @@ package at.gv.egovernment.moa.id.process.api; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.commons.api.IRequest; /** 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 index b60434b2a..dd0d87dd7 100644 --- 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 @@ -9,7 +9,7 @@ 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.moduls.IRequest; +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; 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 index bf00cadaf..4e44f4043 100644 --- 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 @@ -34,14 +34,14 @@ 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.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; 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.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.moduls.SSOManager; import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; 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 index 0ab630dc2..302c60c5e 100644 --- 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 @@ -34,10 +34,10 @@ import org.springframework.web.bind.annotation.RequestMethod; 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.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; +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.utils.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; 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 index 048293fc2..eff839e4e 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java index 0e6dc1838..f1d88f877 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/BirthdateAttributeBuilder.java @@ -25,7 +25,7 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.text.DateFormat; import java.text.SimpleDateFormat; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 2d15edc7b..dab3810e3 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 @@ -24,7 +24,7 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 998377472..623acd18e 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,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 14199d808..cfc6b102c 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,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 index 13addc1fd..9e5d4198c 100644 --- 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 @@ -24,7 +24,7 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 index 3d7260af1..ab41b1229 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 43a0458cb..b1474acda 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 @@ -25,7 +25,7 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 index 2ca56a791..c3300d60f 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 204c0c15d..1172d3cec 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,7 +25,7 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java index 69f0c3088..a6a5f1dd4 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/EIDSourcePIN.java @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 index 58f18ee23..1d836802a 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 76866c336..9dfbe00b2 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,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 index 61771de66..af87a319a 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 4def39d54..1d3faff2d 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,8 +24,8 @@ package at.gv.egovernment.moa.id.protocols.builder.attributes; import java.io.IOException; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 index ace4c0be0..5b44f02aa 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 ca66700a2..53cfbecc1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateFullMandateAttributeBuilder.java @@ -26,7 +26,7 @@ import java.io.IOException; import javax.xml.transform.TransformerException; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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.NoMandateDataAttributeException; 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 67eb92d9b..97043a3a0 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,7 +26,7 @@ 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.config.auth.IOAAuthParameters; +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.NoMandateDataAttributeException; 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 9474cd832..46472c983 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,7 +26,7 @@ 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.config.auth.IOAAuthParameters; +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.NoMandateDataAttributeException; 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 8391c8230..41c35dad3 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,7 +26,7 @@ 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.config.auth.IOAAuthParameters; +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.NoMandateDataAttributeException; 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 df077a631..df8f86f7e 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 @@ -29,7 +29,7 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.Identificati 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.auth.exception.BuildException; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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.NoMandateDataAttributeException; 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 663e927fc..a64880889 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,7 +31,7 @@ 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.config.auth.IOAAuthParameters; +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; 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 dd49b2a1e..085579108 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,7 +29,7 @@ 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.config.auth.IOAAuthParameters; +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.NoMandateDataAttributeException; 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 55c864335..4cd2ca670 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,7 +28,7 @@ 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.config.auth.IOAAuthParameters; +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.NoMandateDataAttributeException; 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 53eca141e..69a731e53 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 @@ -28,7 +28,7 @@ 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.data.AuthenticationSession; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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.AuthenticationData; import at.gv.egovernment.moa.id.data.IAuthData; 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 46562c506..41a821c98 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,7 +27,7 @@ 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.config.auth.IOAAuthParameters; +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; 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 d1da36aa3..b4eed85d0 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,7 +25,7 @@ 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.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepOIDAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateProfRepOIDAttributeBuilder.java index 3cfc40d22..bef9afd8f 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,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateReferenceValueAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateReferenceValueAttributeBuilder.java index a1fa6c2a8..5ad562ffa 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,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 573f0584a..a531e31fc 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,7 +25,7 @@ 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.config.auth.IOAAuthParameters; +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.NoMandateDataAttributeException; 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 index 456634fb1..285a6977f 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 index 33f3a1d05..b2465b5c1 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.builder.attributes; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; 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 142810d45..f992737b6 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 @@ -44,19 +44,19 @@ import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.auth.builder.AuthenticationDataBuilder; import at.gv.egovernment.moa.id.auth.builder.DynamicOAAuthParameterBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.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.MOAIDException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.OASessionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; import at.gv.egovernment.moa.id.data.Trible; import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.SoapBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AuthResponseBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; @@ -217,14 +217,16 @@ public class AttributQueryAction implements IAction { + " for authentication information."); //load configuration of next IDP - OAAuthParameter idp = authConfig.getOnlineApplicationParameter(nextIDPInformation.getIdpurlprefix()); - if (idp == null) { + IOAAuthParameters idpLoaded = authConfig.getOnlineApplicationParameter(nextIDPInformation.getIdpurlprefix()); + if (idpLoaded == null || !(idpLoaded instanceof OAAuthParameter)) { Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() + "is not loadable."); throw new MOAIDException("auth.32", new Object[]{nextIDPInformation.getIdpurlprefix()}); } + OAAuthParameter idp = (OAAuthParameter) idpLoaded; + //check if next IDP config allows inbound messages if (!idp.isInboundSSOInterfederationAllowed()) { Logger.warn("Configuration for federated IDP:" + nextIDPInformation.getIdpurlprefix() diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java index a214dad9d..2d13609d8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java @@ -37,13 +37,13 @@ import org.opensaml.xml.security.SecurityException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.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.moduls.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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java index 15fe1e9d7..2a688da68 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java @@ -30,11 +30,11 @@ import org.springframework.stereotype.Service; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.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.moduls.IRequest; 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; 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 8065af1a6..eec1ccb78 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 @@ -56,15 +56,16 @@ 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.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.auth.frontend.velocity.VelocityLogAdapter; +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.MOAIDException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; @@ -95,7 +96,6 @@ 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.util.VelocityLogAdapter; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -496,7 +496,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { String oaURL = metadata.getEntityID(); oaURL = StringEscapeUtils.escapeHtml(oaURL); - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(oaURL); + IOAAuthParameters oa = authConfig.getOnlineApplicationParameter(oaURL); Logger.info("Dispatch PVP2 SingleLogOut: OAURL=" + oaURL + " Binding=" + msg.getRequestBinding()); @@ -579,7 +579,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12"); - OAAuthParameter oa = authConfig.getOnlineApplicationParameter(moaRequest.getEntityID()); + IOAAuthParameters oa = authConfig.getOnlineApplicationParameter(moaRequest.getEntityID()); 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); @@ -733,7 +733,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { String oaURL = moaRequest.getEntityMetadata().getEntityID(); oaURL = StringEscapeUtils.escapeHtml(oaURL); - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(oaURL); + IOAAuthParameters oa = authConfig.getOnlineApplicationParameter(oaURL); Logger.info("Dispatch PVP2 AuthnRequest: OAURL=" + oaURL + " Binding=" + consumerService.getBinding()); 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 5afa10a72..ae88f3ea4 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 @@ -40,11 +40,12 @@ import org.opensaml.saml2.metadata.SingleLogoutService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; 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.MOAIDException; import at.gv.egovernment.moa.id.auth.servlet.RedirectServlet; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.api.IRequest; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; @@ -54,7 +55,6 @@ 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.IRequest; 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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index 46381fcc2..9977e607b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -50,6 +50,7 @@ import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.credential.Credential; +import at.gv.egovernment.moa.id.auth.frontend.velocity.VelocityProvider; 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; @@ -58,7 +59,6 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; import at.gv.egovernment.moa.id.protocols.pvp2x.validation.MOAPVPSignedRequestPolicyRule; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; -import at.gv.egovernment.moa.id.util.VelocityProvider; 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/protocols/pvp2x/builder/AttributQueryBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AttributQueryBuilder.java index 9c097780b..2df72637d 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,8 +49,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.w3c.dom.Document; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java index aea3c2ee7..78ddab488 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/AuthResponseBuilder.java @@ -51,7 +51,7 @@ 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.config.ConfigurationException; +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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java index c48caed29..b82e6c1f0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAttributeBuilder.java @@ -32,7 +32,7 @@ import java.util.ServiceLoader; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.metadata.RequestedAttribute; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java index d5d84dd51..ba5c19de7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java @@ -44,7 +44,7 @@ import org.opensaml.ws.message.encoder.MessageEncodingException; import org.opensaml.xml.security.SecurityException; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.moduls.IRequest; +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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java index 3418ffb69..62e3b9620 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java @@ -72,7 +72,7 @@ import org.opensaml.xml.signature.Signer; import org.springframework.stereotype.Service; import org.w3c.dom.Document; -import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; 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 63452bee0..c793b5dee 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 @@ -63,10 +63,11 @@ import org.springframework.stereotype.Service; import org.w3c.dom.Document; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +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.dao.session.OASessionStore; -import at.gv.egovernment.moa.id.config.ConfigurationException; +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; @@ -83,7 +84,6 @@ 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.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; /** diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index 3aa05bb2d..3ca6a64e0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -61,9 +61,9 @@ import at.gv.e_government.reference.namespace.persondata._20020228_.Identificati 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.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +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.SLOInformationImpl; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; 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 9a51e75e4..91f43b10b 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,7 +32,7 @@ import org.opensaml.saml2.metadata.Organization; import org.opensaml.saml2.metadata.RequestedAttribute; import org.opensaml.xml.security.credential.Credential; -import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.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; 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 58210a72c..480656e30 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 @@ -44,10 +44,10 @@ import org.opensaml.saml2.metadata.OrganizationURL; import org.opensaml.saml2.metadata.SurName; import org.opensaml.saml2.metadata.TelephoneNumber; +import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; -import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; 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 index fcd8472b1..1e029f567 100644 --- 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 @@ -22,7 +22,7 @@ */ package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; -import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; /** * @author tlenz 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 index 7ed438471..f65c4d265 100644 --- 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 @@ -22,7 +22,7 @@ */ package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; -import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.commons.api.IRequest; /** * @author tlenz 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 index 709c1e34b..00fb97151 100644 --- 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 @@ -24,7 +24,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; import org.opensaml.saml2.core.StatusCode; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; public abstract class PVP2Exception extends MOAIDException { 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 618346485..3002ca179 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 @@ -45,12 +45,12 @@ import org.opensaml.saml2.metadata.provider.MetadataProviderException; import org.opensaml.saml2.metadata.provider.ObservableMetadataProvider; import org.opensaml.xml.XMLObject; +import at.gv.egovernment.moa.id.commons.api.IOAAuthParameters; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; -import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing; import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.InterfederatedIDPPublicServiceFilter; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.PVPMetadataFilterChain; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.SchemaValidationFilter; @@ -121,7 +121,7 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider @Override public boolean refreshMetadataProvider(String entityID) { try { - OAAuthParameter oaParam = + IOAAuthParameters oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(entityID); if (oaParam != null) { String metadataURL = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); @@ -230,7 +230,7 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider while (oaInterator.hasNext()) { Entry oaKeyPair = oaInterator.next(); - OAAuthParameter oaParam = + IOAAuthParameters oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(oaKeyPair.getValue()); if (oaParam != null) { String metadataurl = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); @@ -361,7 +361,7 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider while (oaInterator.hasNext()) { Entry oaKeyPair = oaInterator.next(); - OAAuthParameter oaParam = + IOAAuthParameters oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(oaKeyPair.getValue()); if (oaParam != null) { String metadataurl = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); @@ -425,7 +425,7 @@ public class MOAMetadataProvider extends SimpleMOAMetadataProvider internalProvider = chainProvider; } - private PVPMetadataFilterChain buildMetadataFilterChain(OAAuthParameter oaParam, String metadataURL, byte[] certificate) throws CertificateException { + private PVPMetadataFilterChain buildMetadataFilterChain(IOAAuthParameters oaParam, String metadataURL, byte[] certificate) throws CertificateException { PVPMetadataFilterChain filterChain = new PVPMetadataFilterChain(metadataURL, certificate); filterChain.getFilters().add(new SchemaValidationFilter()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java index 6d646c609..442455d4b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/metadata/SimpleMOAMetadataProvider.java @@ -32,9 +32,9 @@ import org.opensaml.saml2.metadata.provider.MetadataFilter; import org.opensaml.saml2.metadata.provider.MetadataProvider; import org.opensaml.xml.parse.BasicParserPool; +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.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SchemaValidationException; 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 index a47c34c0b..1e1c37621 100644 --- 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 @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.signer; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; public class CredentialsNotAvailableException extends MOAIDException { 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 abc4eb4a9..381289824 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 @@ -27,7 +27,7 @@ import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.commons.api.AuthConfiguration; import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; 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 75ef7e5a1..0426c2a6a 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,9 +35,9 @@ import org.opensaml.xml.XMLObject; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; +import at.gv.egovernment.moa.id.commons.api.exceptions.ConfigurationException; 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.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.logging.Logger; 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 0b2bbafeb..a9f9b206e 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,7 @@ import java.util.List; import org.opensaml.saml2.core.RequestAbstractType; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; public class ChainSAMLValidator implements ISAMLValidator { 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 index f9dab1cb5..4f697d986 100644 --- 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 @@ -24,7 +24,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.validation; import org.opensaml.saml2.core.RequestAbstractType; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +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/SAMLSignatureValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/SAMLSignatureValidator.java index d65b847dc..952a6024a 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,7 +27,7 @@ import org.opensaml.saml2.core.RequestAbstractType; import org.opensaml.security.SAMLSignatureProfileValidator; import org.opensaml.xml.validation.ValidationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SAMLRequestNotSignedException; public class SAMLSignatureValidator implements ISAMLValidator { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/ChainSAMLVerifier.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/ChainSAMLVerifier.java index 749f613f8..d0596d50b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/ChainSAMLVerifier.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/ChainSAMLVerifier.java @@ -28,7 +28,7 @@ import java.util.List; import org.opensaml.saml2.core.RequestAbstractType; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; public class ChainSAMLVerifier implements ISAMLVerifier { 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 4650327b4..2ded32bac 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 @@ -34,11 +34,11 @@ 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.auth.exception.MOAIDException; +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.commons.config.MOAIDConfigurationConstants; -import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; 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; @@ -53,7 +53,7 @@ public class EntityVerifier { // List oaList = ConfigurationDBRead // .getAllActiveOnlineApplications(); try { - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(entityID); + IOAAuthParameters oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(entityID); String certBase64 = oa.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); if (MiscUtil.isNotEmpty(certBase64)) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/ISAMLVerifier.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/ISAMLVerifier.java index 8bbf8ee1a..e032edc9b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/ISAMLVerifier.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/ISAMLVerifier.java @@ -24,7 +24,7 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.verification; import org.opensaml.saml2.core.RequestAbstractType; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; public interface ISAMLVerifier { public void verifyRequest(RequestAbstractType request) throws MOAIDException; 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 1e13da179..d9bc7daaf 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,9 +47,9 @@ import org.opensaml.xml.validation.ValidationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +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/metadata/MOASPMetadataSignatureFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/MOASPMetadataSignatureFilter.java index f67c475bb..a4ab92f58 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 @@ -39,7 +39,7 @@ import org.opensaml.xml.XMLObject; import at.gv.egovernment.moa.id.auth.builder.SignatureVerificationUtils; import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.logging.Logger; /** 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 149874ce0..679bdd10f 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 @@ -36,8 +36,7 @@ import org.opensaml.saml2.metadata.provider.MetadataFilter; import org.opensaml.xml.XMLObject; import org.opensaml.xml.security.x509.BasicX509Credential; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; - +import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoCredentialsException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SignatureValidationException; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.EntityVerifier; 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 index 69fe0ee6a..83a2b61d2 100644 --- 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 @@ -31,7 +31,7 @@ import org.opensaml.saml2.metadata.provider.MetadataFilter; import org.opensaml.xml.XMLObject; import org.xml.sax.SAXException; -import at.gv.egovernment.moa.id.config.ConfigurationException; +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; 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 10594d6fc..43b4ecf17 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 @@ -41,6 +41,9 @@ 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.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.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AuthenticatedSessionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.InterfederationSessionStore; @@ -48,11 +51,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.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.EncryptedData; import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.util.Random; @@ -804,7 +804,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt idp.setIdpurlprefix(idpEntityID); idp.setAuthURL(req.getAuthURL()); - OAAuthParameter oa = authConfig.getOnlineApplicationParameter(idp.getIdpurlprefix()); + IOAAuthParameters oa = authConfig.getOnlineApplicationParameter(idp.getIdpurlprefix()); idp.setStoreSSOInformation(oa.isInterfederationSSOStorageAllowed()); idp.setMoasession(dbsession); idpList.add(idp); 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 666511425..b5d816eaf 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 @@ -29,12 +29,12 @@ 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.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.ex.MOADatabaseException; import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; 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 index 8bd682421..655675f00 100644 --- 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 @@ -26,7 +26,7 @@ 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.auth.exception.MOAIDException; +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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/FormBuildUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/FormBuildUtils.java deleted file mode 100644 index 9a1237b80..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/FormBuildUtils.java +++ /dev/null @@ -1,136 +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.HashMap; -import java.util.Map; -import java.util.Set; - -import at.gv.egovernment.moa.util.MiscUtil; - -public class FormBuildUtils { - - private static Map defaultmap = null; - - public static String MAIN_BACKGROUNDCOLOR = "#MAIN_BACKGOUNDCOLOR#"; - public static String MAIN_COLOR = "#MAIN_COLOR#"; - public static String HEADER_BACKGROUNDCOLOR = "#HEADER_BACKGROUNDCOLOR#"; - public static String HEADER_COLOR = "#HEADER_COLOR#"; - public static String BUTTON_BACKGROUNDCOLOR = "#BUTTON_BACKGROUNDCOLOR#"; - public static String BUTTON_BACKGROUNDCOLOR_FOCUS = "#BUTTON_BACKGROUNDCOLOR_FOCUS#"; - public static String BUTTON_COLOR = "#BUTTON_COLOR#"; - public static String FONTFAMILY = "#FONTTYPE#"; - public static String HEADER_TEXT = "#HEADER_TEXT#"; - public static String REDIRECTTARGET = "#REDIRECTTARGET#"; - public static String APPLET_HEIGHT = "#APPLETHEIGHT#"; - public static String APPLET_WIDTH = "#APPLETWIDTH#"; - - private static String MANDATEVISIBLE = "#MANDATEVISIBLE#"; - private static String MANDATECHECKED = "#MANDATECHECKED#"; - - private static String STORKVISIBLE = "#STORKVISIBLE#"; - - private static final String TEMPLATEVISIBLE = " display: none"; - private static final String TEMPLATEDISABLED = "disabled=\"true\""; - private static final String TEMPLATECHECKED = "checked=\"true\""; - private static final String TEMPLATE_ARIACHECKED = "aria-checked="; - - - static { - if (defaultmap == null) { - defaultmap = new HashMap(); - defaultmap.put(MAIN_BACKGROUNDCOLOR, "#F7F8F7"); - defaultmap.put(MAIN_COLOR, "#000000"); - - defaultmap.put(HEADER_BACKGROUNDCOLOR, "#C3D2E2"); - defaultmap.put(HEADER_COLOR, "#000000"); - defaultmap.put(HEADER_TEXT, "Login"); - - defaultmap.put(BUTTON_BACKGROUNDCOLOR, "#EBEBEB"); - defaultmap.put(BUTTON_BACKGROUNDCOLOR_FOCUS, "#EBEBEB"); - defaultmap.put(BUTTON_COLOR, "#000000"); - - defaultmap.put(FONTFAMILY, "Verdana,Geneva,Arial,sans-serif"); - - defaultmap.put(REDIRECTTARGET, "_top"); - } - } - - - public static String customiceLayoutBKUSelection(String value, boolean isShowMandateCheckbox, - boolean isOnlyMandateAllowed, - Map map, boolean showStorkLogin) { - - if (isShowMandateCheckbox) - value = value.replace(MANDATEVISIBLE, ""); - else - value = value.replace(MANDATEVISIBLE, TEMPLATEVISIBLE); - - if (isOnlyMandateAllowed) { - value = value.replace(MANDATECHECKED, TEMPLATECHECKED + " " + - TEMPLATEDISABLED + " " + - TEMPLATE_ARIACHECKED + "\"true\""); - - } else - value = value.replace(MANDATECHECKED, TEMPLATE_ARIACHECKED + "\"false\""); - - if (showStorkLogin) - value = value.replace(STORKVISIBLE, ""); - else - value = value.replace(STORKVISIBLE, TEMPLATEVISIBLE); - - String fonttype = map.get(FONTFAMILY); - if (MiscUtil.isNotEmpty(fonttype)) { - String[] fonttypeList = fonttype.split(","); - String fonttypeformated = "\"" + fonttypeList[0].trim().replace("\"", "") + "\""; - - for (int i=1; i elements = map.keySet(); - for (String element: elements) { - value = value.replace(element, map.get(element)); - } - - return value; - } - - public static Map getDefaultMap() { - return defaultmap; - } - - /** - * @param value - * @return - */ - public static String defaultLayoutBKUSelection(String value) { - return customiceLayoutBKUSelection(value, false, false, getDefaultMap(), false); - - } - - -} 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 0b517e783..81041260c 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,8 +35,8 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.ConfigurationException; +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; 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/util/MOAIDMessageProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/MOAIDMessageProvider.java deleted file mode 100644 index b7a866370..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/MOAIDMessageProvider.java +++ /dev/null @@ -1,104 +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.util.Locale; - -import at.gv.egovernment.moa.util.Messages; - -/** - * A singleton wrapper around a Message object, providing the messages used in MOA-ID. - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class MOAIDMessageProvider { - - /** DEFAULT_MESSAGE_RESOURCES are resources/properties/id_messages */ - private static final String[] DEFAULT_MESSAGE_RESOURCES = - { "resources/properties/id_messages" }; - /** DEFAULT_MESSAGE_LOCALES are "de", "AT" */ - private static final Locale[] DEFAULT_MESSAGE_LOCALES = - new Locale[] { new Locale("de", "AT") }; - /** The instance for our singleton */ - private static MOAIDMessageProvider instance; - /** The Messages */ - private Messages messages; - - /** - * Returns the single instance of MOAIDMessageProvider. - * - * @return the single instance of MOAIDMessageProvider - */ - public static MOAIDMessageProvider getInstance() { - if (instance == null) - instance = new MOAIDMessageProvider(DEFAULT_MESSAGE_RESOURCES, DEFAULT_MESSAGE_LOCALES); - return instance; - } - - /** - * Create a MOAIDMessageProvider. - * - * @param resourceNames The names of the resources containing the messages. - * @param locales The corresponding locales. - */ - protected MOAIDMessageProvider(String[] resourceNames, Locale[] locales) { - this.messages = new Messages(resourceNames, locales); - } - - /** - * Get the message corresponding to a given message ID. - * - * @param messageId The ID of the message. - * @param parameters The parameters to fill in into the message arguments. - * @return The formatted message. - */ - public String getMessage(String messageId, Object[] parameters) { - return messages.getMessage(messageId, parameters); - } - -} 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 47010a735..f97d646b6 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,10 +62,10 @@ import javax.xml.parsers.ParserConfigurationException; import org.xml.sax.InputSource; import org.xml.sax.SAXException; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +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.MiscUtil; 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 af3424881..f0cec1d61 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 @@ -65,11 +65,11 @@ import javax.net.ssl.SSLSocketFactory; import org.apache.regexp.RE; import org.apache.regexp.RESyntaxException; +import at.gv.egovernment.moa.id.commons.api.ConfigurationProvider; +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.commons.utils.ssl.SSLConfigurationException; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.ConfigurationProvider; import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.ConnectionParameterInterface; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/VelocityLogAdapter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/VelocityLogAdapter.java deleted file mode 100644 index 269e21d4f..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/VelocityLogAdapter.java +++ /dev/null @@ -1,99 +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 org.apache.velocity.app.Velocity; -import org.apache.velocity.runtime.RuntimeServices; -import org.apache.velocity.runtime.log.LogChute; - -import at.gv.egovernment.moa.logging.Logger; - -public class VelocityLogAdapter implements LogChute { - - public VelocityLogAdapter() { - try - { - /* - * register this class as a logger with the Velocity singleton - * (NOTE: this would not work for the non-singleton method.) - */ - Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, this ); - Velocity.init(); - } - catch (Exception e) - { - Logger.error("Failed to register Velocity logger"); - } - } - - public void init(RuntimeServices arg0) throws Exception { - } - - public boolean isLevelEnabled(int arg0) { - switch(arg0) { - case LogChute.DEBUG_ID: - return Logger.isDebugEnabled(); - case LogChute.TRACE_ID: - return Logger.isTraceEnabled(); - default: - return true; - } - } - - public void log(int arg0, String arg1) { - switch(arg0) { - case LogChute.DEBUG_ID: - Logger.debug(arg1); - break; - case LogChute.TRACE_ID: - Logger.trace(arg1); - break; - case LogChute.INFO_ID: - Logger.info(arg1); - break; - case LogChute.WARN_ID: - Logger.warn(arg1); - break; - case LogChute.ERROR_ID: - default: - Logger.error(arg1); - break; - } - } - - public void log(int arg0, String arg1, Throwable arg2) { - switch(arg0) { - case LogChute.DEBUG_ID: - case LogChute.TRACE_ID: - case LogChute.INFO_ID: - case LogChute.WARN_ID: - Logger.warn(arg1, arg2); - break; - case LogChute.ERROR_ID: - default: - Logger.error(arg1, arg2); - break; - } - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/VelocityProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/VelocityProvider.java deleted file mode 100644 index 231f36fa8..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/VelocityProvider.java +++ /dev/null @@ -1,112 +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 2011 by Graz University of Technology, Austria - * The Austrian STORK Modules have been developed by the E-Government - * Innovation Center EGIZ, a joint initiative of the Federal Chancellery - * Austria 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 org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.runtime.RuntimeConstants; - -/** - * Gets a Velocity Engine - * - * @author bzwattendorfer - * - */ -public class VelocityProvider { - - /** - * Gets velocityEngine from Classpath - * @return VelocityEngine - * @throws Exception - */ - public static VelocityEngine getClassPathVelocityEngine() throws Exception { - VelocityEngine velocityEngine = getBaseVelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); - velocityEngine.setProperty("classpath.resource.loader.class", - "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - - velocityEngine.init(); - - return velocityEngine; - } - - /** - * Gets VelocityEngine from File - * @param rootPath File Path to template file - * @return VelocityEngine - * @throws Exception - */ - public static VelocityEngine getFileVelocityEngine(String rootPath) throws Exception { - VelocityEngine velocityEngine = getBaseVelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "file"); - velocityEngine.setProperty("file.resource.loader.class", - "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); - velocityEngine.setProperty("file.resource.loader.path", rootPath); - - velocityEngine.init(); - - return velocityEngine; - } - - /** - * Gets a basic VelocityEngine - * @return VelocityEngine - */ - private static VelocityEngine getBaseVelocityEngine() { - VelocityEngine velocityEngine = new VelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8"); - velocityEngine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); - velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, - "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); - - return velocityEngine; - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/legacy/LegacyHelper.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/legacy/LegacyHelper.java index dd4e67bcd..48e1460f9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/legacy/LegacyHelper.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/legacy/LegacyHelper.java @@ -26,8 +26,8 @@ import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringEscapeUtils; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; +import at.gv.egovernment.moa.id.commons.MOAIDAuthConstants; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; public class LegacyHelper extends MOAIDAuthConstants{ -- cgit v1.2.3 From b01fc5becad147315bbd8d168f5435ee126e638d Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 14 Mar 2016 11:40:13 +0100 Subject: add independent mandate-service selection step to choose between MIS and ELGA mandate-service --- .../StartAuthentificationParameterParser.java | 22 +-- .../id/auth/servlet/GUILayoutBuilderServlet.java | 150 +++++++++++++++++++++ 2 files changed, 161 insertions(+), 11 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java index f91dc6d3e..69c155c1e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/parser/StartAuthentificationParameterParser.java @@ -78,20 +78,20 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ //check UseMandate flag - String useMISMandateString = null; - boolean useMISMandateBoolean = false; + String useMandateString = null; + boolean useMandateBoolean = false; if ((useMandate != null) && (useMandate.compareTo("") != 0)) { - useMISMandateString = useMandate; + useMandateString = useMandate; } else { - useMISMandateString = "false"; + useMandateString = "false"; } - if (useMISMandateString.compareToIgnoreCase("true") == 0) - useMISMandateBoolean = true; + if (useMandateString.compareToIgnoreCase("true") == 0) + useMandateBoolean = true; else - useMISMandateBoolean = false; + useMandateBoolean = false; - moasession.setUseMandate(useMISMandateString); + moasession.setUseMandate(useMandateString); //load OnlineApplication configuration @@ -155,7 +155,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ } else { Logger.debug("Service-Provider is of type 'PrivateService' with DomainIdentifier:" + oaParam.getIdentityLinkDomainIdentifier()); - if (useMISMandateBoolean) { + if (useMandateBoolean) { Logger.error("Online-Mandate Mode for business application not supported."); throw new AuthenticationException("auth.17", null); } @@ -213,8 +213,8 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ protocolReq.setNeedSingleSignOnFunctionality(false); } - if (protocolReq.needSingleSignOnFunctionality() && useMISMandateBoolean) { - Logger.info("Usage of MIS-MandateService does not allow Single Sign-On. --> SSO is disabled for this request."); + if (protocolReq.needSingleSignOnFunctionality() && useMandateBoolean) { + Logger.info("Usage of Mandate-Service does not allow Single Sign-On. --> SSO is disabled for this request."); protocolReq.setNeedSingleSignOnFunctionality(false); } 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 new file mode 100644 index 000000000..09b344f9d --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java @@ -0,0 +1,150 @@ +/* + * 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 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.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; +import at.gv.egovernment.moa.id.auth.frontend.builder.ServiceProviderSpecificGUIFormBuilderConfiguration; +import at.gv.egovernment.moa.id.auth.servlet.AbstractController; +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.moduls.IRequestStorage; +import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +@Controller +public class GUILayoutBuilderServlet extends AbstractController { + + public static final String ENDPOINT_CSS = "/css/buildCSS"; + public static final String ENDPOINT_JS = "/js/buildJS"; + + @Autowired AuthConfiguration authConfig; + @Autowired IRequestStorage requestStoreage; + @Autowired IGUIFormBuilder formBuilder; + + public GUILayoutBuilderServlet() { + super(); + Logger.debug("Registering servlet " + getClass().getName() + + " with mappings '" + ENDPOINT_CSS + + "' and '" + ENDPOINT_JS + "'."); + + } + + @RequestMapping(value = "/css/buildCSS", method = {RequestMethod.GET}) + public void buildCSS(HttpServletRequest req, HttpServletResponse resp) throws IOException { + try { + IRequest pendingReq = extractPendingRequest(req); + + //initialize GUI builder configuration + ServiceProviderSpecificGUIFormBuilderConfiguration config = null; + if (pendingReq != null) + config = new ServiceProviderSpecificGUIFormBuilderConfiguration( + pendingReq, + ServiceProviderSpecificGUIFormBuilderConfiguration.VIEW_TEMPLATE_CSS, + null); + + else + config = new ServiceProviderSpecificGUIFormBuilderConfiguration( + HTTPUtils.extractAuthURLFromRequest(req), + ServiceProviderSpecificGUIFormBuilderConfiguration.VIEW_TEMPLATE_CSS, + null); + + //build GUI component + formBuilder.build(resp, config, "text/css;charset=UTF-8", "CSS-Form"); + + } catch (Exception e) { + Logger.warn("GUI ressource:'CSS' generation FAILED."); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Created resource failed"); + } + + } + + @RequestMapping(value = "/js/buildJS", method = {RequestMethod.GET}) + public void buildJavaScript(HttpServletRequest req, HttpServletResponse resp) throws IOException { + try { + IRequest pendingReq = extractPendingRequest(req); + + //initialize GUI builder configuration + ServiceProviderSpecificGUIFormBuilderConfiguration config = null; + if (pendingReq != null) + config = new ServiceProviderSpecificGUIFormBuilderConfiguration( + pendingReq, + ServiceProviderSpecificGUIFormBuilderConfiguration.VIEW_TEMPLATE_JS, + null); + + else + config = new ServiceProviderSpecificGUIFormBuilderConfiguration( + HTTPUtils.extractAuthURLFromRequest(req), + ServiceProviderSpecificGUIFormBuilderConfiguration.VIEW_TEMPLATE_JS, + null); + + //build GUI component + formBuilder.build(resp, config, "text/javascript;charset=UTF-8", "JavaScript"); + + } catch (Exception e) { + Logger.warn("GUI ressource:'JavaScript' generation FAILED."); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Created resource failed"); + } + + } + + private IRequest extractPendingRequest(HttpServletRequest req) { + try { + String pendingReqID = StringEscapeUtils.escapeHtml( + req.getParameter(MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID)); + + if (MiscUtil.isNotEmpty(pendingReqID)) { + IRequest pendingReq = requestStorage.getPendingRequest(pendingReqID); + if (pendingReq != null) { + Logger.trace("GUI-Layout builder: Pending-request:" + + pendingReqID + " found -> Build specific template"); + return pendingReq; + + } + } + + Logger.trace("GUI-Layout builder: No pending-request found -> Use default templates"); + + } catch (Exception e) { + Logger.warn("GUI-Layout builder-servlet has an error during request-preprocessing.", e); + } + + return null; + } +} -- cgit v1.2.3 From 0000acfdc7ca31b9ba2d2956c0ce36c4146c3033 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 14 Mar 2016 12:02:19 +0100 Subject: fix typo --- .../java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 f39421a21..d9386d404 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 @@ -110,7 +110,7 @@ public class RedirectServlet { null); config.putCustomParameter(URL, url); config.putCustomParameter(TARGET, redirectTarget); - guiBuilder.build(resp, config, "RedirectForm"); + guiBuilder.build(resp, config, "RedirectForm.html"); } else if (MiscUtil.isNotEmpty(interIDP)) { //store IDP identifier and redirect to generate AuthRequst service -- cgit v1.2.3 From 8f5e8a21a7087061d16aae2e592b7d196d8a08e3 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 15 Mar 2016 09:03:37 +0100 Subject: fix typos in GUIBuilder --- .../gv/egovernment/moa/id/auth/servlet/GUILayoutBuilderServlet.java | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 09b344f9d..babc87866 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 @@ -35,7 +35,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import at.gv.egovernment.moa.id.auth.frontend.builder.IGUIFormBuilder; import at.gv.egovernment.moa.id.auth.frontend.builder.ServiceProviderSpecificGUIFormBuilderConfiguration; -import at.gv.egovernment.moa.id.auth.servlet.AbstractController; 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; @@ -106,13 +105,13 @@ public class GUILayoutBuilderServlet extends AbstractController { config = new ServiceProviderSpecificGUIFormBuilderConfiguration( pendingReq, ServiceProviderSpecificGUIFormBuilderConfiguration.VIEW_TEMPLATE_JS, - null); + GeneralProcessEngineSignalController.ENDPOINT_BKUSELECTION_EVALUATION); else config = new ServiceProviderSpecificGUIFormBuilderConfiguration( HTTPUtils.extractAuthURLFromRequest(req), ServiceProviderSpecificGUIFormBuilderConfiguration.VIEW_TEMPLATE_JS, - null); + GeneralProcessEngineSignalController.ENDPOINT_BKUSELECTION_EVALUATION); //build GUI component formBuilder.build(resp, config, "text/javascript;charset=UTF-8", "JavaScript"); -- cgit v1.2.3 From 428cfea80ba50ce3835d70c0329add9354a70e2e Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 15 Mar 2016 09:04:05 +0100 Subject: add log message into PVP AssertionBuilder --- .../id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index 3ca6a64e0..68301d000 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -282,7 +282,8 @@ public class PVP2AssertionBuilder implements PVPConstants { String bpk = null; Element mandate = authData.getMandate(); - if(mandate != null) { + if(mandate != null) { + Logger.debug("Read mandator bPK|baseID from full-mandate ... "); Mandate mandateObject = MandateBuilder.buildMandate(mandate); if(mandateObject == null) { throw new NoMandateDataAvailableException(); @@ -307,7 +308,7 @@ public class PVP2AssertionBuilder implements PVPConstants { bpk = id.getValue().getValue(); } else { - Logger.debug("Read mandatpr bPK|baseID from PVP attributes ... "); + 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); -- cgit v1.2.3 From e03689468de9aaa0bd2b3234b8e6842988a29684 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 15 Mar 2016 10:43:39 +0100 Subject: change PVP EntityID to metadata-URL (SAML2 'well-known-location' method) --- .../moa/id/protocols/pvp2x/AttributQueryAction.java | 8 ++++---- .../moa/id/protocols/pvp2x/AuthenticationAction.java | 12 ++++++++---- .../protocols/pvp2x/config/IDPPVPMetadataConfiguration.java | 9 ++++++++- 3 files changed, 20 insertions(+), 9 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 f992737b6..2168316ab 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 @@ -61,6 +61,7 @@ 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.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; @@ -128,10 +129,9 @@ public class AttributQueryAction implements IAction { + " validTo:" + responseInfo.getSecond().toString()); //build PVP 2.1 assertion - - String issuerEntityID = pendingReq.getAuthURL(); - if (issuerEntityID.endsWith("/")) - issuerEntityID = issuerEntityID.substring(0, issuerEntityID.length()-1); + + String issuerEntityID = PVPConfiguration.getInstance().getIDPSSOMetadataService( + pendingReq.getAuthURL()); Assertion assertion = PVP2AssertionBuilder.buildAssertion(issuerEntityID, attrQuery, responseInfo.getFirst(), date, new DateTime(responseInfo.getSecond().getTime()), diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java index 2d13609d8..8de44a2e8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java @@ -49,6 +49,7 @@ 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; @@ -81,10 +82,13 @@ public class AuthenticationAction implements IAction { SLOInformationImpl sloInformation = new SLOInformationImpl(); //change to entity value from entity name to IDP EntityID (URL) - String issuerEntityID = pvpRequest.getAuthURL(); - if (issuerEntityID.endsWith("/")) - issuerEntityID = issuerEntityID.substring(0, issuerEntityID.length()-1); - +// 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); 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 91f43b10b..5bb1131a6 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 @@ -97,7 +97,14 @@ public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfigura */ @Override public String getEntityID() { - return authURL; + try { + return PVPConfiguration.getInstance().getIDPSSOMetadataService(authURL); + + } catch (ConfigurationException e) { + Logger.error("Can not load Metadata entry: EntityID", e); + return null; + + } } /* (non-Javadoc) -- cgit v1.2.3 From 58c2bcfcdc9bccb417dae80b0bfefc3713e2cd7c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 10:03:12 +0100 Subject: fix wrong PVP redirect service-endpoint --- .../at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java | 2 +- .../egovernment/moa/id/protocols/pvp2x/binding/MOAURICompare.java | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 eec1ccb78..3eaa332c7 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 @@ -243,7 +243,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { //get POST-Binding decoder implementation InboundMessage msg = (InboundMessage) new RedirectBinding().decode( req, resp, MOAMetadataProvider.getInstance(), false, - new MOAURICompare(PVPConfiguration.getInstance().getIDPSSOPostService(pendingReq.getAuthURL()))); + new MOAURICompare(PVPConfiguration.getInstance().getIDPSSORedirectService(pendingReq.getAuthURL()))); pendingReq.setRequest(msg); //preProcess Message 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 index 6080f8a33..7bb64a106 100644 --- 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 @@ -24,6 +24,8 @@ 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 { /** @@ -40,8 +42,12 @@ public class MOAURICompare implements URIComparator { if (this.serviceURL.equals(uri1)) return true; - else + else { + Logger.warn("PVP request destination-endpoint: " + uri1 + + " does not match to IDP endpoint:" + serviceURL); return false; + + } } } -- cgit v1.2.3 From 9530f4dc07e8328a2f54d921d248e797dac54b6a Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 10:06:28 +0100 Subject: remove unused constans --- .../java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java | 5 ----- 1 file changed, 5 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 3eaa332c7..2cb62b993 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 @@ -114,12 +114,7 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { public static final String METADATA = "Metadata"; public static final String ATTRIBUTEQUERY = "AttributeQuery"; public static final String SINGLELOGOUT = "SingleLogOut"; - - public static final String ENDPOINT_IDP = "idp"; - public static final String ENDPOINT_SP = "sp"; - public static final String PARAMETER_ENDPOINT = "endpointtype"; - public static final List DEFAULTREQUESTEDATTRFORINTERFEDERATION = Arrays.asList( new String[] { PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME -- cgit v1.2.3 From 5ce6653606098ae346257cb477f67b9e204ab04f Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 10:16:45 +0100 Subject: fix typo --- .../gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 7278c9c6c..279038967 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -183,7 +183,7 @@ public class RedirectBinding implements IDecoder, IEncoder { } if (metadataProvider instanceof IMOARefreshableMetadataProvider) { - Logger.debug("PVP2X message validation FAILED. Relead metadata for entityID: " + messageContext.getPeerEntityId()); + Logger.debug("PVP2X message validation FAILED. Reload metadata for entityID: " + messageContext.getInboundMessageIssuer()); if (!((IMOARefreshableMetadataProvider) metadataProvider).refreshMetadataProvider(messageContext.getInboundMessageIssuer())) throw e; -- cgit v1.2.3 From f6d265549193e3db5ce574d33425d06e738a025c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 10:55:51 +0100 Subject: fix problem with entityID in single logout functionality --- .../moa/id/protocols/pvp2x/builder/SingleLogOutBuilder.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 c793b5dee..e5c897aa6 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 @@ -77,6 +77,7 @@ 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; @@ -232,7 +233,7 @@ public class SingleLogOutBuilder { DateTime now = new DateTime(); Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - issuer.setValue(sloInfo.getAuthURL()); + issuer.setValue(PVPConfiguration.getInstance().getIDPSSOMetadataService(sloInfo.getAuthURL())); issuer.setFormat(NameID.ENTITY); sloReq.setIssuer(issuer); sloReq.setIssueInstant(now); @@ -321,7 +322,8 @@ public class SingleLogOutBuilder { private LogoutResponse buildBasicResponse(SingleLogoutService sloService, PVPTargetConfiguration spRequest) throws ConfigurationException, MOAIDException { LogoutResponse sloResp = SAML2Utils.createSAMLObject(LogoutResponse.class); Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - issuer.setValue(spRequest.getAuthURLWithOutSlash()); + issuer.setValue(PVPConfiguration.getInstance().getIDPSSOMetadataService( + spRequest.getAuthURLWithOutSlash())); issuer.setFormat(NameID.ENTITY); sloResp.setIssuer(issuer); sloResp.setIssueInstant(new DateTime()); -- cgit v1.2.3 From 20afefb3ffcfd9381c286653f310fbc3b989c512 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 10:56:30 +0100 Subject: fix some problems with logging and error codes --- .../moa/id/protocols/pvp2x/PVP2XProtocol.java | 17 +++++++++++++---- .../pvp2x/signer/AbstractCredentialProvider.java | 19 ++++++++++--------- .../signer/CredentialsNotAvailableException.java | 5 +++++ 3 files changed, 28 insertions(+), 13 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 2cb62b993..bca080ba6 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 @@ -203,12 +203,15 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { String samlRequest = req.getParameter("SAMLRequest"); Logger.warn("Receive INVALID protocol request: " + samlRequest, e); throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + + } catch (MOAIDException e) { + throw e; } catch (Throwable e) { String samlRequest = req.getParameter("SAMLRequest"); Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - throw new MOAIDException(e.getMessage(), new Object[] {}); + throw new MOAIDException("pvp2.24", new Object[] {e.getMessage()}); } } @@ -254,11 +257,14 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { Logger.warn("Receive INVALID protocol request: " + samlRequest, e); throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); + } catch (MOAIDException e) { + throw e; + } catch (Throwable e) { String samlRequest = req.getParameter("SAMLRequest"); Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - throw new MOAIDException(e.getMessage(), new Object[] {}); + throw new MOAIDException("pvp2.24", new Object[] {e.getMessage()}); } } @@ -304,12 +310,15 @@ public class PVP2XProtocol extends AbstractAuthProtocolModulController { String samlRequest = req.getParameter("SAMLRequest"); Logger.warn("Receive INVALID protocol request: " + samlRequest, e); throw new InvalidProtocolRequestException("pvp2.22", new Object[] {e.getMessage()}); - + + } catch (MOAIDException e) { + throw e; + } catch (Throwable e) { String samlRequest = req.getParameter("SAMLRequest"); Logger.warn("Receive INVALID protocol request: " + samlRequest, e); - throw new MOAIDException(e.getMessage(), new Object[] {}); + throw new MOAIDException("pvp2.24", new Object[] {e.getMessage()}); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java index 4c9a1e59f..bf4cfd480 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/AbstractCredentialProvider.java @@ -121,15 +121,15 @@ public abstract class AbstractCredentialProvider { 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(getFriendlyName() + " Assertion Signing credentials (Alias: " - + getMetadataKeyAlias() + ") is not found or contains no PrivateKey.", null); + 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(e.getMessage(), null); + throw new CredentialsNotAvailableException("config.27", new Object[]{e.getMessage()}, e); } } @@ -146,8 +146,8 @@ public abstract class AbstractCredentialProvider { 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(getFriendlyName() + " Assertion Signing credentials (Alias: " - + getSignatureKeyAlias() + ") is not found or contains no PrivateKey.", null); + throw new CredentialsNotAvailableException("config.27", new Object[]{getFriendlyName() + " Assertion Signing credentials (Alias: " + + getSignatureKeyAlias() + ") is not found or contains no PrivateKey."}); } @@ -155,7 +155,7 @@ public abstract class AbstractCredentialProvider { } catch (Exception e) { Logger.error("Failed to generate " + getFriendlyName() + " Assertion Signing credentials"); e.printStackTrace(); - throw new CredentialsNotAvailableException(e.getMessage(), null); + throw new CredentialsNotAvailableException("config.27", new Object[]{e.getMessage()}, e); } } @@ -177,16 +177,17 @@ public abstract class AbstractCredentialProvider { if (credentials.getPrivateKey() == null && credentials.getSecretKey() == null) { Logger.error(getFriendlyName() + " Assertion Encryption credentials is not found or contains no PrivateKey."); - throw new CredentialsNotAvailableException(getFriendlyName() + " Assertion Encryption credentials (Alias: " - + getEncryptionKeyAlias() + ") is not found or contains no PrivateKey.", null); + 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(e.getMessage(), null); + throw new CredentialsNotAvailableException("config.27", new Object[]{e.getMessage()}, e); } } 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 index 1e1c37621..85de666c9 100644 --- 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 @@ -31,6 +31,11 @@ public class CredentialsNotAvailableException extends MOAIDException { super(messageId, parameters); } + public CredentialsNotAvailableException(String messageId, + Object[] parameters, Throwable e) { + super(messageId, parameters, e); + } + /** * */ -- cgit v1.2.3 From 328c1dc9f22623f6e7cdf1c23dd104c10011ee91 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 12:00:33 +0100 Subject: add missing PVP attribute 'mandate-type-oid' --- .../attributes/MandateTypeOIDAttributeBuilder.java | 59 ++++++++++++++++++++++ .../moa/id/protocols/pvp2x/PVPConstants.java | 5 ++ 2 files changed, 64 insertions(+) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeOIDAttributeBuilder.java (limited to 'id/server/idserverlib/src/main/java/at') 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 new file mode 100644 index 000000000..80d330172 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/MandateTypeOIDAttributeBuilder.java @@ -0,0 +1,59 @@ +/******************************************************************************* + * 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.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +public class MandateTypeOIDAttributeBuilder implements IPVPAttributeBuilder { + + public String getName() { + return MANDATE_TYPE_OID_NAME; + } + + public ATT build(IOAAuthParameters oaParam, IAuthData authData, + IAttributeGenerator 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; + + } + + return g.buildStringAttribute(MANDATE_TYPE_OID_FRIENDLY_NAME, MANDATE_TYPE_OID_NAME, mandateType); + } + return null; + + } + + public ATT buildEmpty(IAttributeGenerator g) { + return g.buildEmptyAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME); + } + +} 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 c2b61aaa7..eaddd0789 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 @@ -190,6 +190,11 @@ public interface PVPConstants { 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"; -- cgit v1.2.3 From 402cfcf7e5a8f3bb040ebe9fae5904c202e1e94f Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 12:14:09 +0100 Subject: Change default PVP assertion encryption-algorithm to AES256-CBC --- .../java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPConstants.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 eaddd0789..73d6e978e 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 @@ -31,7 +31,7 @@ public interface PVPConstants { 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_AES128; + 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; -- cgit v1.2.3 From f1c588836f613209984c15a761d65b20c66ca4e9 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 13:29:52 +0100 Subject: add missing error codes --- .../auth/exception/MOAIllegalStateException.java | 46 ++++++++++++++++++++++ .../AbstractProcessEngineSignalController.java | 7 +++- 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIllegalStateException.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIllegalStateException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIllegalStateException.java new file mode 100644 index 000000000..bc19a3f39 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/exception/MOAIllegalStateException.java @@ -0,0 +1,46 @@ +/* + * 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 MOAIllegalStateException extends MOAIDException { + + /** + * + */ + private static final long serialVersionUID = 613582783125887683L; + + /** + * + */ + public MOAIllegalStateException(String code, Object[] params) { + super(code, params); + + } + +} 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 index a23938f97..f22c82e95 100644 --- 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 @@ -9,6 +9,7 @@ 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; @@ -30,7 +31,8 @@ public abstract class AbstractProcessEngineSignalController extends AbstractCont try { if (pendingRequestID == null) { - throw new IllegalStateException("Unable to determine MOA pending-request id."); + throw new MOAIllegalStateException("process.03", new Object[]{"Unable to determine MOA pending-request id."}); + } IRequest pendingReq = requestStorage.getPendingRequest(pendingRequestID); @@ -49,7 +51,8 @@ public abstract class AbstractProcessEngineSignalController extends AbstractCont // process instance is mandatory if (pendingReq.getProcessInstanceId() == null) { - throw new IllegalStateException("MOA session does not provide process instance id."); + throw new MOAIllegalStateException("process.03", new Object[]{"MOA session does not provide process instance id."}); + } // wake up next task -- cgit v1.2.3 From f7361a2d7964c73873e699cfe9b971fe57704cb6 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 13:37:59 +0100 Subject: fix compilation problem --- .../moa/id/auth/exception/InvalidProtocolRequestException.java | 3 +++ 1 file changed, 3 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') 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 index 712d90fd8..c6b8a4b6e 100644 --- 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 @@ -43,4 +43,7 @@ public class InvalidProtocolRequestException extends MOAIDException { super(messageId, parameters); } + public InvalidProtocolRequestException(String messageId, Object[] parameters, Throwable e) { + super(messageId, parameters, e); + } } -- cgit v1.2.3 From 8746e1a7e3e4a3d19922acf81a952bf27618989f Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 13:55:13 +0100 Subject: update default revisions log entries --- .../moa/id/advancedlogging/MOAReversionLogger.java | 40 ++++++++++++++++++---- 1 file changed, 33 insertions(+), 7 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 4620a5c6b..6fa07a098 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 @@ -49,6 +49,9 @@ public class MOAReversionLogger { @Autowired protected AuthConfiguration authConfig; + public static final String NAT_PERSON = "nat"; + public static final String JUR_PERSON = "jur"; + private static final List defaultEventCodes = Arrays.asList( MOAIDEventConstants.SESSION_CREATED, MOAIDEventConstants.SESSION_DESTROYED, @@ -60,6 +63,11 @@ public class MOAReversionLogger { MOAIDEventConstants.AUTHPROTOCOL_TYPE, MOAIDEventConstants.AUTHPROTOCOL_PVP_METADATA, + MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER, + MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION, + MOAIDEventConstants.AUTHPROCESS_STORK_REQUESTED, + MOAIDEventConstants.AUTHPROCESS_MANDATES_REQUESTED, + MOAIDEventConstants.AUTHPROCESS_START, MOAIDEventConstants.AUTHPROCESS_FINISHED, MOAIDEventConstants.AUTHPROCESS_BKU_URL, @@ -67,10 +75,28 @@ public class MOAReversionLogger { MOAIDEventConstants.AUTHPROCESS_IDL_VALIDATED, MOAIDEventConstants.AUTHPROCESS_CERTIFICATE_VALIDATED, MOAIDEventConstants.AUTHPROCESS_AUTHBLOCK_VALIDATED, + + MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_SERVICE_REQUESTED, + MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_RECEIVED_IP, + + MOAIDEventConstants.AUTHPROCESS_FOREIGN_FOUND, + MOAIDEventConstants.AUTHPROCESS_FOREIGN_SZRGW_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_PEPS_REQUESTED, + MOAIDEventConstants.AUTHPROCESS_PEPS_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_PEPS_IDL_RECEIVED, + + MOAIDEventConstants.AUTHPROCESS_MANDATE_SERVICE_REQUESTED, + MOAIDEventConstants.AUTHPROCESS_MANDATE_REDIRECT, + MOAIDEventConstants.AUTHPROCESS_MANDATE_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_SSO, - MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION, - MOAIDEventConstants.AUTHPROCESS_STORK_REQUESTED, - MOAIDEventConstants.AUTHPROCESS_SERVICEPROVIDER + MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_START, + MOAIDEventConstants.AUTHPROCESS_SSO_ASK_USER_FINISHED, + MOAIDEventConstants.AUTHPROCESS_SSO_INVALID + + ); public void logEvent(IOAAuthParameters oaConfig, @@ -159,7 +185,7 @@ public class MOAReversionLogger { if (jaxBMandate.getMandator().getCorporateBody() != null) { logEvent(pendingReq, MOAIDEventConstants.PERSONAL_INFORMATION_MANDATE_MANDATOR_TYPE, - "jur"); + JUR_PERSON); try { String jurBaseID = jaxBMandate.getMandator().getCorporateBody().getIdentification().get(0).getType() + "+" + jaxBMandate.getMandator().getCorporateBody().getIdentification().get(0).getId(); @@ -173,7 +199,7 @@ public class MOAReversionLogger { } else { logEvent(pendingReq, MOAIDEventConstants.PERSONAL_INFORMATION_MANDATE_MANDATOR_TYPE, - "nat"); + NAT_PERSON); logEvent(pendingReq, MOAIDEventConstants.PERSONAL_INFORMATION_MANDATE_MANDATOR_HASH, buildPersonInformationHash( jaxBMandate.getMandator().getPhysicalPerson().getName().getGivenName().get(0), @@ -182,7 +208,7 @@ public class MOAReversionLogger { } } } - + /** * @param pendingReq * @param identityLink @@ -209,7 +235,7 @@ public class MOAReversionLogger { return OASpecificEventCodes; } - private String buildPersonInformationHash(String givenName, String familyName, String dateofBirth) { + public String buildPersonInformationHash(String givenName, String familyName, String dateofBirth) { // {"hash":"hashvalue","salt":"testSalt"} // {"person":{"givenname":"value","familyname":"value","dateofbirth":"value"},"salt":"saltvalue"} -- cgit v1.2.3 From 54a26c8e353069abacefe5232f8270bec6b3cc60 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 21 Mar 2016 15:49:24 +0100 Subject: update libs --- .../moa/id/config/ConfigurationProviderImpl.java | 2 - .../moa/id/protocols/pvp2x/SingleLogOutAction.java | 3 +- .../storage/DBAuthenticationSessionStoreage.java | 29 +-- .../moa/id/util/AxisSecureSocketFactory.java | 258 --------------------- 4 files changed, 17 insertions(+), 275 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/AxisSecureSocketFactory.java (limited to 'id/server/idserverlib/src/main/java/at') 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 db6ff8d9b..395aeaadb 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 @@ -57,7 +57,6 @@ import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.StatisticLogDBUtils; import at.gv.egovernment.moa.id.commons.db.dao.session.AssertionStore; import at.gv.egovernment.moa.id.commons.db.dao.session.AuthenticatedSessionStore; -import at.gv.egovernment.moa.id.commons.db.dao.session.ExceptionStore; 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; @@ -221,7 +220,6 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider config.addAnnotatedClass(AuthenticatedSessionStore.class); config.addAnnotatedClass(OASessionStore.class); config.addAnnotatedClass(OldSSOSessionIDStore.class); - config.addAnnotatedClass(ExceptionStore.class); config.addAnnotatedClass(InterfederationSessionStore.class); config.addAnnotatedClass(ProcessInstanceStore.class); config.addProperties(moaSessionProp); 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 ae88f3ea4..dfe9ecb49 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 @@ -34,6 +34,7 @@ import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; +import org.hibernate.resource.transaction.spi.TransactionStatus; import org.opensaml.saml2.core.LogoutRequest; import org.opensaml.saml2.core.LogoutResponse; import org.opensaml.saml2.metadata.SingleLogoutService; @@ -274,7 +275,7 @@ public class SingleLogOutAction implements IAction { throw new AuthenticationException("pvp2.13", new Object[]{}); } finally { - if (tx != null && !tx.wasCommitted()) { + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) { tx.commit(); } 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 43b4ecf17..094e25040 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 @@ -32,6 +32,7 @@ import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; +import org.hibernate.resource.transaction.spi.TransactionStatus; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -231,7 +232,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; @@ -321,7 +322,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } @@ -371,7 +372,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return result.get(0); } } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } @@ -477,7 +478,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } catch(HibernateException e) { Logger.warn("Error during database saveOrUpdate. Rollback.", e); - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw new AuthenticationException("SSO Session information can not be stored! --> SSO is deactivated", null); } @@ -504,7 +505,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } catch (Exception e) { if (session != null && session.getTransaction() != null - && !session.getTransaction().wasCommitted()) { + && !session.getTransaction().getStatus().equals(TransactionStatus.COMMITTED)) { session.getTransaction().rollback(); throw e; @@ -534,7 +535,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } catch (Exception e) { if (session != null && session.getTransaction() != null - && !session.getTransaction().wasCommitted()) { + && !session.getTransaction().getStatus().equals(TransactionStatus.COMMITTED)) { session.getTransaction().rollback(); throw e; @@ -583,7 +584,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return null; } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } @@ -626,7 +627,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return result.get(0).getActiveOAsessions().get(0); } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } @@ -665,7 +666,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } catch (Throwable e) { Logger.warn("MOASession deserialization-exception by using MOASessionID=" + nameID); - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); return null; } @@ -702,7 +703,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return result.get(0).getInderfederation().get(0); } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } @@ -740,7 +741,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return result.get(0).getInderfederation().get(0); } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } @@ -856,7 +857,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return result.get(0).getInderfederation().get(0); } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } @@ -948,7 +949,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt } } catch (Exception e) { - if (tx != null && !tx.wasCommitted()) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED)) tx.rollback(); throw e; } @@ -1018,7 +1019,7 @@ public class DBAuthenticationSessionStoreage implements IAuthenticationSessionSt return (AuthenticatedSessionStore) result.get(0); } catch (Exception e) { - if (tx != null && !tx.wasCommitted() && commit) + if (tx != null && !tx.getStatus().equals(TransactionStatus.COMMITTED) && commit) tx.rollback(); throw e; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/AxisSecureSocketFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/AxisSecureSocketFactory.java deleted file mode 100644 index fff5fac96..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/AxisSecureSocketFactory.java +++ /dev/null @@ -1,258 +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.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.Socket; -import java.security.GeneralSecurityException; -import java.util.Hashtable; - -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; - -import org.apache.axis.components.net.BooleanHolder; -import org.apache.axis.components.net.DefaultSocketFactory; -import org.apache.axis.components.net.SocketFactory; -import org.apache.axis.components.net.TransportClientProperties; -import org.apache.axis.components.net.TransportClientPropertiesFactory; -import org.apache.axis.utils.Messages; -import org.apache.axis.utils.XMLUtils; - -import at.gv.egovernment.moa.logging.Logger; - -/** - * Secure socket factory for Axis webs service clients of the MOA-ID component, - * which are the MOA-SP calls from MOA-ID Auth, - * and the MOA-ID Auth calls from MOA-ID Proxy. - *
Use this initialization code:
- * // ConnectionParameter connParam = ... get from ConfigurationProvider - * AxisSecureSocketFactory.initialize(connParam); - *
See the Apache Axis documentation on how to configure this class - * as the default secure socket factory to be used by Axis. - *
- * This code has been copied from JSSESocketFactory, the - * method initialize() has been added. - * - * - * @author Paul Ivancsics - * @version $Id$ - */ -public class AxisSecureSocketFactory - extends DefaultSocketFactory implements SocketFactory { - - /** Field sslFactory */ - private static SSLSocketFactory sslFactory; - - /** - * Constructor for AxisSecureSocketFactory. - * @param attributes ??? - */ - public AxisSecureSocketFactory(Hashtable attributes) { - super(attributes); - } - /** - * Initializes the factory by setting the connection parameters to be used for - * setting the secure socket factory, and by setting the system property - * axis.socketSecureFactory. - * @param ssf SSLSocketFactory to initialize with - */ - public static void initialize(SSLSocketFactory ssf) - throws IOException, GeneralSecurityException { - - Logger.debug("Initialize AxisSecureSocketFactory"); - sslFactory = ssf; - } - - /** - * creates a secure socket - * - * @param host - * @param port - * @param otherHeaders - * @param useFullURL - * - * @return Socket - * @throws Exception - */ - public Socket create( - String host, - int port, - StringBuffer otherHeaders, - BooleanHolder useFullURL) - throws Exception { - if (port == -1) { - port = 443; - } - - TransportClientProperties tcp = - TransportClientPropertiesFactory.create("https"); - - boolean hostInNonProxyList = - isHostInNonProxyList(host, tcp.getNonProxyHosts()); - - Socket sslSocket = null; - if (tcp.getProxyHost().length() == 0 || hostInNonProxyList) { - // direct SSL connection - sslSocket = sslFactory.createSocket(host, port); - } - else { - - // Default proxy port is 80, even for https - int tunnelPort = - (tcp.getProxyPort().length() != 0) - ? Integer.parseInt(tcp.getProxyPort()) - : 80; - if (tunnelPort < 0) - tunnelPort = 80; - - // Create the regular socket connection to the proxy - Socket tunnel = new Socket(tcp.getProxyHost(), tunnelPort); - - // The tunnel handshake method (condensed and made reflexive) - OutputStream tunnelOutputStream = tunnel.getOutputStream(); - PrintWriter out = - new PrintWriter( - new BufferedWriter(new OutputStreamWriter(tunnelOutputStream))); - - // More secure version... engage later? - // PasswordAuthentication pa = - // Authenticator.requestPasswordAuthentication( - // InetAddress.getByName(tunnelHost), - // tunnelPort, "SOCK", "Proxy","HTTP"); - // if(pa == null){ - // printDebug("No Authenticator set."); - // }else{ - // printDebug("Using Authenticator."); - // tunnelUser = pa.getUserName(); - // tunnelPassword = new String(pa.getPassword()); - // } - out.print( - "CONNECT " - + host - + ":" - + port - + " HTTP/1.0\r\n" - + "User-Agent: AxisClient"); - if (tcp.getProxyUser().length() != 0 - && tcp.getProxyPassword().length() != 0) { - - // add basic authentication header for the proxy - String encodedPassword = - XMLUtils.base64encode( - (tcp.getProxyUser() + ":" + tcp.getProxyPassword()).getBytes()); - - out.print("\nProxy-Authorization: Basic " + encodedPassword); - } - out.print("\nContent-Length: 0"); - out.print("\nPragma: no-cache"); - out.print("\r\n\r\n"); - out.flush(); - InputStream tunnelInputStream = tunnel.getInputStream(); - - if (log.isDebugEnabled()) { - log.debug( - Messages.getMessage( - "isNull00", - "tunnelInputStream", - "" + (tunnelInputStream == null))); - } - String replyStr = ""; - - // Make sure to read all the response from the proxy to prevent SSL negotiation failure - // Response message terminated by two sequential newlines - int newlinesSeen = 0; - boolean headerDone = false; /* Done on first newline */ - - while (newlinesSeen < 2) { - int i = tunnelInputStream.read(); - - if (i < 0) { - throw new IOException("Unexpected EOF from proxy"); - } - if (i == '\n') { - headerDone = true; - ++newlinesSeen; - } - else if (i != '\r') { - newlinesSeen = 0; - if (!headerDone) { - replyStr += String.valueOf((char) i); - } - } - } - if (!replyStr.startsWith("HTTP/1.0 200") - && !replyStr.startsWith("HTTP/1.1 200")) { - throw new IOException( - Messages.getMessage( - "cantTunnel00", - new String[] { tcp.getProxyHost(), "" + tunnelPort, replyStr })); - } - - // End of condensed reflective tunnel handshake method - sslSocket = sslFactory.createSocket(tunnel, host, port, true); - if (log.isDebugEnabled()) { - log.debug( - Messages.getMessage( - "setupTunnel00", - tcp.getProxyHost(), - "" + tunnelPort)); - } - } - - ((SSLSocket) sslSocket).startHandshake(); - if (log.isDebugEnabled()) { - log.debug(Messages.getMessage("createdSSL00")); - } - return sslSocket; - } - -} -- cgit v1.2.3 From 836a7cf93aca1a84f2827f78e849e012a1a368a3 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 22 Mar 2016 07:31:17 +0100 Subject: add revisions log entries --- .../java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java | 3 ++- .../moa/id/protocols/AbstractAuthProtocolModulController.java | 4 ++++ .../egovernment/moa/id/protocols/ProtocolFinalizationController.java | 5 ++++- .../protocols/builder/attributes/MandateTypeOIDAttributeBuilder.java | 2 +- 4 files changed, 11 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 5aceb8eec..e5c517da7 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 @@ -470,7 +470,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { //terminate MOASession try { authenticatedSessionStore.destroySession(session.getSessionID()); - ssoManager.deleteSSOSessionID(httpReq, httpResp); + ssoManager.deleteSSOSessionID(httpReq, httpResp); + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, pvpReq.getUniqueSessionIdentifier()); Logger.debug("Active SSO Session on IDP is remove."); } catch (MOADatabaseException e) { 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 index 4e44f4043..79afba412 100644 --- 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 @@ -30,6 +30,7 @@ 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; @@ -90,6 +91,9 @@ public abstract class AbstractAuthProtocolModulController extends AbstractContro //authenticated MOASession already exists --> protocol-specific postProcessing can start directly finalizeAuthenticationProcess(req, resp, pendingReq, moaSession); + //transaction is finished, log transaction finished event + revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); + } } else { 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 index 302c60c5e..991c6a881 100644 --- 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 @@ -166,8 +166,11 @@ public class ProtocolFinalizationController extends AbstractAuthProtocolModulCon } //remove pending-request - if (pendingReq != null) + if (pendingReq != null) { requestStorage.removePendingRequest(pendingReq.getRequestID()); + revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_DESTROYED, pendingReq.getUniqueTransactionIdentifier()); + + } } 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 80d330172..b967ad42c 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 @@ -53,7 +53,7 @@ public class MandateTypeOIDAttributeBuilder implements IPVPAttributeBuilder { } public ATT buildEmpty(IAttributeGenerator g) { - return g.buildEmptyAttribute(MANDATE_TYPE_FRIENDLY_NAME, MANDATE_TYPE_NAME); + return g.buildEmptyAttribute(MANDATE_TYPE_OID_FRIENDLY_NAME, MANDATE_TYPE_OID_NAME); } } -- cgit v1.2.3 From 9b980ba714e6d59abcccb10df5036c0c318721c5 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 22 Mar 2016 08:49:17 +0100 Subject: fix nullpointer during IDP initiated Single LogOut --- .../gv/egovernment/moa/id/moduls/AuthenticationManager.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 e5c517da7..1e064f24f 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 @@ -469,9 +469,19 @@ public class AuthenticationManager extends MOAIDAuthConstants { //terminate MOASession try { + String uniqueSessionIdentifier = "notSet"; + AuthenticationSessionExtensions sessionExt = + authenticatedSessionStore.getAuthenticationSessionExtensions(session.getSessionID()); + if (sessionExt != null) + uniqueSessionIdentifier = sessionExt.getUniqueSessionId(); + authenticatedSessionStore.destroySession(session.getSessionID()); ssoManager.deleteSSOSessionID(httpReq, httpResp); - revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, pvpReq.getUniqueSessionIdentifier()); + if (pvpReq != null) + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, pvpReq.getUniqueSessionIdentifier()); + else + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, uniqueSessionIdentifier); + Logger.debug("Active SSO Session on IDP is remove."); } catch (MOADatabaseException e) { -- cgit v1.2.3 From b29150526d95af2f1c30f4543c88d35c2965dfe6 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 22 Mar 2016 14:43:22 +0100 Subject: add revisionslog info's to eIDAS and SLO methods --- .../id/advancedlogging/MOAIDEventConstants.java | 15 ++++-- .../moa/id/advancedlogging/MOAReversionLogger.java | 14 ++++-- .../moa/id/data/ISLOInformationContainer.java | 7 ++- .../moa/id/data/SLOInformationContainer.java | 37 +++++++++++++- .../moa/id/moduls/AuthenticationManager.java | 56 +++++++++++++++------- .../moa/id/protocols/pvp2x/SingleLogOutAction.java | 15 ++++-- 6 files changed, 113 insertions(+), 31 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 054543c3e..9d26cc05f 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 @@ -47,7 +47,12 @@ public interface MOAIDEventConstants extends EventConstants { public static final int AUTHPROTOCOL_OPENIDCONNECT_TOKENREQUEST = 3201; public static final int AUTHPROTOCOL_SAML1_AUTHNREQUEST = 3300; - + + public static final int AUTHPROCESS_IDP_SLO_REQUESTED = 4400; + public static final int AUTHPROCESS_SLO_STARTED = 4401; + public static final int AUTHPROCESS_SLO_ALL_VALID = 4402; + public static final int AUTHPROCESS_SLO_NOT_ALL_VALID = 4403; + //authentication process information public static final int AUTHPROCESS_START = 4000; public static final int AUTHPROCESS_FINISHED = 4001; @@ -78,9 +83,11 @@ public interface MOAIDEventConstants extends EventConstants { public static final int AUTHPROCESS_MANDATE_REDIRECT = 4301; public static final int AUTHPROCESS_MANDATE_RECEIVED = 4302; - public static final int AUTHPROCESS_PEPS_REQUESTED = 4400; - public static final int AUTHPROCESS_PEPS_RECEIVED = 4401; - public static final int AUTHPROCESS_PEPS_IDL_RECEIVED = 4402; + public static final int AUTHPROCESS_PEPS_SELECTED = 6100; + public static final int AUTHPROCESS_PEPS_REQUESTED = 6101; + 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; //person information public static final int PERSONAL_INFORMATION_PROF_REPRESENTATIVE_BPK = 5000; 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 6fa07a098..4a5cbd55f 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 @@ -75,18 +75,26 @@ public class MOAReversionLogger { MOAIDEventConstants.AUTHPROCESS_IDL_VALIDATED, MOAIDEventConstants.AUTHPROCESS_CERTIFICATE_VALIDATED, MOAIDEventConstants.AUTHPROCESS_AUTHBLOCK_VALIDATED, - + + MOAIDEventConstants.AUTHPROCESS_IDP_SLO_REQUESTED, + MOAIDEventConstants.AUTHPROCESS_SLO_STARTED, + MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID, + MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID, + MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_SERVICE_REQUESTED, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_ERROR_RECEIVED, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_RECEIVED, MOAIDEventConstants.AUTHPROCESS_ELGA_MANDATE_RECEIVED_IP, - MOAIDEventConstants.AUTHPROCESS_FOREIGN_FOUND, - MOAIDEventConstants.AUTHPROCESS_FOREIGN_SZRGW_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_PEPS_SELECTED, MOAIDEventConstants.AUTHPROCESS_PEPS_REQUESTED, MOAIDEventConstants.AUTHPROCESS_PEPS_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_PEPS_RECEIVED_ERROR, MOAIDEventConstants.AUTHPROCESS_PEPS_IDL_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_FOREIGN_FOUND, + MOAIDEventConstants.AUTHPROCESS_FOREIGN_SZRGW_RECEIVED, + MOAIDEventConstants.AUTHPROCESS_MANDATE_SERVICE_REQUESTED, MOAIDEventConstants.AUTHPROCESS_MANDATE_REDIRECT, MOAIDEventConstants.AUTHPROCESS_MANDATE_RECEIVED, 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 index 18ffc5c6d..38f6948d3 100644 --- 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 @@ -24,8 +24,8 @@ package at.gv.egovernment.moa.id.data; import java.util.Iterator; import java.util.List; -import java.util.Set; import java.util.Map.Entry; +import java.util.Set; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPTargetConfiguration; @@ -63,5 +63,8 @@ public interface ISLOInformationContainer { List 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/SLOInformationContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/SLOInformationContainer.java index fd1749129..20588ad0b 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 @@ -44,6 +44,8 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon private LinkedHashMap activeFrontChannalOAs; private LinkedHashMap activeBackChannelOAs; private List sloFailedOAs = null; + private String transactionID = null; + private String sessionID = null; /** * @@ -146,6 +148,7 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon @Override public void setSloRequest(PVPTargetConfiguration sloRequest) { this.sloRequest = sloRequest; + } /* (non-Javadoc) @@ -164,5 +167,37 @@ public class SLOInformationContainer implements Serializable, ISLOInformationCon if (sloFailedOAs == null) sloFailedOAs = new ArrayList(); sloFailedOAs.add(oaID); - } + } + + + /** + * @return the transactionID + */ + public String getTransactionID() { + return transactionID; + } + + + /** + * @param transactionID the transactionID to set + */ + public void setTransactionID(String transactionID) { + this.transactionID = transactionID; + } + + public String getSessionID() { + return this.sessionID; + + } + + + /** + * @param sessionID the sessionID to set + */ + public void setSessionID(String sessionID) { + this.sessionID = sessionID; + } + + + } 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 1e064f24f..a1f2c6558 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 @@ -443,6 +443,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { HttpServletResponse httpResp, AuthenticationSession session, PVPTargetConfiguration pvpReq, String authURL) throws MOAIDException { String pvpSLOIssuer = null; String inboundRelayState = null; + String uniqueSessionIdentifier = "notSet"; + String uniqueTransactionIdentifier = "notSet"; Logger.debug("Start technical Single LogOut process ... "); @@ -451,14 +453,33 @@ public class AuthenticationManager extends MOAIDAuthConstants { LogoutRequest logOutReq = (LogoutRequest) samlReq.getSamlRequest(); pvpSLOIssuer = logOutReq.getIssuer().getValue(); inboundRelayState = samlReq.getRelayState(); + uniqueSessionIdentifier = pvpReq.getUniqueSessionIdentifier(); + uniqueTransactionIdentifier = pvpReq.getUniqueTransactionIdentifier(); + } else { + AuthenticationSessionExtensions sessionExt; + try { + sessionExt = authenticatedSessionStore.getAuthenticationSessionExtensions(session.getSessionID()); + if (sessionExt != null) + uniqueSessionIdentifier = sessionExt.getUniqueSessionId(); + + } catch (MOADatabaseException e) { + Logger.error("Error during database communication. Can not evaluate 'uniqueSessionIdentifier'", e); + + } + uniqueTransactionIdentifier = Random.nextLongRandom(); + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_IDP_SLO_REQUESTED); + } //store active OAs to SLOContaine List dbOAs = authenticatedSessionStore.getAllActiveOAFromMOASession(session); List dbIDPs = authenticatedSessionStore.getAllActiveIDPsFromMOASession(session); - SLOInformationContainer sloContainer = new SLOInformationContainer(); - sloContainer.setSloRequest(pvpReq); + SLOInformationContainer sloContainer = new SLOInformationContainer(); + sloContainer.setTransactionID(uniqueTransactionIdentifier); + sloContainer.setSessionID(uniqueSessionIdentifier); + sloContainer.setSloRequest(pvpReq); + sloBuilder.parseActiveIDPs(sloContainer, dbIDPs, pvpSLOIssuer); sloBuilder.parseActiveOAs(sloContainer, dbOAs, pvpSLOIssuer); @@ -468,19 +489,10 @@ public class AuthenticationManager extends MOAIDAuthConstants { + " NO_SLO_Support:" + sloContainer.getSloFailedOAs().size()); //terminate MOASession - try { - String uniqueSessionIdentifier = "notSet"; - AuthenticationSessionExtensions sessionExt = - authenticatedSessionStore.getAuthenticationSessionExtensions(session.getSessionID()); - if (sessionExt != null) - uniqueSessionIdentifier = sessionExt.getUniqueSessionId(); - + try { authenticatedSessionStore.destroySession(session.getSessionID()); ssoManager.deleteSSOSessionID(httpReq, httpResp); - if (pvpReq != null) - revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, pvpReq.getUniqueSessionIdentifier()); - else - revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, uniqueSessionIdentifier); + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_DESTROYED, uniqueSessionIdentifier); Logger.debug("Active SSO Session on IDP is remove."); @@ -490,8 +502,9 @@ public class AuthenticationManager extends MOAIDAuthConstants { } - Logger.trace("Starting Service-Provider logout process ... "); - //start service provider back channel logout process + Logger.trace("Starting Service-Provider logout process ... "); + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_STARTED); + //start service provider back channel logout process Iterator nextOAInterator = sloContainer.getNextBackChannelOA(); while (nextOAInterator.hasNext()) { SLOInformationImpl sloDescr = sloContainer.getBackChannelOASessionDescripten(nextOAInterator.next()); @@ -592,13 +605,17 @@ public class AuthenticationManager extends MOAIDAuthConstants { null); if (sloContainer.getSloFailedOAs() == null || - sloContainer.getSloFailedOAs().size() == 0) + sloContainer.getSloFailedOAs().size() == 0) { + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); config.putCustomParameter("successMsg", MOAIDMessageProvider.getInstance().getMessage("slo.00", null)); - else + + } else { + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); config.putCustomParameter("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", null)); - + + } guiBuilder.build(httpResp, config, "Single-LogOut GUI"); } @@ -615,6 +632,8 @@ public class AuthenticationManager extends MOAIDAuthConstants { SingleLogoutService sloService = sloBuilder.getResponseSLODescriptor(pvpReq); LogoutResponse message = sloBuilder.buildSLOErrorResponse(sloService, pvpReq, StatusCode.RESPONDER_URI); sloBuilder.sendFrontChannelSLOMessage(sloService, message, httpReq, httpResp, inboundRelayState); + + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); }else { //print SLO information directly @@ -623,6 +642,7 @@ public class AuthenticationManager extends MOAIDAuthConstants { DefaultGUIFormBuilderConfiguration.VIEW_SINGLELOGOUT, null); + revisionsLogger.logEvent(uniqueSessionIdentifier, uniqueTransactionIdentifier, MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); config.putCustomParameter("errorMsg", MOAIDMessageProvider.getInstance().getMessage("slo.01", 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 dfe9ecb49..af6c79140 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 @@ -41,6 +41,8 @@ import org.opensaml.saml2.metadata.SingleLogoutService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.servlet.RedirectServlet; @@ -80,6 +82,7 @@ public class SingleLogOutAction implements IAction { @Autowired private IAuthenticationSessionStoreage authenticationSessionStorage; @Autowired private ITransactionStorage transactionStorage; @Autowired private SingleLogOutBuilder sloBuilder; + @Autowired private MOAReversionLogger revisionsLogger; /* (non-Javadoc) @@ -240,11 +243,17 @@ public class SingleLogOutAction implements IAction { String statusCode = null; if (sloContainer.getSloFailedOAs() == null || - sloContainer.getSloFailedOAs().size() == 0) + sloContainer.getSloFailedOAs().size() == 0) { statusCode = MOAIDAuthConstants.SLOSTATUS_SUCCESS; - else + revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), + MOAIDEventConstants.AUTHPROCESS_SLO_ALL_VALID); + + } else { + revisionsLogger.logEvent(sloContainer.getSessionID(), sloContainer.getTransactionID(), + MOAIDEventConstants.AUTHPROCESS_SLO_NOT_ALL_VALID); statusCode = MOAIDAuthConstants.SLOSTATUS_ERROR; - + + } transactionStorage.put(artifact, statusCode); redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_SLOSTATUS, artifact); -- cgit v1.2.3 From 1bef953a8baed149db2bf234687c9d0eebb85524 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 22 Mar 2016 14:44:04 +0100 Subject: move ProcessInstanzDAO into transactionstorage --- .../moa/id/process/dao/ProcessInstanceStore.java | 4 +- .../process/dao/ProcessInstanceStoreDAOImpl.java | 67 ++++++++++++---------- 2 files changed, 40 insertions(+), 31 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 index d690c37bf..3620f2950 100644 --- 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 @@ -17,7 +17,9 @@ import at.gv.egovernment.moa.id.process.ProcessInstanceState; @Entity @Table(name = "processinstance") -public class ProcessInstanceStore { +public class ProcessInstanceStore implements Serializable{ + + private static final long serialVersionUID = -6147519767313903808L; /** * A process instance identifier qualifies as natural primary key by satisfying these requirements diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java index 577e971db..a9a9322ad 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/process/dao/ProcessInstanceStoreDAOImpl.java @@ -1,15 +1,12 @@ package at.gv.egovernment.moa.id.process.dao; -import org.hibernate.Criteria; -import org.hibernate.Session; -import org.hibernate.Transaction; -import org.hibernate.criterion.Restrictions; 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.MOASessionDBUtils; 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} @@ -20,10 +17,14 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { private Logger log = LoggerFactory.getLogger(getClass()); + @Autowired ITransactionStorage transactionStorage; + @Override public void saveOrUpdate(ProcessInstanceStore pIStore) throws MOADatabaseException { try { - MOASessionDBUtils.saveOrUpdate(pIStore); + transactionStorage.put(pIStore.getProcessInstanceId(), pIStore); + +// 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."); @@ -35,31 +36,35 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { public ProcessInstanceStore load(String processInstanceId) throws MOADatabaseException { log.debug("Retrieve the ProcessInstanceStore for id='{}' from the database.", processInstanceId); - Session session = MOASessionDBUtils.getCurrentSession(); - + + +// Session session = MOASessionDBUtils.getCurrentSession(); +// ProcessInstanceStore result = null; - Transaction tx = null; - synchronized (session) { +// Transaction tx = null; +// synchronized (session) { try { - 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(); - + 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(); - } + processInstanceId); +// if (tx != null) { +// tx.rollback(); +// } throw e; } finally { //MOASessionDBUtils.closeSession(); } - } +// } if (result != null) { log.debug("Found process instance store for instance '{}'.", processInstanceId); } else { @@ -71,14 +76,16 @@ public class ProcessInstanceStoreDAOImpl implements ProcessInstanceStoreDAO { @Override public void remove(String processInstanceId) throws MOADatabaseException { - log.debug("Delete the ProcessInstanceStore for id='{}' from the database.", processInstanceId); - ProcessInstanceStore toBeDeleted = load(processInstanceId); - if (toBeDeleted != null) { - 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 + "'."); - } + 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); } -- cgit v1.2.3 From fcf068ba38d2bd44976b49ee0ecef44e7182b8c5 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 22 Mar 2016 14:46:42 +0100 Subject: remove ProcessInstanceStore from Hibernate DB config --- .../at/gv/egovernment/moa/id/config/ConfigurationProviderImpl.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 395aeaadb..5c2f86732 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 @@ -62,7 +62,6 @@ 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.dao.statistic.StatisticLog; import at.gv.egovernment.moa.id.data.IssuerAndSerial; -import at.gv.egovernment.moa.id.process.dao.ProcessInstanceStore; import at.gv.egovernment.moa.id.protocols.pvp2x.config.MOADefaultBootstrap; import at.gv.egovernment.moa.logging.Logger; import at.gv.util.config.EgovUtilPropertiesConfiguration; @@ -221,7 +220,7 @@ public abstract class ConfigurationProviderImpl implements ConfigurationProvider config.addAnnotatedClass(OASessionStore.class); config.addAnnotatedClass(OldSSOSessionIDStore.class); config.addAnnotatedClass(InterfederationSessionStore.class); - config.addAnnotatedClass(ProcessInstanceStore.class); + //config.addAnnotatedClass(ProcessInstanceStore.class); config.addProperties(moaSessionProp); MOASessionDBUtils.initHibernate(config, moaSessionProp); -- cgit v1.2.3 From db813d7524890a60bbd13f60c9c448dc1ef6cfd6 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 23 Mar 2016 15:16:19 +0100 Subject: add additional parameters to ELGA mandate-service client implementation --- .../pvp2x/builder/PVPAuthnRequestBuilder.java | 16 ++++++++++++++++ .../id/protocols/pvp2x/builder/PVPMetadataBuilder.java | 6 +++--- .../pvp2x/config/IDPPVPMetadataConfiguration.java | 16 ++++++++++++++++ .../config/IPVPAuthnRequestBuilderConfiguruation.java | 18 +++++++++++++++++- .../pvp2x/config/IPVPMetadataBuilderConfiguration.java | 14 ++++++++++++++ 5 files changed, 66 insertions(+), 4 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java index ba5c19de7..01ef4a43d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPAuthnRequestBuilder.java @@ -38,6 +38,8 @@ 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; @@ -175,6 +177,20 @@ public class PVPAuthnRequestBuilder { 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 ); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java index 62e3b9620..ab96e4df7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java @@ -214,8 +214,8 @@ public class PVPMetadataBuilder { private RoleDescriptor generateSPMetadata(IPVPMetadataBuilderConfiguration config) throws CredentialsNotAvailableException, SecurityException, ConfigurationException { SPSSODescriptor spSSODescriptor = SAML2Utils.createSAMLObject(SPSSODescriptor.class); spSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); - spSSODescriptor.setAuthnRequestsSigned(true); - spSSODescriptor.setWantAssertionsSigned(false); + spSSODescriptor.setAuthnRequestsSigned(config.wantAuthnRequestSigned()); + spSSODescriptor.setWantAssertionsSigned(config.wantAssertionSigned()); KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); @@ -367,7 +367,7 @@ public class PVPMetadataBuilder { idpSSODescriptor.addSupportedProtocol(SAMLConstants.SAML20P_NS); //set ass default value, because PVP 2.x specification defines this feature as MUST - idpSSODescriptor.setWantAuthnRequestsSigned(true); + idpSSODescriptor.setWantAuthnRequestsSigned(config.wantAuthnRequestSigned()); // add WebSSO descriptor for POST-Binding if (MiscUtil.isNotEmpty(config.getIDPWebSSOPostBindingURL())) { 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 5bb1131a6..c0fb5bf5b 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 @@ -300,4 +300,20 @@ public class IDPPVPMetadataConfiguration implements IPVPMetadataBuilderConfigura return "MOA-ID-Auth"; } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration#wantAssertionSigned() + */ + @Override + public boolean wantAssertionSigned() { + return false; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration#wantAuthnRequestSigned() + */ + @Override + public boolean wantAuthnRequestSigned() { + return true; + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java index 6e1798ed1..814a2387d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/IPVPAuthnRequestBuilderConfiguruation.java @@ -25,6 +25,7 @@ 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 @@ -136,11 +137,26 @@ public interface IPVPAuthnRequestBuilderConfiguruation { public String getSubjectNameIDFormat(); /** - * Define a SP specific SAMK2 requestID + * 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 index 56274535b..3a8404cae 100644 --- 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 @@ -221,4 +221,18 @@ public interface IPVPMetadataBuilderConfiguration { * @return a List of SAML2 nameID types */ public List getSPAllowedNameITTypes(); + + /** + * Set the 'wantAssertionSigned' attribute in SP metadata + * + * @return + */ + public boolean wantAssertionSigned(); + + /** + * Set the 'wantAuthnRequestSigned' attribute + * + * @return + */ + public boolean wantAuthnRequestSigned(); } -- cgit v1.2.3 From 1bad771fdccff20e21b79f88266d194ea71a0df1 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 24 Mar 2016 14:55:02 +0100 Subject: fix empty attribute problem --- .../builder/attributes/EIDIssuingNationAttributeBuilder.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 index ab41b1229..fc80ad7fe 100644 --- 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 @@ -23,9 +23,9 @@ 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.util.MiscUtil; public class EIDIssuingNationAttributeBuilder implements IPVPAttributeBuilder { @@ -36,9 +36,12 @@ public class EIDIssuingNationAttributeBuilder implements IPVPAttributeBuilder { public ATT build(IOAAuthParameters oaParam, IAuthData authData, IAttributeGenerator g) throws AttributeException { String countryCode = authData.getCcc(); - - return g.buildStringAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, - EID_ISSUING_NATION_NAME, countryCode); + if (MiscUtil.isNotEmpty(countryCode)) + return g.buildStringAttribute(EID_ISSUING_NATION_FRIENDLY_NAME, + EID_ISSUING_NATION_NAME, countryCode); + + else + return null; } public ATT buildEmpty(IAttributeGenerator g) { -- cgit v1.2.3 From 5b1f6e34fa4c9fd6c992efd347127db863fb1031 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 24 Mar 2016 15:46:48 +0100 Subject: fix possible NullPointer in error handling --- .../at/gv/egovernment/moa/id/auth/servlet/AbstractController.java | 4 ++++ .../moa/id/auth/servlet/AbstractProcessEngineSignalController.java | 1 + 2 files changed, 5 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index 1a029a9fa..e51f3e6c9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -111,6 +111,10 @@ public abstract class AbstractController extends MOAIDAuthConstants { //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)) 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 index f22c82e95..7a4ee35fa 100644 --- 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 @@ -44,6 +44,7 @@ public abstract class AbstractProcessEngineSignalController extends AbstractCont //change pending-request ID requestStorage.changePendingRequestID(pendingReq); + pendingRequestID = pendingReq.getRequestID(); //add transactionID and unique sessionID to Logger TransactionIDUtils.setSessionId(pendingReq.getUniqueSessionIdentifier()); -- cgit v1.2.3 From 5848cd0057ad9f607e8c117c18481f5caebfd357 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 24 Mar 2016 17:03:22 +0100 Subject: update Session-Transfer-Module to restore session --- .../pvp2x/verification/SAMLVerificationEngineSP.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 d9bc7daaf..385fe90fb 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 @@ -62,7 +62,7 @@ import at.gv.egovernment.moa.logging.Logger; public class SAMLVerificationEngineSP extends SAMLVerificationEngine { @Autowired AuthConfiguration authConfig; - + /** * Validate a PVP response and all included assertions * @@ -74,6 +74,13 @@ public class SAMLVerificationEngineSP extends SAMLVerificationEngine { * @throws AssertionValidationExeption */ public void validateAssertion(Response samlResp, boolean validateDestination, Credential assertionDecryption, String spEntityID, String loggerSPName) throws AssertionValidationExeption { + validateAssertion(samlResp, validateDestination, assertionDecryption, spEntityID, loggerSPName, true); + + } + + + public void validateAssertion(Response samlResp, boolean validateDestination, Credential assertionDecryption, String spEntityID, String loggerSPName, + boolean validateDateTime) throws AssertionValidationExeption { try { if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { List saml2assertions = new ArrayList(); @@ -102,7 +109,7 @@ public class SAMLVerificationEngineSP extends SAMLVerificationEngine { throw new AssertionValidationExeption("sp.pvp2.07", new Object[]{loggerSPName, "'IssueInstant' attribute is not included"}); } - if (issueInstant.minusMinutes(MOAIDAuthConstants.TIME_JITTER).isAfterNow()) { + if (validateDateTime && issueInstant.minusMinutes(MOAIDAuthConstants.TIME_JITTER).isAfterNow()) { Logger.warn("PVP response: IssueInstant DateTime is not valid anymore."); throw new AssertionValidationExeption("sp.pvp2.07", new Object[]{loggerSPName, "'IssueInstant' Time is not valid any more"}); @@ -150,7 +157,8 @@ public class SAMLVerificationEngineSP extends SAMLVerificationEngine { if (conditions != null) { DateTime notbefore = conditions.getNotBefore().minusMinutes(5); DateTime notafter = conditions.getNotOnOrAfter(); - if ( notbefore.isAfterNow() || notafter.isBeforeNow() ) { + if (validateDateTime && + (notbefore.isAfterNow() || notafter.isBeforeNow()) ) { isAssertionValid = false; Logger.info("Assertion:" + saml2assertion.getID() + " is out of Date. " -- cgit v1.2.3 From d945e481a418fcfedba616915cc77eb45ae62827 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Tue, 29 Mar 2016 14:04:59 +0200 Subject: fix missing ID in SP metadata --- .../egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java | 2 ++ 1 file changed, 2 insertions(+) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java index ab96e4df7..567faf1d8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java @@ -186,6 +186,8 @@ public class PVPMetadataBuilder { entityDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); entityDescriptor.setSignature(signature); + entityDescriptor.setID(SAML2Utils.getSecureIdentifier()); + //marshall document Marshaller out = Configuration.getMarshallerFactory() -- cgit v1.2.3 From bd53025fa776091cd82d0fca57a28a5404fb4f37 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 30 Mar 2016 08:36:03 +0200 Subject: fix problem with XML parser and additional features options --- .../metadata/MOASPMetadataSignatureFilter.java | 26 +++++++++---------- .../moa/id/util/ParamValidatorUtils.java | 30 +++++++++++++++------- 2 files changed, 33 insertions(+), 23 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 a4ab92f58..3d69b0380 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 @@ -23,14 +23,9 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata; import java.io.IOException; -import java.io.StringWriter; -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.opensaml.saml2.metadata.EntityDescriptor; import org.opensaml.saml2.metadata.provider.FilterException; @@ -41,6 +36,7 @@ import at.gv.egovernment.moa.id.auth.builder.SignatureVerificationUtils; import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; import at.gv.egovernment.moa.id.commons.api.exceptions.MOAIDException; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; /** * @author tlenz @@ -69,19 +65,21 @@ public class MOASPMetadataSignatureFilter implements MetadataFilter { EntityDescriptor entityDes = (EntityDescriptor) metadata; //check signature; try { - Transformer transformer = TransformerFactory.newInstance() - .newTransformer(); - StringWriter sw = new StringWriter(); - StreamResult sr = new StreamResult(sw); - DOMSource source = new DOMSource(metadata.getDOM()); - transformer.transform(source, sr); - sw.close(); - String metadataXML = sw.toString(); + byte[] serialized = DOMUtils.serializeNode(metadata.getDOM(), "UTF-8"); + +// Transformer transformer = TransformerFactory.newInstance() +// .newTransformer(); +// StringWriter sw = new StringWriter(); +// StreamResult sr = new StreamResult(sw); +// DOMSource source = new DOMSource(metadata.getDOM()); +// transformer.transform(source, sr); +// sw.close(); +// String metadataXML = sw.toString(); SignatureVerificationUtils sigVerify = new SignatureVerificationUtils(); VerifyXMLSignatureResponse result = sigVerify.verify( - metadataXML.getBytes(), trustProfileID); + serialized, trustProfileID); //check signature-verification result if (result.getSignatureCheckCode() != 0) { 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 f97d646b6..47ea91753 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 @@ -46,20 +46,20 @@ package at.gv.egovernment.moa.id.util; +import java.io.ByteArrayInputStream; import java.io.IOException; -import java.io.StringReader; import java.net.MalformedURLException; import java.net.URL; +import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; -import org.xml.sax.InputSource; import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; @@ -68,12 +68,22 @@ 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; public class ParamValidatorUtils extends MOAIDAuthConstants{ + private static final Map parserFeatures = + Collections.unmodifiableMap(new HashMap() { + private static final long serialVersionUID = 1L; + { + put(DOMUtils.DISALLOW_DOCTYPE_FEATURE, true); + + } + }); + /** * Checks if the given target is valid * @param target HTTP parameter from request @@ -482,11 +492,13 @@ public class ParamValidatorUtils extends MOAIDAuthConstants{ return false; Logger.debug("Ueberpruefe Parameter XMLDocument"); - try { - DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); - DocumentBuilder builder = factory.newDocumentBuilder(); - InputSource is = new InputSource(new StringReader(document)); - builder.parse(is); + try { + DOMUtils.parseXmlValidating(new ByteArrayInputStream(document.getBytes()), parserFeatures); + +// DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); +// DocumentBuilder builder = factory.newDocumentBuilder(); +// InputSource is = new InputSource(new StringReader(document)); +// builder.parse(is); Logger.debug("Parameter XMLDocument erfolgreich ueberprueft"); return true; -- cgit v1.2.3 From c33f026d4e41a0d5faa27cd8cc924988343b95fd Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Wed, 30 Mar 2016 08:36:36 +0200 Subject: add 'ID' attribute to metadata 'entityDescriptor' element --- .../egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java index 567faf1d8..855925272 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/PVPMetadataBuilder.java @@ -184,9 +184,10 @@ public class PVPMetadataBuilder { } else { entityDescriptor.setValidUntil(date.plusHours(config.getMetadataValidUntil())); + entityDescriptor.setID(SAML2Utils.getSecureIdentifier()); entityDescriptor.setSignature(signature); - entityDescriptor.setID(SAML2Utils.getSecureIdentifier()); + //marshall document -- cgit v1.2.3 From ab67fbdf5d661a33b67436c70db0dcb8b840cf57 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 31 Mar 2016 08:03:28 +0200 Subject: if database cleanUP process found some unhandled exception, write error messages to technical log --- .../moa/id/auth/AuthenticationSessionCleaner.java | 76 +++++++++++++++++++++- .../moa/id/auth/servlet/AbstractController.java | 24 ++++++- .../AbstractProcessEngineSignalController.java | 6 +- .../moa/id/data/ExceptionContainer.java | 65 ++++++++++++++++++ .../protocols/ProtocolFinalizationController.java | 12 ++-- .../moa/id/storage/DBTransactionStorage.java | 37 ++++++----- .../moa/id/storage/ITransactionStorage.java | 15 ++++- 7 files changed, 203 insertions(+), 32 deletions(-) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ExceptionContainer.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationSessionCleaner.java index 94138e0fc..e0552c337 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 @@ -4,15 +4,22 @@ package at.gv.egovernment.moa.id.auth; import java.util.Date; +import java.util.List; +import org.hibernate.HibernateException; 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.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; /** * Thread cleaning the AuthenticationServer session store @@ -53,11 +60,55 @@ public class AuthenticationSessionCleaner implements Runnable { authenticationSessionStorage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); //clean TransactionStorage - transactionStorage.clean(now, authDataTimeOut); + List entryKeysToClean = transactionStorage.clean(now, authDataTimeOut); + if (entryKeysToClean != null && entryKeysToClean.size() != 0) { + for(String entryKey : entryKeysToClean) { + try { + try { + Object entry = transactionStorage.get(entryKey); + //if entry is an exception --> log it because is could be unhandled + if (entry != null && entry instanceof ExceptionContainer) { + ExceptionContainer exContainer = (ExceptionContainer) entry; + + if (exContainer.getExceptionThrown() != null) { + //add session and transaction ID to log if exists + if (MiscUtil.isNotEmpty(exContainer.getUniqueTransactionID())) + TransactionIDUtils.setTransactionId(exContainer.getUniqueTransactionID()); + + if (MiscUtil.isNotEmpty(exContainer.getUniqueSessionID())) + TransactionIDUtils.setSessionId(exContainer.getUniqueSessionID()); + + //log exception to technical log + logExceptionToTechnicalLog(exContainer.getExceptionThrown()); + + //remove session and transaction ID from thread + TransactionIDUtils.removeSessionId(); + TransactionIDUtils.removeTransactionId(); + } + } + + } catch (Exception e) { + Logger.info("Transaction info is not loadable. " + + "Key:" + entryKey + + " ErrorMsg:" + e.getMessage()); + + } + + transactionStorage.remove(entryKey); + Logger.info("Remove stored information with ID: " + entryKey + + " after timeout."); + + } catch (HibernateException e){ + Logger.warn("Transaction information with ID=" + entryKey + + " not removed after timeout! (Error during Database communication)", e); + } + + } + } } catch (Exception e) { - Logger.error("Session cleanUp FAILED!" , e); + Logger.error("Session/Transaction cleanUp FAILED!" , e); } @@ -72,6 +123,27 @@ public class AuthenticationSessionCleaner implements Runnable { } } + /** + * 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.info(loggedException.getMessage()); + + } + } + } + /** * start the sessionCleaner */ diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index e51f3e6c9..fd2e03afa 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -32,6 +32,7 @@ import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.ExceptionHandler; +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.advancedlogging.StatisticLogger; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; @@ -42,10 +43,12 @@ 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.db.ex.MOADatabaseException; 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; @@ -101,8 +104,12 @@ public abstract class AbstractController extends MOAIDAuthConstants { } protected void handleError(String errorMessage, Throwable exceptionThrown, - HttpServletRequest req, HttpServletResponse resp, String pendingRequestID) throws IOException { + HttpServletRequest req, HttpServletResponse resp, IRequest pendingReq) throws IOException { + String pendingRequestID = null; + if (pendingReq != null) + pendingRequestID = pendingReq.getRequestID(); + Throwable loggedException = null; Throwable extractedException = extractOriginalExceptionFromProcessException(exceptionThrown); @@ -127,8 +134,19 @@ public abstract class AbstractController extends MOAIDAuthConstants { //switch to protocol-finalize method to generate a protocol-specific error message //put exception into transaction store for redirect - String key = Random.nextRandom(); - transactionStorage.put(key, loggedException); + String key = Random.nextLongRandom(); + if (pendingReq != null) { + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR); + transactionStorage.put(key, + new ExceptionContainer(pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), loggedException)); + + } else { + transactionStorage.put(key, + new ExceptionContainer(null, + null, loggedException)); + + } //build up redirect URL String redirectURL = null; 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 index 7a4ee35fa..0ce7b0050 100644 --- 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 @@ -28,14 +28,14 @@ public abstract class AbstractProcessEngineSignalController extends AbstractCont 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."}); } - IRequest pendingReq = requestStorage.getPendingRequest(pendingRequestID); + 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}); @@ -60,7 +60,7 @@ public abstract class AbstractProcessEngineSignalController extends AbstractCont processEngine.signal(pendingReq); } catch (Exception ex) { - handleError(null, ex, req, resp, pendingRequestID); + handleError(null, ex, req, resp, pendingReq); } finally { //MOASessionDBUtils.closeSession(); 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 new file mode 100644 index 000000000..5e3fb5df6 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/data/ExceptionContainer.java @@ -0,0 +1,65 @@ +/* + * 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 class ExceptionContainer { + + private Throwable exceptionThrown = null; + private String uniqueSessionID = null; + private String uniqueTransactionID = null; + + /** + * + */ + public ExceptionContainer(String uniqueSessionID, String uniqueTransactionID, Throwable exception) { + this.uniqueSessionID = uniqueSessionID; + this.uniqueTransactionID = uniqueTransactionID; + 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; + } + + + +} 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 index 991c6a881..0da43d818 100644 --- 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 @@ -38,6 +38,7 @@ import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; 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.utils.MOAIDMessageProvider; +import at.gv.egovernment.moa.id.data.ExceptionContainer; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; @@ -66,15 +67,14 @@ public class ProtocolFinalizationController extends AbstractAuthProtocolModulCon if (errorid != null) { try { //load stored exception from database - Throwable throwable = transactionStorage.get(errorid, Throwable.class); - - if (throwable != null) { + ExceptionContainer container = transactionStorage.get(errorid, ExceptionContainer.class); + if (container != null) { //remove exception if it was found transactionStorage.remove(errorid); - if (pendingReq != null) { - revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.TRANSACTION_ERROR); - + Throwable throwable = container.getExceptionThrown(); + + if (pendingReq != null) { //build protocol-specific error message if possible buildProtocolSpecificErrorResponse(throwable, req, resp, pendingReq); 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 ff631a720..6778dc32e 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 @@ -23,6 +23,7 @@ package at.gv.egovernment.moa.id.storage; import java.io.Serializable; +import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -99,6 +100,17 @@ public class DBTransactionStorage implements ITransactionStorage { } } + public Object get(String key) throws MOADatabaseException { + AssertionStore element = searchInDatabase(key); + + if (element == null) + return null; + + return SerializationUtils.deserialize(element.getAssertion()); + + + } + public T get(String key, final Class clazz, long dataTimeOut) throws MOADatabaseException, AuthenticationException { AssertionStore element = searchInDatabase(key); @@ -134,10 +146,11 @@ public class DBTransactionStorage implements ITransactionStorage { } } - public void clean(Date now, long dataTimeOut) { + public List clean(Date now, long dataTimeOut) { Date expioredate = new Date(now.getTime() - dataTimeOut); List results; + List returnValues = new ArrayList();; Session session = MOASessionDBUtils.getCurrentSession(); synchronized (session) { @@ -146,22 +159,14 @@ public class DBTransactionStorage implements ITransactionStorage { query.setTimestamp("timeout", expioredate); results = query.list(); session.getTransaction().commit(); - - if (results.size() != 0) { - for(AssertionStore result : results) { - try { - cleanDelete(result); - Logger.info("Remove stored information with ID: " + result.getArtifact() - + " after timeout."); - - } catch (HibernateException e){ - Logger.warn("Sessioninformation with ID=" + result.getArtifact() - + " not removed after timeout! (Error during Database communication)", e); - } - - } - } } + + if (results != null) { + for (AssertionStore el : results) + returnValues.add(el.getArtifact()); + + } + return returnValues; } public void remove(String key) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java index 48283d2b6..fe959c39d 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java @@ -23,6 +23,7 @@ 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; @@ -50,6 +51,15 @@ public interface ITransactionStorage { */ public void put(String key, Object value) 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 * @@ -91,11 +101,12 @@ public interface ITransactionStorage { public void remove(String key); /** - * Clean-up the transaction storage + * 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 void clean(Date now, long dataTimeOut); + public List clean(Date now, long dataTimeOut); } -- cgit v1.2.3 From 4a347b1c7784e2c756c2bcae973d3b6da0ba8e62 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 31 Mar 2016 14:36:38 +0200 Subject: fix missing implementation in ExceptionContainer --- .../main/java/at/gv/egovernment/moa/id/data/ExceptionContainer.java | 5 ++++- .../java/at/gv/egovernment/moa/id/storage/DBTransactionStorage.java | 6 ++++++ .../java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java | 3 ++- 3 files changed, 12 insertions(+), 2 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 index 5e3fb5df6..1c6fdcb65 100644 --- 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 @@ -22,12 +22,15 @@ */ package at.gv.egovernment.moa.id.data; +import java.io.Serializable; + /** * @author tlenz * */ -public class ExceptionContainer { +public class ExceptionContainer implements Serializable { + private static final long serialVersionUID = 5355860753609684995L; private Throwable exceptionThrown = null; private String uniqueSessionID = null; private String uniqueTransactionID = null; 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 6778dc32e..c2b3b0fc5 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 @@ -242,6 +242,12 @@ public class DBTransactionStorage implements ITransactionStorage { element.setType(value.getClass().getName()); element.setDatatime(new Date()); + if (!Serializable.class.isInstance(value)) { + Logger.warn("Transaction-Storage can only store objects which implements the 'Seralizable' interface"); + throw new MOADatabaseException("Transaction-Storage can only store objects which implements the 'Seralizable' interface", null); + + } + //serialize the Assertion for Database storage byte[] data = SerializationUtils.serialize((Serializable) value); element.setAssertion(data); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java index fe959c39d..493f24ee8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/ITransactionStorage.java @@ -46,7 +46,8 @@ public interface ITransactionStorage { * 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 + * @param value Data object which should be stored. + * This data must implement the java.io.Serializable interface * @throws MOADatabaseException In case of store operation failed */ public void put(String key, Object value) throws MOADatabaseException; -- cgit v1.2.3 From 5481121cf1c33392b5ae599c42f670b563c16b1c Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Mon, 4 Apr 2016 11:49:19 +0200 Subject: add log-message to log MOA-SPSS initialization errors --- .../main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthInitializer.java | 1 + 1 file changed, 1 insertion(+) (limited to 'id/server/idserverlib/src/main/java/at') 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 a8b9509bc..d1cf3338a 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 @@ -136,6 +136,7 @@ public class MOAIDAuthInitializer { new IaikConfigurator().configure(config); } catch (at.gv.egovernment.moa.spss.server.config.ConfigurationException ex) { + Logger.error("MOA-SP initialization FAILED!", ex.getWrapped()); throw new ConfigurationException("config.10", new Object[] { ex .toString() }, ex); -- cgit v1.2.3 From 4b932484d66ef161bb547a419fdc32f04677fe57 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 7 Apr 2016 10:44:11 +0200 Subject: fix some possible problems with STORK configuration in config-GUI --- .../id/auth/parser/StartAuthentificationParameterParser.java | 2 +- .../id/config/auth/PropertyBasedAuthConfigurationProvider.java | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) (limited to 'id/server/idserverlib/src/main/java/at') 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 69c155c1e..140c7aebc 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 @@ -206,7 +206,7 @@ public class StartAuthentificationParameterParser extends MOAIDAuthConstants{ //validate SSO functionality - String domainIdentifier = authConfig.getSSOTagetIdentifier().trim(); + String domainIdentifier = authConfig.getSSOTagetIdentifier(); if (MiscUtil.isEmpty(domainIdentifier) && protocolReq.needSingleSignOnFunctionality()) { //do not use SSO if no Target is set Logger.warn("NO SSO-Target found in configuration. Single Sign-On is deaktivated!"); 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 210bda3e6..348b1c45a 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 @@ -738,13 +738,17 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide */ public String getSSOTagetIdentifier() throws ConfigurationException { try { - return configuration.getStringValue( + String value = configuration.getStringValue( MOAIDConfigurationConstants.GENERAL_AUTH_SSO_TARGET); - + if (MiscUtil.isNotEmpty(value)) + return value.trim(); + } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { Logger.warn("Single Sign-On Target can not be read from configuration.", e); - return null; + } + + return null; } /** -- cgit v1.2.3 From 581d87d939820b9e74130279692f2825baff6594 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 7 Apr 2016 16:23:18 +0200 Subject: add initial version of a virtual IDP REST URL rewrite filter --- .../interceptor/VHostUrlRewriteServletFilter.java | 185 +++++++++++++++++++++ .../at/gv/egovernment/moa/id/util/HTTPUtils.java | 11 ++ 2 files changed, 196 insertions(+) create mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/VHostUrlRewriteServletFilter.java (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/VHostUrlRewriteServletFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/VHostUrlRewriteServletFilter.java new file mode 100644 index 000000000..93d74d7ef --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/interceptor/VHostUrlRewriteServletFilter.java @@ -0,0 +1,185 @@ +/* + * 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.interceptor; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; + +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.FilterConfig; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; + +import org.springframework.context.ApplicationContext; + +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; + +/** + * @author tlenz + * + */ +public class VHostUrlRewriteServletFilter implements Filter { + + private static final String VHOST_PATH = "/vhost/"; + private static final String AUTHURL = "authURL"; + + + private ApplicationContext context = null; + + public VHostUrlRewriteServletFilter(ApplicationContext context) { + Logger.info("Register vHost Servelt Filter"); + this.context = context; + + } + + /* (non-Javadoc) + * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) + */ + @Override + public void init(FilterConfig filterConfig) throws ServletException { + + } + + /* (non-Javadoc) + * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) + */ + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest httpReq = (HttpServletRequest) request; + try { + AuthConfiguration authConfig = context.getBean(AuthConfiguration.class); + List configuredPublicURLPrefix = authConfig.getPublicURLPrefix(); + + //check if End-Point is valid + String publicURLString = HTTPUtils.extractAuthURLFromRequest(httpReq); + URL publicURL; + try { + publicURL = new URL(publicURLString); + + } catch (MalformedURLException e) { + Logger.error("IDP AuthenticationServiceURL Prefix is not a valid URL." + publicURLString, e); + throw new ConfigurationException("1299", null, e); + + } + + //check if virtual IDPs are enabled + if (!authConfig.isVirtualIDPsEnabled()) { + Logger.trace("Virtual IDPs are disabled. Use default IDP PublicURLPrefix from configuration: " + configuredPublicURLPrefix.get(0)); + httpReq.setAttribute(AUTHURL, configuredPublicURLPrefix.get(0)); + chain.doFilter(request, response); + + } else { + String authURLString = HTTPUtils.extractAuthServletPathFromRequest(httpReq); + 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); + + } + + 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 && + authURL.getPath().startsWith(configuredURL.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 { + httpReq.setAttribute(AUTHURL, resultURL.toExternalForm()); + + } + + String servletPath = httpReq.getServletPath(); + if (servletPath.startsWith(VHOST_PATH)) { + Logger.trace("Found V-IDP selection via REST URL ... "); + String vHostDescriptor = resultURL.toExternalForm().substring(0, publicURLString.length()); + String requestedServlet = authURLString.substring(0, vHostDescriptor.length()); + String newURL = publicURL.toExternalForm().concat(requestedServlet); + httpReq.setAttribute(AUTHURL, newURL); + httpReq.getRequestDispatcher(newURL).forward(httpReq, response); + + } else { + Logger.trace("Found V-IDP selection via Domain ..."); + chain.doFilter(request, response); + + } + + } + + } catch (ConfigurationException e) { + + + } + + } + + /* (non-Javadoc) + * @see javax.servlet.Filter#destroy() + */ + @Override + public void destroy() { + // TODO Auto-generated method stub + + } + +} 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 index d2499af9d..4cb6af127 100644 --- 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 @@ -173,6 +173,17 @@ public class HTTPUtils { } + /** + * Extract the IDP requested URL from authrequest + * + * @param req HttpServletRequest + * @return RequestURL 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; -- cgit v1.2.3 From 1e66fa62ef2114aa412e4c207c8180c18aa07a0b Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 8 Apr 2016 06:22:13 +0200 Subject: fix bug in PVP2 assertion builder. - https://docs.oasis-open.org/security/saml/v2.0/saml-profiles-2.0-os.pdf does not allow 'NotBefore' attribute in when 'Method' contains 'urn:oasis:names:tc:SAML:2.0:cm:bearer' (see 554 - 560 chapter 4.1.4.2) --- .../moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index 68301d000..483bcb1ec 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -436,7 +436,7 @@ public class PVP2AssertionBuilder implements PVPConstants { .createSAMLObject(SubjectConfirmationData.class); subjectConfirmationData.setInResponseTo(authnRequest.getID()); subjectConfirmationData.setNotOnOrAfter(new DateTime(authData.getSsoSessionValidTo().getTime())); - subjectConfirmationData.setNotBefore(date); +// subjectConfirmationData.setNotBefore(date); subjectConfirmationData.setRecipient(assertionConsumerService.getLocation()); -- cgit v1.2.3 From 41882a0c5601dda478c2749ac99c2087b864c912 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Fri, 8 Apr 2016 07:48:40 +0200 Subject: change logLevel to warn --- .../java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'id/server/idserverlib/src/main/java/at') diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java index fd2e03afa..d87480cc1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/AbstractController.java @@ -221,7 +221,7 @@ public abstract class AbstractController extends MOAIDAuthConstants { Logger.warn(loggedException.getMessage(), loggedException); } else { - Logger.info(loggedException.getMessage()); + Logger.warn(loggedException.getMessage()); } } -- cgit v1.2.3