From 5bc01dab26425144a41dbece04b642fb963e1315 Mon Sep 17 00:00:00 2001 From: Thomas Lenz Date: Thu, 2 Jul 2015 07:26:30 +0200 Subject: devel --- .../moa/id/advancedlogging/StatisticLogger.java | 99 +- .../moa/id/auth/AuthenticationServer.java | 317 --- .../moa/id/auth/builder/LoginFormBuilder.java | 38 +- .../StartAuthentificationParameterParser.java | 7 +- .../servlet/GenerateIFrameTemplateServlet.java | 8 +- .../moa/id/auth/servlet/GetForeignIDServlet.java | 325 --- .../id/auth/servlet/GetMISSessionIDServlet.java | 272 --- .../moa/id/auth/servlet/LogOutServlet.java | 5 +- .../moa/id/auth/servlet/PEPSConnectorServlet.java | 776 ------- .../PEPSConnectorWithLocalSigningServlet.java | 816 ------- .../moa/id/auth/servlet/RedirectServlet.java | 10 +- .../servlet/VerifyAuthenticationBlockServlet.java | 343 --- .../id/auth/servlet/VerifyCertificateServlet.java | 235 -- .../id/auth/servlet/VerifyIdentityLinkServlet.java | 279 --- .../moa/id/config/ConfigurationProviderImpl.java | 165 +- .../gv/egovernment/moa/id/config/OAParameter.java | 172 -- .../moa/id/config/auth/AuthConfigLoader.java | 46 +- .../moa/id/config/auth/AuthConfiguration.java | 41 +- .../id/config/auth/AuthConfigurationProvider.java | 2400 ++++++++++---------- .../moa/id/config/auth/IOAAuthParameters.java | 94 +- .../moa/id/config/auth/OAAuthParameter.java | 790 ++++--- .../PropertyBasedAuthConfigurationProvider.java | 204 +- .../config/auth/data/DynamicOAAuthParameters.java | 151 +- .../id/config/legacy/BuildFromLegacyConfig.java | 18 +- .../moa/id/config/stork/STORKConfig.java | 22 +- .../oauth20/protocol/OAuth20AuthRequest.java | 11 +- .../oauth20/protocol/OAuth20BaseRequest.java | 12 +- .../oauth20/protocol/OAuth20TokenRequest.java | 10 +- .../protocols/pvp2x/binding/RedirectBinding.java | 31 +- .../protocols/pvp2x/config/PVPConfiguration.java | 101 +- .../pvp2x/metadata/MOAMetadataProvider.java | 348 +-- .../pvp2x/verification/EntityVerifier.java | 40 +- .../pvp2x/verification/SAMLVerificationEngine.java | 50 +- .../InterfederatedIDPPublicServiceFilter.java | 8 +- .../protocols/saml1/SAML1AuthenticationServer.java | 6 +- .../moa/id/protocols/saml1/SAML1Protocol.java | 5 +- .../moa/id/protocols/saml1/SAML1RequestImpl.java | 4 +- .../id/protocols/stork2/AttributeCollector.java | 4 - .../protocols/stork2/AttributeProviderFactory.java | 8 +- .../moa/id/util/ParamValidatorUtils.java | 10 +- .../resources/properties/id_messages_de.properties | 3 +- 41 files changed, 2632 insertions(+), 5652 deletions(-) delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java delete mode 100644 id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java (limited to 'id/server/idserverlib/src/main') 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 cd1acaa8c..67547d8a2 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 @@ -26,6 +26,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Date; +import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; @@ -43,18 +44,15 @@ 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.db.ConfigurationDBRead; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; import at.gv.egovernment.moa.id.commons.db.StatisticLogDBUtils; -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.OnlineApplication; 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.moduls.IRequest; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; @@ -106,20 +104,27 @@ public class StatisticLogger { if ( isAktive && protocolRequest != null && authData != null) { - OnlineApplication dbOA = ConfigurationDBRead.getOnlineApplication(protocolRequest.getOAURL()); - - if (dbOA == null) { - Logger.warn("Advanced logging failed: OA can not be found in database."); + OAAuthParameter dbOA = null; + try { + dbOA = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(protocolRequest.getOAURL()); + + 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); return; } - + StatisticLog dblog = new StatisticLog(); //set actual date and time dblog.setTimestamp(new Date()); //set OA databaseID - dblog.setOaID(dbOA.getHjid()); + //dblog.setOaID(dbOA.getHjid()); //log basic AuthInformation dblog.setOaurlprefix(protocolRequest.getOAURL()); @@ -258,40 +263,46 @@ public class StatisticLogger { dblog.setProtocoltype(errorRequest.requestedModule()); dblog.setProtocolsubtype(errorRequest.requestedAction()); - OnlineApplication dbOA = ConfigurationDBRead.getOnlineApplication(errorRequest.getOAURL()); - if (dbOA != null) { - dblog.setOafriendlyName(dbOA.getFriendlyName()); - dblog.setOatarget(dbOA.getTarget()); - dblog.setOaID(dbOA.getHjid()); - dblog.setBusinessservice(isBusinessService(dbOA)); - } + 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()); - if (moasession != null) { - if (MiscUtil.isNotEmpty(moasession.getBkuURL())) { - dblog.setBkuurl(moasession.getBkuURL()); - dblog.setBkutype(findBKUType(moasession.getBkuURL(), dbOA)); - } + AuthenticationSession moasession = AuthenticationSessionStoreage.getSessionWithPendingRequestID(errorRequest.getRequestID()); + if (moasession != null) { + if (MiscUtil.isNotEmpty(moasession.getBkuURL())) { + dblog.setBkuurl(moasession.getBkuURL()); + dblog.setBkutype(findBKUType(moasession.getBkuURL(), dbOA)); + } - dblog.setMandatelogin(moasession.getUseMandate()); - } + dblog.setMandatelogin(moasession.getUseMandate()); + } - generateErrorLogFormThrowable(throwable, dblog); - - ConfigurationDBUtils.closeSession(); + generateErrorLogFormThrowable(throwable, dblog); + + ConfigurationDBUtils.closeSession(); - try { - StatisticLogDBUtils.saveOrUpdate(dblog); + try { + StatisticLogDBUtils.saveOrUpdate(dblog); - } catch (MOADatabaseException e) { - Logger.warn("Statistic Log can not be stored into Database", e); + } 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(OnlineApplication oa) { + private boolean isBusinessService(OAAuthParameter dbOA) { - if (oa.getType().equals("businessService")) + if (dbOA.getOaType().equals("businessService")) return true; else return false; @@ -352,23 +363,17 @@ public class StatisticLogger { } - private String findBKUType(String bkuURL, OnlineApplication dbOA) { + private String findBKUType(String bkuURL, OAAuthParameter dbOA) { if (dbOA != null) { - AuthComponentOA oaAuth = dbOA.getAuthComponentOA(); - if (oaAuth != null) { - BKUURLS bkuurls = oaAuth.getBKUURLS(); - if (bkuurls != null) { - if (bkuURL.equals(bkuurls.getHandyBKU())) - return IOAAuthParameters.HANDYBKU; + if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameter.HANDYBKU))) + return IOAAuthParameters.HANDYBKU; - if (bkuURL.equals(bkuurls.getLocalBKU())) - return IOAAuthParameters.LOCALBKU; + if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameter.LOCALBKU))) + return IOAAuthParameters.LOCALBKU; - if (bkuURL.equals(bkuurls.getOnlineBKU())) - return IOAAuthParameters.ONLINEBKU; - } - } + if (bkuURL.equals(dbOA.getBKUURL(OAAuthParameter.ONLINEBKU))) + return IOAAuthParameters.ONLINEBKU; } Logger.trace("Staticic Log search BKUType from DefaultBKUs"); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index 90e094a03..f62c21ed9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -8,16 +8,9 @@ import iaik.x509.X509ExtensionInitException; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; -import java.io.StringWriter; import java.io.UnsupportedEncodingException; -import java.math.BigInteger; -import java.net.URL; -import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.cert.CertificateException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -//import java.security.cert.CertificateFactory; import java.util.Calendar; import java.util.Date; import java.util.List; @@ -25,22 +18,13 @@ import java.util.Map; import java.util.Vector; import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; -import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; import org.apache.xpath.XPathAPI; -import org.opensaml.common.IdentifierGenerator; -import org.opensaml.common.impl.SecureRandomIdentifierGenerator; import org.opensaml.xml.util.Base64; import org.opensaml.xml.util.XMLHelper; -import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -71,8 +55,6 @@ import at.gv.egovernment.moa.id.auth.invoke.SignatureVerificationInvoker; import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; import at.gv.egovernment.moa.id.auth.parser.InfoboxReadResponseParser; import at.gv.egovernment.moa.id.auth.parser.VerifyXMLSignatureResponseParser; -import at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet; -import at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet; import at.gv.egovernment.moa.id.auth.validator.CreateXMLSignatureResponseValidator; import at.gv.egovernment.moa.id.auth.validator.IdentityLinkValidator; import at.gv.egovernment.moa.id.auth.validator.VerifyXMLSignatureResponseValidator; @@ -86,14 +68,11 @@ 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.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.config.stork.CPEPS; -import at.gv.egovernment.moa.id.config.stork.STORKConfig; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; 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.id.util.VelocityProvider; import at.gv.egovernment.moa.id.util.XMLUtil; import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; import at.gv.egovernment.moa.logging.LogMsg; @@ -111,21 +90,6 @@ 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 eu.stork.oasisdss.api.AdditionalProfiles; -import eu.stork.oasisdss.api.ApiUtils; -import eu.stork.oasisdss.api.exceptions.ApiUtilsException; -import eu.stork.oasisdss.api.Profiles; -import eu.stork.oasisdss.api.QualityLevels; -import eu.stork.oasisdss.api.SignatureTypes; -import eu.stork.oasisdss.profile.AnyType; -import eu.stork.oasisdss.profile.DocumentType; -import eu.stork.oasisdss.profile.SignRequest; -import eu.stork.peps.auth.commons.PEPSUtil; -import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.commons.PersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAuthnRequest; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.exceptions.STORKSAMLEngineException; /** * API for MOA ID Authentication Service.
{@link AuthenticationSession} is @@ -1668,287 +1632,6 @@ public class AuthenticationServer implements MOAIDAuthConstants { } - /** - * Starts a MOA-ID authentication process using STORK - * - * @param req HttpServletRequest - * @param resp HttpServletResponse - * @param ccc Citizen country code - * @param oaURL URL of the online application - * @param target Target parameter - * @param targetFriendlyName Friendly Name of Target - * @param authURL Authentication URL - * @param sourceID SourceID parameter - * @throws MOAIDException - * @throws AuthenticationException - * @throws WrongParametersException - * @throws ConfigurationException - */ - public static void startSTORKAuthentication( - HttpServletRequest req, - HttpServletResponse resp, - AuthenticationSession moasession) throws MOAIDException, AuthenticationException, WrongParametersException, ConfigurationException { - - if (moasession == null) { - throw new AuthenticationException("auth.18", new Object[]{}); - } - - //read configuration paramters of OA - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); - if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[]{moasession.getPublicOAURLPrefix()}); - - //Start of STORK Processing - STORKConfig storkConfig = AuthConfigurationProviderFactory.getInstance().getStorkConfig(); - - CPEPS cpeps = storkConfig.getCPEPS(moasession.getCcc()); - - Logger.debug("Preparing to assemble STORK AuthnRequest with the following values:"); - String destination = cpeps.getPepsURL().toExternalForm(); - Logger.debug("C-PEPS URL: " + destination); - - - String issuerValue = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); - // String acsURL = new DataURLBuilder().buildDataURL(issuerValue, - // PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN, moasession.getSessionID()); - - - String providerName = oaParam.getFriendlyName(); - Logger.debug("Issuer value: " + issuerValue); - - // prepare collection of required attributes - // - attributes for online application - List attributesFromConfig = oaParam.getRequestedAttributes(); - - // - prepare attribute list - PersonalAttributeList attributeList = new PersonalAttributeList(); - - // - fill container - for (OAStorkAttribute current : attributesFromConfig) { - PersonalAttribute newAttribute = new PersonalAttribute(); - newAttribute.setName(current.getName()); - - boolean globallyMandatory = false; - for (StorkAttribute currentGlobalAttribute : storkConfig.getStorkAttributes()) - if (current.getName().equals(currentGlobalAttribute.getName())) { - globallyMandatory = BooleanUtils.isTrue(currentGlobalAttribute.isMandatory()); - break; - } - - newAttribute.setIsRequired(current.isMandatory() || globallyMandatory); - attributeList.add(newAttribute); - } - - // add sign request - PersonalAttribute newAttribute = new PersonalAttribute(); - newAttribute.setName("signedDoc"); - newAttribute.setIsRequired(true); - List value = new ArrayList(); - - Logger.debug("PEPS supports XMLSignatures:"+cpeps.isXMLSignatureSupported()); - String acsURL; - if(cpeps.isXMLSignatureSupported())//Send SignRequest to PEPS - { - //solve Problem with sessionIDs - acsURL = issuerValue + PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; - - value.add(generateDssSignRequest(CreateXMLSignatureRequestBuilder.buildForeignIDTextToBeSigned("wie im Signaturzertifikat (as in my signature certificate)", oaParam, moasession), - "application/xhtml+xml", moasession.getCcc())); - newAttribute.setValue(value); - attributeList.add(newAttribute); - - // TODO[branch]: STORK AuthReq CPEPS acsURL "/PEPSConnector" - } - else//Process SignRequest locally with MOCCA - { - String target = moasession.getTarget(); - moasession.setTarget("AT"); - String signedDoc = (generateDssSignRequest(CreateXMLSignatureRequestBuilder.buildForeignIDTextToBeSigned("wie im Signaturzertifikat (as in my signature certificate)", oaParam, moasession), - "application/xhtml+xml", "AT"));//moasession.getCcc() - moasession.setTarget(target); - Logger.warn("signedDoc to store:"+signedDoc); - //attributeList.add(newAttribute); - - //store SignRequest for later... - moasession.setSignedDoc(signedDoc); - - acsURL = issuerValue + PEPSConnectorWithLocalSigningServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; - // TODO[branch]: STORK AuthReq acsURL "/PEPSConnectorWithLocalSigning" - try { - AuthenticationSessionStoreage.storeSession(moasession); - } catch (MOADatabaseException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL); - - if (Logger.isDebugEnabled()) { - Logger.debug("The following attributes are requested for this OA:"); - for (OAStorkAttribute logReqAttr : attributesFromConfig) - Logger.debug("OA specific requested attribute: " + logReqAttr.getName() + ", isRequired: " + logReqAttr.isMandatory()); - } - - //TODO: check Target in case of SSO!! - String spSector = StringUtils.isEmpty(moasession.getTarget()) ? "Business" : moasession.getTarget(); - String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName(); - String spApplication = spInstitution; - String spCountry = "AT"; // intentionally set AT - the flow is limited on that use case only - - //generate AuthnRquest - STORKAuthnRequest authnRequest = new STORKAuthnRequest(); - authnRequest.setDestination(destination); - authnRequest.setAssertionConsumerServiceURL(acsURL);//PEPSConnectorWithLocalSigning - authnRequest.setProviderName(providerName); - authnRequest.setIssuer(issuerValue); - authnRequest.setQaa(oaParam.getQaaLevel()); - authnRequest.setSpInstitution(spInstitution); - authnRequest.setSpCountry(spCountry); - authnRequest.setSpApplication(spApplication); - authnRequest.setSpSector(spSector); - authnRequest.setPersonalAttributeList(attributeList); - - //TODO change - authnRequest.setEIDCrossBorderShare(true); - authnRequest.setEIDCrossSectorShare(true); - authnRequest.setEIDSectorShare(true); - - authnRequest.setCitizenCountryCode(moasession.getCcc()); - - Logger.debug("STORK AuthnRequest succesfully assembled."); - - STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("outgoing"); - - if (samlEngine == null) { - Logger.error("Could not initalize STORK SAML engine."); - throw new MOAIDException("stork.00", null); - } - - try { - authnRequest = samlEngine.generateSTORKAuthnRequest(authnRequest); - } catch (STORKSAMLEngineException e) { - Logger.error("Could not sign STORK SAML AuthnRequest.", e); - throw new MOAIDException("stork.00", null); - } - - Logger.info("STORK AuthnRequest successfully signed!"); - - //validate AuthnRequest - try { - samlEngine.validateSTORKAuthnRequest(authnRequest.getTokenSaml()); - } catch (STORKSAMLEngineException e) { - Logger.error("STORK SAML AuthnRequest not valid.", e); - throw new MOAIDException("stork.01", null); - } - - Logger.debug("STORK AuthnRequest successfully internally validated."); - - //send - moasession.setStorkAuthnRequest(authnRequest); - - // do PEPS-conform logging for easier evaluation - try { - // 2015-03-12 16:44:27.144#S-PEPS receives request from SP#spurl#spepsurl#spapp#spdomain#citizen country#qaa#msghash#msg_id id1# - Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS receives request from SP#" + - moasession.getPublicOAURLPrefix() + "#" + issuerValue + "#" + spApplication + "#" + - new URL(moasession.getPublicOAURLPrefix()).getHost() + "#" + moasession.getCcc() + "#" + oaParam.getQaaLevel() + - "#_hash_#" + moasession.getProcessInstanceId() + "#"); - } catch (Exception e1) { - Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage()); - } - - AuthenticationSessionStoreage.changeSessionID(moasession, authnRequest.getSamlId()); - - - Logger.info("Preparing to send STORK AuthnRequest."); - Logger.info("prepared STORKAuthnRequest: "); - Logger.info(new String(authnRequest.getTokenSaml())); - - try { - Logger.trace("Initialize VelocityEngine..."); - - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/saml2-post-binding-moa.vm"); - VelocityContext context = new VelocityContext(); - context.put("SAMLRequest", PEPSUtil.encodeSAMLToken(authnRequest.getTokenSaml())); - context.put("RelayState", moasession.getSessionID()); - context.put("action", destination); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - // TODO[branch]: SAML2 Form Submit to CPEPS, response to acsURL Servlet - - resp.setContentType("text/html;charset=UTF-8"); - resp.getOutputStream().write(writer.toString().getBytes("UTF-8")); - - } catch (Exception e) { - Logger.error("Error sending STORK SAML AuthnRequest.", e); - throw new MOAIDException("stork.02", new Object[]{destination}); - - } - - Logger.info("STORK AuthnRequest successfully successfully prepared for client with target location: " + authnRequest.getDestination()); - - // do PEPS-conform logging for easier evaluation - try { - // 2015-03-12 16:44:27.144#S-PEPS generates request to C-PEPS#spepsurl#cpepsurl#spapp#spdomain#citizen country#qaa#msghash#msg_id id1#id2# - Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS generates request to C-PEPS#" + - issuerValue + "#" + destination + "#" + spApplication + "#" + - new URL(moasession.getPublicOAURLPrefix()).getHost() + "#" + moasession.getCcc() + "#" + oaParam.getQaaLevel() + - "#_hash_#" + moasession.getProcessInstanceId() + "#" + authnRequest.getSamlId() + "#"); - } catch (Exception e1) { - Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage()); - } - } - - private static String generateDssSignRequest(String text, String mimeType, String citizenCountry) { - IdentifierGenerator idGenerator; - try { - idGenerator = new SecureRandomIdentifierGenerator(); - - DocumentType doc = new DocumentType(); - doc.setBase64XML(text.getBytes("UTF-8")); - doc.setID(idGenerator.generateIdentifier()); - - SignRequest request = new SignRequest(); - request.setInputDocuments(ApiUtils.createInputDocuments(doc)); - - String id = idGenerator.generateIdentifier(); - request.setRequestID(id); - request.setDocUI(id); - - request.setProfile(Profiles.XADES_BES.toString()); - request.setNumberOfSigners(BigInteger.ONE); - request.setTargetCountry(citizenCountry); - - // no, no todo. PEPS will alter this value anyhow. - request.setReturnURL("http://invalid_return"); - - AnyType required = new AnyType(); - required.getAny().add(ApiUtils.createSignatureType(SignatureTypes.XMLSIG_RFC3275.toString())); - required.getAny().add(ApiUtils.createAdditionalProfile(AdditionalProfiles.XADES.toString())); - required.getAny().add(ApiUtils.createQualityRequirements(QualityLevels.QUALITYLEVEL_QUALIFIEDSIG)); - required.getAny().add(ApiUtils.createIncludeObject(doc)); - request.setOptionalInputs(required); - - return IOUtils.toString(ApiUtils.marshalToInputStream(request)); - } catch (NoSuchAlgorithmException e) { - Logger.error("Cannot generate id", e); - throw new RuntimeException(e); - } catch (ApiUtilsException e) { - Logger.error("Could not create SignRequest", e); - throw new RuntimeException(e); - } catch (DOMException e) { - Logger.error("Could not create SignRequest", e); - throw new RuntimeException(e); - } catch (IOException e) { - Logger.error("Could not create SignRequest", e); - throw new RuntimeException(e); - } - } - /** * Extracts an X509 Certificate out of an XML signagture element * 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 a8e5a4253..35717af4d 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 @@ -29,17 +29,15 @@ import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.URI; -import java.util.List; import org.apache.commons.io.IOUtils; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; -import at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS; 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.protocols.saml1.SAML1Protocol; import at.gv.egovernment.moa.id.util.FormBuildUtils; import at.gv.egovernment.moa.logging.Logger; @@ -153,26 +151,20 @@ public class LoginFormBuilder { if (oaParam.isShowStorkLogin()) { String pepslist = ""; - List cpepsList = null; - try { - cpepsList = ConfigurationDBRead.getMOAIDConfiguration().getAuthComponentGeneral().getForeignIdentities().getSTORK().getCPEPS(); - - for (CPEPS current : oaParam.getPepsList()) - // check if master config has changed... - if(cpepsList != null && cpepsList.contains(current)) { - 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); + 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) { 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 89e2eac14..a26dec969 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 @@ -34,7 +34,6 @@ 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.dao.config.TemplateType; 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; @@ -224,14 +223,14 @@ public class StartAuthentificationParameterParser implements MOAIDAuthConstants{ if (MiscUtil.isEmpty(templateURL)) { - List templateURLList = oaParam.getTemplateURL(); + List templateURLList = oaParam.getTemplateURL(); List defaulTemplateURLList = AuthConfigurationProviderFactory.getInstance().getSLRequestTemplates(); if ( templateURLList != null && templateURLList.size() > 0 - && MiscUtil.isNotEmpty(templateURLList.get(0).getURL()) ) { + && MiscUtil.isNotEmpty(templateURLList.get(0)) ) { templateURL = FileUtils.makeAbsoluteURL( - oaParam.getTemplateURL().get(0).getURL(), + oaParam.getTemplateURL().get(0), AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir()); Logger.info("No SL-Template in request, load SL-Template from OA configuration (URL: " + templateURL + ")"); 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 d0c7118ca..5802ce3b9 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 @@ -38,7 +38,6 @@ import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.registration.ModuleRegistration; import at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.TemplateType; 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; @@ -48,7 +47,6 @@ import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol; import at.gv.egovernment.moa.id.process.ExecutionContextImpl; -import at.gv.egovernment.moa.id.process.ProcessInstance; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; @@ -123,10 +121,10 @@ public class GenerateIFrameTemplateServlet extends AuthServlet { //search for OA specific template String templateURL = null; - List oaTemplateURLList = oaParam.getTemplateURL(); + List oaTemplateURLList = oaParam.getTemplateURL(); if ( oaTemplateURLList != null && oaTemplateURLList.size() > 0 - && MiscUtil.isNotEmpty(oaTemplateURLList.get(0).getURL()) ) { - templateURL = oaTemplateURLList.get(0).getURL(); + && MiscUtil.isNotEmpty(oaTemplateURLList.get(0)) ) { + templateURL = oaTemplateURLList.get(0); } else { templateURL = AuthConfigurationProviderFactory.getInstance().getSLRequestTemplates(bkuid); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java deleted file mode 100644 index 41c2a9c6a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java +++ /dev/null @@ -1,325 +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.ByteArrayInputStream; -import java.io.IOException; -import java.security.cert.CertificateException; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.transform.TransformerException; - -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.lang.StringEscapeUtils; -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.data.CreateXMLSignatureResponse; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; -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.WrongParametersException; -import at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetForeignIDTask; -import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser; -import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; -import at.gv.egovernment.moa.id.client.SZRGWClientException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -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.DOMUtils; -import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; - -/** - * Servlet requested for getting the foreign eID - * provided by the security layer implementation. - * Utilizes the {@link AuthenticationServer}. - * @deprecated Use {@link GetForeignIDTask} instead. - * - */ -public class GetForeignIDServlet extends AuthServlet { - - /** - * - */ - private static final long serialVersionUID = -3415644214702379483L; - -/** - * Constructor for GetForeignIDServlet. - */ - public GetForeignIDServlet() { - super(); - } - - /** - * GET requested by security layer implementation to verify - * that data URL resource is available. - * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse) - */ - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - super.doGet(req, resp); - } - - /** - * Verifies the identity link and responds with a new - * CreateXMLSignatureRequest. - *
- * Request parameters: - *
    - *
  • MOASessionID: ID of associated authentication session
  • - *
  • XMLResponse: <InfoboxReadResponse>
  • - *
- * Response: - *
    - *
  • Content type: "text/xml"
  • - *
  • Content: see return value of {@link AuthenticationServer#verifyIdentityLink}
  • - *
  • Error status: 500 - *
- * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) - */ - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - Logger.debug("POST GetForeignIDServlet"); - - Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); - - 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); - - Map parameters; - - String pendingRequestID = null; - - try - { - parameters = getParameters(req); - } catch (FileUploadException e) - { - Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - } - String sessionID = req.getParameter(PARAM_SESSIONID); - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - - String redirectURL = null; - AuthenticationSession session = null; - try { - String xmlCreateXMLSignatureResponse = (String)parameters.get(PARAM_XMLRESPONSE); - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("GetForeignID", PARAM_SESSIONID, "auth.12"); - if (!ParamValidatorUtils.isValidXMLDocument(xmlCreateXMLSignatureResponse)) - throw new WrongParametersException("GetForeignID", PARAM_XMLRESPONSE, "auth.12"); - - session = AuthenticationServer.getSession(sessionID); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.debug(xmlCreateXMLSignatureResponse); - - CreateXMLSignatureResponse csresp = - new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse).parseResponseDsig(); - - try { - String serializedAssertion = DOMUtils.serializeNode(csresp - .getDsigSignature()); - session.setAuthBlock(serializedAssertion); - - } catch (TransformerException e) { - throw new ParseException("parser.04", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); - - } catch (IOException e) { - throw new ParseException("parser.04", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); - - } - - Element signature = csresp.getDsigSignature(); - - try { - session.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature)); - } catch (CertificateException e) { - Logger.error("Could not extract certificate from CreateXMLSignatureResponse"); - throw new MOAIDException("auth.14", null); - } - - // make SZR request to the identity link - CreateIdentityLinkResponse response = AuthenticationServer.getInstance().getIdentityLink(signature); - - - if (null != response.getErrorResponse()){ - // TODO fix exception parameter - throw new SZRGWClientException("service.08", (String)response.getErrorResponse().getErrorCode(), - (String)response.getErrorResponse().getInfo()); - } - else { - IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(new ByteArrayInputStream(response.getIdentityLink())); - IdentityLink identitylink = ilParser.parseIdentityLink(); - session.setIdentityLink(identitylink); - - //set QAA Level four in case of card authentifcation - session.setQAALevel(PVPConstants.STORK_QAA_1_4); - - String samlArtifactBase64 = - AuthenticationServer.getInstance().getForeignAuthenticationData(session); - - - //session is implicit stored in changeSessionID!!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.info("Changed MOASession " + sessionID + " to Session " + newMOASessionID); - Logger.info("Daten angelegt zu MOASession " + newMOASessionID); - - if (!samlArtifactBase64.equals("Redirect to Input Processor")) { - /*redirectURL = session.getOAURLRequested(); - if (!session.getBusinessService()) { - redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8")); - } - redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8")); - redirectURL = resp.encodeRedirectURL(redirectURL);*/ - - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), - ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), newMOASessionID); - redirectURL = resp.encodeRedirectURL(redirectURL); - - } else { - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, newMOASessionID); - - } - - try { - AuthenticationSessionStoreage.storeSession(session); - } catch (MOADatabaseException e) { - throw new MOAIDException("Session store error", null); - } - - - resp.setContentType("text/html"); - resp.setStatus(302); - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - } - - } - catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("GetForeignIDServlet has an interal Error.", e); - - } - } - - - - - - /** - * Builds the szrgw:GetIdentityLinkRequest fuer the SZR-GW - * @param givenname - * @param familyname - * @param birthday - * @return - */ -// private static Document buildGetIdentityLinkRequest(X509Certificate cert) { -// -// try { -// byte[] certbyte = cert.getEncoded(); -// String certstring = Base64.encode(certbyte); -// -// DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance(); -// factory.setNamespaceAware(true); -// DocumentBuilder builder = factory.newDocumentBuilder(); -// Document doc = builder.newDocument(); -// -// Element getIdentityLink = doc.createElementNS(SZRGWConstants.SZRGW_REQUEST_NS, "szrgw:GetIdentityLinkRequest"); -// getIdentityLink.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:szrgw", SZRGWConstants.SZRGW_REQUEST_NS); -// doc.appendChild(getIdentityLink); -// -// Element x509certificate = doc.createElementNS(SZRGWConstants.SZRGW_REQUEST_NS, "szrgw:X509Certificate"); -// getIdentityLink.appendChild(x509certificate); -// Text certbase64 = doc.createTextNode(certstring); -// x509certificate.appendChild(certbase64); -// -// return doc; -// } catch (ParserConfigurationException e) { -// e.printStackTrace(); -// } catch (CertificateEncodingException e) { -// e.printStackTrace(); -// } -// return null; -// -// } -// -// /** -// * Checks a parameter. -// * @param param parameter -// * @return true if the parameter is null or empty -// */ -// 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/GetMISSessionIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java deleted file mode 100644 index f2b788e26..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java +++ /dev/null @@ -1,272 +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 iaik.pki.PKIException; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; - -import javax.net.ssl.SSLSocketFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.parsers.ParserConfigurationException; - -import org.apache.commons.lang.StringEscapeUtils; -import org.xml.sax.SAXException; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.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.internal.tasks.GetMISSessionIDTask; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -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.moduls.ModulUtils; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.SSLUtils; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISMandate; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; - -/** - * Servlet requested for getting the foreign eID provided by the security layer - * implementation. Utilizes the {@link AuthenticationServer}. - * @deprecated Use {@link GetMISSessionIDTask} instead. - */ -public class GetMISSessionIDServlet extends AuthServlet { - - /** - * - */ - private static final long serialVersionUID = 4666952867085392597L; - - /** - * Constructor for GetMISSessionIDServlet. - */ - public GetMISSessionIDServlet() { - super(); - } - - /** - * GET requested by security layer implementation to verify that data URL - * resource is available. - * - * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, - * HttpServletResponse) - */ - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - doPost(req, resp); - - // Logger.debug("GET GetMISSessionIDServlet"); - // - // 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); - } - - /** - * Gets the signer certificate from the InfoboxReadRequest and responds with - * a new CreateXMLSignatureRequest.
- * Request parameters: - *
    - *
  • MOASessionID: ID of associated authentication session
  • - *
  • XMLResponse: <InfoboxReadResponse>
  • - *
- * - * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, - * HttpServletResponse) - */ - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - Logger.debug("POST GetMISSessionIDServlet"); - - Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); - - 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); - - // Map parameters; - // try - // { - // parameters = getParameters(req); - // } catch (FileUploadException e) - // { - // Logger.error("Parsing mulitpart/form-data request parameters failed: " - // + e.getMessage()); - // throw new IOException(e.getMessage()); - // } - - String sessionID = req.getParameter(PARAM_SESSIONID); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - - AuthenticationSession session = null; - String pendingRequestID = null; - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyCertificate", - PARAM_SESSIONID, "auth.12"); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - session = AuthenticationServer.getSession(sessionID); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - String misSessionID = session.getMISSessionID(); - - AuthConfiguration authConf = AuthConfigurationProviderFactory - .getInstance(); - ConnectionParameter connectionParameters = authConf - .getOnlineMandatesConnectionParameter(); - SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory( - AuthConfigurationProviderFactory.getInstance(), - connectionParameters); - - List list = MISSimpleClient.sendGetMandatesRequest( - connectionParameters.getUrl(), misSessionID, sslFactory); - - if (list == null || list.size() == 0) { - Logger.error("Keine Vollmacht gefunden."); - throw new AuthenticationException("auth.15", null); - } - - // for now: list contains only one element - MISMandate mandate = (MISMandate) list.get(0); - - // TODO[tlenz]: UTF-8 ? - String sMandate = new String(mandate.getMandate()); - if (sMandate == null || sMandate.compareToIgnoreCase("") == 0) { - Logger.error("Mandate is empty."); - throw new AuthenticationException("auth.15", - new Object[] { GET_MIS_SESSIONID }); - } - - //check if it is a parsable XML - byte[] byteMandate = mandate.getMandate(); - // TODO[tlenz]: UTF-8 ? - String stringMandate = new String(byteMandate); - DOMUtils.parseDocument(stringMandate, false, - null, null).getDocumentElement(); - - // extract RepresentationType - AuthenticationServer.getInstance().verifyMandate(session, mandate); - - session.setMISMandate(mandate); - session.setAuthenticatedUsed(false); - session.setAuthenticated(true); - - //set QAA Level four in case of card authentifcation - session.setQAALevel(PVPConstants.STORK_QAA_1_4); - - String oldsessionID = session.getSessionID(); - - //Session is implicite stored in changeSessionID!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); - Logger.info("Daten angelegt zu MOASession " + newMOASessionID); - - String redirectURL = new DataURLBuilder().buildDataURL( - session.getAuthURL(), - ModulUtils.buildAuthURL(session.getModul(), - session.getAction(), pendingRequestID), newMOASessionID); - redirectURL = resp.encodeRedirectURL(redirectURL); - - resp.setContentType("text/html"); - resp.setStatus(302); - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (GeneralSecurityException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (PKIException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (SAXException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (ParserConfigurationException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("MISMandateValidation has an interal Error.", e); - - } - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} 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 8981566eb..77675175e 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 @@ -53,10 +53,9 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; 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; @@ -90,7 +89,7 @@ public class LogOutServlet extends AuthServlet { } else { //return an error if RedirectURL is not a active Online-Applikation - OnlineApplication oa = ConfigurationDBRead.getActiveOnlineApplication(redirectUrl); + 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 = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java deleted file mode 100644 index ed4ef1f5a..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ /dev/null @@ -1,776 +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 iaik.x509.X509Certificate; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.net.URL; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Properties; - -import javax.activation.DataSource; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.transform.stream.StreamSource; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.opensaml.saml2.core.StatusCode; -import org.w3c.dom.Element; -import org.w3c.dom.Node; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.data.IdentityLink; -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.parser.IdentityLinkAssertionParser; -import at.gv.egovernment.moa.id.auth.stork.STORKException; -import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -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.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; -import at.gv.egovernment.moa.id.util.VelocityProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.egovernment.moa.util.StringUtils; -import at.gv.egovernment.moa.util.XPathUtils; -import at.gv.util.xsd.xmldsig.SignatureType; -import at.gv.util.xsd.xmldsig.X509DataType; -import eu.stork.oasisdss.api.ApiUtils; -import eu.stork.oasisdss.api.LightweightSourceResolver; -import eu.stork.oasisdss.api.exceptions.ApiUtilsException; -import eu.stork.oasisdss.api.utils.ByteArrayDataSource; -import eu.stork.oasisdss.profile.DocumentType; -import eu.stork.oasisdss.profile.DocumentWithSignature; -import eu.stork.oasisdss.profile.SignRequest; -import eu.stork.oasisdss.profile.SignResponse; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PEPSUtil; -import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.commons.PersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAttrQueryRequest; -import eu.stork.peps.auth.commons.STORKAuthnRequest; -import eu.stork.peps.auth.commons.STORKAuthnResponse; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.exceptions.STORKSAMLEngineException; - -import eu.stork.documentservice.DocumentService; -import eu.stork.documentservice.data.DatabaseConnectorMySQLImpl; -import javax.xml.namespace.QName; -import javax.xml.ws.Service; -import javax.xml.ws.soap.SOAPBinding; -import javax.xml.ws.BindingProvider; - - -/** - * Endpoint for receiving STORK response messages - * @deprecated Use {@link at.gv.egovernment.moa.id.auth.modules.stork.tasks.PepsConnectorTask} instead. - */ -public class PEPSConnectorServlet extends AuthServlet { - - private static final long serialVersionUID = 1L; - - public static final String PEPSCONNECTOR_SERVLET_URL_PATTERN = "/PEPSConnector"; - - private String dtlUrl = null; - - - public PEPSConnectorServlet() - { - super(); - - try { - AuthConfiguration authConfigurationProvider = AuthConfigurationProviderFactory.getInstance(); - dtlUrl = authConfigurationProvider.getDocumentServiceUrl(); - Logger.info ("PEPSConnectorServlet, using dtlUrl:"+dtlUrl); - } catch (Exception e) { - dtlUrl = "http://testvidp.buergerkarte.at/DocumentService/DocumentService"; - e.printStackTrace(); - Logger.error("Loading documentservice url failed, using default value:"+dtlUrl); - } - -// Properties props = new Properties(); -// try { -// props.load(DatabaseConnectorMySQLImpl.class.getResourceAsStream("docservice.properties")); -// dtlUrl = props.getProperty("docservice.url"); -// } catch (IOException e) { -// dtlUrl = "http://testvidp.buergerkarte.at/DocumentService/DocumentService"; -// Logger.error("Loading DTL config failed, using default value:"+dtlUrl); -// e.printStackTrace(); -// } - } - /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) - */ - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - super.doGet(request, response); - } - - /** - * Handles the reception of a STORK response message - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) - */ - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - String pendingRequestID = null; - - try { - - Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); - - Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message."); - Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request)); - - super.setNoCachingHeadersInHttpRespone(request, response); - Logger.trace("No Caching headers set for HTTP response"); - - //check if https or only http - super.checkIfHTTPisAllowed(request.getRequestURL().toString()); - - Logger.debug("Beginning to extract SAMLResponse out of HTTP Request"); - - //extract STORK Response from HTTP Request - //Decodes SAML Response - byte[] decSamlToken; - try { - decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse")); - Logger.debug("SAMLResponse: " + new String(decSamlToken)); - - } catch(NullPointerException e) { - Logger.error("Unable to retrieve STORK Response", e); - throw new MOAIDException("stork.04", null); - } - - - - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing"); - - STORKAuthnResponse authnResponse = null; - try { - //validate SAML Token - Logger.debug("Starting validation of SAML response"); - authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) request.getRemoteHost()); - Logger.info("SAML response succesfully verified!"); - }catch(STORKSAMLEngineException e){ - Logger.error("Failed to verify STORK SAML Response", e); - throw new MOAIDException("stork.05", null); - } - - Logger.info("STORK SAML Response message succesfully extracted"); - Logger.debug("STORK response: "); - Logger.debug(authnResponse.toString()); - - // do PEPS-conform logging for easier evaluation - try { - // 2015-03-12 16:44:27.144#S-PEPS receives response from C-PEPS#orig_msg_id id2 (in response to)#orig_msg_id id1 (in response to)#status#msghash#msg_id id3# - Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS receives response from C-PEPS#" + - authnResponse.getInResponseTo() + "#NA#" + authnResponse.getMessage() + "#_hash_#" + authnResponse.getSamlId() + "#"); - } catch (Exception e1) { - Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage()); - } - - Logger.debug("Trying to find MOA Session-ID ..."); - //String moaSessionID = request.getParameter(PARAM_SESSIONID); - //first use SAML2 relayState - String moaSessionID = request.getParameter("RelayState"); - - // escape parameter strings - moaSessionID= StringEscapeUtils.escapeHtml(moaSessionID); - - //check if SAML2 relaystate includes a MOA sessionID - if (StringUtils.isEmpty(moaSessionID)) { - //if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier - - moaSessionID = authnResponse.getInResponseTo(); - moaSessionID= StringEscapeUtils.escapeHtml(moaSessionID); - - if (StringUtils.isEmpty(moaSessionID)) { - //No authentication session has been started before - Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started"); - Logger.debug("PEPSConnectorURL was: " + request.getRequestURL()); - throw new AuthenticationException("auth.02", new Object[] { moaSessionID }); - - } else - Logger.trace("Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute."); - - } else - //Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter."); - Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState."); - - /*INFO!!!! - * SAML message IDs has an different format then MOASessionIDs - * This is only a workaround because many PEPS does not support SAML2 relayState or - * MOASessionID as AttributConsumerServiceURL GET parameter - */ -// if (!ParamValidatorUtils.isValidSessionID(moaSessionID)) -// throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12"); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); - - //load MOASession from database - AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID); - //change MOASessionID - moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); - - Logger.info("Found MOA sessionID: " + moaSessionID); - - - - String statusCodeValue = authnResponse.getStatusCode(); - - if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) { - Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue); - throw new MOAIDException("stork.06", new Object[] { statusCodeValue }); - } - - Logger.info("Got SAML response with authentication success message."); - - Logger.debug("MOA session is still valid"); - - STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest(); - - if (storkAuthnRequest == null) { - Logger.error("Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID); - throw new MOAIDException("stork.07", null); - } - - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()); - if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() }); - //================== Check QAA level start ==================== - int reqQaa = -1; - int authQaa = -1; - String authQaaStr = null; - try { - reqQaa = storkAuthnRequest.getQaa(); - - //TODO: found better solution, but QAA Level in response could be not supported yet - try { - - authQaaStr = authnResponse.getAssertions().get(0). - getAuthnStatements().get(0).getAuthnContext(). - getAuthnContextClassRef().getAuthnContextClassRef(); - moaSession.setQAALevel(authQaaStr); - - } catch (Throwable e) { - Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level"); - moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel()); - authQaaStr = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel(); - } - if(authQaaStr != null)//Check value only if set - { - authQaa = Integer.valueOf(authQaaStr.substring(PVPConstants.STORK_QAA_PREFIX.length())); -// authQaa = Integer.valueOf(authQaaStr); - if (reqQaa > authQaa) { - Logger.warn("Requested QAA level does not match to authenticated QAA level"); - throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa}); - - } - } - } catch (MOAIDException e) { - throw e; - - } catch (Exception e) { - if (Logger.isDebugEnabled()) - Logger.warn("STORK QAA Level evaluation error", e); - - else - Logger.warn("STORK QAA Level evaluation error (ErrorMessage=" - + e.getMessage() + ")"); - - throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa}); - - } - //================== Check QAA level end ==================== - - Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID); - - ////////////// incorporate gender from parameters if not in stork response - - IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); - - // but first, check if we have a representation case - if(STORKResponseProcessor.hasAttribute("mandateContent", attributeList) || STORKResponseProcessor.hasAttribute("representative", attributeList) || STORKResponseProcessor.hasAttribute("represented", attributeList)) { - // in a representation case... - moaSession.setUseMandate("true"); - - // and check if we have the gender value - PersonalAttribute gender = attributeList.get("gender"); // TODO Do we need to check gender value if there is no representation case? - if(null == gender) { - String gendervalue = (String) request.getParameter("gender"); - if(null != gendervalue) { - gender = new PersonalAttribute(); - gender.setName("gender"); - ArrayList tmp = new ArrayList(); - tmp.add(gendervalue); - gender.setValue(tmp); - - authnResponse.getPersonalAttributeList().add(gender); - } - } - } - - ////////////////////////////////////////////////////////////////////////// - - Logger.debug("Starting extraction of signedDoc attribute"); - //extract signed doc element and citizen signature - String citizenSignature = null; - try { - String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0); // TODO ERROR HANDLING - - Logger.debug("signatureInfo:"+signatureInfo); - - SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(new java.io.StringReader(signatureInfo))); - - // fetch signed doc - DataSource ds = null; - try{ - ds = LightweightSourceResolver.getDataSource(dssSignResponse); - }catch(Exception e) - { - e.printStackTrace(); - } - if(ds == null){ - //Normal DocumentServices return a http-page, but the SI DocumentService returns HTTP error 500 - //which results in an exception and ds==null - - //try to load document from documentservice - citizenSignature = loadDocumentFromDocumentService(dssSignResponse); - //throw new ApiUtilsException("No datasource found in response"); - } - else - { - InputStream incoming = ds.getInputStream(); - citizenSignature = IOUtils.toString(incoming); - incoming.close(); - - Logger.debug("citizenSignature:"+citizenSignature); - if(isDocumentServiceUsed(citizenSignature)==true) - { - citizenSignature = loadDocumentFromDocumentService(dssSignResponse); - // Logger.debug("Loading document from DocumentService."); - // String url = getDtlUrlFromResponse(dssSignResponse); - // //get Transferrequest - // String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url); - // //Load document from DocumentService - // byte[] data = getDocumentFromDtl(transferRequest, url); - // citizenSignature = new String(data, "UTF-8"); - // Logger.debug("Overridung citizenSignature with:"+citizenSignature); - } - } - JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName()); - SignatureType root = ((JAXBElement) ctx.createUnmarshaller().unmarshal(IOUtils.toInputStream(citizenSignature))).getValue(); - - // memorize signature into authblock - moaSession.setAuthBlock(citizenSignature); - - // extract certificate - for(Object current : root.getKeyInfo().getContent()) - if(((JAXBElement) current).getValue() instanceof X509DataType) { - for(Object currentX509Data : ((JAXBElement) current).getValue().getX509IssuerSerialOrX509SKIOrX509SubjectName()) { - JAXBElement casted = ((JAXBElement) currentX509Data); - if(casted.getName().getLocalPart().equals("X509Certificate")) { - moaSession.setSignerCertificate(new X509Certificate(((String)casted.getValue()).getBytes("UTF-8"))); - break; - } - } - } - - - } catch (Throwable e) { - Logger.error("Could not extract citizen signature from C-PEPS", e); - throw new MOAIDException("stork.09", null); - } - Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)"); - Logger.debug("Citizen signature will be verified by SZR Gateway!"); - - Logger.debug("fetching OAParameters from database"); - -// //read configuration paramters of OA -// AuthenticationSession moasession; -// try { -// moasession = AuthenticationSessionStoreage.getSession(moaSessionID); -// } catch (MOADatabaseException e2) { -// Logger.error("could not retrieve moa session"); -// throw new AuthenticationException("auth.01", null); -// } -// OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()); -// if (oaParam == null) -// throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() }); - - // retrieve target - //TODO: check in case of SSO!!! - String targetType = null; - if(oaParam.getBusinessService()) { - String id = oaParam.getIdentityLinkDomainIdentifier(); - if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) - targetType = id; - else - targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier(); - } else { - targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); - } - - IdentityLink identityLink = null; - try { - AuthConfiguration config = AuthConfigurationProviderFactory.getInstance(); - if(config.isStorkFakeIdLActive() && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) { - // create fake IdL - // - fetch IdL template from resources - InputStream s = PEPSConnectorServlet.class.getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); - Element idlTemplate = DOMUtils.parseXmlValidating(s); - - identityLink = new IdentityLinkAssertionParser(idlTemplate).parseIdentityLink(); - - // replace data - Element idlassertion = identityLink.getSamlAssertion(); - // - set bpk/wpbk; - Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - if(!STORKResponseProcessor.hasAttribute("eIdentifier", attributeList)) - throw new STORKException("eIdentifier is missing"); - String eIdentifier = STORKResponseProcessor.getAttributeValue("eIdentifier", attributeList, false); - prIdentification.getFirstChild().setNodeValue(eIdentifier); - - // - set last name - Node prFamilyName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH); - if(!STORKResponseProcessor.hasAttribute("surname", attributeList)) - throw new STORKException("surname is missing"); - String familyName = STORKResponseProcessor.getAttributeValue("surname", attributeList, false); - prFamilyName.getFirstChild().setNodeValue(familyName); - - // - set first name - Node prGivenName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH); - if(!STORKResponseProcessor.hasAttribute("givenName", attributeList)) - throw new STORKException("givenName is missing"); - String givenName = STORKResponseProcessor.getAttributeValue("givenName", attributeList, false); - prGivenName.getFirstChild().setNodeValue(givenName); - - // - set date of birth - Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH); - if(!STORKResponseProcessor.hasAttribute("dateOfBirth", attributeList)) - throw new STORKException("dateOfBirth is missing"); - String dateOfBirth = STORKResponseProcessor.getAttributeValue("dateOfBirth", attributeList, false); - prDateOfBirth.getFirstChild().setNodeValue(dateOfBirth); - - identityLink = new IdentityLinkAssertionParser(idlassertion).parseIdentityLink(); - - //resign IDL - IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); - Element resignedilAssertion = identitylinkresigner.resignIdentityLink(identityLink.getSamlAssertion(), config.getStorkFakeIdLResigningKey()); - identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink(); - } else { - //contact SZR Gateway - Logger.debug("Starting connecting SZR Gateway"); - identityLink = STORKResponseProcessor.connectToSZRGateway(authnResponse.getPersonalAttributeList(), - oaParam.getFriendlyName(), - targetType, null, - oaParam.getMandateProfiles(), citizenSignature); - } - } catch (STORKException e) { - // this is really nasty but we work against the system here. We are supposed to get the gender attribute from - // stork. If we do not, we cannot register the person in the ERnP - we have to have the - // gender for the represented person. So here comes the dirty hack. - if(e.getCause() instanceof STORKException && e.getCause().getMessage().equals("gender not found in response")) { - try { - Logger.trace("Initialize VelocityEngine..."); - - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html"); - VelocityContext context = new VelocityContext(); - context.put("SAMLResponse", request.getParameter("SAMLResponse")); - context.put("action", request.getRequestURL()); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - response.getOutputStream().write(writer.toString().getBytes("UTF-8")); - } catch (Exception e1) { - Logger.error("Error sending gender retrival form.", e1); -// httpSession.invalidate(); - throw new MOAIDException("stork.10", null); - } - - return; - } - - Logger.error("Error connecting SZR Gateway", e); - throw new MOAIDException("stork.10", null); - } - Logger.debug("SZR communication was successfull"); - - if (identityLink == null) { - Logger.error("SZR Gateway did not return an identity link."); - throw new MOAIDException("stork.10", null); - } - moaSession.setForeigner(true); - - Logger.info("Received Identity Link from SZR Gateway"); - moaSession.setIdentityLink(identityLink); - - Logger.debug("Adding addtional STORK attributes to MOA session"); - moaSession.setStorkAttributes(authnResponse.getPersonalAttributeList()); - - Logger.debug("Add full STORK AuthnResponse to MOA session"); - moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse")); - - //We don't have BKUURL, setting from null to "Not applicable" - moaSession.setBkuURL("Not applicable (STORK Authentication)"); - - // free for single use - moaSession.setAuthenticatedUsed(false); - - // stork did the authentication step - moaSession.setAuthenticated(true); - - // do PEPS-conform logging for easier evaluation - try { - // 2015-03-12 16:44:27.144#S-PEPS generates response to SP#orig_msg_id id1 (in response to)#status#msghash#msg_id id4# - Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS generates response to SP#" + - "#NA#" + authnResponse.getMessage() + "#_hash_#" + moaSession.getProcessInstanceId() + "#"); - } catch (Exception e1) { - Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage()); - } - -// //TODO: found better solution, but QAA Level in response could be not supported yet -// try { -// -// moaSession.setQAALevel(authnResponse.getAssertions().get(0). -// getAuthnStatements().get(0).getAuthnContext(). -// getAuthnContextClassRef().getAuthnContextClassRef()); -// -// } catch (Throwable e) { -// Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level"); -// moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel()); -// -// } - - //session is implicit stored in changeSessionID!!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); - - Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID); - - //redirect - String redirectURL = null; - redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(), - ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID), newMOASessionID); - redirectURL = response.encodeRedirectURL(redirectURL); - -// response.setContentType("text/html"); -// response.setStatus(302); -// response.addHeader("Location", redirectURL); - response.sendRedirect(redirectURL); - Logger.info("REDIRECT TO: " + redirectURL); - - - - } catch (AuthenticationException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (MOAIDException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (Exception e) { - Logger.error("PEPSConnector has an interal Error.", e); - } - - - finally { - ConfigurationDBUtils.closeSession(); - } - - } - - private String loadDocumentFromDocumentService(SignResponse dssSignResponse) throws Exception - { - Logger.debug("Loading document from DocumentService."); - String url = getDtlUrlFromResponse(dssSignResponse); - Logger.debug("Loading document from DocumentService, url:"+url); - //get Transferrequest - String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url); - //Load document from DocumentService - byte[] data = getDocumentFromDtl(transferRequest, url); - String citizenSignature = new String(data, "UTF-8"); - Logger.debug("Overridung citizenSignature with:"+citizenSignature); - return citizenSignature; - } - - private boolean isDocumentServiceUsed(String citizenSignature) //TODo add better check - { - if(citizenSignature.contains("
Service Name:{http://stork.eu}DocumentService
Port Name:{http://stork.eu}DocumentServicePort
")) - { - Logger.trace("isDocumentServiceUsed => true"); - return true; - } - Logger.trace("isDocumentServiceUsed => false"); - return false; - } - - /** - * Get DTL uril from the oasis sign response - * @param signRequest The signature response - * @return The URL of DTL service - * @throws SimpleException - */ - private String getDtlUrlFromResponse(SignResponse dssSignResponse) { - List documents = ApiUtils.findNamedElement(dssSignResponse.getOptionalOutputs(), - ApiUtils.OPTIONAL_OUTPUT_DOCUMENTWITHSIGNATURE, DocumentWithSignature.class); - DocumentType sourceDocument = documents.get(0).getDocument(); - - if (sourceDocument.getDocumentURL() != null) - return sourceDocument.getDocumentURL(); - else - return null;//throw new Exception("No document url found"); - } - -//From DTLPEPSUTIL - - - - /** - * Get document from DTL - * @param transferRequest The transfer request (attribute query) - * @param eDtlUrl The DTL url of external DTL - * @return the document data - * @throws SimpleException - */ - private byte[] getDocumentFromDtl(String transferRequest, String eDtlUrl) throws Exception - { - URL url = null; - try - { - Logger.debug("getDocumentFromDtl, dtlUrl:'"+dtlUrl+"' eDtlUrl:'"+eDtlUrl+"'"); - url = new URL(dtlUrl); - QName qname = new QName("http://stork.eu", - "DocumentService"); - - Service service = Service.create(url, qname); - DocumentService docservice = service.getPort(DocumentService.class); - - BindingProvider bp = (BindingProvider) docservice; - SOAPBinding binding = (SOAPBinding) bp.getBinding(); - binding.setMTOMEnabled(true); - - if (eDtlUrl.equalsIgnoreCase(dtlUrl)) - return docservice.getDocument(transferRequest, ""); - else - return docservice.getDocument(transferRequest, eDtlUrl); - } - catch (Exception e) - { - e.printStackTrace(); - throw new Exception("Error in getDocumentFromDtl", e); - } - } - - /** - * Get a document transfer request (attribute query) - * @param docId - * @return - * @throws SimpleException - */ - private String getDocTransferRequest(String docId, String destinationUrl) throws Exception - { - String spCountry = docId.substring(0, docId.indexOf("/")); - final STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - STORKAttrQueryRequest req = new STORKAttrQueryRequest(); - req.setAssertionConsumerServiceURL(dtlUrl); - req.setDestination(destinationUrl); - req.setSpCountry(spCountry); - req.setQaa(3);//TODO - PersonalAttributeList pal = new PersonalAttributeList(); - PersonalAttribute attr = new PersonalAttribute(); - attr.setName("docRequest"); - attr.setIsRequired(true); - attr.setValue(Arrays.asList(docId)); - pal.add(attr); - req.setPersonalAttributeList(pal); - - STORKAttrQueryRequest req1; - try { - req1 = engine.generateSTORKAttrQueryRequest(req); - return PEPSUtil.encodeSAMLTokenUrlSafe(req1.getTokenSaml()); - } catch (STORKSAMLEngineException e) { - e.printStackTrace(); - throw new Exception("Error in doc request attribute query generation", e); - } - } - - /** - * Get mime type of document from DTL - * @param docId The document id - * @param dtlUrl The url of dtl - * @return The mime type - */ -// private String getDocumentMimeFromDtl(String docId, String eDtlUrl) throws Exception -// { -// URL url = null; -// try -// { -// url = new URL(dtlUrl); -// QName qname = new QName("http://stork.eu", -// "DocumentService"); -// -// Service service = Service.create(url, qname); -// DocumentService docservice = service.getPort(DocumentService.class); -// -// BindingProvider bp = (BindingProvider) docservice; -// SOAPBinding binding = (SOAPBinding) bp.getBinding(); -// binding.setMTOMEnabled(true); -// -// if (eDtlUrl.equalsIgnoreCase(dtlUrl)) -// return docservice.getDocumentMime(docId, ""); -// else -// return docservice.getDocumentMime(docId, eDtlUrl); -// } -// catch (Exception e) -// { -// e.printStackTrace(); -// throw new Exception("Error in getDocumentFromDtl", e); -// } -// } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java deleted file mode 100644 index ff3330491..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorWithLocalSigningServlet.java +++ /dev/null @@ -1,816 +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 iaik.x509.X509Certificate; - -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import javax.activation.DataSource; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.Source; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.stream.StreamSource; - -import org.apache.commons.codec.binary.Base64; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.opensaml.saml2.core.StatusCode; -import org.xml.sax.SAXException; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.data.IdentityLink; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.BKUException; -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.stork.STORKException; -import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; -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.ModulUtils; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -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.spss.MOAException; -import at.gv.egovernment.moa.spss.api.SPSSFactory; -import at.gv.egovernment.moa.spss.api.SignatureVerificationService; -import at.gv.egovernment.moa.spss.api.common.Content; - -import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureInfo; -import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation; -import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; -import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; -import at.gv.egovernment.moa.util.StringUtils; -import at.gv.util.xsd.xmldsig.SignatureType; -import at.gv.util.xsd.xmldsig.X509DataType; -import eu.stork.oasisdss.api.ApiUtils; -import eu.stork.oasisdss.api.LightweightSourceResolver; -import eu.stork.oasisdss.api.exceptions.ApiUtilsException; -import eu.stork.oasisdss.api.exceptions.UtilsException; -import eu.stork.oasisdss.profile.SignRequest; -import eu.stork.oasisdss.profile.SignResponse; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PEPSUtil; -import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.commons.STORKAuthnRequest; -import eu.stork.peps.auth.commons.STORKAuthnResponse; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.exceptions.STORKSAMLEngineException; -//import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; - -/** - * Endpoint for receiving STORK response messages - * @deprecated Use {@link at.gv.egovernment.moa.id.auth.modules.stork.tasks.PepsConnectorHandleResponseWithoutSignatureTask} instead. - */ -public class PEPSConnectorWithLocalSigningServlet extends AuthServlet { - private static final long serialVersionUID = 1L; - - public static final String PEPSCONNECTOR_SERVLET_URL_PATTERN = "/PEPSConnectorWithLocalSigning"; - - private String oasisDssWebFormURL = "https://testvidp.buergerkarte.at/oasis-dss/DSSWebFormServlet";//load from config below - - - /** - * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) - */ - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - super.doGet(request, response); - } - - /** - * Handles the reception of a STORK response message - * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) - */ - protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException - { - Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); - - String moaSessionID1 = request.getParameter("moaSessionID"); - String signResponse = request.getParameter("signresponse"); - Logger.info("moaSessionID1:"+moaSessionID1); - Logger.info("signResponse:"+signResponse); - if(moaSessionID1!=null) - { - if(signResponse!=null) - { - //redirect from oasis with signresponse - handleSignResponse(request, response); - } - else - { - //should not occur - throw new IOException("should not occur"); - } - } - else - { - if(signResponse!=null) - { - //should not occur - throw new IOException("should not occur"); - } - else - { - //normal saml response - handleSAMLResponse(request, response); - } - } - return; - } - - private void handleSignResponse(HttpServletRequest request, HttpServletResponse response) { - Logger.info("handleSignResponse started"); - String moaSessionID = request.getParameter("moaSessionID"); - String signResponse = request.getParameter("signresponse"); - Logger.info("moaSessionID:"+moaSessionID); - Logger.info("signResponse:"+signResponse); - String pendingRequestID = null; - try{ - - - //load MOASession from database - AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID); - //change MOASessionID - moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); - Logger.info("pendingRequestID:"+pendingRequestID); - String signResponseString = new String(Base64.decodeBase64(signResponse), "UTF8"); - Logger.info("RECEIVED signresponse:"+signResponseString); - //create SignResponse object - Source response1 = new StreamSource(new java.io.StringReader(signResponseString)); - SignResponse dssSignResponse = ApiUtils.unmarshal(response1, SignResponse.class); - - // SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(new java.io.StringReader(Base64.signResponse))); - - String citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse); - - // memorize signature into authblock - moaSession.setAuthBlock(citizenSignature); - - X509Certificate cert = getSignerCertificate(citizenSignature); - moaSession.setSignerCertificate(cert); - VerifyXMLSignatureResponse xMLVerifySignatureResponse = verifyXMLSignature(citizenSignature); - at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse tmp = convert(xMLVerifySignatureResponse); - - - moaSession.setXMLVerifySignatureResponse(tmp); - try{ - IPersonalAttributeList personalAttributeList = moaSession.getAuthnResponseGetPersonalAttributeList(); - //Add SignResponse TODO Add signature (extracted from signResponse)? - List values = new ArrayList(); - values.add(signResponseString); -// values.add(citizenSignature); - Logger.debug("Assembling signedDoc attribute"); - PersonalAttribute signedDocAttribute = new PersonalAttribute("signedDoc", false, values, - "Available"); - personalAttributeList.add(signedDocAttribute); - - String authnContextClassRef = moaSession.getAuthnContextClassRef(); - SZRGInsertion(moaSession, personalAttributeList, authnContextClassRef, citizenSignature); - } catch (STORKException e) { - // this is really nasty but we work against the system here. We are supposed to get the gender attribute from - // stork. If we do not, we cannot register the person in the ERnP - we have to have the - // gender for the represented person. So here comes the dirty hack. - if(e.getCause() instanceof STORKException && e.getCause().getMessage().equals("gender not found in response")) { - try { - Logger.trace("Initialize VelocityEngine..."); - - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html"); - VelocityContext context = new VelocityContext(); - context.put("SAMLResponse", request.getParameter("SAMLResponse")); - context.put("action", request.getRequestURL()); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - response.getOutputStream().write(writer.toString().getBytes("UTF-8")); - } catch (Exception e1) { - Logger.error("Error sending gender retrival form.", e1); - // httpSession.invalidate(); - throw new MOAIDException("stork.10", null); - } - - return; - } - - Logger.error("Error connecting SZR Gateway", e); - throw new MOAIDException("stork.10", null); - } - - Logger.debug("Add full STORK AuthnResponse to MOA session"); - moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));//TODO ask Florian/Thomas authnResponse? - moaSession.setForeigner(true); - - //session is implicit stored in changeSessionID!!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); - - Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID); - - //redirect - String redirectURL = null; - redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(), - ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID), newMOASessionID); - redirectURL = response.encodeRedirectURL(redirectURL); - - response.sendRedirect(redirectURL); - Logger.info("REDIRECT TO: " + redirectURL); - - } catch (AuthenticationException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (MOAIDException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (Exception e) { - Logger.error("PEPSConnector has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - - private void handleSAMLResponse(HttpServletRequest request, HttpServletResponse response) { - Logger.info("handleSAMLResponse started"); - String pendingRequestID = null; - - try { - Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message."); - Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request)); - - super.setNoCachingHeadersInHttpRespone(request, response); - Logger.trace("No Caching headers set for HTTP response"); - - //check if https or only http - super.checkIfHTTPisAllowed(request.getRequestURL().toString()); - - Logger.debug("Beginning to extract SAMLResponse out of HTTP Request"); - - //extract STORK Response from HTTP Request - //Decodes SAML Response - byte[] decSamlToken; - try { - decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse")); - Logger.debug("SAMLResponse: " + new String(decSamlToken)); - - } catch(NullPointerException e) { - Logger.error("Unable to retrieve STORK Response", e); - throw new MOAIDException("stork.04", null); - } - - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing"); - - STORKAuthnResponse authnResponse = null; - try { - //validate SAML Token - Logger.debug("Starting validation of SAML response"); - authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) request.getRemoteHost()); - Logger.info("SAML response succesfully verified!"); - }catch(STORKSAMLEngineException e){ - Logger.error("Failed to verify STORK SAML Response", e); - throw new MOAIDException("stork.05", null); - } - - Logger.info("STORK SAML Response message succesfully extracted"); - Logger.debug("STORK response: "); - Logger.debug(authnResponse.toString()); - - Logger.debug("Trying to find MOA Session-ID ..."); - //String moaSessionID = request.getParameter(PARAM_SESSIONID); - //first use SAML2 relayState - String moaSessionID = request.getParameter("RelayState"); - - // escape parameter strings - moaSessionID= StringEscapeUtils.escapeHtml(moaSessionID); - - //check if SAML2 relaystate includes a MOA sessionID - if (StringUtils.isEmpty(moaSessionID)) { - //if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier - - moaSessionID = authnResponse.getInResponseTo(); - moaSessionID= StringEscapeUtils.escapeHtml(moaSessionID); - - if (StringUtils.isEmpty(moaSessionID)) { - //No authentication session has been started before - Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started"); - Logger.debug("PEPSConnectorURL was: " + request.getRequestURL()); - throw new AuthenticationException("auth.02", new Object[] { moaSessionID }); - - } else - Logger.trace("Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute."); - - } else - //Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter."); - Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState."); - - /*INFO!!!! - * SAML message IDs has an different format then MOASessionIDs - * This is only a workaround because many PEPS does not support SAML2 relayState or - * MOASessionID as AttributConsumerServiceURL GET parameter - */ - // if (!ParamValidatorUtils.isValidSessionID(moaSessionID)) - // throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12"); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID); - - //load MOASession from database - AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID); - //change MOASessionID - moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); - - Logger.info("Found MOA sessionID: " + moaSessionID); - - - - String statusCodeValue = authnResponse.getStatusCode(); - - if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) { - Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue); - throw new MOAIDException("stork.06", new Object[] { statusCodeValue }); - } - - Logger.info("Got SAML response with authentication success message."); - - Logger.debug("MOA session is still valid"); - - STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest(); - - if (storkAuthnRequest == null) { - Logger.error("Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID); - throw new MOAIDException("stork.07", null); - } - - Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID); - - ////////////// incorporate gender from parameters if not in stork response - - IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList(); - - // but first, check if we have a representation case - if(STORKResponseProcessor.hasAttribute("mandateContent", attributeList) || STORKResponseProcessor.hasAttribute("representative", attributeList) || STORKResponseProcessor.hasAttribute("represented", attributeList)) { - // in a representation case... - moaSession.setUseMandate("true"); - - // and check if we have the gender value - PersonalAttribute gender = attributeList.get("gender"); - if(null == gender) { - String gendervalue = (String) request.getParameter("gender"); - if(null != gendervalue) { - gender = new PersonalAttribute(); - gender.setName("gender"); - ArrayList tmp = new ArrayList(); - tmp.add(gendervalue); - gender.setValue(tmp); - - authnResponse.getPersonalAttributeList().add(gender); - } - } - } - - ////////////////////////////////////////////////////////////////////////// - - Logger.debug("Starting extraction of signedDoc attribute"); - //extract signed doc element and citizen signature - String citizenSignature = null; - try { - PersonalAttribute signedDoc = authnResponse.getPersonalAttributeList().get("signedDoc"); - String signatureInfo = null; - if(signedDoc!=null) - { - signatureInfo = signedDoc.getValue().get(0); - //should not occur - } - else - { - - //store SAMLResponse - moaSession.setSAMLResponse(request.getParameter("SAMLResponse")); - //store authnResponse - - //moaSession.setAuthnResponse(authnResponse);//not serializable - moaSession.setAuthnResponseGetPersonalAttributeList(authnResponse.getPersonalAttributeList()); - - String authnContextClassRef = null; - try { - authnContextClassRef = authnResponse.getAssertions().get(0).getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef(); - } catch (Throwable e) { - Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level"); - } - - moaSession.setAuthnContextClassRef(authnContextClassRef); - moaSession.setReturnURL(request.getRequestURL()); - - //load signedDoc - String signRequest = moaSession.getSignedDoc(); - - //session is implicit stored in changeSessionID!!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); - - //set return url to PEPSConnectorWithLocalSigningServlet and add newMOASessionID - //signRequest - - String issuerValue = AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(); - String acsURL = issuerValue + PEPSConnectorWithLocalSigningServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; - - String url = acsURL+"?moaSessionID="+newMOASessionID; - //redirect to OASIS module and sign there - - boolean found = false; - try{ - List aps = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()).getStorkAPs(); - Logger.info("Found AttributeProviderPlugins:"+aps.size()); - for(AttributeProviderPlugin ap : aps) - { - Logger.info("Found AttributeProviderPlugin attribute:"+ap.getAttributes()); - if(ap.getAttributes().equalsIgnoreCase("signedDoc")) - { - // FIXME[tlenz]: A servlet's class field is not thread safe. - oasisDssWebFormURL = ap.getUrl(); - found = true; - Logger.info("Loaded signedDoc attribute provider url from config:"+oasisDssWebFormURL); - break; - } - } - }catch(Exception e) - { - e.printStackTrace(); - Logger.error("Loading the signedDoc attribute provider url from config failed"); - } - if(!found) - { - Logger.error("Failed to load the signedDoc attribute provider url from config"); - } - performRedirect(url,request,response,signRequest); - - return; - } - SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(new java.io.StringReader(signatureInfo))); - - citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse); - - // memorize signature into authblock - moaSession.setAuthBlock(citizenSignature); - - X509Certificate cert = getSignerCertificate(citizenSignature); - moaSession.setSignerCertificate(cert); - moaSession.setForeigner(true); - - - } catch (Throwable e) { - Logger.error("Could not extract citizen signature from C-PEPS", e); - throw new MOAIDException("stork.09", null); - } - - try{ - SZRGInsertion(moaSession, authnResponse.getPersonalAttributeList(), authnResponse.getAssertions().get(0).getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef(),citizenSignature); - } catch (STORKException e) { - // this is really nasty but we work against the system here. We are supposed to get the gender attribute from - // stork. If we do not, we cannot register the person in the ERnP - we have to have the - // gender for the represented person. So here comes the dirty hack. - if(e.getCause() instanceof STORKException && e.getCause().getMessage().equals("gender not found in response")) { - try { - Logger.trace("Initialize VelocityEngine..."); - - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html"); - VelocityContext context = new VelocityContext(); - context.put("SAMLResponse", request.getParameter("SAMLResponse")); - context.put("action", request.getRequestURL()); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - response.getOutputStream().write(writer.toString().getBytes("UTF-8")); - } catch (Exception e1) { - Logger.error("Error sending gender retrival form.", e1); - // httpSession.invalidate(); - throw new MOAIDException("stork.10", null); - } - - return; - } - - Logger.error("Error connecting SZR Gateway", e); - throw new MOAIDException("stork.10", null); - } - - Logger.debug("Add full STORK AuthnResponse to MOA session"); - moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));//TODO ask Florian/Thomas authnResponse? - - //session is implicit stored in changeSessionID!!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession); - - Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID); - - //redirect - String redirectURL = null; - redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(), - ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID), newMOASessionID); - redirectURL = response.encodeRedirectURL(redirectURL); - - response.setContentType("text/html"); - response.setStatus(302); - response.addHeader("Location", redirectURL); - Logger.info("REDIRECT TO: " + redirectURL); - - } catch (AuthenticationException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (MOAIDException e) { - handleError(null, e, request, response, pendingRequestID); - - } catch (Exception e) { - Logger.error("PEPSConnector has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - - } - - private void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, String signRequestString) - throws MOAIDException { - - try { - Logger.trace("Initialize VelocityEngine..."); - - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/oasis_dss_webform_binding.vm"); - VelocityContext context = new VelocityContext(); - - Logger.debug("performRedirect, signrequest:"+signRequestString); - Source signDoc = new StreamSource(new java.io.StringReader(signRequestString)); - SignRequest signRequest = ApiUtils.unmarshal(signDoc, SignRequest.class); - signRequest.setReturnURL("TODO"); - signRequestString = IOUtils.toString(ApiUtils.marshalToInputStream(signRequest)); - context.put("signrequest", Base64.encodeBase64String(signRequestString.getBytes("UTF8"))); - context.put("clienturl", url); - context.put("action", oasisDssWebFormURL ); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - resp.getOutputStream().write(writer.toString().getBytes("UTF-8")); - } catch (Exception e) { - Logger.error("Error sending DSS signrequest.", e); - throw new MOAIDException("stork.11", null); - } - } - - private String getCitizienSignatureFromSignResponseFromSAML(STORKAuthnResponse authnResponse) throws ApiUtilsException, IllegalArgumentException, TransformerConfigurationException, UtilsException, TransformerException, TransformerFactoryConfigurationError, IOException, MOAIDException - { - PersonalAttribute signedDoc = authnResponse.getPersonalAttributeList().get("signedDoc"); - String signatureInfo = null; - if(signedDoc==null) - { - Logger.error("SignedDoc = null, failed to extract Signresponse from authnResponse"); - throw new MOAIDException("stork.09", null); - } - signatureInfo = signedDoc.getValue().get(0); - - SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(new java.io.StringReader(signatureInfo))); - String citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse); - return citizenSignature; - - } - - private String getCitizienSignatureFromSignResponse(SignResponse dssSignResponse) throws IllegalArgumentException, TransformerConfigurationException, UtilsException, TransformerException, TransformerFactoryConfigurationError, IOException, ApiUtilsException - { - // fetch signed doc - DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse); - if(ds == null){ - throw new ApiUtilsException("No datasource found in response"); - } - - InputStream incoming = ds.getInputStream(); - String citizenSignature = IOUtils.toString(incoming); - incoming.close(); - - return citizenSignature; - } - - private X509Certificate getSignerCertificate(String citizenSignature) throws CertificateException, JAXBException, UnsupportedEncodingException - { - JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName()); - SignatureType root = ((JAXBElement) ctx.createUnmarshaller().unmarshal(IOUtils.toInputStream(citizenSignature))).getValue(); - - // extract certificate - for(Object current : root.getKeyInfo().getContent()) - if(((JAXBElement) current).getValue() instanceof X509DataType) { - for(Object currentX509Data : ((JAXBElement) current).getValue().getX509IssuerSerialOrX509SKIOrX509SubjectName()) { - JAXBElement casted = ((JAXBElement) currentX509Data); - if(casted.getName().getLocalPart().equals("X509Certificate")) { - return new X509Certificate(((String)casted.getValue()).getBytes("UTF-8")); - } - } - } - return null; - } - - private void SZRGInsertion(AuthenticationSession moaSession, IPersonalAttributeList personalAttributeList, String authnContextClassRef, String citizenSignature) throws STORKException, MOAIDException - { - Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)"); - Logger.debug("Citizen signature will be verified by SZR Gateway!"); - - Logger.debug("fetching OAParameters from database"); - - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()); - if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() }); - - // retrieve target - //TODO: check in case of SSO!!! - String targetType = null; - if(oaParam.getBusinessService()) { - String id = oaParam.getIdentityLinkDomainIdentifier(); - if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) - targetType = id; - else - targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier(); - } else { - targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); - } - - - - Logger.debug("Starting connecting SZR Gateway"); - //contact SZR Gateway - IdentityLink identityLink = null; - - identityLink = STORKResponseProcessor.connectToSZRGateway(personalAttributeList, - oaParam.getFriendlyName(), - targetType, null, - oaParam.getMandateProfiles(),citizenSignature); - Logger.debug("SZR communication was successfull"); - - if (identityLink == null) { - Logger.error("SZR Gateway did not return an identity link."); - throw new MOAIDException("stork.10", null); - } - Logger.info("Received Identity Link from SZR Gateway"); - moaSession.setIdentityLink(identityLink); - - Logger.debug("Adding addtional STORK attributes to MOA session"); - moaSession.setStorkAttributes(personalAttributeList); - - //We don't have BKUURL, setting from null to "Not applicable" - moaSession.setBkuURL("Not applicable (STORK Authentication)"); - - // free for single use - moaSession.setAuthenticatedUsed(false); - - // stork did the authentication step - moaSession.setAuthenticated(true); - - //TODO: found better solution, but QAA Level in response could be not supported yet - try { - if(authnContextClassRef==null) - authnContextClassRef = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel(); - moaSession.setQAALevel(authnContextClassRef); - - } catch (Throwable e) { - Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level"); - moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel()); - - } - - } - - private VerifyXMLSignatureResponse verifyXMLSignature(String signature) throws AuthenticationException, ParseException, BKUException, BuildException, ConfigurationException, ServiceException, UnsupportedEncodingException, SAXException, IOException, ParserConfigurationException, MOAException - { - //Based on MOA demo client - // Factory und Service instanzieren - SPSSFactory spssFac = SPSSFactory.getInstance(); - SignatureVerificationService sigVerifyService = SignatureVerificationService.getInstance(); - - Content sigDocContent1 = spssFac.createContent(IOUtils.toInputStream(signature, "UTF-8"), null); - - // Position der zu prüfenden Signatur im Dokument angeben - // (Nachdem im XPath-Ausdruck ein NS-Präfix verwendet wird, muss in einer Lookup-Tabelle - // der damit bezeichnete Namenraum mitgegeben werden) - HashMap nSMap = new HashMap(); - nSMap.put("dsig", "http://www.w3.org/2000/09/xmldsig#"); - VerifySignatureLocation sigLocation = spssFac.createVerifySignatureLocation("//dsig:Signature", nSMap); - - // Zu prüfendes Dokument und Signaturposition zusammenfassen - - VerifySignatureInfo sigInfo = spssFac.createVerifySignatureInfo(sigDocContent1, sigLocation); - - // Prüfrequest zusammenstellen - VerifyXMLSignatureRequest verifyRequest = spssFac.createVerifyXMLSignatureRequest( - null, // Wird Prüfzeit nicht angegeben, wird aktuelle Zeit verwendet - sigInfo, - null, // Keine Ergänzungsobjekte notwendig - null, // Signaturmanifest-Prüfung soll nicht durchgeführt werden - false, // Hash-Inputdaten, d.h. tatsächlich signierte Daten werden nicht zurückgeliefert - "MOAIDBuergerkartePersonenbindungMitTestkarten");//TODO load from config - //"Test-Signaturdienste"); // ID des verwendeten Vertrauensprofils - - VerifyXMLSignatureResponse verifyResponse = null; - try - { - // Aufruf der Signaturprüfung - verifyResponse = sigVerifyService.verifyXMLSignature(verifyRequest); - } - catch (MOAException e) - { - // Service liefert Fehler - System.err.println("Die Signaturprüfung hat folgenden Fehler geliefert:"); - System.err.println("Fehlercode: " + e.getMessageId()); - System.err.println("Fehlernachricht: " + e.getMessage()); - throw e; - } - -// // Auswertung der Response -// System.out.println(); -// System.out.println("Ergebnisse der Signaturprüfung:"); -// System.out.println(); -// -// // Besondere Eigenschaften des Signatorzertifikats -// SignerInfo signerInfo = verifyResponse.getSignerInfo(); -// System.out.println("*** Ist Zertifikat des Signators qualifiziert? " + ((signerInfo.isQualifiedCertificate()) ? "ja" : "nein")); -// System.out.println("*** Ist Zertifikat des Signators von einer Behörde? " + ((signerInfo.isPublicAuthority()) ? "ja" : "nein")); -// -// // Ergebnisse von Signatur- und Zertifikatsprüfung -// System.out.println(); -// System.out.println("Ergebniscode der Signaturprüfung: " + verifyResponse.getSignatureCheck().getCode()); -// System.out.println("Ergebniscode der Zertifikatsprüfung: " + verifyResponse.getCertificateCheck().getCode()); -// -// // Signatorzertifikat -// System.out.println(); -// System.out.println("*** Zertifikat des Signators:"); -// System.out.println("Aussteller: " + signerInfo.getSignerCertificate().getIssuerDN()); -// System.out.println("Subject: " + signerInfo.getSignerCertificate().getSubjectDN()); -// System.out.println("Seriennummer: " + signerInfo.getSignerCertificate().getSerialNumber()); - return verifyResponse; - } - - private at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse convert(VerifyXMLSignatureResponse xMLVerifySignatureResponse) { - at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse response = new at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse(); - response.setCertificateCheckCode(xMLVerifySignatureResponse.getCertificateCheck().getCode()); - response.setPublicAuthority(xMLVerifySignatureResponse.getSignerInfo().isPublicAuthority()); -// response.setPublicAuthorityCode(publicAuthorityCode) - response.setQualifiedCertificate(xMLVerifySignatureResponse.getSignerInfo().isQualifiedCertificate()); - response.setSignatureCheckCode(xMLVerifySignatureResponse.getSignatureCheck().getCode()); - response.setSignatureManifestCheckCode(xMLVerifySignatureResponse.getSignatureManifestCheck().getCode()); -// response.setSigningDateTime() -// response.setX509certificate(x509certificate) - response.setXmlDSIGManifestCheckCode(xMLVerifySignatureResponse.getSignatureManifestCheck().getCode()); -// response.setXmlDSIGManigest(xMLVerifySignatureResponse.getSignatureManifestCheck()) -// response.setXmlDsigSubjectName(xmlDsigSubjectName) - return response; - } -} 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 3609925a0..7266a3302 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 @@ -30,11 +30,11 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import at.gv.egovernment.moa.id.auth.builder.RedirectFormBuilder; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; 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.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLEncoder; @@ -60,10 +60,10 @@ public class RedirectServlet extends AuthServlet{ String interIDP = req.getParameter(INTERFEDERATION_IDP); Logger.debug("Check URL against online-applications"); - OnlineApplication oa = null; + OAAuthParameter oa = null; String redirectTarget = DEFAULT_REDIRECTTARGET; try { - oa = ConfigurationDBRead.getActiveOnlineApplication(url); + oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(url); if (oa == null && !url.startsWith(AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix())) { resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Parameters not valid"); return; @@ -72,7 +72,7 @@ public class RedirectServlet extends AuthServlet{ //Redirect is a SAML1 send Artifact redirct if (MiscUtil.isNotEmpty(artifact)) { try { - String test = oa.getAuthComponentOA().getTemplates().getBKUSelectionCustomization().getAppletRedirectTarget(); + String test = oa.getFormCustomizaten().get(FormBuildUtils.REDIRECTTARGET); if (MiscUtil.isNotEmpty(test)) redirectTarget = test; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java deleted file mode 100644 index 28d3caba0..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java +++ /dev/null @@ -1,343 +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 iaik.pki.PKIException; - -import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.SSLSocketFactory; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.transform.TransformerException; - -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.lang.StringEscapeUtils; -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.AuthenticationException; -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.WrongParametersException; -import at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyAuthenticationBlockTask; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -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.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.SSLUtils; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISSessionId; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; - -/** - * Servlet requested for verifying the signed authentication block - * provided by the security layer implementation. - * Utilizes the {@link AuthenticationServer}. - * - * @author Paul Ivancsics - * @version $Id$ - * @deprecated Use {@link VerifyAuthenticationBlockTask} instead. - */ -public class VerifyAuthenticationBlockServlet extends AuthServlet { - - - /** - * - */ - private static final long serialVersionUID = -2409629495345900542L; - -/** - * Constructor for VerifyAuthenticationBlockServlet. - */ - public VerifyAuthenticationBlockServlet() { - super(); - } - - /** - * GET requested by security layer implementation to verify - * that data URL resource is available. - * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse) - */ - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - //doPost(req, resp); - - Logger.debug("GET VerifyAuthenticationBlock"); - - 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); - - } - - /** - * Verifies the signed authentication block and redirects the browser - * to the online application requested, adding a parameter needed for - * retrieving the authentication data. - *
- * Request parameters: - *
    - *
  • MOASessionID: ID of associated authentication session
  • - *
  • XMLResponse: <CreateXMLSignatureResponse>
  • - *
- * Response: - *
    - *
  • Status: 302
  • - *
  • Header "Location": URL of the online application requested, with - * parameters "Target"(only if the online application is - * a public service) and "SAMLArtifact" added
  • - *
  • Error status: 500 - *
- * @see AuthenticationServer#verifyAuthenticationBlock - * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) - */ - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - Logger.debug("POST VerifyAuthenticationBlock"); - - Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); - - 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); - - String pendingRequestID = null; - - Map parameters; - try - { - parameters = getParameters(req); - } catch (FileUploadException e) - { - Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - - } - String sessionID = req.getParameter(PARAM_SESSIONID); - String createXMLSignatureResponse = (String)parameters.get(PARAM_XMLRESPONSE); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - String redirectURL = null; - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12"); - if (!ParamValidatorUtils.isValidXMLDocument(createXMLSignatureResponse)) - throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_XMLRESPONSE, "auth.12"); - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - String samlArtifactBase64 = AuthenticationServer.getInstance().verifyAuthenticationBlock(session, createXMLSignatureResponse); - - - - if (samlArtifactBase64 == null) { - //mandate Mode - - AuthConfiguration authConf= AuthConfigurationProviderFactory.getInstance(); - ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter(); - SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProviderFactory.getInstance(), connectionParameters); - - // get identitity link as byte[] - Element elem = session.getIdentityLink().getSamlAssertion(); - String s = DOMUtils.serializeNode(elem); - - //System.out.println("IDL: " + s); - - byte[] idl = s.getBytes("UTF-8"); - - // redirect url - // build redirect(to the GetMISSessionIdSerlvet) - - //change MOASessionID before MIS request - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - - redirectURL = - new DataURLBuilder().buildDataURL( - session.getAuthURL(), - GET_MIS_SESSIONID, - newMOASessionID); - - String oaURL = session.getOAURLRequested(); - OAAuthParameter oaParam = authConf.getOnlineApplicationParameter(oaURL); - List profiles = oaParam.getMandateProfiles(); - - if (profiles == null) { - Logger.error("No Mandate/Profile for OA configured."); - throw new AuthenticationException("config.21", new Object[] { GET_MIS_SESSIONID}); - } - -// String profilesArray[] = profiles.split(","); -// for(int i = 0; i < profilesArray.length; i++) { -// profilesArray[i] = profilesArray[i].trim(); -// } - - String oaFriendlyName = oaParam.getFriendlyName(); - String mandateReferenceValue = session.getMandateReferenceValue(); - byte[] cert = session.getEncodedSignerCertificate(); - byte[] authBlock = session.getAuthBlock().getBytes("UTF-8"); - - //TODO: check in case of SSO!!! - String targetType = null; - if(oaParam.getBusinessService()) { - String id = oaParam.getIdentityLinkDomainIdentifier(); - if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) - targetType = id; - else - targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_+session.getDomainIdentifier(); - - } else { - targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); - } - - MISSessionId misSessionID = MISSimpleClient.sendSessionIdRequest( - connectionParameters.getUrl(), - idl, - cert, - oaFriendlyName, - redirectURL, - mandateReferenceValue, - profiles, - targetType, - authBlock, - sslFactory); - - if (misSessionID == null) { - Logger.error("Fehler bei Anfrage an Vollmachten Service. MIS Session ID ist null."); - throw new MISSimpleClientException("Fehler bei Anfrage an Vollmachten Service."); - } - - String redirectMISGUI = misSessionID.getRedirectURL(); - session.setMISSessionID(misSessionID.getSessiondId()); - - try { - AuthenticationSessionStoreage.storeSession(session); - } catch (MOADatabaseException e) { - throw new MOAIDException("Session store error", null); - } - - resp.setStatus(302); - resp.addHeader("Location", redirectMISGUI); - Logger.debug("REDIRECT TO: " + redirectURL); - } - else { - - if (!samlArtifactBase64.equals("Redirect to Input Processor")) { - /*redirectURL = session.getOAURLRequested(); - if (!session.getBusinessService()) { - redirectURL = addURLParameter(redirectURL, PARAM_TARGET, URLEncoder.encode(session.getTarget(), "UTF-8")); - - } - redirectURL = addURLParameter(redirectURL, PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8")); - redirectURL = resp.encodeRedirectURL(redirectURL);*/ - - - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), - ModulUtils.buildAuthURL(session.getModul(), session.getAction(), pendingRequestID), samlArtifactBase64); - - } else { - redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, session.getSessionID()); - } - - resp.setContentType("text/html"); - resp.setStatus(302); - - resp.addHeader("Location", redirectURL); - Logger.debug("REDIRECT TO: " + redirectURL); - - } - - } - - catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (GeneralSecurityException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (PKIException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (TransformerException e) { - handleError(null, e, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("AuthBlockValidation has an interal Error.", e); - } - - - finally { - ConfigurationDBUtils.closeSession(); - } - - } - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java deleted file mode 100644 index 2aa717a65..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java +++ /dev/null @@ -1,235 +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 iaik.x509.X509Certificate; - -import java.io.IOException; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.lang.StringEscapeUtils; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -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.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.internal.tasks.VerifyCertificateTask; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.spss.util.CertificateUtils; - -/** - * Servlet requested for getting the foreign eID - * provided by the security layer implementation. - * Utilizes the {@link AuthenticationServer}. - * @deprecated Use {@link VerifyCertificateTask} instead. - * - */ -public class VerifyCertificateServlet extends AuthServlet { - - /** - * - */ - private static final long serialVersionUID = -4110159749768152538L; - -/** - * Constructor for VerifyCertificateServlet. - */ - public VerifyCertificateServlet() { - super(); - } - - /** - * GET requested by security layer implementation to verify - * that data URL resource is available. - * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse) - */ - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - Logger.debug("GET VerifyCertificateServlet"); - - 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); - } - - /** - * Gets the signer certificate from the InfoboxReadRequest and - * responds with a new - * CreateXMLSignatureRequest. - *
- * Request parameters: - *
    - *
  • MOASessionID: ID of associated authentication session
  • - *
  • XMLResponse: <InfoboxReadResponse>
  • - *
- * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) - */ - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - Logger.debug("POST VerifyCertificateServlet"); - - Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); - - 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); - - String pendingRequestID = null; - - Map parameters; - try - { - parameters = getParameters(req); - } catch (FileUploadException e) - { - Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - } - String sessionID = req.getParameter(PARAM_SESSIONID); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - AuthenticationSession session = null; - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12"); - - session = AuthenticationServer.getSession(sessionID); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - X509Certificate cert = AuthenticationServer.getInstance().getCertificate(sessionID, parameters); - if (cert == null) { - Logger.error("Certificate could not be read."); - throw new AuthenticationException("auth.14", null); - } - - boolean useMandate = session.getUseMandate(); - - - if (useMandate) { - - // verify certificate for OrganWalter - String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyCertificate(session, cert); - - try { - AuthenticationSessionStoreage.storeSession(session); - } catch (MOADatabaseException e) { - throw new MOAIDException("session store error", null); - } - - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate"); - - } - else { - - - String countrycode = CertificateUtils.getIssuerCountry(cert); - if (countrycode != null) { - if (countrycode.compareToIgnoreCase("AT") == 0) { - Logger.error("Certificate issuer country code is \"AT\". Login not support in foreign identities mode."); - throw new AuthenticationException("auth.22", null); - } - } - - // Foreign Identities Modus - String createXMLSignatureRequest = AuthenticationServer.getInstance().createXMLSignatureRequestForeignID(session, cert); - // build dataurl (to the GetForeignIDSerlvet) - String dataurl = - new DataURLBuilder().buildDataURL( - session.getAuthURL(), - REQ_GET_FOREIGN_ID, - session.getSessionID()); - - try { - AuthenticationSessionStoreage.storeSession(session); - } catch (MOADatabaseException e) { - throw new MOAIDException("session store error", null); - } - - ServletUtils.writeCreateXMLSignatureRequest(resp, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); - - Logger.debug("Send CreateXMLSignatureRequest to BKU"); - } - } - catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("CertificateValidation has an interal Error.", e); - } - - - finally { - ConfigurationDBUtils.closeSession(); - } - } - - -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java deleted file mode 100644 index d2c63a8b3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java +++ /dev/null @@ -1,279 +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 java.util.Map; - -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.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; -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.ParseException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyIdentityLinkTask; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -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.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.ServletUtils; -import at.gv.egovernment.moa.logging.Logger; - -/** - * Servlet requested for verifying the identity link - * provided by the security layer implementation. - * Utilizes the {@link AuthenticationServer}. - * - * @author Paul Ivancsics - * @version $Id$ - * @deprecated Use {@link VerifyIdentityLinkTask} instead. - */ -public class VerifyIdentityLinkServlet extends AuthServlet { - - /** - * - */ - private static final long serialVersionUID = -7074476974026049958L; - -/** - * Constructor for VerifyIdentityLinkServlet. - */ - public VerifyIdentityLinkServlet() { - super(); - } - - /** - * GET requested by security layer implementation to verify - * that data URL resource is available. - * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest, HttpServletResponse) - */ - protected void doGet(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - Logger.debug("GET VerifyIdentityLink"); - - 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); - } - - /** - * Verifies the identity link and responds with a new - * CreateXMLSignatureRequest or a new - * InfoboxReadRequest (in case of a foreign eID card). - *
- * Request parameters: - *
    - *
  • MOASessionID: ID of associated authentication session
  • - *
  • XMLResponse: <InfoboxReadResponse>
  • - *
- * Response: - *
    - *
  • Content type: "text/xml"
  • - *
  • Content: see return value of {@link AuthenticationServer#verifyIdentityLink}
  • - *
  • Error status: 500 - *
- * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest, HttpServletResponse) - */ - protected void doPost(HttpServletRequest req, HttpServletResponse resp) - throws ServletException, IOException { - - Logger.debug("POST VerifyIdentityLink"); - - Logger.warn(getClass().getName() + " is deprecated and should not be used any more."); - - Map parameters; - String pendingRequestID = null; - - try - { - parameters = getParameters(req); - - } catch (Exception e) - { - Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new IOException(e.getMessage()); - } - String sessionID = req.getParameter(PARAM_SESSIONID); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - 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); - - - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); - - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters); - - Logger.debug(createXMLSignatureRequestOrRedirect); - - - if (createXMLSignatureRequestOrRedirect == null) { - // no identity link found - - boolean useMandate = session.getUseMandate(); - if (useMandate) { - Logger.error("Online-Mandate Mode for foreign citizencs not supported."); - throw new AuthenticationException("auth.13", null); - } - - try { - - Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); - - // create the InfoboxReadRequest to get the certificate - String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); - - // build dataurl (to the VerifyCertificateSerlvet) - String dataurl = - new DataURLBuilder().buildDataURL( - session.getAuthURL(), - REQ_VERIFY_CERTIFICATE, - session.getSessionID()); - - - ServletUtils.writeCreateXMLSignatureRequest(resp, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); - - - } - catch(Exception e) { - handleError(null, e, req, resp, pendingRequestID); - } - - } - else { - boolean useMandate = session.getUseMandate(); - - if (useMandate) { // Mandate modus - // read certificate and set dataurl to - Logger.debug("Send InfoboxReadRequest to BKU to get signer certificate."); - - - String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); - - // build dataurl (to the GetForeignIDSerlvet) - String dataurl = - new DataURLBuilder().buildDataURL( - session.getAuthURL(), - REQ_VERIFY_CERTIFICATE, - session.getSessionID()); - - //Logger.debug("ContentType set to: application/x-www-form-urlencoded (ServletUtils)"); - //ServletUtils.writeCreateXMLSignatureRequestURLEncoded(resp, session, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); - - Logger.debug("ContentType set to: text/xml;charset=UTF-8 (ServletUtils)"); - ServletUtils.writeCreateXMLSignatureRequest(resp, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); - - } - else { - Logger.info("Normal"); - - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - AuthConfiguration authConf = AuthConfigurationProviderFactory - .getInstance(); - - createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance() - .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, - authConf, oaParam); - - ServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink"); - } - } - - try { - AuthenticationSessionStoreage.storeSession(session); - - } catch (MOADatabaseException e) { - Logger.info("No valid MOA session found. Authentification process is abourted."); - throw new AuthenticationException("auth.20", null); - } - } - catch (ParseException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (MOAIDException ex) { - handleError(null, ex, req, resp, pendingRequestID); - - } catch (Exception e) { - Logger.error("IdentityLinkValidation has an interal Error.", e); - } - - finally { - ConfigurationDBUtils.closeSession(); - } - } - -} 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 d7f503454..113e9cdda 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 @@ -47,10 +47,25 @@ package at.gv.egovernment.moa.id.config; import java.util.Map; +import java.util.Properties; +import org.hibernate.cfg.Configuration; + +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; +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; -import com.fasterxml.jackson.annotation.JsonProperty; /** * Base class for AuthConfigurationProvider and ProxyConfigurationProvider, @@ -59,15 +74,18 @@ import com.fasterxml.jackson.annotation.JsonProperty; * @author Paul Ivancsics * @version $Id$ */ -public class ConfigurationProviderImpl implements ConfigurationProvider{ +public abstract class ConfigurationProviderImpl implements ConfigurationProvider{ /** * Constructor */ public ConfigurationProviderImpl() { + super(); } + private EgovUtilPropertiesConfiguration eGovUtilsConfig = null; + /** * The name of the system property which contains the file name of the * configuration file. @@ -125,49 +143,140 @@ public class ConfigurationProviderImpl implements ConfigurationProvider{ protected boolean trustmanagerrevoationchecking = true; + protected Properties configProp = null; + /** * Returns the main configuration file directory used to configure MOA-ID * * @return the directory */ - @JsonProperty("getRootConfigFileDir") public String getRootConfigFileDir() { return rootConfigFileDir; } - @JsonProperty("getDefaultChainingMode") + public String getDefaultChainingMode() { return defaultChainingMode; } - - + /** - * Returns the trustedCACertificates. - * @return String + * Get the DB configuration properties from MOA-ID-Auth configuration file + * + * @return */ - @JsonProperty("getTrustedCACertificates") - public String getTrustedCACertificates() { - - return trustedCACertificates; + public Properties getDBConnectionConfiguration() { + return this.configProp; } -/** - * @return the certstoreDirectory - */ -@JsonProperty("getCertstoreDirectory") -public String getCertstoreDirectory() { - return certstoreDirectory; -} - -/** - * @return the trustmanagerrevoationchecking - */ -@JsonProperty("isTrustmanagerrevoationchecking") -public boolean isTrustmanagerrevoationchecking() { - return trustmanagerrevoationchecking; -} + /** + * @param properties + * @throws ConfigurationException + * @throws org.opensaml.xml.ConfigurationException + */ + public void initial(Properties props) throws ConfigurationException, org.opensaml.xml.ConfigurationException { + //Initial Hibernate Framework + Logger.trace("Initializing Hibernate framework."); + try { + // read MOAID Session Hibernate properties + Properties moaSessionProp = new Properties(); + for (Object key : props.keySet()) { + String propPrefix = "moasession."; + if (key.toString().startsWith(propPrefix+"hibernate")) { + String propertyName = key.toString().substring(propPrefix.length()); + moaSessionProp.put(propertyName, props.get(key.toString())); + } + } + + // read Config Hibernate properties + configProp = new Properties(); + for (Object key : props.keySet()) { + String propPrefix = "configuration."; + if (key.toString().startsWith(propPrefix+"hibernate")) { + String propertyName = key.toString().substring(propPrefix.length()); + configProp.put(propertyName, props.get(key.toString())); + } + } + + // read advanced logging properties + Properties statisticProps = new Properties(); + for (Object key : props.keySet()) { + String propPrefix = "advancedlogging."; + if (key.toString().startsWith(propPrefix+"hibernate")) { + String propertyName = key.toString().substring(propPrefix.length()); + statisticProps.put(propertyName, props.get(key.toString())); + } + } + + // initialize hibernate + synchronized (ConfigurationProviderImpl.class) { + + //Initial config Database + // ConfigurationDBUtils.initHibernate(configProp); + + //initial MOAID Session Database + Configuration config = new Configuration(); + config.addAnnotatedClass(AssertionStore.class); + config.addAnnotatedClass(AuthenticatedSessionStore.class); + config.addAnnotatedClass(OASessionStore.class); + config.addAnnotatedClass(OldSSOSessionIDStore.class); + config.addAnnotatedClass(ExceptionStore.class); + config.addAnnotatedClass(InterfederationSessionStore.class); + config.addAnnotatedClass(ProcessInstanceStore.class); + config.addProperties(moaSessionProp); + MOASessionDBUtils.initHibernate(config, moaSessionProp); + + //initial advanced logging + if (Boolean.valueOf(props.getProperty("configuration.advancedlogging.active", "false"))) { + Logger.info("Advanced statistic log is activated, starting initialization process ..."); + Configuration statisticconfig = new Configuration(); + statisticconfig.addAnnotatedClass(StatisticLog.class); + statisticconfig.addProperties(statisticProps); + StatisticLogDBUtils.initHibernate(statisticconfig, statisticProps); + Logger.info("Advanced statistic log is initialized."); + } + + } + Logger.trace("Hibernate initialization finished."); + + } catch (ExceptionInInitializerError e) { + throw new ConfigurationException("config.17", null, e); + + } finally { + + + } + + + //Initialize OpenSAML for STORK + Logger.info("Starting initialization of OpenSAML..."); + MOADefaultBootstrap.bootstrap(); + //DefaultBootstrap.bootstrap(); + Logger.debug("OpenSAML successfully initialized"); + + + //read eGovUtils client configuration + Properties eGovUtilsConfigProp = new Properties(); + for (Object key : props.keySet()) { + String propPrefix = "service."; + if (key.toString().startsWith(propPrefix+"egovutil")) { + String propertyName = key.toString().substring(propPrefix.length()); + eGovUtilsConfigProp.put(propertyName, props.get(key.toString())); + } + } + if (!eGovUtilsConfigProp.isEmpty()) { + Logger.info("Start eGovUtils client implementation configuration ..."); + eGovUtilsConfig = + new EgovUtilPropertiesConfiguration(eGovUtilsConfigProp, rootConfigFileDir); + } + + } - + /** + * @return the eGovUtilsConfig + */ + public EgovUtilPropertiesConfiguration geteGovUtilsConfig() { + return eGovUtilsConfig; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java deleted file mode 100644 index a2e8bab9b..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java +++ /dev/null @@ -1,172 +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.commons.db.dao.config.OAOAUTH20; -import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; - -/** - * 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 { - - public OAParameter() { } - - public OAParameter(OnlineApplication oa) { - - this.oaType = oa.getType(); - - if (this.oaType.equals("businessService")) - this.businessService = true; - else - this.businessService = false; - - this.publicURLPrefix = oa.getPublicURLPrefix(); - - this.friendlyName = oa.getFriendlyName(); - - this.target = oa.getTarget(); - - this.targetFriendlyName = oa.getTargetFriendlyName(); - - this.removePBKFromAuthblock = oa.isRemoveBPKFromAuthBlock(); - - this.oAuth20Config = oa.getAuthComponentOA().getOAOAUTH20(); - - this.isInderfederationIDP = oa.isIsInterfederationIDP(); - - this.isSTORKPVPGateway = oa.isIsInterfederationGateway(); - - } - - /** - * 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" - */ - protected boolean businessService; - - - /** - * public URL prefix of the online application - */ - protected String publicURLPrefix; - - /** - * specifies a human readable name of the Online Application - */ - protected String friendlyName; - - /** - * specified a specific target for the Online Application (overwrites the target in der request) - */ - protected String target; - /** - * specifies a friendly name for the target - */ - protected String targetFriendlyName; - - protected boolean removePBKFromAuthblock; - - protected Boolean isInderfederationIDP; - - protected Boolean isSTORKPVPGateway; - - /** - * Contains the oAuth 2.0 configuration (client id, secret and redirect uri) - */ - private OAOAUTH20 oAuth20Config; - - public String getOaType() { - return oaType; - } - - public boolean getBusinessService() { - return businessService; - } - - public String getPublicURLPrefix() { - return publicURLPrefix; - } - - public String getFriendlyName() { - return friendlyName; - } - - public String getTarget() { - return target; - } - - public String getTargetFriendlyName() { - return targetFriendlyName; - } - - public boolean isRemovePBKFromAuthBlock() { - return removePBKFromAuthblock; - } - - public OAOAUTH20 getoAuth20Config() { - return oAuth20Config; - } - - /** - * @return the isInderfederationIDP - */ - public boolean isInderfederationIDP() { - if (isInderfederationIDP == null) - return false; - - return isInderfederationIDP; - } - - public boolean isSTORKPVPGateway() { - if (isSTORKPVPGateway == null) - return false; - - return isSTORKPVPGateway; - } - - - -} 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 index 80ecff2d2..87e40c1b3 100644 --- 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 @@ -22,55 +22,25 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.config.auth; -import java.util.Date; - -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.MOAIDConfiguration; 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 = 60; // 60 sec + private static final long INTERVAL = 24 * 60 * 60; // 24 hours public void run() { while (true) { try { - Thread.sleep(INTERVAL * 1000); - - Logger.trace("check for new config."); - MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration(); - - if (moaidconfig != null) { - Date dbdate = moaidconfig.getTimestampItem(); - Date pvprefresh = moaidconfig.getPvp2RefreshItem(); - - //TODO: check!!!! - - //Date date = AuthConfigurationProviderFactory.getInstance().getTimeStamp(); - Date date = new Date(); - + Thread.sleep(INTERVAL * 1000); + Logger.trace("Check consistence of PVP2X metadata"); + MOAMetadataProvider.reInitialize(); - if (dbdate != null && dbdate.after(date)) { - AuthConfiguration instance = AuthConfigurationProviderFactory.getInstance(); -// instance.reloadDataBaseConfig(); - } - - Date pvpdate = MOAMetadataProvider.getTimeStamp(); - if (pvprefresh != null && pvpdate != null && pvprefresh.after(pvpdate)) { - MOAMetadataProvider.reInitialize(); - } - - } else { - Logger.warn("MOA-ID Configuration is actually not found. Reuse old configuration."); - - } - - + } catch (Throwable e) { - Logger.warn("MOA-ID Configuration is actually not loadable. Reuse old configuration.", e); + Logger.warn("MOA-ID Configuration validation is not possible, actually. Reuse old configuration.", e); } finally { ConfigurationDBUtils.closeSession(); @@ -81,8 +51,8 @@ public class AuthConfigLoader implements Runnable { public static void start() { // start the session cleanup thread - Thread configLoader = new Thread(new AuthConfigLoader(), "AuthConfigLoader"); - configLoader.setName("ConfigurationLoader"); + 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/AuthConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfiguration.java index b93312f78..e4072d0c5 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 @@ -1,6 +1,7 @@ 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.commons.db.dao.config.PVP2; @@ -14,6 +15,8 @@ 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(); @@ -23,7 +26,7 @@ public interface AuthConfiguration extends ConfigurationProvider{ @Deprecated public PVP2 getGeneralPVP2DBConfig(); - public Properties getConfigurationWithPrefix(final String Prefix); + public Map getConfigurationWithPrefix(final String Prefix); public String getConfigurationWithKey(final String key); @@ -98,12 +101,48 @@ public interface AuthConfiguration extends ConfigurationProvider{ 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); + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index 7ebde05df..03f4a300a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -1,1221 +1,1221 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "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.auth; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.math.BigInteger; -import java.net.MalformedURLException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Unmarshaller; - -import org.hibernate.cfg.Configuration; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetMISSessionIDTask; -import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; -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.config.AuthComponentGeneral; -import at.gv.egovernment.moa.id.commons.db.dao.config.ChainingModes; -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.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.MOASP; -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.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.TimeOuts; -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.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; -import at.gv.egovernment.moa.id.commons.db.dao.statistic.StatisticLog; -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.legacy.BuildFromLegacyConfig; -import at.gv.egovernment.moa.id.config.stork.STORKConfig; -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.egovernment.moa.util.MiscUtil; -import at.gv.util.config.EgovUtilPropertiesConfiguration; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * A class providing access to the Auth Part of the MOA-ID configuration data. - * - *

Configuration data is read from an XML file, whose location is given by - * the moa.id.configuration system property.

- *

This class implements the Singleton pattern. The reload() - * method can be used to update the configuration data. Therefore, it is not - * guaranteed that consecutive calls to getInstance() will return - * the same AuthConfigurationProvider all the time. During the - * processing of a web service request, the current - * TransactionContext should be used to obtain the - * AuthConfigurationProvider local to that request.

- * - * @author Patrick Peck - * @author Stefan Knirsch - * - * @version $Id$ - * - *@deprecated Use {@link AuthConfigProviderFactory} instead - */ -public class AuthConfigurationProvider extends ConfigurationProviderImpl implements AuthConfiguration { - -// /** DEFAULT_ENCODING is "UTF-8" */ -// private static final String DEFAULT_ENCODING="UTF-8"; - /** - * The name of the generic configuration property giving the authentication session time out. - */ - 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"; - - /** - * BKUSelectionType HTMLComplete, according to schema type BKUSelectionType - */ - public static final String BKU_SELECTION_TYPE_HTMLCOMPLETE = - "HTMLComplete"; - - /** - * BKUSelectionType HTMLSelect, according to schema type BKUSelectionType - */ - public static final String BKU_SELECTION_TYPE_HTMLSELECT = - "HTMLSelect"; - - /** - * The name of the generic configuration property allowing https connection to - * the user frontend servlets ("StartAuthentication" and "SelectBKU" servlets) - */ - public static final String FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY = - "FrontendServlets.EnableHTTPConnection"; - - /** - * The name of the generic configuration property allowing to set a individual - * DATA URL used to communicate with the BKU (SecurityLayer) - */ - public static final String INDIVIDUAL_DATA_URL_PREFIX = - "FrontendServlets.DataURLPrefix"; - - /** Singleton instance. null, if none has been created. */ - private static AuthConfigurationProvider instance; - - // - // configuration data - // - private static MOAIDConfiguration moaidconfig = null; - - private static Properties props = null; - - private static STORKConfig storkconfig = null; - - private static TimeOuts timeouts = null; - - private static PVP2 pvp2general = null; - - private static String alternativesourceid = null; - - private static List legacyallowedprotocols = new ArrayList(); - private static ProtocolAllowed allowedProtcols = null; - - private static VerifyAuthBlock verifyidl = null; - - private static ConnectionParameter MoaSpConnectionParameter = null; - private static ConnectionParameter ForeignIDConnectionParameter = null; - private static ConnectionParameter OnlineMandatesConnectionParameter = null; - - private static String MoaSpIdentityLinkTrustProfileID = null; - - private static List TransformsInfos = null; - private static List IdentityLinkX509SubjectNames = new ArrayList(); - - private static Map SLRequestTemplates = new HashMap(); - private static Map DefaultBKUURLs = new HashMap(); - - private static SSO ssoconfig = null; - - private EgovUtilPropertiesConfiguration eGovUtilsConfig = null; - - private static Date date = null; - - private String publicURLPreFix = null; - - /** - * Return the single instance of configuration data. - * - * @return AuthConfigurationProvider The current configuration data. - * @throws ConfigurationException - */ - public static synchronized AuthConfigurationProvider getInstance() - throws ConfigurationException { - - if (instance == null) { - reload(); - } - return instance; - } - - public static Date getTimeStamp() { - return date; - } - - /** - * Reload the configuration data and set it if successful. - * - * @return AuthConfigurationProvider The loaded configuration data. - * @throws ConfigurationException Failure to load the configuration data. - */ - public static synchronized AuthConfigurationProvider 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); - - instance = new AuthConfigurationProvider(fileName); - return instance; - } - - - /** - * Constructor for AuthConfigurationProvider. - * @param fileName - * @throws ConfigurationException - */ - public AuthConfigurationProvider(String fileName) - throws ConfigurationException { - - load(fileName); - } - - /** - * Protected constructor. Used by unit tests. - */ - protected AuthConfigurationProvider() { - } - - /** - * Load the configuration data from XML file with the given name and build - * the internal data structures representing the MOA ID configuration. - * - * @param fileName The name of the XML file to load. - * @throws ConfigurationException The MOA configuration could not be - * read/built. - */ - private void load(String fileName) throws ConfigurationException { - - try { - //Initial Hibernate Framework - Logger.trace("Initializing Hibernate framework."); - - //Load MOAID-2.0 properties file - File propertiesFile = new File(fileName); - FileInputStream fis = null; - props = new Properties(); - - // determine the directory of the root config file - rootConfigFileDir = new File(fileName).getParent(); - - try { - rootConfigFileDir = new File(rootConfigFileDir).toURL().toString(); - - } catch (MalformedURLException t) { - throw new ConfigurationException("config.03", null, t); - } - - try { - fis = new FileInputStream(propertiesFile); - props.load(fis); - - // read MOAID Session Hibernate properties - Properties moaSessionProp = new Properties(); - for (Object key : props.keySet()) { - String propPrefix = "moasession."; - if (key.toString().startsWith(propPrefix+"hibernate")) { - String propertyName = key.toString().substring(propPrefix.length()); - moaSessionProp.put(propertyName, props.get(key.toString())); - } - } - - // read Config Hibernate properties - Properties configProp = new Properties(); - for (Object key : props.keySet()) { - String propPrefix = "configuration."; - if (key.toString().startsWith(propPrefix+"hibernate")) { - String propertyName = key.toString().substring(propPrefix.length()); - configProp.put(propertyName, props.get(key.toString())); - } - } - - // read advanced logging properties - Properties statisticProps = new Properties(); - for (Object key : props.keySet()) { - String propPrefix = "advancedlogging."; - if (key.toString().startsWith(propPrefix+"hibernate")) { - String propertyName = key.toString().substring(propPrefix.length()); - statisticProps.put(propertyName, props.get(key.toString())); - } - } - - // initialize hibernate - synchronized (AuthConfigurationProvider.class) { - - //Initial config Database - // ConfigurationDBUtils.initHibernate(configProp); - - //initial MOAID Session Database - Configuration config = new Configuration(); - config.addAnnotatedClass(AssertionStore.class); - config.addAnnotatedClass(AuthenticatedSessionStore.class); - config.addAnnotatedClass(OASessionStore.class); - config.addAnnotatedClass(OldSSOSessionIDStore.class); - config.addAnnotatedClass(ExceptionStore.class); - config.addAnnotatedClass(InterfederationSessionStore.class); - config.addAnnotatedClass(ProcessInstanceStore.class); - config.addProperties(moaSessionProp); - MOASessionDBUtils.initHibernate(config, moaSessionProp); - - //initial advanced logging - if (isAdvancedLoggingActive()) { - Logger.info("Advanced statistic log is activated, starting initialization process ..."); - Configuration statisticconfig = new Configuration(); - statisticconfig.addAnnotatedClass(StatisticLog.class); - statisticconfig.addProperties(statisticProps); - StatisticLogDBUtils.initHibernate(statisticconfig, statisticProps); - Logger.info("Advanced statistic log is initialized."); - } - - } - Logger.trace("Hibernate initialization finished."); - - } catch (FileNotFoundException e) { - throw new ConfigurationException("config.03", null, e); - - } catch (IOException e) { - throw new ConfigurationException("config.03", null, e); - - } catch (ExceptionInInitializerError e) { - throw new ConfigurationException("config.17", null, e); - - } finally { - if (fis != null) - fis.close(); - - } - - - //Initialize OpenSAML for STORK - Logger.info("Starting initialization of OpenSAML..."); - MOADefaultBootstrap.bootstrap(); - //DefaultBootstrap.bootstrap(); - Logger.debug("OpenSAML successfully initialized"); - - - String legacyconfig = props.getProperty("configuration.xml.legacy"); - String xmlconfig = props.getProperty("configuration.xml"); -// String xmlconfigout = props.getProperty("configuration.xml.out"); - - - //configure eGovUtils client implementations - - //read eGovUtils client configuration - Properties eGovUtilsConfigProp = new Properties(); - for (Object key : props.keySet()) { - String propPrefix = "service."; - if (key.toString().startsWith(propPrefix+"egovutil")) { - String propertyName = key.toString().substring(propPrefix.length()); - eGovUtilsConfigProp.put(propertyName, props.get(key.toString())); - } - } - if (!eGovUtilsConfigProp.isEmpty()) { - Logger.info("Start eGovUtils client implementation configuration ..."); - eGovUtilsConfig = - new EgovUtilPropertiesConfiguration(eGovUtilsConfigProp, rootConfigFileDir); - } - - - //TODO: removed in MOA-ID 3.x -// //check if XML config should be used -// if (MiscUtil.isNotEmpty(legacyconfig) || MiscUtil.isNotEmpty(xmlconfig)) { -// Logger.warn("WARNING! MOA-ID 2.0 is started with XML configuration. This setup overstrike the actual configuration in the Database!"); -// //moaidconfig = ConfigurationDBRead.getMOAIDConfiguration(); -// moaidconfig = NewConfigurationDBRead.getMOAIDConfiguration(); -// if (moaidconfig.getAuthComponentGeneral()!= null || moaidconfig.getChainingModes() != null || moaidconfig.getTrustedCACertificates() != null || moaidconfig.getDefaultBKUs() != null -// || moaidconfig.getSLRequestTemplates() != null || moaidconfig.getTimestampItem() != null || moaidconfig.getPvp2RefreshItem() != 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. +// ******************************************************************************/ +///* +// * 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.auth; +// +//import java.io.File; +//import java.io.FileInputStream; +//import java.io.FileNotFoundException; +//import java.io.IOException; +//import java.math.BigInteger; +//import java.net.MalformedURLException; +//import java.util.ArrayList; +//import java.util.Arrays; +//import java.util.Date; +//import java.util.HashMap; +//import java.util.List; +//import java.util.Map; +//import java.util.Properties; +// +//import javax.xml.bind.JAXBContext; +//import javax.xml.bind.Unmarshaller; +// +//import org.hibernate.cfg.Configuration; +// +//import at.gv.egovernment.moa.id.auth.AuthenticationServer; +//import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +//import at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetMISSessionIDTask; +//import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; +//import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; +//import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +//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.config.AuthComponentGeneral; +//import at.gv.egovernment.moa.id.commons.db.dao.config.ChainingModes; +//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.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.MOASP; +//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.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.TimeOuts; +//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.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; +//import at.gv.egovernment.moa.id.commons.db.dao.statistic.StatisticLog; +//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.legacy.BuildFromLegacyConfig; +//import at.gv.egovernment.moa.id.config.stork.STORKConfig; +//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.egovernment.moa.util.MiscUtil; +//import at.gv.util.config.EgovUtilPropertiesConfiguration; +// +//import com.fasterxml.jackson.annotation.JsonIgnore; +//import com.fasterxml.jackson.annotation.JsonProperty; +// +///** +// * A class providing access to the Auth Part of the MOA-ID configuration data. +// * +// *

Configuration data is read from an XML file, whose location is given by +// * the moa.id.configuration system property.

+// *

This class implements the Singleton pattern. The reload() +// * method can be used to update the configuration data. Therefore, it is not +// * guaranteed that consecutive calls to getInstance() will return +// * the same AuthConfigurationProvider all the time. During the +// * processing of a web service request, the current +// * TransactionContext should be used to obtain the +// * AuthConfigurationProvider local to that request.

+// * +// * @author Patrick Peck +// * @author Stefan Knirsch +// * +// * @version $Id$ +// * +// *@deprecated Use {@link AuthConfigProviderFactory} instead +// */ +//public class AuthConfigurationProvider extends ConfigurationProviderImpl implements AuthConfiguration { +// +//// /** DEFAULT_ENCODING is "UTF-8" */ +//// private static final String DEFAULT_ENCODING="UTF-8"; +// /** +// * The name of the generic configuration property giving the authentication session time out. +// */ +// 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"; +// +// /** +// * BKUSelectionType HTMLComplete, according to schema type BKUSelectionType +// */ +// public static final String BKU_SELECTION_TYPE_HTMLCOMPLETE = +// "HTMLComplete"; +// +// /** +// * BKUSelectionType HTMLSelect, according to schema type BKUSelectionType +// */ +// public static final String BKU_SELECTION_TYPE_HTMLSELECT = +// "HTMLSelect"; +// +// /** +// * The name of the generic configuration property allowing https connection to +// * the user frontend servlets ("StartAuthentication" and "SelectBKU" servlets) +// */ +// public static final String FRONTEND_SERVLETS_ENABLE_HTTP_CONNECTION_PROPERTY = +// "FrontendServlets.EnableHTTPConnection"; +// +// /** +// * The name of the generic configuration property allowing to set a individual +// * DATA URL used to communicate with the BKU (SecurityLayer) +// */ +// public static final String INDIVIDUAL_DATA_URL_PREFIX = +// "FrontendServlets.DataURLPrefix"; +// +// /** Singleton instance. null, if none has been created. */ +// private static AuthConfigurationProvider instance; +// +// // +// // configuration data +// // +// private static MOAIDConfiguration moaidconfig = null; +// +// private static Properties props = null; +// +// private static STORKConfig storkconfig = null; +// +// private static TimeOuts timeouts = null; +// +// private static PVP2 pvp2general = null; +// +// private static String alternativesourceid = null; +// +// private static List legacyallowedprotocols = new ArrayList(); +// private static ProtocolAllowed allowedProtcols = null; +// +// private static VerifyAuthBlock verifyidl = null; +// +// private static ConnectionParameter MoaSpConnectionParameter = null; +// private static ConnectionParameter ForeignIDConnectionParameter = null; +// private static ConnectionParameter OnlineMandatesConnectionParameter = null; +// +// private static String MoaSpIdentityLinkTrustProfileID = null; +// +// private static List TransformsInfos = null; +// private static List IdentityLinkX509SubjectNames = new ArrayList(); +// +// private static Map SLRequestTemplates = new HashMap(); +// private static Map DefaultBKUURLs = new HashMap(); +// +// private static SSO ssoconfig = null; +// +// private EgovUtilPropertiesConfiguration eGovUtilsConfig = null; +// +// private static Date date = null; +// +// private String publicURLPreFix = null; +// +// /** +// * Return the single instance of configuration data. +// * +// * @return AuthConfigurationProvider The current configuration data. +// * @throws ConfigurationException +// */ +// public static synchronized AuthConfigurationProvider getInstance() +// throws ConfigurationException { +// +// if (instance == null) { +// reload(); +// } +// return instance; +// } +// +// public static Date getTimeStamp() { +// return date; +// } +// +// /** +// * Reload the configuration data and set it if successful. +// * +// * @return AuthConfigurationProvider The loaded configuration data. +// * @throws ConfigurationException Failure to load the configuration data. +// */ +// public static synchronized AuthConfigurationProvider 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); +// +// instance = new AuthConfigurationProvider(fileName); +// return instance; +// } +// +// +// /** +// * Constructor for AuthConfigurationProvider. +// * @param fileName +// * @throws ConfigurationException +// */ +// public AuthConfigurationProvider(String fileName) +// throws ConfigurationException { +// +// load(fileName); +// } +// +// /** +// * Protected constructor. Used by unit tests. +// */ +// protected AuthConfigurationProvider() { +// } +// +// /** +// * Load the configuration data from XML file with the given name and build +// * the internal data structures representing the MOA ID configuration. +// * +// * @param fileName The name of the XML file to load. +// * @throws ConfigurationException The MOA configuration could not be +// * read/built. +// */ +// private void load(String fileName) throws ConfigurationException { +// +// try { +// //Initial Hibernate Framework +// Logger.trace("Initializing Hibernate framework."); +// +// //Load MOAID-2.0 properties file +// File propertiesFile = new File(fileName); +// FileInputStream fis = null; +// props = new Properties(); +// +// // determine the directory of the root config file +// rootConfigFileDir = new File(fileName).getParent(); +// +// try { +// rootConfigFileDir = new File(rootConfigFileDir).toURL().toString(); +// +// } catch (MalformedURLException t) { +// throw new ConfigurationException("config.03", null, t); +// } +// +// try { +// fis = new FileInputStream(propertiesFile); +// props.load(fis); +// +// // read MOAID Session Hibernate properties +// Properties moaSessionProp = new Properties(); +// for (Object key : props.keySet()) { +// String propPrefix = "moasession."; +// if (key.toString().startsWith(propPrefix+"hibernate")) { +// String propertyName = key.toString().substring(propPrefix.length()); +// moaSessionProp.put(propertyName, props.get(key.toString())); +// } +// } +// +// // read Config Hibernate properties +// Properties configProp = new Properties(); +// for (Object key : props.keySet()) { +// String propPrefix = "configuration."; +// if (key.toString().startsWith(propPrefix+"hibernate")) { +// String propertyName = key.toString().substring(propPrefix.length()); +// configProp.put(propertyName, props.get(key.toString())); +// } +// } +// +// // read advanced logging properties +// Properties statisticProps = new Properties(); +// for (Object key : props.keySet()) { +// String propPrefix = "advancedlogging."; +// if (key.toString().startsWith(propPrefix+"hibernate")) { +// String propertyName = key.toString().substring(propPrefix.length()); +// statisticProps.put(propertyName, props.get(key.toString())); +// } +// } +// +// // initialize hibernate +// synchronized (AuthConfigurationProvider.class) { +// +// //Initial config Database +// // ConfigurationDBUtils.initHibernate(configProp); +// +// //initial MOAID Session Database +// Configuration config = new Configuration(); +// config.addAnnotatedClass(AssertionStore.class); +// config.addAnnotatedClass(AuthenticatedSessionStore.class); +// config.addAnnotatedClass(OASessionStore.class); +// config.addAnnotatedClass(OldSSOSessionIDStore.class); +// config.addAnnotatedClass(ExceptionStore.class); +// config.addAnnotatedClass(InterfederationSessionStore.class); +// config.addAnnotatedClass(ProcessInstanceStore.class); +// config.addProperties(moaSessionProp); +// MOASessionDBUtils.initHibernate(config, moaSessionProp); // -// // ConfigurationDBUtils.delete(moaidconfig); -// for(String key : MOAIDConfigurationConstants.getMOAIDConfigurationKeys()){ -// NewConfigurationDBWrite.delete(key); +// //initial advanced logging +// if (isAdvancedLoggingActive()) { +// Logger.info("Advanced statistic log is activated, starting initialization process ..."); +// Configuration statisticconfig = new Configuration(); +// statisticconfig.addAnnotatedClass(StatisticLog.class); +// statisticconfig.addProperties(statisticProps); +// StatisticLogDBUtils.initHibernate(statisticconfig, statisticProps); +// Logger.info("Advanced statistic log is initialized."); // } -// } // +// } +// Logger.trace("Hibernate initialization finished."); // -// //List oas = ConfigurationDBRead.getAllOnlineApplications(); -// List oas = NewConfigurationDBRead.getAllOnlineApplications(); -// if (oas != null && oas.size() > 0) { -// // for (OnlineApplication oa : oas) -// // ConfigurationDBUtils.delete(oa); -// NewConfigurationDBWrite.delete(MOAIDConfigurationConstants.ONLINE_APPLICATIONS_KEY); -// } -// } -// -// //load legacy config if it is configured -// if (MiscUtil.isNotEmpty(legacyconfig)) { -// Logger.warn("WARNING! MOA-ID 2.0 is started with legacy configuration. This setup is not recommended!"); +// } catch (FileNotFoundException e) { +// throw new ConfigurationException("config.03", null, e); // -// MOAIDConfiguration moaconfig = BuildFromLegacyConfig.build(new File(legacyconfig), rootConfigFileDir, null); +// } catch (IOException e) { +// throw new ConfigurationException("config.03", null, e); // -// List oas = moaconfig.getOnlineApplication(); -// // for (OnlineApplication oa : oas) -// // ConfigurationDBUtils.save(oa); -// NewConfigurationDBWrite.saveOnlineApplications(oas); -// -// moaconfig.setOnlineApplication(null); -// // ConfigurationDBUtils.save(moaconfig); -// NewConfigurationDBWrite.save(moaconfig); +// } catch (ExceptionInInitializerError e) { +// throw new ConfigurationException("config.17", null, e); // -// Logger.info("Legacy Configuration load is completed."); +// } finally { +// if (fis != null) +// fis.close(); // -// // } -// -// //load MOA-ID 2.x config from XML -// if (MiscUtil.isNotEmpty(xmlconfig)) { -// Logger.warn("Load configuration from MOA-ID 2.x XML configuration"); // -// try { -// JAXBContext jc = JAXBContext.newInstance("at.gv.egovernment.moa.id.commons.db.dao.config"); -// Unmarshaller m = jc.createUnmarshaller(); -// File file = new File(xmlconfig); -// MOAIDConfiguration moaconfig = (MOAIDConfiguration) m.unmarshal(file); -// //ConfigurationDBUtils.save(moaconfig); // -// List importoas = moaconfig.getOnlineApplication(); -// // for (OnlineApplication importoa : importoas) { -// // ConfigurationDBUtils.saveOrUpdate(importoa); -// // } +// //Initialize OpenSAML for STORK +// Logger.info("Starting initialization of OpenSAML..."); +// MOADefaultBootstrap.bootstrap(); +// //DefaultBootstrap.bootstrap(); +// Logger.debug("OpenSAML successfully initialized"); +// // -// NewConfigurationDBWrite.saveOnlineApplications(importoas); +// String legacyconfig = props.getProperty("configuration.xml.legacy"); +// String xmlconfig = props.getProperty("configuration.xml"); +//// String xmlconfigout = props.getProperty("configuration.xml.out"); +// +// +// //configure eGovUtils client implementations +// +// //read eGovUtils client configuration +// Properties eGovUtilsConfigProp = new Properties(); +// for (Object key : props.keySet()) { +// String propPrefix = "service."; +// if (key.toString().startsWith(propPrefix+"egovutil")) { +// String propertyName = key.toString().substring(propPrefix.length()); +// eGovUtilsConfigProp.put(propertyName, props.get(key.toString())); +// } +// } +// if (!eGovUtilsConfigProp.isEmpty()) { +// Logger.info("Start eGovUtils client implementation configuration ..."); +// eGovUtilsConfig = +// new EgovUtilPropertiesConfiguration(eGovUtilsConfigProp, rootConfigFileDir); +// } +// +// +// //TODO: removed in MOA-ID 3.x +//// //check if XML config should be used +//// if (MiscUtil.isNotEmpty(legacyconfig) || MiscUtil.isNotEmpty(xmlconfig)) { +//// Logger.warn("WARNING! MOA-ID 2.0 is started with XML configuration. This setup overstrike the actual configuration in the Database!"); +//// //moaidconfig = ConfigurationDBRead.getMOAIDConfiguration(); +//// moaidconfig = NewConfigurationDBRead.getMOAIDConfiguration(); +//// if (moaidconfig.getAuthComponentGeneral()!= null || moaidconfig.getChainingModes() != null || moaidconfig.getTrustedCACertificates() != null || moaidconfig.getDefaultBKUs() != null +//// || moaidconfig.getSLRequestTemplates() != null || moaidconfig.getTimestampItem() != null || moaidconfig.getPvp2RefreshItem() != null) { +//// +//// // ConfigurationDBUtils.delete(moaidconfig); +//// for(String key : MOAIDConfigurationConstants.getMOAIDConfigurationKeys()){ +//// NewConfigurationDBWrite.delete(key); +//// } +//// } +//// +//// +//// //List oas = ConfigurationDBRead.getAllOnlineApplications(); +//// List oas = NewConfigurationDBRead.getAllOnlineApplications(); +//// if (oas != null && oas.size() > 0) { +//// // for (OnlineApplication oa : oas) +//// // ConfigurationDBUtils.delete(oa); +//// NewConfigurationDBWrite.delete(MOAIDConfigurationConstants.ONLINE_APPLICATIONS_KEY); +//// } +//// } +//// +//// //load legacy config if it is configured +//// if (MiscUtil.isNotEmpty(legacyconfig)) { +//// Logger.warn("WARNING! MOA-ID 2.0 is started with legacy configuration. This setup is not recommended!"); +//// +//// MOAIDConfiguration moaconfig = BuildFromLegacyConfig.build(new File(legacyconfig), rootConfigFileDir, null); +//// +//// List oas = moaconfig.getOnlineApplication(); +//// // for (OnlineApplication oa : oas) +//// // ConfigurationDBUtils.save(oa); +//// NewConfigurationDBWrite.saveOnlineApplications(oas); +//// +//// moaconfig.setOnlineApplication(null); +//// // ConfigurationDBUtils.save(moaconfig); +//// NewConfigurationDBWrite.save(moaconfig); +//// +//// Logger.info("Legacy Configuration load is completed."); +//// +//// +//// } +//// +//// //load MOA-ID 2.x config from XML +//// if (MiscUtil.isNotEmpty(xmlconfig)) { +//// Logger.warn("Load configuration from MOA-ID 2.x XML configuration"); +//// +//// try { +//// JAXBContext jc = JAXBContext.newInstance("at.gv.egovernment.moa.id.commons.db.dao.config"); +//// Unmarshaller m = jc.createUnmarshaller(); +//// File file = new File(xmlconfig); +//// MOAIDConfiguration moaconfig = (MOAIDConfiguration) m.unmarshal(file); +//// //ConfigurationDBUtils.save(moaconfig); +//// +//// List importoas = moaconfig.getOnlineApplication(); +//// // for (OnlineApplication importoa : importoas) { +//// // ConfigurationDBUtils.saveOrUpdate(importoa); +//// // } +//// +//// NewConfigurationDBWrite.saveOnlineApplications(importoas); +//// +//// moaconfig.setOnlineApplication(null); +//// //ConfigurationDBUtils.saveOrUpdate(moaconfig); +//// NewConfigurationDBWrite.save(moaconfig); +//// +//// } catch (Exception e) { +//// Logger.warn("MOA-ID XML configuration can not be loaded from File.", e); +//// throw new ConfigurationException("config.02", null); +//// } +//// Logger.info("XML Configuration load is completed."); +//// } +// +// reloadDataBaseConfig(); +// +// +// } catch (Throwable t) { +// throw new ConfigurationException("config.02", null, t); +// } +// } +// +// protected MOAIDConfiguration loadDataBaseConfig() { +// return ConfigurationDBRead.getMOAIDConfiguration(); +// } +// +// public synchronized void reloadDataBaseConfig() throws ConfigurationException { +// +// Logger.info("Read MOA-ID 2.0 configuration from database."); +// moaidconfig = loadDataBaseConfig(); +// Logger.info("MOA-ID 2.0 is loaded."); +// +// if (moaidconfig == null) { +// Logger.warn("NO MOA-ID configuration found."); +// throw new ConfigurationException("config.18", null); +// } +// +// //build STORK Config +// AuthComponentGeneral auth = getAuthComponentGeneral(); +// ForeignIdentities foreign = auth.getForeignIdentities(); +// if (foreign == null ) { +// Logger.warn("Error in MOA-ID Configuration. No STORK configuration found."); +// } else +// storkconfig = new STORKConfig(foreign.getSTORK(), props, rootConfigFileDir); +// +// //load Chaining modes +// ChainingModes cm = moaidconfig.getChainingModes(); +// if (cm != null) { +// defaultChainingMode = cm.getSystemDefaultMode().value(); +// +// List tas = cm.getTrustAnchor(); +// +// chainingModes = new HashMap(); +// for (TrustAnchor ta : tas) { +// IssuerAndSerial is = new IssuerAndSerial(ta.getX509IssuerName(), ta.getX509SerialNumber()); +// chainingModes.put(is, ta.getMode().value()); +// } +// } else { +// Logger.warn("Error in MOA-ID Configuration. No ChainingMode configuration found."); +// throw new ConfigurationException("config.02", null); +// } +// +// //set Trusted CA certs directory +// trustedCACertificates = rootConfigFileDir + moaidconfig.getTrustedCACertificates(); +// +// //set CertStoreDirectory +// setCertStoreDirectory(); +// +// //set TrustManagerRevocationChecking +// setTrustManagerRevocationChecking(); +// +// //set default timeouts +// timeouts = new TimeOuts(); +// timeouts.setAssertion(new BigInteger("300")); +// timeouts.setMOASessionCreated(new BigInteger("2700")); +// timeouts.setMOASessionUpdated(new BigInteger("1200")); +// +// //search timeouts in config +// if (auth.getGeneralConfiguration() != null) { +// if (auth.getGeneralConfiguration().getTimeOuts() != null) { +// if (auth.getGeneralConfiguration().getTimeOuts().getAssertion() != null) +// timeouts.setAssertion(auth.getGeneralConfiguration().getTimeOuts().getAssertion()); +// +// if (auth.getGeneralConfiguration().getTimeOuts().getMOASessionCreated() != null) +// timeouts.setMOASessionCreated(auth.getGeneralConfiguration().getTimeOuts().getMOASessionCreated()); +// +// if (auth.getGeneralConfiguration().getTimeOuts().getMOASessionUpdated() != null) +// timeouts.setMOASessionUpdated(auth.getGeneralConfiguration().getTimeOuts().getMOASessionUpdated()); +// +// } else { +// Logger.info("No TimeOuts defined. Use default values"); +// } +// } +// +// // sets the authentication session and authentication data time outs +// AuthenticationServer.getInstance() +// .setSecondsSessionTimeOutCreated(timeouts.getMOASessionCreated().longValue()); +// +// AuthenticationServer.getInstance() +// .setSecondsSessionTimeOutUpdated(timeouts.getMOASessionUpdated().longValue()); +// +// AuthenticationServer.getInstance() +// .setSecondsAuthDataTimeOut(timeouts.getAssertion().longValue()); +// +// +// +// //set PVP2 general config +// Protocols protocols = auth.getProtocols(); +// if (protocols != null) { +// +// allowedProtcols = new ProtocolAllowed(); // -// moaconfig.setOnlineApplication(null); -// //ConfigurationDBUtils.saveOrUpdate(moaconfig); -// NewConfigurationDBWrite.save(moaconfig); +// if (protocols.getSAML1() != null) { +// allowedProtcols.setSAML1Active(protocols.getSAML1().isIsActive()); +// +// //load alternative sourceID +// if (MiscUtil.isNotEmpty(protocols.getSAML1().getSourceID())) +// alternativesourceid = protocols.getSAML1().getSourceID(); +// +// } +// +// if (protocols.getOAuth() != null) { +// allowedProtcols.setOAUTHActive(protocols.getOAuth().isIsActive()); +// } // -// } catch (Exception e) { -// Logger.warn("MOA-ID XML configuration can not be loaded from File.", e); -// throw new ConfigurationException("config.02", null); +// if (protocols.getPVP2() != null) { +// PVP2 el = protocols.getPVP2(); +// +// allowedProtcols.setPVP21Active(el.isIsActive()); +// +// pvp2general = new PVP2(); +// pvp2general.setIssuerName(el.getIssuerName()); +// pvp2general.setPublicURLPrefix(el.getPublicURLPrefix()); +// +// if (el.getOrganization() != null) { +// Organization org = new Organization(); +// pvp2general.setOrganization(org); +// org.setDisplayName(el.getOrganization().getDisplayName()); +// org.setName(el.getOrganization().getName()); +// org.setURL(el.getOrganization().getURL()); +// } +// +// if (el.getContact() != null) { +// List cont = new ArrayList(); +// pvp2general.setContact(cont); +// for (Contact e : el.getContact()) { +// Contact c = new Contact(); +// c.setCompany(e.getCompany()); +// c.setGivenName(e.getGivenName()); +// c.getMail().addAll(e.getMail()); +// c.getPhone().addAll(e.getPhone()); +// c.setSurName(e.getSurName()); +// c.setType(e.getType()); +// cont.add(c); +// } +// } +// } +// } else { +// Logger.warn("Error in MOA-ID Configuration. No general Protcol configuration found."); +// } +// +// //set alternativeSourceID +// if (auth.getGeneralConfiguration() != null) { +// +// //TODO: can be removed in a further version, because it is moved to SAML1 config +// if (MiscUtil.isEmpty(alternativesourceid)) +// alternativesourceid = auth.getGeneralConfiguration().getAlternativeSourceID(); +// +// if (MiscUtil.isNotEmpty(auth.getGeneralConfiguration().getPublicURLPreFix())) +// publicURLPreFix = auth.getGeneralConfiguration().getPublicURLPreFix(); +// +// else { +// Logger.error("No Public URL Prefix configured."); +// throw new ConfigurationException("config.05", new Object[]{"Public URL Prefix"}); // } -// Logger.info("XML Configuration load is completed."); +// +// } else { +// Logger.warn("Error in MOA-ID Configuration. No GeneralConfig defined."); +// throw new ConfigurationException("config.02", null); +// } +// +// //set LegacyAllowedProtocols +// try { +// if (auth.getProtocols() != null) { +// Protocols procols = auth.getProtocols(); +// if (procols.getLegacyAllowed() != null) { +// LegacyAllowed legacy = procols.getLegacyAllowed(); +// legacyallowedprotocols = new ArrayList(legacy.getProtocolName()); +// } +// } +// } catch (Exception e) { +// Logger.info("No protocols found with legacy allowed flag!"); +// } +// +// //set VerifyAuthBlockConfig +// MOASP moasp = getMOASPConfig(auth); +// +// VerifyAuthBlock el = moasp.getVerifyAuthBlock(); +// if (el != null) { +// verifyidl = new VerifyAuthBlock(); +// verifyidl.setTrustProfileID(el.getTrustProfileID()); +// verifyidl.setVerifyTransformsInfoProfileID(new ArrayList(el.getVerifyTransformsInfoProfileID())); +// } +// else { +// Logger.warn("Error in MOA-ID Configuration. No Trustprofile for AuthBlock validation."); +// throw new ConfigurationException("config.02", null); // } - - reloadDataBaseConfig(); - - - } catch (Throwable t) { - throw new ConfigurationException("config.02", null, t); - } - } - - protected MOAIDConfiguration loadDataBaseConfig() { - return ConfigurationDBRead.getMOAIDConfiguration(); - } - - public synchronized void reloadDataBaseConfig() throws ConfigurationException { - - Logger.info("Read MOA-ID 2.0 configuration from database."); - moaidconfig = loadDataBaseConfig(); - Logger.info("MOA-ID 2.0 is loaded."); - - if (moaidconfig == null) { - Logger.warn("NO MOA-ID configuration found."); - throw new ConfigurationException("config.18", null); - } - - //build STORK Config - AuthComponentGeneral auth = getAuthComponentGeneral(); - ForeignIdentities foreign = auth.getForeignIdentities(); - if (foreign == null ) { - Logger.warn("Error in MOA-ID Configuration. No STORK configuration found."); - } else - storkconfig = new STORKConfig(foreign.getSTORK(), props, rootConfigFileDir); - - //load Chaining modes - ChainingModes cm = moaidconfig.getChainingModes(); - if (cm != null) { - defaultChainingMode = cm.getSystemDefaultMode().value(); - - List tas = cm.getTrustAnchor(); - - chainingModes = new HashMap(); - for (TrustAnchor ta : tas) { - IssuerAndSerial is = new IssuerAndSerial(ta.getX509IssuerName(), ta.getX509SerialNumber()); - chainingModes.put(is, ta.getMode().value()); - } - } else { - Logger.warn("Error in MOA-ID Configuration. No ChainingMode configuration found."); - throw new ConfigurationException("config.02", null); - } - - //set Trusted CA certs directory - trustedCACertificates = rootConfigFileDir + moaidconfig.getTrustedCACertificates(); - - //set CertStoreDirectory - setCertStoreDirectory(); - - //set TrustManagerRevocationChecking - setTrustManagerRevocationChecking(); - - //set default timeouts - timeouts = new TimeOuts(); - timeouts.setAssertion(new BigInteger("300")); - timeouts.setMOASessionCreated(new BigInteger("2700")); - timeouts.setMOASessionUpdated(new BigInteger("1200")); - - //search timeouts in config - if (auth.getGeneralConfiguration() != null) { - if (auth.getGeneralConfiguration().getTimeOuts() != null) { - if (auth.getGeneralConfiguration().getTimeOuts().getAssertion() != null) - timeouts.setAssertion(auth.getGeneralConfiguration().getTimeOuts().getAssertion()); - - if (auth.getGeneralConfiguration().getTimeOuts().getMOASessionCreated() != null) - timeouts.setMOASessionCreated(auth.getGeneralConfiguration().getTimeOuts().getMOASessionCreated()); - - if (auth.getGeneralConfiguration().getTimeOuts().getMOASessionUpdated() != null) - timeouts.setMOASessionUpdated(auth.getGeneralConfiguration().getTimeOuts().getMOASessionUpdated()); - - } else { - Logger.info("No TimeOuts defined. Use default values"); - } - } - - // sets the authentication session and authentication data time outs - AuthenticationServer.getInstance() - .setSecondsSessionTimeOutCreated(timeouts.getMOASessionCreated().longValue()); - - AuthenticationServer.getInstance() - .setSecondsSessionTimeOutUpdated(timeouts.getMOASessionUpdated().longValue()); - - AuthenticationServer.getInstance() - .setSecondsAuthDataTimeOut(timeouts.getAssertion().longValue()); - - - - //set PVP2 general config - Protocols protocols = auth.getProtocols(); - if (protocols != null) { - - allowedProtcols = new ProtocolAllowed(); - - if (protocols.getSAML1() != null) { - allowedProtcols.setSAML1Active(protocols.getSAML1().isIsActive()); - - //load alternative sourceID - if (MiscUtil.isNotEmpty(protocols.getSAML1().getSourceID())) - alternativesourceid = protocols.getSAML1().getSourceID(); - - } - - if (protocols.getOAuth() != null) { - allowedProtcols.setOAUTHActive(protocols.getOAuth().isIsActive()); - } - - if (protocols.getPVP2() != null) { - PVP2 el = protocols.getPVP2(); - - allowedProtcols.setPVP21Active(el.isIsActive()); - - pvp2general = new PVP2(); - pvp2general.setIssuerName(el.getIssuerName()); - pvp2general.setPublicURLPrefix(el.getPublicURLPrefix()); - - if (el.getOrganization() != null) { - Organization org = new Organization(); - pvp2general.setOrganization(org); - org.setDisplayName(el.getOrganization().getDisplayName()); - org.setName(el.getOrganization().getName()); - org.setURL(el.getOrganization().getURL()); - } - - if (el.getContact() != null) { - List cont = new ArrayList(); - pvp2general.setContact(cont); - for (Contact e : el.getContact()) { - Contact c = new Contact(); - c.setCompany(e.getCompany()); - c.setGivenName(e.getGivenName()); - c.getMail().addAll(e.getMail()); - c.getPhone().addAll(e.getPhone()); - c.setSurName(e.getSurName()); - c.setType(e.getType()); - cont.add(c); - } - } - } - } else { - Logger.warn("Error in MOA-ID Configuration. No general Protcol configuration found."); - } - - //set alternativeSourceID - if (auth.getGeneralConfiguration() != null) { - - //TODO: can be removed in a further version, because it is moved to SAML1 config - if (MiscUtil.isEmpty(alternativesourceid)) - alternativesourceid = auth.getGeneralConfiguration().getAlternativeSourceID(); - - if (MiscUtil.isNotEmpty(auth.getGeneralConfiguration().getPublicURLPreFix())) - publicURLPreFix = auth.getGeneralConfiguration().getPublicURLPreFix(); - - else { - Logger.error("No Public URL Prefix configured."); - throw new ConfigurationException("config.05", new Object[]{"Public URL Prefix"}); - } - - } else { - Logger.warn("Error in MOA-ID Configuration. No GeneralConfig defined."); - throw new ConfigurationException("config.02", null); - } - - //set LegacyAllowedProtocols - try { - if (auth.getProtocols() != null) { - Protocols procols = auth.getProtocols(); - if (procols.getLegacyAllowed() != null) { - LegacyAllowed legacy = procols.getLegacyAllowed(); - legacyallowedprotocols = new ArrayList(legacy.getProtocolName()); - } - } - } catch (Exception e) { - Logger.info("No protocols found with legacy allowed flag!"); - } - - //set VerifyAuthBlockConfig - MOASP moasp = getMOASPConfig(auth); - - VerifyAuthBlock el = moasp.getVerifyAuthBlock(); - if (el != null) { - verifyidl = new VerifyAuthBlock(); - verifyidl.setTrustProfileID(el.getTrustProfileID()); - verifyidl.setVerifyTransformsInfoProfileID(new ArrayList(el.getVerifyTransformsInfoProfileID())); - } - else { - Logger.warn("Error in MOA-ID Configuration. No Trustprofile for AuthBlock validation."); - throw new ConfigurationException("config.02", null); - } - - //set MOASP connection parameters - if (moasp.getConnectionParameter() != null) - MoaSpConnectionParameter = new ConnectionParameterMOASP(moasp.getConnectionParameter(), props, this.rootConfigFileDir); - else - MoaSpConnectionParameter = null; - - //set ForeignIDConnectionParameters - if (foreign != null) { - ForeignIDConnectionParameter = new ConnectionParameterForeign(foreign.getConnectionParameter(), props, this.rootConfigFileDir); - } else { - Logger.warn("Error in MOA-ID Configuration. No Connectionconfiguration to SZRGW Service found"); - } - - //set OnlineMandateConnectionParameters - OnlineMandates ovs = auth.getOnlineMandates(); - if (ovs != null) { - OnlineMandatesConnectionParameter = new ConnectionParameterMandate(ovs.getConnectionParameter(), props, this.rootConfigFileDir); - - } else { - Logger.warn("Error in MOA-ID Configuration. No Connectionconfiguration to OVS Service found"); - } - - //set MOASP IdentityLink Trust-ProfileID - VerifyIdentityLink verifyidl = moasp.getVerifyIdentityLink(); - if (verifyidl != null) - MoaSpIdentityLinkTrustProfileID = verifyidl.getTrustProfileID(); - else { - Logger.warn("Error in MOA-ID Configuration. No Trustprofile for IdentityLink validation."); - throw new ConfigurationException("config.02", null); - } - - //set SL transformation infos - SecurityLayer seclayer = auth.getSecurityLayer(); - if (seclayer == null) { - Logger.warn("Error in MOA-ID Configuration. No generalAuthConfiguration->SecurityLayer found"); - throw new ConfigurationException("config.02", null); - } else { - TransformsInfos = ConfigurationUtils.getTransformInfos(seclayer.getTransformsInfo()); - - if (TransformsInfos == null || TransformsInfos.size() == 0) { - Logger.error("No Security-Layer Transformation found."); - throw new ConfigurationException("config.05", new Object[]{"Security-Layer Transformation"}); - } - - } - - //set IdentityLinkSignerSubjectNames - IdentityLinkX509SubjectNames = new ArrayList(); - IdentityLinkSigners idlsigners = auth.getIdentityLinkSigners(); - if (idlsigners != null) { - Logger.debug("Load own IdentityLinkX509SubjectNames"); - IdentityLinkX509SubjectNames.addAll(new ArrayList(idlsigners.getX509SubjectName())); - } - - // now add the default identity link signers - String[] identityLinkSignersWithoutOID = MOAIDAuthConstants.IDENTITY_LINK_SIGNERS_WITHOUT_OID; - for (int i=0; i getLegacyAllowedProtocols() { - return legacyallowedprotocols; - } - - - /** - * Provides configuration information regarding the online application behind - * the given URL, relevant to the MOA-ID Auth component. - * - * @param oaURL URL requested for an online application - * @return an OAAuthParameter, or null - * if none is applicable - */ - public OAAuthParameter getOnlineApplicationParameter(String oaURL) { - - OnlineApplication oa = ConfigurationDBRead.getActiveOnlineApplication(oaURL); - - if (oa == null) { - Logger.warn("Online application with identifier " + oaURL + " is not found."); - return null; - } - - return new OAAuthParameter(oa); - } - - - /** - * 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 - * @throws ConfigurationException - */ - public String getMoaSpAuthBlockTrustProfileID() throws ConfigurationException { - return verifyidl.getTrustProfileID(); - } - - /** - * Return 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 - * @throws ConfigurationException - */ - public List getMoaSpAuthBlockVerifyTransformsInfoIDs() throws ConfigurationException { - return verifyidl.getVerifyTransformsInfoProfileID(); - } - - /** - * Return a ConnectionParameter bean containing all information - * of the authentication component moa-sp element - * @return ConnectionParameter of the authentication component moa-sp element - * @throws ConfigurationException - */ - public ConnectionParameter getMoaSpConnectionParameter() throws ConfigurationException { - return MoaSpConnectionParameter; - } - - /** - * Return a ConnectionParameter bean containing all information - * of the authentication component foreigid element - * @return ConnectionParameter of the authentication component foreignid element - * @throws ConfigurationException - */ - public ConnectionParameter getForeignIDConnectionParameter() throws ConfigurationException { - return ForeignIDConnectionParameter; - } - - /** - * Return a ConnectionParameter bean containing all information - * of the authentication component OnlineMandates element - * @return ConnectionParameter of the authentication component OnlineMandates element - * @throws ConfigurationException - */ - public ConnectionParameter getOnlineMandatesConnectionParameter() throws ConfigurationException { - return OnlineMandatesConnectionParameter; - } - - /** - * 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 - * @throws ConfigurationException - */ - public String getMoaSpIdentityLinkTrustProfileID() throws ConfigurationException { - return MoaSpIdentityLinkTrustProfileID; - } - - /** - * Returns the transformsInfos. - * @return String[] - * @throws ConfigurationException - */ - public List getTransformsInfos() throws ConfigurationException { - return TransformsInfos; - } - - /** - * Returns the identityLinkX509SubjectNames. - * @return List - * @throws ConfigurationException - */ - public List getIdentityLinkX509SubjectNames() throws ConfigurationException { - return IdentityLinkX509SubjectNames; - } - - public List getSLRequestTemplates() throws ConfigurationException { - return new ArrayList(SLRequestTemplates.values()); - } - - public String getSLRequestTemplates(String type) throws ConfigurationException { - String el = SLRequestTemplates.get(type); - if (MiscUtil.isNotEmpty(el)) - return el; - else { - Logger.warn("getSLRequestTemplates: BKU Type does not match: " - + IOAAuthParameters.ONLINEBKU + " or " + IOAAuthParameters.HANDYBKU + " or " + IOAAuthParameters.LOCALBKU); - return null; - } - } - - public List getDefaultBKUURLs() throws ConfigurationException { - return new ArrayList(DefaultBKUURLs.values()); - } - - public String getDefaultBKUURL(String type) throws ConfigurationException { - String el = DefaultBKUURLs.get(type); - if (MiscUtil.isNotEmpty(el)) - return el; - else { - Logger.warn("getSLRequestTemplates: BKU Type does not match: " - + IOAAuthParameters.ONLINEBKU + " or " + IOAAuthParameters.HANDYBKU + " or " + IOAAuthParameters.LOCALBKU); - return null; - } - } - -// public boolean isSSOBusinessService() throws ConfigurationException { +// +// //set MOASP connection parameters +// if (moasp.getConnectionParameter() != null) +// MoaSpConnectionParameter = new ConnectionParameterMOASP(moasp.getConnectionParameter(), props, this.rootConfigFileDir); +// else +// MoaSpConnectionParameter = null; +// +// //set ForeignIDConnectionParameters +// if (foreign != null) { +// ForeignIDConnectionParameter = new ConnectionParameterForeign(foreign.getConnectionParameter(), props, this.rootConfigFileDir); +// } else { +// Logger.warn("Error in MOA-ID Configuration. No Connectionconfiguration to SZRGW Service found"); +// } +// +// //set OnlineMandateConnectionParameters +// OnlineMandates ovs = auth.getOnlineMandates(); +// if (ovs != null) { +// OnlineMandatesConnectionParameter = new ConnectionParameterMandate(ovs.getConnectionParameter(), props, this.rootConfigFileDir); +// +// } else { +// Logger.warn("Error in MOA-ID Configuration. No Connectionconfiguration to OVS Service found"); +// } +// +// //set MOASP IdentityLink Trust-ProfileID +// VerifyIdentityLink verifyidl = moasp.getVerifyIdentityLink(); +// if (verifyidl != null) +// MoaSpIdentityLinkTrustProfileID = verifyidl.getTrustProfileID(); +// else { +// Logger.warn("Error in MOA-ID Configuration. No Trustprofile for IdentityLink validation."); +// throw new ConfigurationException("config.02", null); +// } +// +// //set SL transformation infos +// SecurityLayer seclayer = auth.getSecurityLayer(); +// if (seclayer == null) { +// Logger.warn("Error in MOA-ID Configuration. No generalAuthConfiguration->SecurityLayer found"); +// throw new ConfigurationException("config.02", null); +// } else { +// TransformsInfos = ConfigurationUtils.getTransformInfos(seclayer.getTransformsInfo()); +// +// if (TransformsInfos == null || TransformsInfos.size() == 0) { +// Logger.error("No Security-Layer Transformation found."); +// throw new ConfigurationException("config.05", new Object[]{"Security-Layer Transformation"}); +// } +// +// } +// +// //set IdentityLinkSignerSubjectNames +// IdentityLinkX509SubjectNames = new ArrayList(); +// IdentityLinkSigners idlsigners = auth.getIdentityLinkSigners(); +// if (idlsigners != null) { +// Logger.debug("Load own IdentityLinkX509SubjectNames"); +// IdentityLinkX509SubjectNames.addAll(new ArrayList(idlsigners.getX509SubjectName())); +// } +// +// // now add the default identity link signers +// String[] identityLinkSignersWithoutOID = MOAIDAuthConstants.IDENTITY_LINK_SIGNERS_WITHOUT_OID; +// for (int i=0; i getLegacyAllowedProtocols() { +// return legacyallowedprotocols; +// } +// +// +// /** +// * Provides configuration information regarding the online application behind +// * the given URL, relevant to the MOA-ID Auth component. +// * +// * @param oaURL URL requested for an online application +// * @return an OAAuthParameter, or null +// * if none is applicable +// */ +// public OAAuthParameter getOnlineApplicationParameter(String oaURL) { +// +// OnlineApplication oa = ConfigurationDBRead.getActiveOnlineApplication(oaURL); +// +// if (oa == null) { +// Logger.warn("Online application with identifier " + oaURL + " is not found."); +// return null; +// } // -// if (ssoconfig != null && ssoconfig.getIdentificationNumber() != null) -// return true; -// else -// return false; +// return new OAAuthParameter(oa); +// } +// +// +// /** +// * 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 +// * @throws ConfigurationException +// */ +// public String getMoaSpAuthBlockTrustProfileID() throws ConfigurationException { +// return verifyidl.getTrustProfileID(); +// } +// +// /** +// * Return 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 +// * @throws ConfigurationException +// */ +// public List getMoaSpAuthBlockVerifyTransformsInfoIDs() throws ConfigurationException { +// return verifyidl.getVerifyTransformsInfoProfileID(); +// } +// +// /** +// * Return a ConnectionParameter bean containing all information +// * of the authentication component moa-sp element +// * @return ConnectionParameter of the authentication component moa-sp element +// * @throws ConfigurationException +// */ +// public ConnectionParameter getMoaSpConnectionParameter() throws ConfigurationException { +// return MoaSpConnectionParameter; +// } +// +// /** +// * Return a ConnectionParameter bean containing all information +// * of the authentication component foreigid element +// * @return ConnectionParameter of the authentication component foreignid element +// * @throws ConfigurationException +// */ +// public ConnectionParameter getForeignIDConnectionParameter() throws ConfigurationException { +// return ForeignIDConnectionParameter; +// } +// +// /** +// * Return a ConnectionParameter bean containing all information +// * of the authentication component OnlineMandates element +// * @return ConnectionParameter of the authentication component OnlineMandates element +// * @throws ConfigurationException +// */ +// public ConnectionParameter getOnlineMandatesConnectionParameter() throws ConfigurationException { +// return OnlineMandatesConnectionParameter; +// } +// +// /** +// * 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 +// * @throws ConfigurationException +// */ +// public String getMoaSpIdentityLinkTrustProfileID() throws ConfigurationException { +// return MoaSpIdentityLinkTrustProfileID; +// } +// +// /** +// * Returns the transformsInfos. +// * @return String[] +// * @throws ConfigurationException +// */ +// public List getTransformsInfos() throws ConfigurationException { +// return TransformsInfos; +// } +// +// /** +// * Returns the identityLinkX509SubjectNames. +// * @return List +// * @throws ConfigurationException +// */ +// public List getIdentityLinkX509SubjectNames() throws ConfigurationException { +// return IdentityLinkX509SubjectNames; +// } +// +// public List getSLRequestTemplates() throws ConfigurationException { +// return new ArrayList(SLRequestTemplates.values()); +// } +// +// public String getSLRequestTemplates(String type) throws ConfigurationException { +// String el = SLRequestTemplates.get(type); +// if (MiscUtil.isNotEmpty(el)) +// return el; +// else { +// Logger.warn("getSLRequestTemplates: BKU Type does not match: " +// + IOAAuthParameters.ONLINEBKU + " or " + IOAAuthParameters.HANDYBKU + " or " + IOAAuthParameters.LOCALBKU); +// return null; +// } // } - - public String getSSOTagetIdentifier() throws ConfigurationException { - if (ssoconfig != null) - return ssoconfig.getTarget(); - else - return null; - } - -// public String getSSOTarget() throws ConfigurationException { -// if (ssoconfig!= null) +// +// public List getDefaultBKUURLs() throws ConfigurationException { +// return new ArrayList(DefaultBKUURLs.values()); +// } +// +// public String getDefaultBKUURL(String type) throws ConfigurationException { +// String el = DefaultBKUURLs.get(type); +// if (MiscUtil.isNotEmpty(el)) +// return el; +// else { +// Logger.warn("getSLRequestTemplates: BKU Type does not match: " +// + IOAAuthParameters.ONLINEBKU + " or " + IOAAuthParameters.HANDYBKU + " or " + IOAAuthParameters.LOCALBKU); +// return null; +// } +// } +// +//// public boolean isSSOBusinessService() throws ConfigurationException { +//// +//// if (ssoconfig != null && ssoconfig.getIdentificationNumber() != null) +//// return true; +//// else +//// return false; +//// } +// +// public String getSSOTagetIdentifier() throws ConfigurationException { +// if (ssoconfig != null) // return ssoconfig.getTarget(); +// else +// return null; +// } +// +//// public String getSSOTarget() throws ConfigurationException { +//// if (ssoconfig!= null) +//// return ssoconfig.getTarget(); +//// +//// return null; +//// } +// +// public String getSSOFriendlyName() { +// if (ssoconfig!= null) { +// if (MiscUtil.isNotEmpty(ssoconfig.getFriendlyName())) +// return ssoconfig.getFriendlyName(); +// } +// +// return "Default MOA-ID friendly name for SSO"; +// } +// +// public String getSSOSpecialText() { +// if (ssoconfig!= null) { +// String text = ssoconfig.getSpecialText(); +// if (MiscUtil.isEmpty(text)) +// text = new String(); +// +// return text; +// } +// return new String(); +// } +// +// public String getMOASessionEncryptionKey() { +// +// String prop = props.getProperty("configuration.moasession.key"); +// if (MiscUtil.isEmpty(prop)) +// return null; +// else +// return prop; +// } +// +// /** +// * @return +// */ +// public String getMOAConfigurationEncryptionKey() { +// String prop = props.getProperty("configuration.moaconfig.key"); +// if (MiscUtil.isEmpty(prop)) +// return null; +// else +// return prop; +// } +// +// public boolean isIdentityLinkResigning() { +// String prop = props.getProperty("configuration.resignidentitylink.active", "false"); +// return Boolean.valueOf(prop); +// } +// +// public String getIdentityLinkResigningKey() { +// String prop = props.getProperty("configuration.resignidentitylink.keygroup"); +// if (MiscUtil.isNotEmpty(prop)) +// return prop; +// else +// return null; +// } +// +// /** +// * Checks if is fakeIdL is activated. +// * +// * @return true, if fake IdLs are available for stork +// */ +// public boolean isStorkFakeIdLActive() { +// String prop = props.getProperty("stork.fakeIdL.active", "false"); +// return Boolean.valueOf(prop); +// } +// +// /** +// * Gets the countries which will receive a fake IdL +// * +// * @return the countries +// */ +// public List getStorkFakeIdLCountries() { +// String prop = props.getProperty("stork.fakeIdL.countries", ""); +// return Arrays.asList(prop.replaceAll(" ", "").split(",")); +// } +// +// /** +// * Gets the resigning key (group) for the stork fake IdL. +// * +// * @return the resigning key +// */ +// public String getStorkFakeIdLResigningKey() { +// String prop = props.getProperty("stork.fakeIdL.keygroup"); +// if (MiscUtil.isNotEmpty(prop)) +// return prop; +// else +// return null; +// } +// +// /** +// * Gets the countries for which it is configured to require no signature +// * +// * @return the stork no signature countries +// */ +// public List getStorkNoSignatureCountries() { +// String prop = props.getProperty("stork.fakeIdL.noSignatureCountries", ""); +// return Arrays.asList(prop.replaceAll(" ", "").split(",")); +// } +// +// @JsonProperty("isMonitoringActive") +// public boolean isMonitoringActive() { +// String prop = props.getProperty("configuration.monitoring.active", "false"); +// return Boolean.valueOf(prop); +// } +// +// public String getMonitoringTestIdentityLinkURL() { +// String prop = props.getProperty("configuration.monitoring.test.identitylink.url"); +// if (MiscUtil.isNotEmpty(prop)) +// return prop; +// else +// return null; +// } +// +// public String getMonitoringMessageSuccess() { +// String prop = props.getProperty("configuration.monitoring.message.success"); +// if (MiscUtil.isNotEmpty(prop)) +// return prop; +// else +// return null; +// } +// +// public boolean isAdvancedLoggingActive() { +// String prop = props.getProperty("configuration.advancedlogging.active", "false"); +// return Boolean.valueOf(prop); +// } +// +// public String getPublicURLPrefix() { +// return publicURLPreFix; +// } +// +// public boolean isPVP2AssertionEncryptionActive() { +// String prop = props.getProperty("protocols.pvp2.assertion.encryption.active", "true"); +// return Boolean.valueOf(prop); +// } +// +// public boolean isCertifiacteQCActive() { +// String prop = props.getProperty("configuration.validation.certificate.QC.ignore", "false"); +// return !Boolean.valueOf(prop); +// } +// +// +// //Load document service url from moa properties +// public String getDocumentServiceUrl() { +// String prop = props.getProperty("stork.documentservice.url", "false"); +// return prop; +// } +// +// +// public boolean isPVPSchemaValidationActive() { +// String prop = props.getProperty("protocols.pvp2.schemavalidation", "true"); +// return Boolean.valueOf(prop); +// } +// +// /** +// * Returns the STORK Configuration +// * @return STORK Configuration +// * @throws ConfigurationException +// */ +// public STORKConfig getStorkConfig() throws ConfigurationException { +// +// return storkconfig; +// } +// +// /** +// * @return the eGovUtilsConfig +// */ +//@JsonIgnore +//public EgovUtilPropertiesConfiguration geteGovUtilsConfig() { +// return eGovUtilsConfig; +//} +// +//private void setCertStoreDirectory() throws ConfigurationException { +// AuthComponentGeneral auth = getAuthComponentGeneral(); +// +// if (auth.getGeneralConfiguration() != null) +// certstoreDirectory = rootConfigFileDir + auth.getGeneralConfiguration().getCertStoreDirectory(); +// else { +// Logger.warn("Error in MOA-ID Configuration. No CertStoreDirectory defined."); +// throw new ConfigurationException("config.02", null); +// } +// } +// +// private void setTrustManagerRevocationChecking() throws ConfigurationException { +// AuthComponentGeneral auth = getAuthComponentGeneral(); +// +// if (auth.getGeneralConfiguration() != null && +// auth.getGeneralConfiguration().isTrustManagerRevocationChecking() != null) +// trustmanagerrevoationchecking = auth.getGeneralConfiguration().isTrustManagerRevocationChecking(); +// else { +// Logger.warn("No TrustMangerRevoationChecking defined. Use default value = TRUE"); +// throw new ConfigurationException("config.02", null); +// } +// } +// +// private static AuthComponentGeneral getAuthComponentGeneral() throws ConfigurationException { +// AuthComponentGeneral authgeneral = moaidconfig.getAuthComponentGeneral(); +// if (authgeneral == null) { +// Logger.warn("Error in MOA-ID Configuration. No generalAuthConfiguration found"); +// throw new ConfigurationException("config.02", null); +// } +// return authgeneral; +// } +// +// private static MOASP getMOASPConfig(AuthComponentGeneral authgeneral) throws ConfigurationException { +// MOASP moasp = authgeneral.getMOASP(); // -// return null; +// if (moasp == null) { +// Logger.warn("Error in MOA-ID Configuration. No MOASP configuration found"); +// throw new ConfigurationException("config.02", null); +// } +// return moasp; // } - - public String getSSOFriendlyName() { - if (ssoconfig!= null) { - if (MiscUtil.isNotEmpty(ssoconfig.getFriendlyName())) - return ssoconfig.getFriendlyName(); - } - - return "Default MOA-ID friendly name for SSO"; - } - - public String getSSOSpecialText() { - if (ssoconfig!= null) { - String text = ssoconfig.getSpecialText(); - if (MiscUtil.isEmpty(text)) - text = new String(); - - return text; - } - return new String(); - } - - public String getMOASessionEncryptionKey() { - - String prop = props.getProperty("configuration.moasession.key"); - if (MiscUtil.isEmpty(prop)) - return null; - else - return prop; - } - - /** - * @return - */ - public String getMOAConfigurationEncryptionKey() { - String prop = props.getProperty("configuration.moaconfig.key"); - if (MiscUtil.isEmpty(prop)) - return null; - else - return prop; - } - - public boolean isIdentityLinkResigning() { - String prop = props.getProperty("configuration.resignidentitylink.active", "false"); - return Boolean.valueOf(prop); - } - - public String getIdentityLinkResigningKey() { - String prop = props.getProperty("configuration.resignidentitylink.keygroup"); - if (MiscUtil.isNotEmpty(prop)) - return prop; - else - return null; - } - - /** - * Checks if is fakeIdL is activated. - * - * @return true, if fake IdLs are available for stork - */ - public boolean isStorkFakeIdLActive() { - String prop = props.getProperty("stork.fakeIdL.active", "false"); - return Boolean.valueOf(prop); - } - - /** - * Gets the countries which will receive a fake IdL - * - * @return the countries - */ - public List getStorkFakeIdLCountries() { - String prop = props.getProperty("stork.fakeIdL.countries", ""); - return Arrays.asList(prop.replaceAll(" ", "").split(",")); - } - - /** - * Gets the resigning key (group) for the stork fake IdL. - * - * @return the resigning key - */ - public String getStorkFakeIdLResigningKey() { - String prop = props.getProperty("stork.fakeIdL.keygroup"); - if (MiscUtil.isNotEmpty(prop)) - return prop; - else - return null; - } - - /** - * Gets the countries for which it is configured to require no signature - * - * @return the stork no signature countries - */ - public List getStorkNoSignatureCountries() { - String prop = props.getProperty("stork.fakeIdL.noSignatureCountries", ""); - return Arrays.asList(prop.replaceAll(" ", "").split(",")); - } - - @JsonProperty("isMonitoringActive") - public boolean isMonitoringActive() { - String prop = props.getProperty("configuration.monitoring.active", "false"); - return Boolean.valueOf(prop); - } - - public String getMonitoringTestIdentityLinkURL() { - String prop = props.getProperty("configuration.monitoring.test.identitylink.url"); - if (MiscUtil.isNotEmpty(prop)) - return prop; - else - return null; - } - - public String getMonitoringMessageSuccess() { - String prop = props.getProperty("configuration.monitoring.message.success"); - if (MiscUtil.isNotEmpty(prop)) - return prop; - else - return null; - } - - public boolean isAdvancedLoggingActive() { - String prop = props.getProperty("configuration.advancedlogging.active", "false"); - return Boolean.valueOf(prop); - } - - public String getPublicURLPrefix() { - return publicURLPreFix; - } - - public boolean isPVP2AssertionEncryptionActive() { - String prop = props.getProperty("protocols.pvp2.assertion.encryption.active", "true"); - return Boolean.valueOf(prop); - } - - public boolean isCertifiacteQCActive() { - String prop = props.getProperty("configuration.validation.certificate.QC.ignore", "false"); - return !Boolean.valueOf(prop); - } - - - //Load document service url from moa properties - public String getDocumentServiceUrl() { - String prop = props.getProperty("stork.documentservice.url", "false"); - return prop; - } - - - public boolean isPVPSchemaValidationActive() { - String prop = props.getProperty("protocols.pvp2.schemavalidation", "true"); - return Boolean.valueOf(prop); - } - - /** - * Returns the STORK Configuration - * @return STORK Configuration - * @throws ConfigurationException - */ - public STORKConfig getStorkConfig() throws ConfigurationException { - - return storkconfig; - } - - /** - * @return the eGovUtilsConfig - */ -@JsonIgnore -public EgovUtilPropertiesConfiguration geteGovUtilsConfig() { - return eGovUtilsConfig; -} - -private void setCertStoreDirectory() throws ConfigurationException { - AuthComponentGeneral auth = getAuthComponentGeneral(); - - if (auth.getGeneralConfiguration() != null) - certstoreDirectory = rootConfigFileDir + auth.getGeneralConfiguration().getCertStoreDirectory(); - else { - Logger.warn("Error in MOA-ID Configuration. No CertStoreDirectory defined."); - throw new ConfigurationException("config.02", null); - } - } - - private void setTrustManagerRevocationChecking() throws ConfigurationException { - AuthComponentGeneral auth = getAuthComponentGeneral(); - - if (auth.getGeneralConfiguration() != null && - auth.getGeneralConfiguration().isTrustManagerRevocationChecking() != null) - trustmanagerrevoationchecking = auth.getGeneralConfiguration().isTrustManagerRevocationChecking(); - else { - Logger.warn("No TrustMangerRevoationChecking defined. Use default value = TRUE"); - throw new ConfigurationException("config.02", null); - } - } - - private static AuthComponentGeneral getAuthComponentGeneral() throws ConfigurationException { - AuthComponentGeneral authgeneral = moaidconfig.getAuthComponentGeneral(); - if (authgeneral == null) { - Logger.warn("Error in MOA-ID Configuration. No generalAuthConfiguration found"); - throw new ConfigurationException("config.02", null); - } - return authgeneral; - } - - private static MOASP getMOASPConfig(AuthComponentGeneral authgeneral) throws ConfigurationException { - MOASP moasp = authgeneral.getMOASP(); - - if (moasp == null) { - Logger.warn("Error in MOA-ID Configuration. No MOASP configuration found"); - throw new ConfigurationException("config.02", null); - } - return moasp; - } - -/* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getConfigurationWithPrefix(java.lang.String) - */ -@Override -public Properties getConfigurationWithPrefix(String Prefix) { - // TODO Auto-generated method stub - return null; -} - -/* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getConfigurationWithKey(java.lang.String) - */ -@Override -public String getConfigurationWithKey(String key) { - // TODO Auto-generated method stub - return null; -} - -} +// +///* (non-Javadoc) +// * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getConfigurationWithPrefix(java.lang.String) +// */ +//@Override +//public Properties getConfigurationWithPrefix(String Prefix) { +// // TODO Auto-generated method stub +// return null; +//} +// +///* (non-Javadoc) +// * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getConfigurationWithKey(java.lang.String) +// */ +//@Override +//public String getConfigurationWithKey(String key) { +// // TODO Auto-generated method stub +// return null; +//} +// +//} 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 c336eb316..6bf9388dc 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 @@ -23,16 +23,14 @@ 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.commons.db.dao.config.AttributeProviderPlugin; -import at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS; -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.OAStorkAttribute; -import at.gv.egovernment.moa.id.commons.db.dao.config.TemplateType; -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.StorkAttribute; +import at.gv.egovernment.moa.id.config.stork.StorkAttributeProviderPlugin; /** * @author tlenz @@ -45,13 +43,33 @@ public interface IOAAuthParameters { 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(); public String getTarget(); + public String getTargetFriendlyName(); + public boolean isInderfederationIDP(); public boolean isSTORKPVPGateway(); @@ -66,34 +84,46 @@ public interface IOAAuthParameters { */ public String getKeyBoxIdentifier(); + public SAML1ConfigurationParameters getSAML1Parameter(); + /** - * @return the transformsInfos + * Get a list of online application specific trusted security layer templates + * + * @return a {List} with template URLs, maybe empty but never null */ - public List getTransformsInfos(); - - public OASAML1 getSAML1Parameter(); - - public OAPVP2 getPVP2Parameter(); + public List getTemplateURL(); + /** - * @return the templateURL + * Return the additional AuthBlock text for this online application + * + * @return authblock text {String} or null if no text is configured */ - public List getTemplateURL(); - 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(); - public String getSingleLogOutURL(); - /** - * @return the mandateProfiles + * Return all mandate-profile types configured for this online application + * + * @return the mandateProfiles {List} or null if no profile is defined */ public List getMandateProfiles(); @@ -117,20 +147,25 @@ public interface IOAAuthParameters { public Integer getQaaLevel(); - /** - * @return the requestedAttributes - */ - public List getRequestedAttributes(); - public boolean isRequireConsentForStorkAttributes(); - public List getStorkAPs(); + /** + * Return a {Collection} of requested STORK attributes + * + * @return {Collection} maybe empty but never null + */ + public Collection getRequestedSTORKAttributes(); public byte[] getBKUSelectionTemplate(); public byte[] getSendAssertionTemplate(); - public List getPepsList(); + /** + * Return a {Collection} of configured STORK CPEPS + * + * @return {Collection} maybe empty but never null + */ + public Collection getPepsList(); public String getIDPAttributQueryServiceURL(); @@ -164,5 +199,12 @@ public interface IOAAuthParameters { * @return */ boolean isPerformLocalAuthenticationOnInterfederationError(); + + /** + * Get a {Collection} of configured STORK attribute provider plug-ins + * + * @return {Collection} maybe empty but never null + */ + public Collection getStorkAPs(); } \ 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 933dddb31..dfe4a7448 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 @@ -49,134 +49,196 @@ package at.gv.egovernment.moa.id.config.auth; import java.io.IOException; import java.security.PrivateKey; import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; import org.apache.commons.lang.SerializationUtils; import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; -import at.gv.egovernment.moa.id.commons.db.dao.config.AuthComponentOA; -import at.gv.egovernment.moa.id.commons.db.dao.config.BKUSelectionCustomizationType; -import at.gv.egovernment.moa.id.commons.db.dao.config.BKUURLS; -import at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS; -import at.gv.egovernment.moa.id.commons.db.dao.config.IdentificationNumber; -import at.gv.egovernment.moa.id.commons.db.dao.config.InterfederationGatewayType; -import at.gv.egovernment.moa.id.commons.db.dao.config.InterfederationIDPType; -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.OAStorkAttribute; -import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; -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.TestCredentials; -import at.gv.egovernment.moa.id.commons.db.dao.config.TransformsInfoType; -import at.gv.egovernment.moa.id.config.ConfigurationUtils; -import at.gv.egovernment.moa.id.config.OAParameter; +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; + + /** * Configuration parameters belonging to an online application, * to use with the MOA ID Auth component. * - * @author Stefan Knirsch - * @version $Id$ + * @author Thomas Lenz */ -/** - * - * - * @author Harald Bratko - */ -public class OAAuthParameter extends OAParameter implements IOAAuthParameters { - - private AuthComponentOA oa_auth; - private String keyBoxIdentifier; - private InterfederationIDPType inderfederatedIDP = null; - private InterfederationGatewayType interfederatedGateway = null; +public class OAAuthParameter implements IOAAuthParameters { - public OAAuthParameter(OnlineApplication oa) { - super(oa); + final public static String DEFAULT_KEYBOXIDENTIFIER = "SECURE_SIGNATURE_KEYPAIR"; - this.oa_auth = oa.getAuthComponentOA(); + private Map oaConfiguration; - this.keyBoxIdentifier = oa.getKeyBoxIdentifier().value(); - this.inderfederatedIDP = oa.getInterfederationIDP(); - - this.interfederatedGateway = oa.getInterfederationGateway(); + public OAAuthParameter(final Map oa) { + this.oaConfiguration = oa; } + public Map getFullConfiguration() { + return Collections.unmodifiableMap(this.oaConfiguration); + } + + public String getConfigurationValue(String key) { + return this.oaConfiguration.get(key); + } + + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getIdentityLinkDomainIdentifier() */ @Override public String getIdentityLinkDomainIdentifier() { + String type = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_BUSINESS_TYPE); + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_BUSINESS_VALUE); + if (MiscUtil.isNotEmpty(type) && MiscUtil.isNotEmpty(value)) { + if (MOAIDConfigurationConstants.IDENIFICATIONTYPE_STORK.equals(type)) { + return MOAIDConfigurationConstants.PREFIX_STORK + "AT" + "+" + value; + + } else { + return MOAIDConfigurationConstants.PREFIX_WPBK + type + "+" + value; + + } + } - IdentificationNumber idnumber = oa_auth.getIdentificationNumber(); - if (idnumber != null) - return idnumber.getValue(); - return null; } /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getKeyBoxIdentifier() + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getIdentityLinkDomainIdentifierType() */ @Override -public String getKeyBoxIdentifier() { +public String getIdentityLinkDomainIdentifierType() { + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_BUSINESS_TYPE); + if (MiscUtil.isNotEmpty(value)) + return MOAIDConfigurationConstants.BUSINESSSERVICENAMES.get(value); - return keyBoxIdentifier; + else + return null; +} + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getTarget() + */ +@Override +public String getTarget() { + if (Boolean.parseBoolean(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_USE_OWN))) + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_OWN_TARGET); + + else { + if (Boolean.parseBoolean(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_USE_SUB))) { + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET) + + "-" + + oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET_SUB); + + } else { + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET); + } + } } /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getTransformsInfos() + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getTargetFriendlyName() */ @Override -public List getTransformsInfos() { +public String getTargetFriendlyName() { + if (Boolean.parseBoolean(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_USE_OWN))) + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_OWN_NAME); + + else + return TargetValidator.getTargetFriendlyName(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TARGET_PUBLIC_TARGET)); + +} + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getKeyBoxIdentifier() + */ +@Override +public String getKeyBoxIdentifier() { + String keyBoxId = oaConfiguration.get( + MOAIDConfigurationConstants.SERVICE_AUTH_BKU_KEYBOXIDENTIFIER); + if (MiscUtil.isNotEmpty(keyBoxId)) + return keyBoxId; + else + return DEFAULT_KEYBOXIDENTIFIER; - List transformations = oa_auth.getTransformsInfo(); - return ConfigurationUtils.getTransformInfos(transformations); } /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getSAML1Parameter() */ @Override - public OASAML1 getSAML1Parameter() { - return oa_auth.getOASAML1(); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getPVP2Parameter() - */ - @Override - public OAPVP2 getPVP2Parameter() { - return oa_auth.getOAPVP2(); + public SAML1ConfigurationParameters getSAML1Parameter() { + SAML1ConfigurationParameters returnValue = new SAML1ConfigurationParameters(); + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_ENABLED)) + returnValue.setActive( + Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_ENABLED))); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_AUTHBLOCK)) + returnValue.setProvideAuthBlock( + Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_AUTHBLOCK))); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_IDL)) + returnValue.setProvideIdl( + Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_IDL))); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_BASEID)) + returnValue.setProvideBaseId( + Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_BASEID))); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_CERTIFICATE)) + returnValue.setProvideCertificate( + Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_CERTIFICATE))); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_MANDATE)) + returnValue.setProvideMandate( + Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_MANDATE))); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_RETURNERROR)) + returnValue.setProvideAllErrors( + Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_SAML1_RETURNERROR))); + + return returnValue; } - + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getTemplateURL() */ @Override - public List getTemplateURL() { - TemplatesType templates = oa_auth.getTemplates(); - - if (templates != null) { - if (templates.getTemplate() != null) { - return templates.getTemplate(); - } - } - return null; + public List getTemplateURL() { + List list = new ArrayList(); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_FIRST_VALUE)) + list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_FIRST_VALUE)); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_SECOND_VALUE)) + list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_SECOND_VALUE)); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_THIRD_VALUE)) + list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_TEMPLATE_THIRD_VALUE)); + + return list; } /* (non-Javadoc) @@ -184,12 +246,8 @@ public List getTransformsInfos() { */ @Override public String getAditionalAuthBlockText() { - TemplatesType templates = oa_auth.getTemplates(); - - if (templates != null) { - return templates.getAditionalAuthBlockText(); - } - return null; + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_AUTHBLOCKTEXT); + } /* (non-Javadoc) @@ -197,16 +255,17 @@ public List getTransformsInfos() { */ @Override public String getBKUURL(String bkutype) { - BKUURLS bkuurls = oa_auth.getBKUURLS(); - if (bkuurls != null) { - if (bkutype.equals(ONLINEBKU)) - return bkuurls.getOnlineBKU(); - else if (bkutype.equals(HANDYBKU)) - return bkuurls.getHandyBKU(); - else if (bkutype.equals(LOCALBKU)) - return bkuurls.getLocalBKU(); + if (bkutype.equals(ONLINEBKU)) { + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_ONLINE); + + } else if (bkutype.equals(HANDYBKU)) { + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_HANDY); + + } else if (bkutype.equals(LOCALBKU)) { + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_LOCAL); } + Logger.warn("BKU Type does not match: " + ONLINEBKU + " or " + HANDYBKU + " or " + LOCALBKU); return null; @@ -216,19 +275,18 @@ public List getTransformsInfos() { * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getBKUURL() */ @Override - public List getBKUURL() { - BKUURLS bkuurls = oa_auth.getBKUURLS(); - + public List getBKUURL() { List list = new ArrayList(); - if (bkuurls == null) { - Logger.warn("BKU Type does not match: " - + ONLINEBKU + " or " + HANDYBKU + " or " + LOCALBKU); - } else { - list.add(bkuurls.getOnlineBKU()); - list.add(bkuurls.getHandyBKU()); - list.add(bkuurls.getLocalBKU()); - } + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_ONLINE)) + list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_ONLINE)); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_HANDY)) + list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_HANDY)); + + if (oaConfiguration.containsKey(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_LOCAL)) + list.add(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_LOCAL)); + return list; } @@ -238,11 +296,14 @@ public List getTransformsInfos() { */ @Override public boolean useSSO() { - OASSO sso = oa_auth.getOASSO(); - if (sso != null) - return sso.isUseSSO(); - else + try { + return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_SSO_ENABLED)); + + } catch (Exception e) { + Logger.warn("Use SSO configuration parameter is not parseable.", e); return false; + } + } /* (non-Javadoc) @@ -250,86 +311,48 @@ public List getTransformsInfos() { */ @Override public boolean useSSOQuestion() { - OASSO sso = oa_auth.getOASSO(); - if (sso != null) - return sso.isAuthDataFrame(); - else + try { + return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_SSO_USERREQUEST)); + + } catch (Exception e) { + Logger.warn("SSO user question configuration parameter is not parseable.", e); return true; - + } } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getSingleLogOutURL() - */ - @Override - public String getSingleLogOutURL() { - OASSO sso = oa_auth.getOASSO(); - if (sso != null) - return sso.getSingleLogOutURL(); - else - return null; - } - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getMandateProfiles() */ @Override public List getMandateProfiles() { + String profileConfig = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_MANDATES_PROFILES); + + if (MiscUtil.isNotEmpty(profileConfig)) { + List list = new ArrayList(); + String profilesArray[] = profileConfig.split(","); + for(int i = 0; i < profilesArray.length; i++) { + list.add(profilesArray[i].trim()); + + } + return list; + + } - Mandates mandates = oa_auth.getMandates(); - - List list = new ArrayList(); - - if (mandates != null) { - String oldProfilList = mandates.getProfiles(); - - List profileList = mandates.getProfileNameItems(); - for (MandatesProfileNameItem el : profileList) { - list.add(el.getItem()); - - } - - //only for RC1 - if (MiscUtil.isNotEmpty(oldProfilList)) { - String profilesArray[] = oldProfilList.split(","); - for(int i = 0; i < profilesArray.length; i++) { - list.add(profilesArray[i].trim()); - } - } - - return list; - - } else - return null; -} - -/* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getIdentityLinkDomainIdentifierType() - */ -@Override -public String getIdentityLinkDomainIdentifierType() { - IdentificationNumber idnumber = oa_auth.getIdentificationNumber(); - if (idnumber != null) - return idnumber.getType(); - return null; } - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isShowMandateCheckBox() */ @Override public boolean isShowMandateCheckBox() { - TemplatesType templates = oa_auth.getTemplates(); - if (templates != null) { - BKUSelectionCustomizationType bkuselection = templates.getBKUSelectionCustomization(); - if (bkuselection != null) { - if (bkuselection.isMandateLoginButton() != null) - return bkuselection.isMandateLoginButton(); - } + try { + return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_MANDATES_USE)); + + } catch (Exception e) { + Logger.warn("Enable mandates configuration parameter is not parseable.", e); + return true; } - return true; } /* (non-Javadoc) @@ -337,15 +360,13 @@ public boolean isShowMandateCheckBox() { */ @Override public boolean isOnlyMandateAllowed() { - TemplatesType templates = oa_auth.getTemplates(); - if (templates != null) { - BKUSelectionCustomizationType bkuselection = templates.getBKUSelectionCustomization(); - if (bkuselection != null) { - if (bkuselection.isOnlyMandateLoginAllowed() != null) - return bkuselection.isOnlyMandateLoginAllowed(); - } + try { + return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_MANDATES_ONLY)); + + } catch (Exception e) { + Logger.warn("Use ONLY mandates configuration parameter is not parseable.", e); + return false; } - return false; } /* (non-Javadoc) @@ -354,9 +375,10 @@ public boolean isOnlyMandateAllowed() { @Override public boolean isShowStorkLogin() { try { - return oa_auth.getOASTORK().isStorkLogonEnabled(); - - } catch (NullPointerException e) { + return Boolean.valueOf(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ENABLED)); + + } catch (Exception e) { + Logger.warn("Enable STORK login configuration parameter is not parseable.", e); return false; } } @@ -365,54 +387,46 @@ public boolean isOnlyMandateAllowed() { * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getFormCustomizaten() */ @Override -public Map getFormCustomizaten() { - TemplatesType templates = oa_auth.getTemplates(); - +public Map getFormCustomizaten() { Map map = new HashMap(); map.putAll(FormBuildUtils.getDefaultMap()); - if (templates != null) { - BKUSelectionCustomizationType bkuselection = templates.getBKUSelectionCustomization(); - if (bkuselection != null) { - if (MiscUtil.isNotEmpty(bkuselection.getBackGroundColor())) - map.put(FormBuildUtils.MAIN_BACKGROUNDCOLOR, bkuselection.getBackGroundColor()); - - if (MiscUtil.isNotEmpty(bkuselection.getButtonBackGroundColor())) - map.put(FormBuildUtils.BUTTON_BACKGROUNDCOLOR, bkuselection.getButtonBackGroundColor()); - - if (MiscUtil.isNotEmpty(bkuselection.getButtonBackGroundColorFocus())) - map.put(FormBuildUtils.BUTTON_BACKGROUNDCOLOR_FOCUS, bkuselection.getButtonBackGroundColorFocus()); - - if (MiscUtil.isNotEmpty(bkuselection.getButtonFontColor())) - map.put(FormBuildUtils.BUTTON_COLOR, bkuselection.getButtonFontColor()); - - if (MiscUtil.isNotEmpty(bkuselection.getFontType())) - map.put(FormBuildUtils.FONTFAMILY, bkuselection.getFontType()); - - if (MiscUtil.isNotEmpty(bkuselection.getFrontColor())) - map.put(FormBuildUtils.MAIN_COLOR, bkuselection.getFrontColor()); - - if (MiscUtil.isNotEmpty(bkuselection.getHeaderBackGroundColor())) - map.put(FormBuildUtils.HEADER_BACKGROUNDCOLOR, bkuselection.getHeaderBackGroundColor()); - - if (MiscUtil.isNotEmpty(bkuselection.getHeaderFrontColor())) - map.put(FormBuildUtils.HEADER_COLOR, bkuselection.getHeaderFrontColor()); - - if (MiscUtil.isNotEmpty(bkuselection.getHeaderText())) - map.put(FormBuildUtils.HEADER_TEXT, bkuselection.getHeaderText()); - - if (MiscUtil.isNotEmpty(bkuselection.getAppletRedirectTarget())) - map.put(FormBuildUtils.REDIRECTTARGET, bkuselection.getAppletRedirectTarget()); - - if (MiscUtil.isNotEmpty(bkuselection.getAppletHeight())) - map.put(FormBuildUtils.APPLET_HEIGHT, bkuselection.getAppletHeight()); - - if (MiscUtil.isNotEmpty(bkuselection.getAppletWidth())) - map.put(FormBuildUtils.APPLET_WIDTH, bkuselection.getAppletWidth()); - - } - } + 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; } @@ -421,21 +435,75 @@ public Map getFormCustomizaten() { */ @Override public Integer getQaaLevel() { - if (oa_auth.getOASTORK() != null && - oa_auth.getOASTORK().getQaa() != null && - oa_auth.getOASTORK().getQaa() >= 1 && - oa_auth.getOASTORK().getQaa() <= 4) - return oa_auth.getOASTORK().getQaa(); - else + try { + Integer storkQAALevel = Integer.parseInt(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_MINQAALEVEL)); + + if (storkQAALevel >= 1 && + storkQAALevel <= 4) + return storkQAALevel; + + else { + Logger.info("STORK minimal QAA level is not in a valid range. Use minimal QAA 4"); + return 4; + + } + + } catch (NumberFormatException e) { + Logger.warn("STORK minimal QAA level is not a number.", e); return 4; + + } } /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getRequestedAttributes() */ @Override -public List getRequestedAttributes() { - return oa_auth.getOASTORK().getOAAttributes(); +public Collection getRequestedSTORKAttributes() { + Map attrMap = new HashMap(); + Map resultMap = new HashMap(); + + Set configKeys = oaConfiguration.keySet(); + for (String el : configKeys) { + if (el.startsWith(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST)) { + String index = KeyValueUtils.getFirstChildAfterPrefix(el, MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST); + if (!attrMap.containsKey(index)) { + String isRequested = oaConfiguration.get( + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST + + "." + index + "." + + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST_REQUESTED); + + if (MiscUtil.isNotEmpty(isRequested) && Boolean.parseBoolean(isRequested)) { + StorkAttribute attr = new StorkAttribute( + oaConfiguration.get( + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST + + "." + index + "." + + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST_NAME), + Boolean.valueOf(oaConfiguration.get( + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST + + "." + index + "." + + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTES_LIST_MANDATORY))); + attrMap.put(index, 0); + resultMap.put(attr.getName(), attr); + } + } + } + } + + //add mandatory attributes from general config + try { + for (StorkAttribute el : AuthConfigurationProviderFactory.getInstance().getStorkConfig().getStorkAttributes()) { + if (el.getMandatory()) + resultMap.put(el.getName(), el); + + } + + } catch (Exception e) { + Logger.warn("Mandatory STORK attributes can not added.", e); + + } + + return resultMap.values(); } /* (non-Javadoc) @@ -446,12 +514,17 @@ public boolean isRequireConsentForStorkAttributes() { try{ if (isSTORKPVPGateway()) return false; + + if (MiscUtil.isEmpty(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_REQUIRECONSENT))) { + Logger.info("isRequireConsentForStorkAttributes() is empty, returning default value 'true'"); + return true; + + } - return oa_auth.getOASTORK().isRequireConsent(); + return Boolean.parseBoolean(oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_REQUIRECONSENT)); }catch(Exception e) { - e.printStackTrace(); - Logger.warn("isRequireConsentForStorkAttributes() failed, returning default value 'true'"); + Logger.warn("isRequireConsentForStorkAttributes() failed, returning default value 'true'", e); return true; } } @@ -460,14 +533,32 @@ public boolean isRequireConsentForStorkAttributes() { * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getStorkAPs() */ @Override -public List getStorkAPs() { - if (oa_auth.getOASTORK() != null && - oa_auth.getOASTORK().getAttributeProviders() != null) - return oa_auth.getOASTORK().getAttributeProviders(); - - else - return new ArrayList(); - +public Collection getStorkAPs() { + Map pluginMap = new HashMap(); + Set configKeys = oaConfiguration.keySet(); + for (String el : configKeys) { + if (el.startsWith(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST)) { + String index = KeyValueUtils.getFirstChildAfterPrefix(el, MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST); + if (!pluginMap.containsKey(index)) { + StorkAttributeProviderPlugin attr = new StorkAttributeProviderPlugin( + oaConfiguration.get( + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST + + "." + index + "." + + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST_NAME), + oaConfiguration.get( + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST + + "." + index + "." + + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST_URL), + oaConfiguration.get( + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST + + "." + index + "." + + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_ATTRIBUTPROVIDER_LIST_ATTRIBUTES)); + pluginMap.put(index, attr); + } + } + } + + return pluginMap.values(); } /* (non-Javadoc) @@ -475,11 +566,16 @@ public List getStorkAPs() { */ @Override public byte[] getBKUSelectionTemplate() { - - TemplatesType templates = oa_auth.getTemplates(); - if (templates != null && templates.getBKUSelectionTemplate() != null) { - return templates.getBKUSelectionTemplate().getTransformation(); - + try { + String bkuSelectionTemplateBase64 = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_BKUSELECTION); + if (MiscUtil.isNotEmpty(bkuSelectionTemplateBase64)) { + return Base64Utils.decode(bkuSelectionTemplateBase64, false); + + } + + } catch (Exception e) { + Logger.warn("OA specific BKU selection template is not decodeable", e); + } return null; @@ -490,11 +586,16 @@ public byte[] getBKUSelectionTemplate() { */ @Override public byte[] getSendAssertionTemplate() { - - TemplatesType templates = oa_auth.getTemplates(); - if (templates != null && templates.getSendAssertionTemplate() != null) { - return templates.getSendAssertionTemplate().getTransformation(); - + try { + String bkuSelectionTemplateBase64 = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TEMPLATES_SENDASSERTION); + if (MiscUtil.isNotEmpty(bkuSelectionTemplateBase64)) { + return Base64Utils.decode(bkuSelectionTemplateBase64, false); + + } + + } catch (Exception e) { + Logger.warn("OA specific BKU selection template is not decodeable", e); + } return null; @@ -504,8 +605,41 @@ public byte[] getSendAssertionTemplate() { * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getPepsList() */ @Override -public List getPepsList() { - return new ArrayList(oa_auth.getOASTORK().getCPEPS()); +public Collection getPepsList() { + Map cPEPSMap = new HashMap(); + try { + STORKConfig availableSTORKConfig = AuthConfigurationProviderFactory.getInstance().getStorkConfig(); + if (availableSTORKConfig != null) { + Set configKeys = oaConfiguration.keySet(); + + for (String el : configKeys) { + if (el.startsWith(MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST)) { + String index = KeyValueUtils.getFirstChildAfterPrefix(el, MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST); + if (!cPEPSMap.containsKey(index)) { + if (Boolean.parseBoolean(oaConfiguration.get( + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST + + "." + index + "." + + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST_ENABLED))) { + CPEPS availableCPEPS = availableSTORKConfig.getCPEPS( + oaConfiguration.get( + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST + + "." + index + "." + + MOAIDConfigurationConstants.SERVICE_AUTH_STORK_COUNTRIES_LIST_COUNTRYCODE)); + + if (availableCPEPS != null) + cPEPSMap.put(index, availableCPEPS); + } + } + } + } + } + + } catch (ConfigurationException e) { + Logger.error("MOA-ID configuration is not accessable.", e); + + } + + return cPEPSMap.values(); } /* (non-Javadoc) @@ -513,52 +647,53 @@ public List getPepsList() { */ @Override public String getIDPAttributQueryServiceURL() { - if (inderfederatedIDP != null) - return inderfederatedIDP.getAttributeQueryURL(); - - else - return null; - + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_ATTRIBUTQUERY_URL); + } @Override public boolean isInboundSSOInterfederationAllowed() { - if (inderfederatedIDP != null) - return inderfederatedIDP.isInboundSSO(); + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_SSO_INBOUND); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); else return false; } @Override public boolean isOutboundSSOInterfederationAllowed() { - if (inderfederatedIDP != null) - return inderfederatedIDP.isOutboundSSO(); + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_SSO_OUTBOUND); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); else return false; } @Override public boolean isPassivRequestUsedForInterfederation() { - if (inderfederatedIDP != null) - return inderfederatedIDP.isPerformPassivRequest().booleanValue(); + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_PASSIVEREQUEST); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); else - return false; + return false; } @Override public boolean isPerformLocalAuthenticationOnInterfederationError() { - if (inderfederatedIDP != null) - return inderfederatedIDP.isPerformLocalAuthenticationOnError().booleanValue(); + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_LOCALAUTHONERROR); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); else return false; } @Override public boolean isInterfederationSSOStorageAllowed() { - if (inderfederatedIDP != null) - return inderfederatedIDP.isStoreSSOSession().booleanValue(); + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_SSO_STORE); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); else - return false; + return false; } public boolean isIDPPublicService() { @@ -568,11 +703,7 @@ public boolean isIDPPublicService() { public String getSTORKPVPForwardEntity() { - if (interfederatedGateway != null) { - return interfederatedGateway.getForwardIDPIdentifier(); - - } else - return null; + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_INTERFEDERATION_FORWARD_IDPIDENTIFIER); } @@ -581,11 +712,11 @@ public String getSTORKPVPForwardEntity() { */ @Override public boolean isTestCredentialEnabled() { - TestCredentials testing = oa_auth.getTestCredentials(); - if (testing != null && testing.isEnableTestCredentials()) - return true; + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_ENABLED); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); else - return false; + return false; } @@ -594,10 +725,17 @@ public boolean isTestCredentialEnabled() { */ @Override public List getTestCredentialOIDs() { - TestCredentials testing = oa_auth.getTestCredentials(); - if (testing != null && testing.getCredentialOID().size() > 0) - return testing.getCredentialOID(); - else + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_TESTCREDENTIALS_ENABLED); + if (MiscUtil.isNotEmpty(value)) { + List list = new ArrayList(); + String profilesArray[] = value.split(","); + for(int i = 0; i < profilesArray.length; i++) { + list.add(profilesArray[i].trim()); + + } + return list; + + } else return null; } @@ -610,8 +748,11 @@ public PrivateKey getBPKDecBpkDecryptionKey() { try { EncryptedData encdata = new EncryptedData( - oa_auth.getEncBPKInformation().getBPKDecryption().getKeyInformation(), - oa_auth.getEncBPKInformation().getBPKDecryption().getIv()); + Base64Utils.decode( + oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_FOREIGNBPK_DECRYPT_BLOB), false), + Base64Utils.decode( + oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_FOREIGNBPK_DECRYPT_IV), false)); + byte[] serializedData = ConfigurationEncrytionUtil.getInstance().decrypt(encdata); BPKDecryptionParameters data = (BPKDecryptionParameters) SerializationUtils.deserialize(serializedData); @@ -619,15 +760,96 @@ public PrivateKey getBPKDecBpkDecryptionKey() { return data.getPrivateKey(); } catch (BuildException e) { - // TODO Auto-generated catch block Logger.error("Can not decrypt key information for bPK decryption", e); } catch (NullPointerException e) { Logger.error("No keyInformation found for bPK decryption"); - } + } catch (IOException e) { + Logger.error("Can not decode key information for bPK decryption.", e); + } + return null; } + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getPublicURLPrefix() + */ +@Override +public String getPublicURLPrefix() { + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_UNIQUEIDENTIFIER); +} + + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getBusinessService() + */ +@Override +public boolean getBusinessService() { + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_BUSINESSSERVICE); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); + else + return true; +} + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isInderfederationIDP() + */ +@Override +public boolean isInderfederationIDP() { + String value = oaConfiguration.get(MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES); + return MOAIDConfigurationConstants.PREFIX_IIDP.equals(value); + +} + + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isSTORKPVPGateway() + */ +@Override +public boolean isSTORKPVPGateway() { + String value = oaConfiguration.get(MOAIDConfigurationConstants.PREFIX_MOAID_SERVICES); + return MOAIDConfigurationConstants.PREFIX_GATEWAY.equals(value); +} + + + + + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getFriendlyName() + */ +@Override +public String getFriendlyName() { + return oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_FRIENDLYNAME); +} + + +/* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getOaType() + */ +@Override +public String getOaType() { + if (getBusinessService()) + return "businessService"; + else + return "publicService"; +} + + +/** + * + * @return true/false if bPK or wbPK should not be visible in AuthBlock + */ +public boolean isRemovePBKFromAuthBlock() { + String value = oaConfiguration.get(MOAIDConfigurationConstants.SERVICE_AUTH_BKU_AUTHBLOCK_REMOVEBPK); + if (MiscUtil.isNotEmpty(value)) + return Boolean.parseBoolean(value); + else + return false; +} + } 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 2cd14e607..60ae3882e 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 @@ -9,41 +9,22 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.Date; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Properties; import org.springframework.beans.factory.annotation.Autowired; - -import com.fasterxml.jackson.annotation.JsonIgnore; +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.config.MOAIDConfigurationConstants; import at.gv.egovernment.moa.id.commons.config.persistence.MOAIDConfiguration; -import at.gv.egovernment.moa.id.commons.db.dao.config.AuthComponentGeneral; -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.IdentityLinkSigners; -import at.gv.egovernment.moa.id.commons.db.dao.config.LegacyAllowed; -import at.gv.egovernment.moa.id.commons.db.dao.config.MOASP; -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.TimeOuts; -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.config.ConfigurationProviderImpl; import at.gv.egovernment.moa.id.config.ConfigurationUtils; import at.gv.egovernment.moa.id.config.ConnectionParameter; @@ -54,10 +35,8 @@ 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.id.protocols.saml1.SAML1Protocol; -import at.gv.egovernment.moa.id.protocols.saml1.SAML1RequestImpl; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -import at.gv.util.config.EgovUtilPropertiesConfiguration; /** * A class providing access to the Auth Part of the MOA-ID configuration data. @@ -68,12 +47,11 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide private static final boolean TRUST_MANAGER_REVOCATION_CHECKING_DEFAULT = true; private MOAIDConfiguration configuration; - private final Properties properties = new Properties(); - private EgovUtilPropertiesConfiguration eGovUtilsConfig = null; - + private ApplicationContext context = null; public PropertyBasedAuthConfigurationProvider() { + } /** @@ -86,29 +64,39 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide File propertiesFile = new File(fileName); rootConfigFileDir = propertiesFile.getParent(); - try (FileInputStream in = new FileInputStream(propertiesFile);) { - properties.load(in); - - //read eGovUtils client configuration - Properties eGovUtilsConfigProp = new Properties(); - for (Object key : properties.keySet()) { - String propPrefix = "service."; - if (key.toString().startsWith(propPrefix+"egovutil")) { - String propertyName = key.toString().substring(propPrefix.length()); - eGovUtilsConfigProp.put(propertyName, properties.get(key.toString())); - } - } - if (!eGovUtilsConfigProp.isEmpty()) { - Logger.info("Start eGovUtils client implementation configuration ..."); - eGovUtilsConfig = - new EgovUtilPropertiesConfiguration(eGovUtilsConfigProp, rootConfigFileDir); - } - + 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); + + FileInputStream in = null; + try { + in = new FileInputStream(propertiesFile); + properties.load(in); + super.initial(properties); } catch (FileNotFoundException e) { throw new ConfigurationException("config.03", null, e); + } catch (IOException e) { throw new ConfigurationException("config.03", null, e); + + } catch (org.opensaml.xml.ConfigurationException e) { + Logger.error("OpenSAML initilalization FAILED. ", e); + throw new ConfigurationException("config.23", null, e); + + } finally { + if (in != null) + try { + in.close(); + + } catch (IOException e) { + Logger.warn("Close MOA-ID-Auth configuration file FAILED.", e); + + } } } @@ -147,17 +135,33 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getPropertiesWithPrefix(java.lang.String) */ @Override - public Properties getConfigurationWithPrefix(String Prefix) { + public Map getConfigurationWithPrefix(String Prefix) { try { return configuration.getPropertySubset(Prefix); } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { Logger.warn("Loading property with Prefix " + Prefix + " FAILED.", e); - return new Properties(); + return new HashMap(); } } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getPropertiesWithPrefix(java.lang.String) + */ + @Override + public Map getConfigurationWithWildCard(String key) { + try { + return configuration.searchPropertiesWithWildcard(key); + + } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { + Logger.warn("Loading property with searchKey " + key + " FAILED.", e); + return new HashMap(); + + } + } + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getPropertyWithKey(java.lang.String) */ @@ -358,8 +362,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @return an OAAuthParameter, or null if none is applicable */ public OAAuthParameter getOnlineApplicationParameter(String oaURL) { - //TODO: update!!!!! - OnlineApplication oa = getActiveOnlineApplication(oaURL); + Map oa = getActiveOnlineApplication(oaURL); if (oa == null) { Logger.warn("Online application with identifier " + oaURL + " is not found."); return null; @@ -835,7 +838,7 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide public STORKConfig getStorkConfig() throws ConfigurationException { STORKConfig result = null; try { - Properties storkProps = configuration.getPropertySubset( + Map storkProps = configuration.getPropertySubset( MOAIDConfigurationConstants.GENERAL_AUTH_STORK); if (storkProps == null) { Logger.warn("Error in MOA-ID Configuration. No STORK configuration found."); @@ -975,50 +978,6 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide } } - /** - * Returns the default chaining mode or {@code null} if there is no chaining mode defined. - * - * @return the default chaining mode or {@code null} - */ - @Override - public String getDefaultChainingMode() { - return "pkix"; - } - - /** - * Returns a list of all {@link OnlineApplication}. - * - * @return list of all OnlineApplications - */ - public List getAllOnlineApplications() { - Logger.trace("Get all OnlineApplications from database."); - - return configuration.getList(MOAIDConfigurationConstants.ONLINE_APPLICATIONS_KEY, OnlineApplication.class); - } - - /** - * Returns a list of all active {@link OnlineApplication} or {@code null} if no active online application was found. - * - * @return list of all active OnlineApplications or {@code null}. - */ - public List getAllActiveOnlineApplications() { - Logger.debug("Get all new OnlineApplications from database."); - - List result = new ArrayList(); - List allOAs = getAllOnlineApplications(); - - for (OnlineApplication oa : nullGuard(allOAs)) { - if (oa.isIsActive()) { - result.add(oa); - } - } - if (result.size() == 0) { - Logger.trace("No entries found."); - return null; - } - return result; - } - /** * Returns the active {@link OnlineApplication} with the given ID or {@code null} if either no matching online application is found or if the {@code id} * matches more than one entry. @@ -1026,26 +985,25 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide * @param id the id of the requested online application * @return the requested online application or {@code null} */ - public OnlineApplication getActiveOnlineApplication(String id) { - Logger.trace("Get active OnlineApplication with ID " + id + " from database."); - - OnlineApplication result = null; - List allActiveOAs = getAllActiveOnlineApplications(); - - for (OnlineApplication oa : nullGuard(allActiveOAs)) { - String publicUrlPrefix = oa.getPublicURLPrefix(); - if (publicUrlPrefix != null && publicUrlPrefix.length() <= id.length()) { - if ((id.substring(1, publicUrlPrefix.length()).equals(publicUrlPrefix))) { - if (result != null) { - Logger.warn("OAIdentifier matches more than one DB-entry!"); - return null; - } else { - result = oa; - } - } + public Map getActiveOnlineApplication(String id) { + Logger.trace("Get active OnlineApplication with ID " + id + " from database."); + try { + Map oaConfig = configuration.getOnlineApplication(id); + if (oaConfig != null) { + String isActiveString = oaConfig.get(MOAIDConfigurationConstants.SERVICE_ISACTIVE); + if (isActiveString != null && Boolean.valueOf(isActiveString)) + return oaConfig; + } - } - return result; + + + } catch (at.gv.egiz.components.configuration.api.ConfigurationException e) { + Logger.error("Error during OnlineApplication load operationen (oaId=." + + id + ")" , e); + + } + return null; + } //Load document service url from moa properties @@ -1093,12 +1051,14 @@ public class PropertyBasedAuthConfigurationProvider extends ConfigurationProvide return null; } - /** - * @return the eGovUtilsConfig - */ - @JsonIgnore - public EgovUtilPropertiesConfiguration geteGovUtilsConfig() { - return eGovUtilsConfig; - } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.AuthConfiguration#getStorkNoSignatureCountries() + */ + @Override + public List getStorkNoSignatureCountries() { + String prop = properties.getProperty("stork.fakeIdL.noSignatureCountries", ""); + return Arrays.asList(prop.replaceAll(" ", "").split(",")); + } } 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 e576522bf..ac1470dc6 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 @@ -23,27 +23,31 @@ package at.gv.egovernment.moa.id.config.auth.data; import java.security.PrivateKey; +import java.util.Collection; import java.util.List; import java.util.Map; -import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; -import at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS; -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.OAStorkAttribute; -import at.gv.egovernment.moa.id.commons.db.dao.config.TemplateType; -import at.gv.egovernment.moa.id.config.OAParameter; 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; /** * @author tlenz * */ -public class DynamicOAAuthParameters extends OAParameter implements IOAAuthParameters { +public class DynamicOAAuthParameters implements IOAAuthParameters { + + private String publicURLPrefix; private String businessTarget; + private boolean businessService; + + private boolean isInderfederationIDP; + private String IDPQueryURL; + + private String target; /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getTarget() @@ -78,29 +82,11 @@ public class DynamicOAAuthParameters extends OAParameter implements IOAAuthParam return null; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getTransformsInfos() - */ - @Override - public List getTransformsInfos() { - // TODO Auto-generated method stub - return null; - } - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getSAML1Parameter() */ @Override - public OASAML1 getSAML1Parameter() { - // TODO Auto-generated method stub - return null; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getPVP2Parameter() - */ - @Override - public OAPVP2 getPVP2Parameter() { + public SAML1ConfigurationParameters getSAML1Parameter() { // TODO Auto-generated method stub return null; } @@ -109,7 +95,7 @@ public class DynamicOAAuthParameters extends OAParameter implements IOAAuthParam * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getTemplateURL() */ @Override - public List getTemplateURL() { + public List getTemplateURL() { // TODO Auto-generated method stub return null; } @@ -159,15 +145,6 @@ public class DynamicOAAuthParameters extends OAParameter implements IOAAuthParam return false; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getSingleLogOutURL() - */ - @Override - public String getSingleLogOutURL() { - // TODO Auto-generated method stub - return null; - } - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getMandateProfiles() */ @@ -231,15 +208,6 @@ public class DynamicOAAuthParameters extends OAParameter implements IOAAuthParam return null; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getRequestedAttributes() - */ - @Override - public List getRequestedAttributes() { - // TODO Auto-generated method stub - return null; - } - /* (non-Javadoc) * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isRequireConsentForStorkAttributes() */ @@ -253,7 +221,7 @@ public class DynamicOAAuthParameters extends OAParameter implements IOAAuthParam * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getStorkAPs() */ @Override - public List getStorkAPs() { + public Collection getStorkAPs() { // TODO Auto-generated method stub return null; } @@ -280,7 +248,7 @@ public class DynamicOAAuthParameters extends OAParameter implements IOAAuthParam * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getPepsList() */ @Override - public List getPepsList() { + public Collection getPepsList() { // TODO Auto-generated method stub return null; } @@ -398,4 +366,91 @@ public class DynamicOAAuthParameters extends OAParameter implements IOAAuthParam // TODO Auto-generated method stub return false; } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getFullConfiguration() + */ + @Override + public Map getFullConfiguration() { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getConfigurationValue(java.lang.String) + */ + @Override + public String getConfigurationValue(String key) { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getFriendlyName() + */ + @Override + public String getFriendlyName() { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getPublicURLPrefix() + */ + @Override + public String getPublicURLPrefix() { + return this.publicURLPrefix; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getOaType() + */ + @Override + public String getOaType() { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getBusinessService() + */ + @Override + public boolean getBusinessService() { + return this.businessService; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getTargetFriendlyName() + */ + @Override + public String getTargetFriendlyName() { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isInderfederationIDP() + */ + @Override + public boolean isInderfederationIDP() { + return this.isInderfederationIDP; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isSTORKPVPGateway() + */ + @Override + public boolean isSTORKPVPGateway() { + // TODO Auto-generated method stub + return false; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#getRequestedSTORKAttributes() + */ + @Override + public Collection getRequestedSTORKAttributes() { + // TODO Auto-generated method stub + return null; + } } 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 index 3d4b53f7c..54156330f 100644 --- 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 @@ -80,7 +80,6 @@ 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.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.data.IssuerAndSerial; import at.gv.egovernment.moa.logging.Logger; @@ -97,6 +96,15 @@ public class BuildFromLegacyConfig { 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; @@ -163,13 +171,13 @@ public class BuildFromLegacyConfig { //Load Assertion and Session timeouts TimeOuts timeOuts = new TimeOuts(); - if (genericConfiguration.containsKey(AuthConfigurationProvider.AUTH_DATA_TIMEOUT_PROPERTY)) - timeOuts.setAssertion(BigInteger.valueOf(Long.valueOf((String)genericConfiguration.get(AuthConfigurationProvider.AUTH_DATA_TIMEOUT_PROPERTY)))); + 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(AuthConfigurationProvider.AUTH_SESSION_TIMEOUT_PROPERTY)) - timeOuts.setAssertion(BigInteger.valueOf(Long.valueOf((String)genericConfiguration.get(AuthConfigurationProvider.AUTH_SESSION_TIMEOUT_PROPERTY)))); + 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 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 81caa13ee..c926e2b01 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 @@ -50,7 +50,7 @@ public class STORKConfig { /** STORK SAML signature creation parameters */ private Properties props = null; - private Map cpepsMap = null; + private Map cpepsMap = new HashMap(); private String basedirectory = null; private SignatureVerificationParameter sigverifyparam = null; private List attr = null; @@ -63,11 +63,11 @@ public class STORKConfig { //create CPEPS map List cpeps = new ArrayList(); - Properties storkCPEPSProps = + Map storkCPEPSProps = AuthConfigurationProviderFactory.getInstance().getConfigurationWithPrefix( MOAIDConfigurationConstants.GENERAL_AUTH_STORK_CPEPS_LIST); if (storkCPEPSProps != null) { - Set keyValues = storkCPEPSProps.keySet(); + Set keyValues = storkCPEPSProps.keySet(); for (Object elObj : keyValues) { if (elObj instanceof String) { String el = (String) elObj; @@ -76,14 +76,14 @@ public class STORKConfig { String listCounter = el.substring(0, index); try { CPEPS moacpep = - new CPEPS(storkCPEPSProps.getProperty(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_CPEPS_LIST_COUNTRY), - new URL(storkCPEPSProps.getProperty(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_CPEPS_LIST_URL)), - Boolean.valueOf(storkCPEPSProps.getProperty(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_CPEPS_LIST_SUPPORT_XMLDSIG))); + new CPEPS(storkCPEPSProps.get(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_CPEPS_LIST_COUNTRY), + new URL(storkCPEPSProps.get(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_CPEPS_LIST_URL)), + Boolean.valueOf(storkCPEPSProps.get(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_CPEPS_LIST_SUPPORT_XMLDSIG))); cpepsMap.put(moacpep.getCountryCode(), moacpep); } catch (MalformedURLException e) { Logger.warn("CPEPS URL " + - storkCPEPSProps.getProperty(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_CPEPS_LIST_URL) + + storkCPEPSProps.get(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_CPEPS_LIST_URL) + " are not parseable.", e); } @@ -93,11 +93,11 @@ public class STORKConfig { } attr = new ArrayList(); - Properties storkAttributeProps = + Map storkAttributeProps = AuthConfigurationProviderFactory.getInstance().getConfigurationWithPrefix( MOAIDConfigurationConstants.GENERAL_AUTH_STORK_ATTRIBUTES_LIST); if (storkAttributeProps != null) { - Set keyValues = storkAttributeProps.keySet(); + Set keyValues = storkAttributeProps.keySet(); for (Object elObj : keyValues) { if (elObj instanceof String) { String el = (String) elObj; @@ -105,8 +105,8 @@ public class STORKConfig { int index = el.indexOf("."); String listCounter = el.substring(0, index); StorkAttribute moaStorkAttr = - new StorkAttribute(storkAttributeProps.getProperty(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_ATTRIBUTES_LIST_NAME), - Boolean.valueOf(storkAttributeProps.getProperty(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_ATTRIBUTES_LIST_MANDATORY))); + new StorkAttribute(storkAttributeProps.get(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_ATTRIBUTES_LIST_NAME), + Boolean.valueOf(storkAttributeProps.get(listCounter + "." + MOAIDConfigurationConstants.GENERAL_AUTH_STORK_ATTRIBUTES_LIST_MANDATORY))); attr.add(moaStorkAttr); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java index 4879942ae..03b5d98f9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java @@ -30,7 +30,7 @@ import javax.servlet.http.HttpServletRequest; import org.opensaml.saml2.core.Attribute; -import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +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; @@ -152,11 +152,10 @@ class OAuth20AuthRequest extends OAuth20BaseRequest { // check if client id and redirect uri are ok try { // OAOAUTH20 cannot be null at this point. check was done in base request - OAOAUTH20 oAuthConfig = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(this.getOAURL()) - .getoAuth20Config(); - - if (!this.getClientID().equals(oAuthConfig.getOAuthClientId()) - || !this.getRedirectUri().equals(oAuthConfig.getOAuthRedirectUri())) { + OAAuthParameter oAuthConfig = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(this.getOAURL()); + + if (!this.getClientID().equals(oAuthConfig.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTID)) + || !this.getRedirectUri().equals(oAuthConfig.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_REDIRECTURL))) { throw new OAuth20AccessDeniedException(); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java index 9a7e44f70..844cfa815 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java @@ -31,7 +31,7 @@ import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +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; @@ -40,7 +40,6 @@ import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidRequestException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20OANotSupportedException; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; @@ -84,12 +83,9 @@ abstract class OAuth20BaseRequest extends RequestImpl { } this.setTarget(oaParam.getTarget()); - OAOAUTH20 config = oaParam.getoAuth20Config(); - if (config == null) { - throw new OAuth20InvalidRequestException(); - } - if (StringUtils.isEmpty(config.getOAuthClientSecret()) || StringUtils.isEmpty(config.getOAuthClientId()) - || StringUtils.isEmpty(config.getOAuthRedirectUri())) { + if (StringUtils.isEmpty(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTSECRET)) + || StringUtils.isEmpty(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTID)) + || StringUtils.isEmpty(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_REDIRECTURL))) { throw new OAuth20OANotSupportedException(); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java index 5cb5108ed..1b6d93fdd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java @@ -28,9 +28,10 @@ import javax.servlet.http.HttpServletRequest; import org.opensaml.saml2.core.Attribute; -import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; +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.oauth20.OAuth20Constants; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20AccessDeniedException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; @@ -121,14 +122,13 @@ class OAuth20TokenRequest extends OAuth20BaseRequest { // check if client id and secret are ok try { // OAOAUTH20 cannot be null at this point. check was done in base request - OAOAUTH20 oAuthConfig = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(this.getOAURL()) - .getoAuth20Config(); + OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(this.getOAURL()); - if (!this.getClientID().equals(oAuthConfig.getOAuthClientId())) { + if (!this.getClientID().equals(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTID))) { throw new OAuth20AccessDeniedException(); } - if (!this.getClientSecret().equals(oAuthConfig.getOAuthClientSecret())) { + if (!this.getClientSecret().equals(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTSECRET))) { throw new OAuth20AccessDeniedException(); } 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 587d8e935..0b6cb6eea 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 @@ -33,7 +33,6 @@ import org.opensaml.saml2.binding.encoding.HTTPRedirectDeflateEncoder; import org.opensaml.saml2.binding.security.SAML2AuthnRequestsSignedRule; import org.opensaml.saml2.binding.security.SAML2HTTPRedirectDeflateSignatureRule; import org.opensaml.saml2.core.RequestAbstractType; -import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.StatusResponseType; import org.opensaml.saml2.metadata.IDPSSODescriptor; import org.opensaml.saml2.metadata.SPSSODescriptor; @@ -48,7 +47,6 @@ import org.opensaml.ws.transport.http.HttpServletRequestAdapter; import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; -import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.x509.X509Credential; import at.gv.egovernment.moa.id.config.ConfigurationException; @@ -63,7 +61,7 @@ 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.verification.TrustEngineFactory; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.egovernment.moa.util.MiscUtil; public class RedirectBinding implements IDecoder, IEncoder { @@ -173,11 +171,32 @@ public class RedirectBinding implements IDecoder, IEncoder { else messageContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME); - decode.decode(messageContext); + try { + decode.decode(messageContext); - //check signature - signatureRule.evaluate(messageContext); + //check signature + signatureRule.evaluate(messageContext); + + } catch (SecurityException e) { + if (MiscUtil.isEmpty(messageContext.getPeerEntityId())) { + throw e; + + } + Logger.debug("PVP2X message validation FAILED. Relead metadata for entityID: " + messageContext.getPeerEntityId()); + if (!MOAMetadataProvider.getInstance().refreshMetadataProvider(messageContext.getPeerEntityId())) + throw e; + + else { + Logger.trace("PVP2X metadata reload finished. Check validate message again."); + decode.decode(messageContext); + //check signature + signatureRule.evaluate(messageContext); + + } + Logger.trace("Second PVP2X message validation finished"); + } + InboundMessage msg = null; if (messageContext.getInboundMessage() instanceof RequestAbstractType) { RequestAbstractType inboundMessage = (RequestAbstractType) messageContext 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 5c473f32d..ca95ff90c 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 @@ -24,10 +24,12 @@ 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; 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; @@ -46,18 +48,16 @@ import org.opensaml.saml2.metadata.SurName; import org.opensaml.saml2.metadata.TelephoneNumber; import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; -import at.gv.egovernment.moa.id.commons.db.dao.config.OAPVP2; 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.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; -//TODO!!!!! - public class PVPConfiguration { private static PVPConfiguration instance; @@ -116,6 +116,9 @@ public class PVPConfiguration { props = AuthConfigurationProviderFactory.getInstance().getGeneralPVP2ProperiesConfig(); rootDir = AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir(); + //load PVP2X metadata for all active online applications + MOAMetadataProvider.getInstance(); + } catch (ConfigurationException e) { e.printStackTrace(); } @@ -201,52 +204,39 @@ public class PVPConfiguration { return AuthConfigurationProviderFactory.getInstance().getConfigurationWithKey( MOAIDConfigurationConstants.GENERAL_PROTOCOLS_PVP2X_METADATA_SERVICENAMME) + moaIDVersion; } - - //TODO: - public String getTargetForSP(String sp) { - - try { - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(sp); - - if (oaParam != null) - return oaParam.getTarget(); - - Logger.warn("OnlineApplication with ID "+ sp + " is not found."); - return null; - - } catch (ConfigurationException e) { - Logger.warn("OnlineApplication with ID "+ sp + " is not found."); - return null; - } - - } - public iaik.x509.X509Certificate getTrustEntityCertificate(String entityID) { + + try { + Logger.trace("Load metadata signing certificate for online application " + entityID); + IOAAuthParameters oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(entityID); + if (oaParam == null) { + Logger.info("Online Application with ID " + entityID + " not found!"); + return null; + } - try { - IOAAuthParameters oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(entityID); - - if (oaParam == null) { - Logger.warn("Online Application with ID " + entityID + " not found!"); - return null; - } - - OAPVP2 pvp2param = oaParam.getPVP2Parameter(); - - if (pvp2param == null) { - return null; - } - - Logger.info("Load TrustEntityCertificate ("+entityID+") from Database."); - return new X509Certificate(pvp2param.getCertificate()); + String pvp2MetadataCertificateString = + oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); + if (MiscUtil.isEmpty(pvp2MetadataCertificateString)) { + Logger.info("Online Application with ID " + entityID + " include not PVP2X metadata signing certificate!"); + return null; + + } + + X509Certificate cert = new X509Certificate(Base64Utils.decode(pvp2MetadataCertificateString, false)); + Logger.debug("Metadata signing certificate is loaded for ("+entityID+") is loaded."); + return cert; } catch (CertificateException e) { - Logger.warn("Signer certificate can not be loaded from session database!", e); + Logger.warn("Metadata signer certificate is not parsed.", e); return null; } catch (ConfigurationException e) { - e.printStackTrace(); + Logger.error("Configuration is not accessable.", e); + return null; + + } catch (IOException e) { + Logger.warn("Metadata signer certificate is not decodeable.", e); return null; } } @@ -254,16 +244,16 @@ public class PVPConfiguration { public List getIDPContacts() throws ConfigurationException { List list = new ArrayList(); - Properties contacts = AuthConfigurationProviderFactory.getInstance().getConfigurationWithPrefix( + Map contacts = AuthConfigurationProviderFactory.getInstance().getConfigurationWithPrefix( MOAIDConfigurationConstants.GENERAL_PROTOCOLS_PVP2X_METADATA_CONTACT + "."); ContactPerson person = SAML2Utils .createSAMLObject(ContactPerson.class); - String type = contacts.getProperty(IDP_CONTACT_TYPE); + String type = contacts.get(IDP_CONTACT_TYPE); if (type == null) { - Logger.error("IDP Contact with SurName " + contacts.getProperty(IDP_CONTACT_SURNAME) + Logger.error("IDP Contact with SurName " + contacts.get(IDP_CONTACT_SURNAME) + " has no type defined!"); } @@ -287,13 +277,13 @@ public class PVPConfiguration { } if (enumType == null) { - Logger.error("IDP Contact with SurName " + contacts.getProperty(IDP_CONTACT_SURNAME) + Logger.error("IDP Contact with SurName " + contacts.get(IDP_CONTACT_SURNAME) + " has invalid type defined: " + type); } person.setType(enumType); - String givenName = contacts.getProperty(IDP_CONTACT_GIVENNAME); + String givenName = contacts.get(IDP_CONTACT_GIVENNAME); if (givenName != null) { GivenName name = SAML2Utils @@ -302,7 +292,7 @@ public class PVPConfiguration { person.setGivenName(name); } - String company = contacts.getProperty(IDP_CONTACT_COMPANY); + String company = contacts.get(IDP_CONTACT_COMPANY); if (company != null) { Company comp = SAML2Utils.createSAMLObject(Company.class); @@ -310,7 +300,7 @@ public class PVPConfiguration { person.setCompany(comp); } - String surname = contacts.getProperty(IDP_CONTACT_SURNAME); + String surname = contacts.get(IDP_CONTACT_SURNAME); if (surname != null) { SurName name = SAML2Utils.createSAMLObject(SurName.class); @@ -318,7 +308,7 @@ public class PVPConfiguration { person.setSurName(name); } - String phone = contacts.getProperty(IDP_CONTACT_PHONE); + String phone = contacts.get(IDP_CONTACT_PHONE); if (phone != null) { TelephoneNumber telePhone = SAML2Utils .createSAMLObject(TelephoneNumber.class); @@ -326,7 +316,7 @@ public class PVPConfiguration { person.getTelephoneNumbers().add(telePhone); } - String mail = contacts.getProperty(IDP_CONTACT_MAIL); + String mail = contacts.get(IDP_CONTACT_MAIL); if (mail != null) { EmailAddress mailAddress = SAML2Utils .createSAMLObject(EmailAddress.class); @@ -341,12 +331,12 @@ public class PVPConfiguration { public Organization getIDPOrganisation() throws ConfigurationException { Organization org = SAML2Utils.createSAMLObject(Organization.class); - Properties organisation = AuthConfigurationProviderFactory.getInstance().getConfigurationWithPrefix( + Map organisation = AuthConfigurationProviderFactory.getInstance().getConfigurationWithPrefix( MOAIDConfigurationConstants.GENERAL_PROTOCOLS_PVP2X_METADATA_ORG + "."); - String org_name = organisation.getProperty(IDP_ORG_NAME); - String org_dispname = organisation.getProperty(IDP_ORG_DISPNAME); - String org_url = organisation.getProperty(IDP_ORG_URL); + String org_name = organisation.get(IDP_ORG_NAME); + String org_dispname = organisation.get(IDP_ORG_DISPNAME); + String org_url = organisation.get(IDP_ORG_URL); if (org_name == null || org_dispname == null || org_url == null) { return null; @@ -373,6 +363,7 @@ public class PVPConfiguration { private String parseMOAIDVersionFromManifest() { try { + @SuppressWarnings("rawtypes") Class clazz = PVPConfiguration.class; String className = clazz.getSimpleName() + ".class"; String classPath = clazz.getResource(className).toString(); 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 0ec79c79a..c2127a2af 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 @@ -22,6 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.metadata; +import java.io.IOException; import java.security.cert.CertificateException; import java.util.ArrayList; import java.util.Collection; @@ -30,6 +31,7 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Timer; import javax.net.ssl.SSLHandshakeException; @@ -47,13 +49,13 @@ import org.opensaml.saml2.metadata.provider.MetadataProviderException; import org.opensaml.xml.XMLObject; import org.opensaml.xml.parse.BasicParserPool; -import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; -import at.gv.egovernment.moa.id.commons.db.dao.config.ChainingModeType; -import at.gv.egovernment.moa.id.commons.db.dao.config.OAPVP2; -import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; +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.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; @@ -61,6 +63,7 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.Interfeder import at.gv.egovernment.moa.id.protocols.pvp2x.verification.metadata.MetadataFilterChain; 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; import at.gv.egovernment.moa.util.MiscUtil; public class MOAMetadataProvider implements MetadataProvider { @@ -68,7 +71,6 @@ public class MOAMetadataProvider implements MetadataProvider { private static MOAMetadataProvider instance = null; private static Object mutex = new Object(); - private static Date timestamp = null; public static MOAMetadataProvider getInstance() { if (instance == null) { @@ -80,18 +82,19 @@ public class MOAMetadataProvider implements MetadataProvider { } return instance; } - - public static Date getTimeStamp() { - return timestamp; - } public static void reInitialize() { synchronized (mutex) { /**add new Metadataprovider or remove Metadataprovider which are not in use any more.**/ if (instance != null) - instance.addAndRemoveMetadataProvider(); - + try { + instance.addAndRemoveMetadataProvider(); + + } catch (ConfigurationException e) { + Logger.error("Access to MOA-ID configuration FAILED.", e); + + } else Logger.info("MOAMetadataProvider is not loaded."); } @@ -109,89 +112,165 @@ public class MOAMetadataProvider implements MetadataProvider { MetadataProvider internalProvider; - private void addAndRemoveMetadataProvider() { + public boolean refreshMetadataProvider(String entityID) { + try { + OAAuthParameter oaParam = + AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(entityID); + if (oaParam != null) { + String metadataURL = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); + if (MiscUtil.isNotEmpty(metadataURL)) { + Map actuallyLoadedProviders = getAllActuallyLoadedProviders(); + + // check if MetadataProvider is actually loaded + if (actuallyLoadedProviders.containsKey(metadataURL)) { + actuallyLoadedProviders.get(metadataURL).refresh(); + Logger.info("PVP2X metadata for onlineApplication: " + + entityID + " is refreshed."); + return true; + + } else { + //load new Metadata Provider + String certBase64 = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); + if (MiscUtil.isNotEmpty(certBase64)) { + byte[] cert = Base64Utils.decode(certBase64, false); + String oaFriendlyName = oaParam.getFriendlyName(); + + ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; + HTTPMetadataProvider newMetadataProvider = createNewHTTPMetaDataProvider(metadataURL, + cert, oaFriendlyName, + buildMetadataFilterChain(oaParam, metadataURL, + cert)); + + chainProvider.addMetadataProvider(newMetadataProvider); + Logger.info("PVP2X metadata for onlineApplication: " + + entityID + " is added."); + return true; + + } else + Logger.debug("Can not refresh PVP2X metadata: NO PVP2X metadata certificate for OA with Id: " + entityID); + + } + + } else + Logger.debug("Can not refresh PVP2X metadata: NO PVP2X metadata URL for OA with Id: " + entityID); + + } else + Logger.debug("Can not refresh PVP2X metadata: NO onlineApplication with Id: " + entityID); + + + } catch (ConfigurationException e) { + Logger.warn("Access MOA-ID configuration FAILED.", e); + + } catch (MetadataProviderException e) { + Logger.warn("Refresh PVP2X metadata for onlineApplication: " + + entityID + " FAILED.", e); + + } catch (IOException e) { + Logger.warn("Refresh PVP2X metadata for onlineApplication: " + + entityID + " FAILED.", e); + + } catch (CertificateException e) { + Logger.warn("Refresh PVP2X metadata for onlineApplication: " + + entityID + " FAILED.", e); + + } + + return false; + + } + + private Map getAllActuallyLoadedProviders() { + Map loadedproviders = new HashMap(); + ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; + + //make a Map of all actually loaded HTTPMetadataProvider + List providers = chainProvider.getProviders(); + for (MetadataProvider provider : providers) { + if (provider instanceof HTTPMetadataProvider) { + HTTPMetadataProvider httpprovider = (HTTPMetadataProvider) provider; + loadedproviders.put(httpprovider.getMetadataURI(), httpprovider); + + } + } + + return loadedproviders; + } + + + private void addAndRemoveMetadataProvider() throws ConfigurationException { if (internalProvider != null && internalProvider instanceof ChainingMetadataProvider) { Logger.info("Relaod MOAMetaDataProvider."); /*OpenSAML ChainingMetadataProvider can not remove a MetadataProvider (UnsupportedOperationException) *The ChainingMetadataProvider use internal a unmodifiableList to hold all registrated MetadataProviders.*/ Map providersinuse = new HashMap(); - - Map loadedproviders = new HashMap(); ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; - //make a Map of all actually loaded HTTPMetadataProvider - List providers = chainProvider.getProviders(); - for (MetadataProvider provider : providers) { - if (provider instanceof HTTPMetadataProvider) { - HTTPMetadataProvider httpprovider = (HTTPMetadataProvider) provider; - loadedproviders.put(httpprovider.getMetadataURI(), httpprovider); - } - } - - //set Timestamp - Date oldTimeStamp = timestamp; - timestamp = new Date(); + //get all actually loaded metadata providers + Map loadedproviders = getAllActuallyLoadedProviders(); //load all PVP2 OAs form ConfigurationDatabase and //compare actually loaded Providers with configured PVP2 OAs - List oaList = ConfigurationDBRead - .getAllActiveOnlineApplications(); - - Iterator oaIt = oaList.iterator(); - while (oaIt.hasNext()) { - HTTPMetadataProvider httpProvider = null; - - try { - OnlineApplication oa = oaIt.next(); - OAPVP2 pvp2Config = oa.getAuthComponentOA().getOAPVP2(); - if (pvp2Config != null && MiscUtil.isNotEmpty(pvp2Config.getMetadataURL())) { - - String metadataurl = pvp2Config.getMetadataURL(); + Map allOAs = AuthConfigurationProviderFactory.getInstance().getConfigurationWithWildCard( + MOAIDConfigurationConstants.PREFIX_SERVICES + + ".%." + + MOAIDConfigurationConstants.SERVICE_UNIQUEIDENTIFIER); + + if (allOAs != null) { + Iterator> oaInterator = allOAs.entrySet().iterator(); + while (oaInterator.hasNext()) { + Entry oaKeyPair = oaInterator.next(); + + OAAuthParameter oaParam = + AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(oaKeyPair.getValue()); + if (oaParam != null) { + String metadataurl = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); - if (loadedproviders.containsKey(metadataurl)) { - - if (pvp2Config.getUpdateRequiredItem() != null && - pvp2Config.getUpdateRequiredItem().after(oldTimeStamp)) { - //PVP2 OA is actually loaded, but update is requested - Logger.info("Reload metadata for: " + oa.getFriendlyName()); - loadedproviders.get(metadataurl).refresh(); - - } - - // PVP2 OA is actually loaded, to nothing - providersinuse.put(metadataurl, loadedproviders.get(metadataurl)); - loadedproviders.remove(metadataurl); + HTTPMetadataProvider httpProvider = null; + try { + if (MiscUtil.isNotEmpty(metadataurl)) { + if (loadedproviders.containsKey(metadataurl)) { + // PVP2 OA is actually loaded, to nothing + providersinuse.put(metadataurl, loadedproviders.get(metadataurl)); + loadedproviders.remove(metadataurl); - } else if ( MiscUtil.isNotEmpty(metadataurl) && - !providersinuse.containsKey(metadataurl) ) { - //PVP2 OA is new, add it to MOAMetadataProvider - - Logger.info("Loading metadata for: " + oa.getFriendlyName()); - httpProvider = createNewHTTPMetaDataProvider( - pvp2Config.getMetadataURL(), - pvp2Config.getCertificate(), - oa.getFriendlyName(), - buildMetadataFilterChain(oa, pvp2Config.getMetadataURL(), - pvp2Config.getCertificate())); + } else if ( MiscUtil.isNotEmpty(metadataurl) && + !providersinuse.containsKey(metadataurl) ) { + //PVP2 OA is new, add it to MOAMetadataProvider + String certBase64 = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); + if (MiscUtil.isNotEmpty(certBase64)) { + byte[] cert = Base64Utils.decode(certBase64, false); + String oaFriendlyName = oaParam.getFriendlyName(); + + + Logger.info("Loading metadata for: " + oaFriendlyName); + httpProvider = createNewHTTPMetaDataProvider( + metadataurl, + cert, + oaFriendlyName, + buildMetadataFilterChain(oaParam, metadataurl, + cert)); - if (httpProvider != null) - providersinuse.put(metadataurl, httpProvider); + if (httpProvider != null) + providersinuse.put(metadataurl, httpProvider); + } - } - } - } catch (Throwable e) { - Logger.error( + } + } + } catch (Throwable e) { + Logger.error( "Failed to add Metadata (unhandled reason: " + e.getMessage(), e); - if (httpProvider != null) { - Logger.debug("Destroy failed Metadata provider"); - httpProvider.destroy(); - } + if (httpProvider != null) { + Logger.debug("Destroy failed Metadata provider"); + httpProvider.destroy(); + } - } + } + } + } } //remove all actually loaded MetadataProviders with are not in ConfigurationDB any more @@ -261,77 +340,90 @@ public class MOAMetadataProvider implements MetadataProvider { Logger.info("Loading metadata"); Map providersinuse = new HashMap(); - - List oaList = ConfigurationDBRead - .getAllActiveOnlineApplications(); - - if (oaList.size() == 0) - Logger.info("No Online-Application configuration found. PVP 2.1 metadata provider initialization failed!"); - - Iterator oaIt = oaList.iterator(); - while (oaIt.hasNext()) { - HTTPMetadataProvider httpProvider = null; + try { + Map allOAs = AuthConfigurationProviderFactory.getInstance().getConfigurationWithWildCard( + MOAIDConfigurationConstants.PREFIX_SERVICES + + ".%." + + MOAIDConfigurationConstants.SERVICE_UNIQUEIDENTIFIER); - try { - OnlineApplication oa = oaIt.next(); - Logger.info("Loading metadata for: " + oa.getFriendlyName()); - OAPVP2 pvp2Config = oa.getAuthComponentOA().getOAPVP2(); - if (pvp2Config != null && MiscUtil.isNotEmpty(pvp2Config.getMetadataURL())) { - String metadataURL = pvp2Config.getMetadataURL(); + if (allOAs != null) { + Iterator> oaInterator = allOAs.entrySet().iterator(); + while (oaInterator.hasNext()) { + Entry oaKeyPair = oaInterator.next(); - if (!providersinuse.containsKey(metadataURL)) { - - httpProvider = createNewHTTPMetaDataProvider( - metadataURL, - pvp2Config.getCertificate(), - oa.getFriendlyName(), - buildMetadataFilterChain(oa, metadataURL, - pvp2Config.getCertificate())); - - if (httpProvider != null) - providersinuse.put(metadataURL, httpProvider); + OAAuthParameter oaParam = + AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(oaKeyPair.getValue()); + if (oaParam != null) { + String metadataurl = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_URL); + String oaFriendlyName = oaParam.getFriendlyName(); + HTTPMetadataProvider httpProvider = null; + + try { + String certBase64 = oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); + if (MiscUtil.isNotEmpty(certBase64) || MiscUtil.isNotEmpty(metadataurl)) { + byte[] cert = Base64Utils.decode(certBase64, false); + + + Logger.info("Loading metadata for: " + oaFriendlyName); + if (!providersinuse.containsKey(metadataurl)) { + httpProvider = createNewHTTPMetaDataProvider( + metadataurl, + cert, + oaFriendlyName, + buildMetadataFilterChain(oaParam, metadataurl, + cert)); - } else { - Logger.info(metadataURL + " are already added."); - } + if (httpProvider != null) + providersinuse.put(metadataurl, httpProvider); + + } else { + Logger.info(metadataurl + " are already added."); + } + + } else { + Logger.info(oaFriendlyName + + " is not a PVP2 Application skipping"); + } + } catch (Throwable e) { + Logger.error( + "Failed to add Metadata (unhandled reason: " + + e.getMessage(), e); - } else { - Logger.info(oa.getFriendlyName() - + " is not a PVP2 Application skipping"); + if (httpProvider != null) { + Logger.debug("Destroy failed Metadata provider"); + httpProvider.destroy(); + } + } + } } - } catch (Throwable e) { + + } else + Logger.info("No Online-Application configuration found. PVP 2.1 metadata provider initialization failed!"); + + try { + chainProvider.setProviders(new ArrayList(providersinuse.values())); + + } catch (MetadataProviderException e) { Logger.error( "Failed to add Metadata (unhandled reason: " + e.getMessage(), e); - - if (httpProvider != null) { - Logger.debug("Destroy failed Metadata provider"); - httpProvider.destroy(); - } - } - } - - - try { - chainProvider.setProviders(new ArrayList(providersinuse.values())); + } + + } catch (ConfigurationException e) { + Logger.error("Access MOA-ID configuration FAILED.", e); - } catch (MetadataProviderException e) { - Logger.error( - "Failed to add Metadata (unhandled reason: " - + e.getMessage(), e); } internalProvider = chainProvider; - timestamp = new Date(); } - private MetadataFilterChain buildMetadataFilterChain(OnlineApplication oa, String metadataURL, byte[] certificate) throws CertificateException { + private MetadataFilterChain buildMetadataFilterChain(OAAuthParameter oaParam, String metadataURL, byte[] certificate) throws CertificateException { MetadataFilterChain filterChain = new MetadataFilterChain(metadataURL, certificate); filterChain.getFilters().add(new SchemaValidationFilter()); - if (oa.isIsInterfederationIDP() != null && oa.isIsInterfederationIDP()) { + if (oaParam.isInderfederationIDP()) { Logger.info("Online-Application is an interfederated IDP. Add addional Metadata policies"); - filterChain.getFilters().add(new InterfederatedIDPPublicServiceFilter(metadataURL, oa.getType())); + filterChain.getFilters().add(new InterfederatedIDPPublicServiceFilter(metadataURL, oaParam.getBusinessService())); } @@ -352,7 +444,7 @@ public class MOAMetadataProvider implements MetadataProvider { AuthConfigurationProviderFactory.getInstance().getCertstoreDirectory(), AuthConfigurationProviderFactory.getInstance().getTrustedCACertificates(), null, - ChainingModeType.fromValue(AuthConfigurationProviderFactory.getInstance().getDefaultChainingMode()), + AuthConfiguration.DEFAULT_X509_CHAININGMODE, AuthConfigurationProviderFactory.getInstance().isTrustmanagerrevoationchecking()); httpClient.setCustomSSLTrustStore(metadataURL, protoSocketFactory); 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 550643da1..69c760f19 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 @@ -22,6 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.verification; +import java.io.IOException; import java.util.List; import org.opensaml.saml2.metadata.EntitiesDescriptor; @@ -32,36 +33,39 @@ 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.db.ConfigurationDBRead; -import at.gv.egovernment.moa.id.commons.db.dao.config.OAPVP2; -import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; +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.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.logging.Logger; +import at.gv.egovernment.moa.util.Base64Utils; +import at.gv.egovernment.moa.util.MiscUtil; public class EntityVerifier { public static byte[] fetchSavedCredential(String entityID) { // List oaList = ConfigurationDBRead // .getAllActiveOnlineApplications(); + try { + OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(entityID); - OnlineApplication oa = ConfigurationDBRead - .getActiveOnlineApplication(entityID); - -// Iterator oaIt = oaList.iterator(); -// while (oaIt.hasNext()) { -// OnlineApplication oa = oaIt.next(); -// if (oa.getPublicURLPrefix().equals(entityID)) { - - if (oa != null && oa.getAuthComponentOA() != null) { - - OAPVP2 pvp2Config = oa.getAuthComponentOA().getOAPVP2(); - if (pvp2Config != null) { - return pvp2Config.getCertificate(); - } + String certBase64 = oa.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_PVP2X_CERTIFICATE); + if (MiscUtil.isNotEmpty(certBase64)) { + return Base64Utils.decode(certBase64, false); + } -// } + + } catch (ConfigurationException e) { + Logger.error("Access MOA-ID configuration FAILED.", e); + + } catch (IOException e) { + Logger.warn("Decoding PVP2X metadata certificate FAILED.", e); + + } + return null; } 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 257f9dac4..70b778c49 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 @@ -38,7 +38,6 @@ 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.core.validator.AuthnRequestSchemaValidator; import org.opensaml.saml2.encryption.Decrypter; import org.opensaml.saml2.encryption.EncryptedElementTypeEncryptedKeyResolver; import org.opensaml.saml2.metadata.IDPSSODescriptor; @@ -68,25 +67,50 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SchemaValidationExcep 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; public class SAMLVerificationEngine { public void verify(InboundMessage msg, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { - if (msg instanceof MOARequest && - ((MOARequest)msg).getSamlRequest() instanceof RequestAbstractType) - verifyRequest(((RequestAbstractType)((MOARequest)msg).getSamlRequest()), sigTrustEngine); - - else - verifyResponse(((MOAResponse)msg).getResponse(), sigTrustEngine); + try { + if (msg instanceof MOARequest && + ((MOARequest)msg).getSamlRequest() instanceof RequestAbstractType) + verifyRequest(((RequestAbstractType)((MOARequest)msg).getSamlRequest()), sigTrustEngine); + else + verifyResponse(((MOAResponse)msg).getResponse(), sigTrustEngine); + + } catch (InvalidProtocolRequestException e) { + if (MiscUtil.isEmpty(msg.getEntityID())) { + throw e; + + } + Logger.debug("PVP2X message validation FAILED. Relead metadata for entityID: " + msg.getEntityID()); + if (!MOAMetadataProvider.getInstance().refreshMetadataProvider(msg.getEntityID())) + throw e; + + else { + Logger.trace("PVP2X metadata reload finished. Check validate message again."); + + if (msg instanceof MOARequest && + ((MOARequest)msg).getSamlRequest() instanceof RequestAbstractType) + verifyRequest(((RequestAbstractType)((MOARequest)msg).getSamlRequest()), sigTrustEngine); + + else + verifyResponse(((MOAResponse)msg).getResponse(), sigTrustEngine); + + } + Logger.trace("Second PVP2X message validation finished"); + } } - public void verifyResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { + public void verifyResponse(StatusResponseType samlObj, SignatureTrustEngine sigTrustEngine ) throws InvalidProtocolRequestException{ SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); try { profileValidator.validate(samlObj.getSignature()); @@ -110,13 +134,13 @@ public class SAMLVerificationEngine { if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); } - } catch (SecurityException e) { - e.printStackTrace(); + } catch (org.opensaml.xml.security.SecurityException e) { + Logger.warn("PVP2x message signature validation FAILED.", e); throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); } } - public void verifyRequest(RequestAbstractType samlObj, SignatureTrustEngine sigTrustEngine ) throws org.opensaml.xml.security.SecurityException, Exception { + public void verifyRequest(RequestAbstractType samlObj, SignatureTrustEngine sigTrustEngine ) throws InvalidProtocolRequestException { SAMLSignatureProfileValidator profileValidator = new SAMLSignatureProfileValidator(); try { profileValidator.validate(samlObj.getSignature()); @@ -140,8 +164,8 @@ public class SAMLVerificationEngine { if (!sigTrustEngine.validate(samlObj.getSignature(), criteriaSet)) { throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); } - } catch (SecurityException e) { - e.printStackTrace(); + } catch (org.opensaml.xml.security.SecurityException e) { + Logger.warn("PVP2x message signature validation FAILED.", e); throw new InvalidProtocolRequestException("pvp2.21", new Object[] {}); } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/InterfederatedIDPPublicServiceFilter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/InterfederatedIDPPublicServiceFilter.java index 4d9b97a52..918863d05 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/InterfederatedIDPPublicServiceFilter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/verification/metadata/InterfederatedIDPPublicServiceFilter.java @@ -41,14 +41,10 @@ public class InterfederatedIDPPublicServiceFilter implements MetadataFilter { /** * */ - public InterfederatedIDPPublicServiceFilter(String metadataURL, String oaType) { + public InterfederatedIDPPublicServiceFilter(String metadataURL, boolean isBusinessService) { Logger.debug("Add " + this.getClass().getName() + " to metadata policy"); this.metadataURL = metadataURL; - - if (oaType.equals("businessService")) - this.isPublicService = false; - else - this.isPublicService = true; + this.isPublicService = !isBusinessService; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java index c8a480cac..e70e71d49 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java @@ -51,10 +51,10 @@ import at.gv.egovernment.moa.id.auth.exception.ServiceException; import at.gv.egovernment.moa.id.auth.exception.ValidateException; import at.gv.egovernment.moa.id.auth.parser.SAMLArtifactParser; import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; -import at.gv.egovernment.moa.id.commons.db.dao.config.OASAML1; 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.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters; import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.storage.AssertionStorage; @@ -173,10 +173,10 @@ public class SAML1AuthenticationServer extends AuthenticationServer { throws ConfigurationException, BuildException, AuthenticationException { //Load SAML1 Parameter from OA config - OASAML1 saml1parameter = oaParam.getSAML1Parameter(); + SAML1ConfigurationParameters saml1parameter = oaParam.getSAML1Parameter(); boolean useCondition = saml1parameter.isUseCondition(); - int conditionLength = saml1parameter.getConditionLength().intValue(); + int conditionLength = saml1parameter.getConditionLength(); try { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java index f86d5f769..bc38735ac 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java @@ -32,15 +32,14 @@ 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.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.RedirectServlet; -import at.gv.egovernment.moa.id.commons.db.dao.config.OASAML1; 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.data.SAML1ConfigurationParameters; import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IModulInfo; import at.gv.egovernment.moa.id.moduls.IRequest; @@ -149,7 +148,7 @@ public class SAML1Protocol implements IModulInfo, MOAIDAuthConstants { throw new InvalidProtocolRequestException("auth.00", new Object[] { null }); - OASAML1 saml1 = oaParam.getSAML1Parameter(); + SAML1ConfigurationParameters saml1 = oaParam.getSAML1Parameter(); if (saml1 == null || !(saml1.isIsActive() != null && saml1.isIsActive()) ) { Logger.info("Online-Application " + oaURL + " can not use SAML1 for authentication."); throw new InvalidProtocolRequestException("auth.00", diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java index f73726890..5370573a7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java @@ -27,10 +27,10 @@ import java.util.List; import org.opensaml.saml2.core.Attribute; -import at.gv.egovernment.moa.id.commons.db.dao.config.OASAML1; 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.data.SAML1ConfigurationParameters; 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.builder.AttributQueryBuilder; @@ -71,7 +71,7 @@ public class SAML1RequestImpl extends RequestImpl { try { OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(getOAURL()); - OASAML1 saml1 = oa.getSAML1Parameter(); + SAML1ConfigurationParameters saml1 = oa.getSAML1Parameter(); if (saml1 != null) { if (saml1.isProvideAUTHBlock()) reqAttr.add(PVPConstants.EID_AUTH_BLOCK_NAME); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java index 27b9cd849..71b55d991 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java @@ -26,12 +26,8 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; -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.commons.db.dao.config.AttributeProviderPlugin; -import at.gv.egovernment.moa.id.commons.db.dao.config.OAStorkAttribute; -import at.gv.egovernment.moa.id.commons.db.dao.config.StorkAttribute; 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; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java index 10b325234..f0b0f58de 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java @@ -23,6 +23,7 @@ package at.gv.egovernment.moa.id.protocols.stork2; import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; +import at.gv.egovernment.moa.id.config.stork.StorkAttributeProviderPlugin; import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider; import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.EHvdAttributeProviderPlugin; import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.EHvdAttribute_deprecatedProviderPlugin; @@ -33,6 +34,7 @@ import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.StorkAttribu import at.gv.egovernment.moa.logging.Logger; import java.util.ArrayList; +import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.PriorityQueue; @@ -91,14 +93,14 @@ public class AttributeProviderFactory { /** * Gets fresh instances of the configured plugins. * - * @param configuredAPs the configured a ps + * @param collection the configured a ps * @return the configured plugins */ public static Iterator getConfiguredPlugins( - List configuredAPs) { + Collection collection) { PriorityQueue result = new PriorityQueue(); - for (AttributeProviderPlugin current : configuredAPs) { + for (StorkAttributeProviderPlugin current : collection) { result.add(create(current.getName(), current.getUrl(), current.getAttributes())); Logger.debug("Adding configured attribute provider: " + current.getClass().getName() + current.getName() + " at " + current.getUrl()); 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 b55dea250..64ae95093 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 @@ -64,12 +64,10 @@ 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.commons.db.dao.config.TemplateType; 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.logging.Logger; -import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.StringUtils; @@ -262,7 +260,7 @@ public class ParamValidatorUtils implements MOAIDAuthConstants{ * @param template * @return */ - public static boolean isValidTemplate(HttpServletRequest req, String template, List oaSlTemplates) { + public static boolean isValidTemplate(HttpServletRequest req, String template, List oaSlTemplates) { Logger.debug("Ueberpruefe Parameter Template bzw. bkuSelectionTemplateURL"); @@ -295,9 +293,9 @@ public class ParamValidatorUtils implements MOAIDAuthConstants{ //get OA specific template URLs if (oaSlTemplates != null && oaSlTemplates.size() > 0) { - for (TemplateType el : oaSlTemplates) - if (MiscUtil.isNotEmpty(el.getURL())) - trustedTemplateURLs.add(el.getURL()); + for (String el : oaSlTemplates) + if (MiscUtil.isNotEmpty(el)) + trustedTemplateURLs.add(el); } boolean b = trustedTemplateURLs.contains(template); diff --git a/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties b/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties index ad01644a1..985d499ba 100644 --- a/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties +++ b/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties @@ -74,7 +74,8 @@ config.18=Keine MOA-ID 2.x Konfiguration gefunden. config.19=Kein Schl\u00FCssel f\u00FCr die Resignierung der Personenbindung gefunden. config.20=Umgebungsvariable "moa.id.proxy.configuration" nicht gesetzt config.21=F\u00FCr diese Online Applikation sind keine Vollmachtsprofile hinterlegt. -config.22=F\u00FCr den Interfederation-Gateway mit der ID {0} ist kein Endpunkt zur Weiterleitung konfiguriert. +config.22=F\u00FCr den Interfederation-Gateway mit der ID {0} ist kein Endpunkt zur Weiterleitung konfiguriert. +config.23=Fehler beim initialisieren von OpenSAML parser.00=Leichter Fehler beim Parsen: {0} parser.01=Fehler beim Parsen: {0} -- cgit v1.2.3