diff options
Diffstat (limited to 'id')
38 files changed, 4113 insertions, 3790 deletions
diff --git a/id/ConfigWebTool/ConfigurationInterface.iml b/id/ConfigWebTool/ConfigurationInterface.iml index 20f45337e..13c327c84 100644 --- a/id/ConfigWebTool/ConfigurationInterface.iml +++ b/id/ConfigWebTool/ConfigurationInterface.iml @@ -35,6 +35,7 @@ <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.6" level="project" /> + <orderEntry type="library" name="Maven: eu.medsea.mimeutil:mime-util:2.1.3" level="project" /> <orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:jstl:1.2" level="project" /> <orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:servlet-api:2.4" level="project" /> <orderEntry type="library" name="Maven: log4j:log4j:1.2.14" level="project" /> @@ -58,6 +59,12 @@ <orderEntry type="library" name="Maven: jaxen:jaxen:1.0-FCS" level="project" /> <orderEntry type="library" name="Maven: saxpath:saxpath:1.0-FCS" level="project" /> <orderEntry type="library" name="Maven: joda-time:joda-time:2.2" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-simple:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:log4j-over-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: commons-io:commons-io:1.3.2" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-runtime:0.5.6" level="project" /> <orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2_commons:jaxb2-basics-runtime:0.6.2" level="project" /> @@ -72,9 +79,6 @@ <orderEntry type="library" scope="TEST" name="Maven: junit:junit:3.8.1" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2_commons:jaxb2-basics-testing:0.6.2" level="project" /> <orderEntry type="library" name="Maven: xmlunit:xmlunit:1.0" level="project" /> - <orderEntry type="library" name="Maven: commons-io:commons-io:2.0.1" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.1" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.6.1" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-persistence:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-customizations:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.springframework:spring:2.0.7" level="project" /> @@ -121,29 +125,15 @@ <orderEntry type="library" name="Maven: org.apache.velocity:velocity:1.7" level="project" /> <orderEntry type="library" name="Maven: org.owasp.esapi:esapi:2.0.1" level="project" /> <orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk16:1.46" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-simple:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:log4j-over-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.5" level="project" /> <orderEntry type="library" name="Maven: eu.stork:oasis-dss-api:1.0.0-SNAPSHOT" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.ws:jaxws-rt:2.1.7" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.ws:jaxws-api:2.1" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.bind:jaxb-api:2.2.6" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.messaging.saaj:saaj-impl:1.3.3" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.soap:saaj-api:1.3" level="project" /> - <orderEntry type="library" name="Maven: javax.activation:activation:1.1" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.stream.buffer:streambuffer:0.9" level="project" /> - <orderEntry type="library" name="Maven: org.jvnet.staxex:stax-ex:1.2" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.stream:stax-api:1.0" level="project" /> - <orderEntry type="library" name="Maven: org.codehaus.woodstox:wstx-asl:3.2.3" level="project" /> - <orderEntry type="library" name="Maven: stax:stax-api:1.0.1" level="project" /> - <orderEntry type="library" name="Maven: org.jvnet:mimepull:1.3" level="project" /> + <orderEntry type="library" name="Maven: eu.medsea.mimeutil:mime-util:2.1.3" level="project" /> <orderEntry type="module" module-name="moa-spss-lib" /> <orderEntry type="library" name="Maven: axis:axis:1.0_IAIK" level="project" /> <orderEntry type="library" name="Maven: org.apache.axis:axis-jaxrpc:1.4" level="project" /> <orderEntry type="library" name="Maven: org.apache.axis:axis-saaj:1.4" level="project" /> <orderEntry type="library" name="Maven: axis:axis-wsdl4j:1.5.1" level="project" /> <orderEntry type="library" name="Maven: commons-discovery:commons-discovery:0.2" level="project" /> + <orderEntry type="library" name="Maven: javax.activation:activation:1.1" level="project" /> <orderEntry type="library" name="Maven: javax.mail:mail:1.4" level="project" /> <orderEntry type="library" scope="RUNTIME" name="Maven: postgresql:postgresql:7.2" level="project" /> <orderEntry type="library" name="Maven: xalan-bin-dist:xalan:2.7.1" level="project" /> @@ -168,6 +158,8 @@ <orderEntry type="library" name="Maven: iaik:iaik_ssl:4.4" level="project" /> <orderEntry type="library" name="Maven: iaik:w3c_http:1.0" level="project" /> <orderEntry type="library" name="Maven: org.xerial:sqlite-jdbc:3.7.8-SNAPSHOT" level="project" /> + <orderEntry type="library" name="Maven: stax:stax-api:1.0.1" level="project" /> + <orderEntry type="library" name="Maven: javax.xml.bind:jaxb-api:2.2.6" level="project" /> <orderEntry type="library" name="Maven: iaik.prod:iaik_util:0.23" level="project" /> <orderEntry type="library" name="Maven: iaik.prod:iaik_xsect:1.1709142" level="project" /> <orderEntry type="library" name="Maven: iaik.prod:iaik_jsse:4.4" level="project" /> @@ -186,6 +178,7 @@ <orderEntry type="library" name="Maven: commons-validator:commons-validator:1.3.1" level="project" /> <orderEntry type="library" name="Maven: commons-digester:commons-digester:1.6" level="project" /> <orderEntry type="library" name="Maven: bouncycastle:bcprov-jdk16:140" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.1" level="project" /> <orderEntry type="library" name="Maven: org.apache.struts:struts2-core:2.3.14.3" level="project" /> <orderEntry type="library" name="Maven: org.apache.struts.xwork:xwork-core:2.3.14.3" level="project" /> <orderEntry type="library" name="Maven: ognl:ognl:3.0.6" level="project" /> diff --git a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/Constants.java b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/Constants.java index b963890af..79a966b81 100644 --- a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/Constants.java +++ b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/Constants.java @@ -69,7 +69,8 @@ public class Constants { public static final String BKU_HANDY = "bkuhandy"; public static final String MOA_CONFIG_BUSINESSSERVICE = "businessService"; - public static final String MOA_CONFIG_PROTOCOL_SAML1 = "id_saml1"; + public static final String MOA_CONFIG_STORKSERVICE = "storkService"; + public static final String MOA_CONFIG_PROTOCOL_SAML1 = "id_saml1"; public static final String MOA_CONFIG_PROTOCOL_PVP2 = "id_pvp2x"; public static final String MOA_CONFIG_PROTOCOL_STORK2 = "id_stork2"; @@ -82,20 +83,24 @@ public class Constants { public static final String IDENIFICATIONTYPE_FN = "FN"; public static final String IDENIFICATIONTYPE_ERSB = "ERSB"; public static final String IDENIFICATIONTYPE_ZVR = "ZVR"; - public static final String IDENIFICATIONTYPE_BASEID = "urn:publicid:gv.at:baseid+"; + public static final String IDENIFICATIONTYPE_STORK = "STORK"; + public static final String IDENIFICATIONTYPE_BASEID = "urn:publicid:gv.at:baseid+"; public static final String IDENIFICATIONTYPE_BASEID_FN = IDENIFICATIONTYPE_BASEID + "X" + IDENIFICATIONTYPE_FN; public static final String IDENIFICATIONTYPE_BASEID_ZVR = IDENIFICATIONTYPE_BASEID + "X" + IDENIFICATIONTYPE_ZVR; public static final String PREFIX_WPBK = "urn:publicid:gv.at:wbpk+"; - - public static final Map<String, String> BUSINESSSERVICENAMES; + public static final String PREFIX_STORK = "urn:publicid:gv.at:storkid+"; + + + public static final Map<String, String> BUSINESSSERVICENAMES; static { Hashtable<String, String> tmp = new Hashtable<String, String>(); tmp.put(IDENIFICATIONTYPE_FN, "Firmenbuchnummer"); tmp.put(IDENIFICATIONTYPE_ZVR, "Vereinsnummer"); tmp.put(IDENIFICATIONTYPE_ERSB, "ERsB Kennzahl"); - - BUSINESSSERVICENAMES = Collections.unmodifiableMap(tmp); + tmp.put(IDENIFICATIONTYPE_STORK, "STORK"); + + BUSINESSSERVICENAMES = Collections.unmodifiableMap(tmp); } } diff --git a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/data/oa/OAGeneralConfig.java b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/data/oa/OAGeneralConfig.java index ba58701fc..c9f5fdde9 100644 --- a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/data/oa/OAGeneralConfig.java +++ b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/data/oa/OAGeneralConfig.java @@ -58,17 +58,19 @@ public class OAGeneralConfig { private String friendlyName = null; private boolean businessService = false; - - private String target = null; + private boolean storkService = false; + + private String target = null; private String target_subsector = null; private String target_admin = null; private static List<String> targetList = null; private String targetFriendlyName = null; private boolean isAdminTarget = false; - + private String identificationNumber = null; private String identificationType = null; private static List<String> identificationTypeList = null; + private String storkSPTargetCountry = null; private String aditionalAuthBlockText = null; @@ -118,7 +120,8 @@ public class OAGeneralConfig { identificationTypeList = Arrays.asList( Constants.IDENIFICATIONTYPE_FN, Constants.IDENIFICATIONTYPE_ZVR, - Constants.IDENIFICATIONTYPE_ERSB); + Constants.IDENIFICATIONTYPE_ERSB, + Constants.IDENIFICATIONTYPE_STORK); } @@ -159,8 +162,17 @@ public class OAGeneralConfig { businessService = true; else businessService = false; - - AuthComponentOA oaauth = dbOAConfig.getAuthComponentOA(); + + if (dbOAConfig.getType().equals(Constants.MOA_CONFIG_STORKSERVICE)) + storkService = true; + else + storkService = false; + + if (dbOAConfig.getStorkSPTargetCountry() != null) + storkSPTargetCountry = dbOAConfig.getStorkSPTargetCountry(); + + + AuthComponentOA oaauth = dbOAConfig.getAuthComponentOA(); if (oaauth != null) { BKUURLS bkuurls = oaauth.getBKUURLS(); @@ -205,7 +217,10 @@ public class OAGeneralConfig { if (Constants.PREFIX_WPBK.startsWith(split[0]) && split.length >= 2) { identificationType = split[1]; identificationNumber = split[2]; - } + } else if (Constants.PREFIX_STORK.startsWith(split[0]) && split.length >= 2) { + identificationType = split[1]; // setting at as iden category ? + identificationNumber = split[2]; // setting sp country as ident type -> sp ident + } } } @@ -301,6 +316,14 @@ public class OAGeneralConfig { return identificationNumber; } + public String getStorkSPTargetCountry() { + return storkSPTargetCountry; + } + + public void setStorkSPTargetCountry(String storkSPTargetCountry) { + this.storkSPTargetCountry = storkSPTargetCountry; + } + public void setIdentificationNumber(String identificationNumber) { this.identificationNumber = identificationNumber; } @@ -341,6 +364,14 @@ public class OAGeneralConfig { return businessService; } + public boolean isStorkService() { + return storkService; + } + + public void setStorkService(boolean storkService) { + this.storkService = storkService; + } + public void setBusinessService(boolean businessService) { this.businessService = businessService; } diff --git a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/struts/action/EditOAAction.java b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/struts/action/EditOAAction.java index 99bdfdc9c..370923ca1 100644 --- a/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/struts/action/EditOAAction.java +++ b/id/ConfigWebTool/src/main/java/at/gv/egovernment/moa/id/configuration/struts/action/EditOAAction.java @@ -22,1337 +22,1325 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.configuration.struts.action; -import iaik.utils.URLDecoder; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.math.BigInteger; -import java.security.cert.CertificateException; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; - -import org.apache.log4j.Logger; -import org.apache.struts2.interceptor.ServletRequestAware; -import org.apache.struts2.interceptor.ServletResponseAware; - import at.gv.egovernment.moa.id.auth.builder.LoginFormBuilder; 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.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.DefaultBKUs; -import at.gv.egovernment.moa.id.commons.db.dao.config.IdentificationNumber; -import at.gv.egovernment.moa.id.commons.db.dao.config.MOAIDConfiguration; -import at.gv.egovernment.moa.id.commons.db.dao.config.MOAKeyBoxSelector; -import at.gv.egovernment.moa.id.commons.db.dao.config.Mandates; -import at.gv.egovernment.moa.id.commons.db.dao.config.OAOAUTH20; -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.OASTORK; -import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; -import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplicationType; -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.TransformsInfoType; -import at.gv.egovernment.moa.id.commons.db.dao.config.UserDatabase; +import at.gv.egovernment.moa.id.commons.db.dao.config.*; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.configuration.Constants; import at.gv.egovernment.moa.id.configuration.auth.AuthenticatedUser; import at.gv.egovernment.moa.id.configuration.config.ConfigurationProvider; import at.gv.egovernment.moa.id.configuration.data.FormularCustomization; -import at.gv.egovernment.moa.id.configuration.data.oa.OAGeneralConfig; -import at.gv.egovernment.moa.id.configuration.data.oa.OAOAuth20Config; -import at.gv.egovernment.moa.id.configuration.data.oa.OAPVP2Config; -import at.gv.egovernment.moa.id.configuration.data.oa.OASAML1Config; -import at.gv.egovernment.moa.id.configuration.data.oa.OASSOConfig; -import at.gv.egovernment.moa.id.configuration.data.oa.OASTORKConfig; +import at.gv.egovernment.moa.id.configuration.data.oa.*; import at.gv.egovernment.moa.id.configuration.exception.ConfigurationException; import at.gv.egovernment.moa.id.configuration.helper.LanguageHelper; import at.gv.egovernment.moa.id.configuration.helper.MailHelper; import at.gv.egovernment.moa.id.configuration.validation.FormularCustomizationValitator; import at.gv.egovernment.moa.id.configuration.validation.TargetValidator; import at.gv.egovernment.moa.id.configuration.validation.ValidationHelper; -import at.gv.egovernment.moa.id.configuration.validation.oa.OAFileUploadValidation; -import at.gv.egovernment.moa.id.configuration.validation.oa.OAGeneralConfigValidation; -import at.gv.egovernment.moa.id.configuration.validation.oa.OAOAUTH20ConfigValidation; -import at.gv.egovernment.moa.id.configuration.validation.oa.OAPVP2ConfigValidation; -import at.gv.egovernment.moa.id.configuration.validation.oa.OASAML1ConfigValidation; -import at.gv.egovernment.moa.id.configuration.validation.oa.OASSOConfigValidation; -import at.gv.egovernment.moa.id.configuration.validation.oa.OASTORKConfigValidation; +import at.gv.egovernment.moa.id.configuration.validation.oa.*; import at.gv.egovernment.moa.id.util.FormBuildUtils; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.util.MiscUtil; - import com.opensymphony.xwork2.ActionSupport; +import iaik.utils.URLDecoder; +import org.apache.log4j.Logger; +import org.apache.struts2.interceptor.ServletRequestAware; +import org.apache.struts2.interceptor.ServletResponseAware; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.*; +import java.math.BigInteger; +import java.security.cert.CertificateException; +import java.util.*; public class EditOAAction extends ActionSupport implements ServletRequestAware, ServletResponseAware { - - private final Logger log = Logger.getLogger(EditOAAction.class); - - private static final long serialVersionUID = 1L; - - private HttpServletRequest request; - private HttpServletResponse response; - - private AuthenticatedUser authUser; - - private String oaidobj; - private boolean newOA; - private String formID; - - private boolean onlyBusinessService = false; - private boolean subTargetSet = false; - private boolean deaktivededBusinessService = false; - private boolean isMetaDataRefreshRequired = false; - - private String nextPage; - - private OAGeneralConfig generalOA = new OAGeneralConfig(); - private OAPVP2Config pvp2OA = new OAPVP2Config(); - private OASAML1Config saml1OA = new OASAML1Config(); - private OASSOConfig ssoOA = new OASSOConfig(); - private OAOAuth20Config oauth20OA = new OAOAuth20Config(); - private OASTORKConfig storkOA = new OASTORKConfig(); - private FormularCustomization formOA = new FormularCustomization(); - - private InputStream stream; - - private Map<String, byte[]> sendAssertionForm = new HashMap<String, byte[]>(); - private Map<String, byte[]> bkuSelectionForm = new HashMap<String, byte[]>(); - - // STRUTS actions - public String inital() { - HttpSession session = request.getSession(); - if (session == null) { - log.info("No http Session found."); - return Constants.STRUTS_ERROR; - } - - Object authUserObj = session.getAttribute(Constants.SESSION_AUTH); - - authUser = (AuthenticatedUser) authUserObj; - - long oaid = -1; - - if (!ValidationHelper.validateOAID(oaidobj)) { - addActionError(LanguageHelper.getErrorString("errors.edit.oa.oaid", request)); - return Constants.STRUTS_ERROR; - } - oaid = Long.valueOf(oaidobj); - - UserDatabase userdb = null; - OnlineApplication onlineapplication = null; - - if (authUser.isAdmin()) - onlineapplication = ConfigurationDBRead.getOnlineApplication(oaid); - - else { - userdb = ConfigurationDBRead.getUserWithID(authUser.getUserID()); - - if (!authUser.isAdmin() && userdb.isIsMailAddressVerified() != null && !userdb.isIsMailAddressVerified()) { - log.info("Online-Applikation managemant disabled. Mail address is not verified."); - addActionError(LanguageHelper.getErrorString("error.editoa.mailverification")); - return Constants.STRUTS_SUCCESS; - } - - // TODO: change to direct Database operation - List<OnlineApplication> oas = userdb.getOnlineApplication(); - for (OnlineApplication oa : oas) { - if (oa.getHjid() == oaid) { - onlineapplication = oa; - break; - } - } - if (onlineapplication == null) { - addActionError(LanguageHelper.getErrorString("errors.edit.oa.oaid", request)); - return Constants.STRUTS_ERROR; - } - } - - generalOA.parse(onlineapplication); - ssoOA.parse(onlineapplication); - saml1OA.parse(onlineapplication); - oauth20OA.parse(onlineapplication); - session.setAttribute(Constants.SESSION_OAUTH20SECRET, this.oauth20OA.getClientSecret()); - - storkOA.parse(onlineapplication); - - Map<String, String> map = new HashMap<String, String>(); - map.putAll(FormBuildUtils.getDefaultMap()); - formOA.parse(onlineapplication, map); - - session.setAttribute(Constants.SESSION_BKUFORMPREVIEW, map); - - List<String> errors = pvp2OA.parse(onlineapplication); - - if (errors.size() > 0) { - for (String el : errors) - addActionError(el); - } - - subTargetSet = MiscUtil.isNotEmpty(generalOA.getTarget_subsector()); - - // set UserSpezific OA Parameters - if (!authUser.isAdmin()) generateUserSpecificConfigurationOptions(userdb); - - ConfigurationDBUtils.closeSession(); - session.setAttribute(Constants.SESSION_OAID, oaid); - - formID = Random.nextRandom(); - session.setAttribute(Constants.SESSION_FORMID, formID); - - newOA = false; - - return Constants.STRUTS_OA_EDIT; - } - - public String newOA() { - log.debug("insert new Online-Application"); - - HttpSession session = request.getSession(); - if (session == null) { - log.info("No http Session found."); - return Constants.STRUTS_ERROR; - } - - session.setAttribute(Constants.SESSION_OAID, null); - nextPage = Constants.STRUTS_RETURNAREA_VALUES.main.name(); - - Object authUserObj = session.getAttribute(Constants.SESSION_AUTH); - - authUser = (AuthenticatedUser) authUserObj; - - UserDatabase userdb = ConfigurationDBRead.getUserWithID(authUser.getUserID()); - - if (!authUser.isAdmin() && userdb.isIsMailAddressVerified() != null && !userdb.isIsMailAddressVerified()) { - log.info("Online-Applikation managemant disabled. Mail address is not verified."); - addActionError(LanguageHelper.getErrorString("error.editoa.mailverification")); - return Constants.STRUTS_SUCCESS; - } - - MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration(); - if (moaidconfig != null) { - DefaultBKUs defaultbkus = moaidconfig.getDefaultBKUs(); - if (defaultbkus != null) { - generalOA.setBkuHandyURL(defaultbkus.getHandyBKU()); - generalOA.setBkuLocalURL(defaultbkus.getLocalBKU()); - generalOA.setBkuOnlineURL(defaultbkus.getOnlineBKU()); - } - } - - // set UserSpezific OA Parameters - if (!authUser.isAdmin()) generateUserSpecificConfigurationOptions(userdb); - - ConfigurationDBUtils.closeSession(); - - newOA = true; - formID = Random.nextRandom(); - session.setAttribute(Constants.SESSION_FORMID, formID); - - session.setAttribute(Constants.SESSION_BKUFORMPREVIEW, null); - - this.oauth20OA.generateClientSecret(); - session.setAttribute(Constants.SESSION_OAUTH20SECRET, this.oauth20OA.getClientSecret()); - - return Constants.STRUTS_OA_EDIT; - } - - public String saveOA() { - HttpSession session = request.getSession(); - if (session == null) { - log.info("No http Session found."); - return Constants.STRUTS_ERROR; - } - - Object authUserObj = session.getAttribute(Constants.SESSION_AUTH); - authUser = (AuthenticatedUser) authUserObj; - - Object formidobj = session.getAttribute(Constants.SESSION_FORMID); - if (formidobj != null && formidobj instanceof String) { - String formid = (String) formidobj; - if (!formid.equals(formID)) { - log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName() - + authUser.getGivenName() + authUser.getUserID()); - return Constants.STRUTS_ERROR; - } - } else { - log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName() - + authUser.getGivenName() + authUser.getUserID()); - return Constants.STRUTS_ERROR; - } - session.setAttribute(Constants.SESSION_FORMID, null); - - UserDatabase userdb = ConfigurationDBRead.getUserWithID(authUser.getUserID()); - if (!authUser.isAdmin() && userdb.isIsMailAddressVerified() != null && !userdb.isIsMailAddressVerified()) { - log.info("Online-Applikation managemant disabled. Mail address is not verified."); - addActionError(LanguageHelper.getErrorString("error.editoa.mailverification")); - return Constants.STRUTS_SUCCESS; - } - - OnlineApplication onlineapplication = null; - List<String> errors = new ArrayList<String>(); - - Object oadbid = request.getSession().getAttribute(Constants.SESSION_OAID); - Long oaid = (long) -1; - - if (oadbid != null) { - try { - oaid = (Long) oadbid; - if (oaid < 0 || oaid > Long.MAX_VALUE) { - addActionError(LanguageHelper.getErrorString("errors.edit.oa.oaid", request)); - return Constants.STRUTS_ERROR; - } - - } - catch (Throwable t) { - addActionError(LanguageHelper.getErrorString("errors.edit.oa.oaid", request)); - return Constants.STRUTS_ERROR; - } - } - - // valid DBID and check entry - String oaidentifier = generalOA.getIdentifier(); - if (MiscUtil.isEmpty(oaidentifier)) { - log.info("Empty OA identifier"); - errors.add(LanguageHelper.getErrorString("validation.general.oaidentifier.empty")); - - } else { - - if (!ValidationHelper.validateURL(oaidentifier)) { - log.warn("OnlineapplikationIdentifier is not a valid URL: " + oaidentifier); - errors.add(LanguageHelper.getErrorString("validation.general.oaidentifier.valid", - new Object[] { ValidationHelper.getNotValidOAIdentifierCharacters() })); - } else { - - if (oaid == -1) { - onlineapplication = ConfigurationDBRead.getOnlineApplication(oaidentifier); - newOA = true; - if (onlineapplication != null) { - log.info("The OAIdentifier is not unique"); - errors.add(LanguageHelper.getErrorString("validation.general.oaidentifier.notunique")); - } - - } else { - onlineapplication = ConfigurationDBRead.getOnlineApplication(oaid); - if (!oaidentifier.equals(onlineapplication.getPublicURLPrefix())) { - - if (ConfigurationDBRead.getOnlineApplication(oaidentifier) != null) { - log.info("The OAIdentifier is not unique"); - errors.add(LanguageHelper.getErrorString("validation.general.oaidentifier.notunique")); - } - } - } - } - } - - // set UserSpezific OA Parameters - if (!authUser.isAdmin()) generateUserSpecificConfigurationOptions(userdb); - - // check form - OAGeneralConfigValidation validatior_general = new OAGeneralConfigValidation(); - OAPVP2ConfigValidation validatior_pvp2 = new OAPVP2ConfigValidation(); - OASAML1ConfigValidation validatior_saml1 = new OASAML1ConfigValidation(); - OASSOConfigValidation validatior_sso = new OASSOConfigValidation(); - OASTORKConfigValidation validator_stork = new OASTORKConfigValidation(); - FormularCustomizationValitator validator_form = new FormularCustomizationValitator(); - OAOAUTH20ConfigValidation validatior_oauth20 = new OAOAUTH20ConfigValidation(); - OAFileUploadValidation valiator_fileUpload = new OAFileUploadValidation(); - - errors.addAll(validatior_general.validate(generalOA, authUser.isAdmin())); - errors.addAll(validatior_pvp2.validate(pvp2OA)); - errors.addAll(validatior_saml1.validate(saml1OA, generalOA)); - errors.addAll(validatior_sso.validate(ssoOA, authUser.isAdmin())); - errors.addAll(validator_stork.validate(storkOA)); - errors.addAll(validator_form.validate(formOA)); - errors.addAll(validatior_oauth20.validate(oauth20OA)); - - //validate BKU-selection template - List<String> templateError = valiator_fileUpload.validate(generalOA.getBkuSelectionFileUploadFileName() - , generalOA.getBkuSelectionFileUpload(), "validation.general.bkuselection", bkuSelectionForm); - if (templateError != null && templateError.size() == 0) { - if (bkuSelectionForm != null && bkuSelectionForm.size() > 0) - session.setAttribute(Constants.SESSION_BKUSELECTIONTEMPLATE, bkuSelectionForm); - - else - bkuSelectionForm = (Map<String, byte[]>) session.getAttribute(Constants.SESSION_BKUSELECTIONTEMPLATE); - - } else { - errors.addAll(templateError); - - } - - //validate send-assertion template - templateError = valiator_fileUpload.validate(generalOA.getSendAssertionFileUploadFileName() - , generalOA.getSendAssertionFileUpload(), "validation.general.sendassertion", sendAssertionForm); - if (templateError != null && templateError.size() == 0) { - if (sendAssertionForm != null && sendAssertionForm.size() > 0) - session.setAttribute(Constants.SESSION_SENDASSERTIONTEMPLATE, sendAssertionForm); - - else - sendAssertionForm = (Map<String, byte[]>) session.getAttribute(Constants.SESSION_SENDASSERTIONTEMPLATE); - - } else { - errors.addAll(templateError); - - } - - - // Do not allow SSO in combination with special BKUSelection features - if (ssoOA.isUseSSO() && (formOA.isOnlyMandateAllowed() || !formOA.isShowMandateLoginButton())) { - log.warn("Special BKUSelection features can not be used in combination with SSO"); - errors.add(LanguageHelper.getErrorString("validation.general.bkuselection.specialfeatures.valid")); - } - - if (errors.size() > 0) { - log.info("OAConfiguration with ID " + generalOA.getIdentifier() + " has some errors."); - for (String el : errors) - addActionError(el); - - formID = Random.nextRandom(); - session.setAttribute(Constants.SESSION_FORMID, formID); - return Constants.STRUTS_ERROR_VALIDATION; - - } else { - - boolean newentry = false; - - if (onlineapplication == null) { - onlineapplication = new OnlineApplication(); - newentry = true; - onlineapplication.setIsActive(false); - - if (!authUser.isAdmin()) { - onlineapplication.setIsAdminRequired(true); - - } else - isMetaDataRefreshRequired = true; - - } else { - if (!authUser.isAdmin() && !onlineapplication.getPublicURLPrefix().equals(generalOA.getIdentifier())) { - - onlineapplication.setIsAdminRequired(true); - onlineapplication.setIsActive(false); - log.info("User with ID " + authUser.getUserID() + " change OA-PublicURLPrefix. Reaktivation is required."); - } - - } - - if ((onlineapplication.isIsAdminRequired() == null) - || (authUser.isAdmin() && generalOA.isActive() && onlineapplication.isIsAdminRequired())) { - - onlineapplication.setIsAdminRequired(false); - isMetaDataRefreshRequired = true; - - if (onlineapplication.getHjid() != null) userdb = ConfigurationDBRead.getUsersWithOADBID(onlineapplication.getHjid()); - - if (userdb != null && !userdb.isIsAdmin()) { - try { - MailHelper.sendUserOnlineApplicationActivationMail(userdb.getGivenname(), userdb.getFamilyname(), - userdb.getInstitut(), onlineapplication.getPublicURLPrefix(), userdb.getMail()); - } - catch (ConfigurationException e) { - log.warn("Sending Mail to User " + userdb.getMail() + " failed", e); - } - } - } - - //save OA configuration - String error = saveOAConfigToDatabase(onlineapplication, newentry); - if (MiscUtil.isNotEmpty(error)) { - log.warn("OA configuration can not be stored!"); - addActionError(error); - - formID = Random.nextRandom(); - session.setAttribute(Constants.SESSION_FORMID, formID); - return Constants.STRUTS_ERROR_VALIDATION; - } - - //set metadata reload flag if reload is required - if (pvp2OA.getMetaDataURL() != null) { - - try { - if (isMetaDataRefreshRequired - || !pvp2OA.getMetaDataURL().equals(onlineapplication.getAuthComponentOA().getOAPVP2().getMetadataURL()) - || pvp2OA.getFileUpload() != null - || pvp2OA.isReLoad()) { - - log.debug("Set PVP2 Metadata refresh flag."); - MOAIDConfiguration moaconfig = ConfigurationDBRead.getMOAIDConfiguration(); - moaconfig.setPvp2RefreshItem(new Date()); - ConfigurationDBUtils.saveOrUpdate(moaconfig); - - } - } - catch (Throwable e) { - log.info("Found no MetadataURL in OA-Databaseconfig!", e); - } - - } - } - - Object nextPageAttr = session.getAttribute(Constants.SESSION_RETURNAREA); - if (nextPageAttr != null && nextPageAttr instanceof String) { - nextPage = (String) nextPageAttr; - session.setAttribute(Constants.SESSION_RETURNAREA, null); - - } else { - nextPage = Constants.STRUTS_RETURNAREA_VALUES.main.name(); - } - - if (onlineapplication.isIsAdminRequired()) { - int numoas = 0; - int numusers = 0; - - List<OnlineApplication> openOAs = ConfigurationDBRead.getAllNewOnlineApplications(); - if (openOAs != null) numoas = openOAs.size(); - - List<UserDatabase> openUsers = ConfigurationDBRead.getAllNewUsers(); - if (openUsers != null) numusers = openUsers.size(); - try { - - addActionMessage(LanguageHelper.getGUIString("webpages.oaconfig.success.admin", generalOA.getIdentifier(), request)); - - if (numusers > 0 || numoas > 0) MailHelper.sendAdminMail(numoas, numusers); - - } - catch (ConfigurationException e) { - log.warn("Sending Mail to Admin failed.", e); - } - - } else - addActionMessage(LanguageHelper.getGUIString("webpages.oaconfig.success", generalOA.getIdentifier(), request)); - - //remove session attributes - session.setAttribute(Constants.SESSION_OAID, null); - session.removeAttribute(Constants.SESSION_BKUSELECTIONTEMPLATE); - session.removeAttribute(Constants.SESSION_SENDASSERTIONTEMPLATE); - - ConfigurationDBUtils.closeSession(); - return Constants.STRUTS_SUCCESS; - } - - public String cancleAndBackOA() { - - HttpSession session = request.getSession(); - if (session == null) { - log.info("No http Session found."); - return Constants.STRUTS_ERROR; - } - - Object nextPageAttr = session.getAttribute(Constants.SESSION_RETURNAREA); - if (nextPageAttr != null && nextPageAttr instanceof String) { - nextPage = (String) nextPageAttr; - session.setAttribute(Constants.SESSION_RETURNAREA, null); - - } else { - nextPage = Constants.STRUTS_RETURNAREA_VALUES.main.name(); - } - - session.setAttribute(Constants.SESSION_OAID, null); - - addActionMessage(LanguageHelper.getGUIString("webpages.oaconfig.cancle", generalOA.getIdentifier(), request)); - - ConfigurationDBUtils.closeSession(); - - return Constants.STRUTS_SUCCESS; - } - - public String deleteOA() { - HttpSession session = request.getSession(); - if (session == null) { - log.info("No http Session found."); - return Constants.STRUTS_ERROR; - } - - Object authUserObj = session.getAttribute(Constants.SESSION_AUTH); - authUser = (AuthenticatedUser) authUserObj; - - Object formidobj = session.getAttribute(Constants.SESSION_FORMID); - if (formidobj != null && formidobj instanceof String) { - String formid = (String) formidobj; - if (!formid.equals(formID)) { - log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName() - + authUser.getGivenName() + authUser.getUserID()); - return Constants.STRUTS_ERROR; - } - } else { - log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName() - + authUser.getGivenName() + authUser.getUserID()); - return Constants.STRUTS_ERROR; - } - session.setAttribute(Constants.SESSION_FORMID, null); - - Object nextPageAttr = session.getAttribute(Constants.SESSION_RETURNAREA); - if (nextPageAttr != null && nextPageAttr instanceof String) { - nextPage = (String) nextPageAttr; - - } else { - nextPage = Constants.STRUTS_RETURNAREA_VALUES.main.name(); - } - - UserDatabase userdb = ConfigurationDBRead.getUserWithID(authUser.getUserID()); - if (!authUser.isAdmin() && userdb.isIsMailAddressVerified() != null && !userdb.isIsMailAddressVerified()) { - log.info("Online-Applikation managemant disabled. Mail address is not verified."); - addActionError(LanguageHelper.getErrorString("error.editoa.mailverification")); - return Constants.STRUTS_SUCCESS; - } - - String oaidentifier = generalOA.getIdentifier(); - if (MiscUtil.isEmpty(oaidentifier)) { - log.info("Empty OA identifier"); - addActionError(LanguageHelper.getErrorString("validation.general.oaidentifier.empty")); - - formID = Random.nextRandom(); - session.setAttribute(Constants.SESSION_FORMID, formID); - return Constants.STRUTS_ERROR_VALIDATION; - - } else { - if (ValidationHelper.isValidOAIdentifier(oaidentifier)) { - log.warn("IdentificationNumber contains potentail XSS characters: " + oaidentifier); - addActionError(LanguageHelper.getErrorString("validation.general.oaidentifier.valid", - new Object[] { ValidationHelper.getNotValidOAIdentifierCharacters() })); - - formID = Random.nextRandom(); - session.setAttribute(Constants.SESSION_FORMID, formID); - return Constants.STRUTS_ERROR_VALIDATION; - } - } - - OnlineApplication onlineapplication = ConfigurationDBRead.getOnlineApplication(oaidentifier); - request.getSession().setAttribute(Constants.SESSION_OAID, null); - - try { - if (MiscUtil.isNotEmpty(onlineapplication.getAuthComponentOA().getOAPVP2().getMetadataURL())) { - - MOAIDConfiguration moaconfig = ConfigurationDBRead.getMOAIDConfiguration(); - moaconfig.setPvp2RefreshItem(new Date()); - ConfigurationDBUtils.saveOrUpdate(moaconfig); - - } - } - catch (Throwable e) { - log.info("Found no MetadataURL in OA-Databaseconfig!", e); - } - - if (ConfigurationDBUtils.delete(onlineapplication)) { - - if (!authUser.isAdmin()) { - UserDatabase user = ConfigurationDBRead.getUserWithID(authUser.getUserID()); - List<OnlineApplication> useroas = user.getOnlineApplication(); - - for (OnlineApplicationType oa : useroas) { - if (oa.getHjid().equals(onlineapplication.getHjid())) { - useroas.remove(oa); - } - } - - try { - ConfigurationDBUtils.saveOrUpdate(user); - - } - catch (MOADatabaseException e) { - log.warn("User information can not be updated in database", e); - addActionError(LanguageHelper.getGUIString("error.db.oa.store", request)); - return Constants.STRUTS_ERROR; - } - } - - ConfigurationDBUtils.closeSession(); - - addActionMessage(LanguageHelper.getGUIString("webpages.oaconfig.delete.message", generalOA.getIdentifier(), request)); - - return Constants.STRUTS_SUCCESS; - - } else { - ConfigurationDBUtils.closeSession(); - addActionError(LanguageHelper.getGUIString("webpages.oaconfig.delete.error", generalOA.getIdentifier(), request)); - return Constants.STRUTS_SUCCESS; - } - - } - - public String bkuFramePreview() { - - String preview = null; - - HttpSession session = request.getSession(); - if (session == null) { - log.info("No http Session found."); - preview = LanguageHelper.getErrorString("error.bkuformpreview.notpossible"); - - } else { - InputStream input = null; - - try { - Object mapobj = session.getAttribute(Constants.SESSION_BKUFORMPREVIEW); - if (mapobj != null && mapobj instanceof Map<?, ?>) { - - ConfigurationProvider config = ConfigurationProvider.getInstance(); - String templateURL = config.getConfigRootDir() + ConfigurationProvider.HTMLTEMPLATE_DIR - + ConfigurationProvider.HTMLTEMPLATE_FILE; - - File file = new File(templateURL); - input = new FileInputStream(file); - - String contextpath = config.getMOAIDInstanceURL(); - if (MiscUtil.isEmpty(contextpath)) { - log.info("NO MOA-ID instance URL configurated."); - throw new ConfigurationException("No MOA-ID instance configurated"); - } - - preview = LoginFormBuilder.getTemplate(input); - preview = preview.replace(LoginFormBuilder.CONTEXTPATH, contextpath); - - Map<String, String> map = (Map<String, String>) mapobj; - - request.setCharacterEncoding("UTF-8"); - - String module = request.getParameter(Constants.REQUEST_FORMCUSTOM_MODULE); - String value = request.getParameter(Constants.REQUEST_FORMCUSTOM_VALUE); - - if (value != null) { - String[] query = URLDecoder.decode(request.getQueryString()).split("&"); - value = query[1].substring("value=".length()); - } - - synchronized (map) { - - if (MiscUtil.isNotEmpty(module)) { - if (map.containsKey("#" + module + "#")) { - if (MiscUtil.isNotEmpty(value)) { - if (FormBuildUtils.FONTFAMILY.contains(module) || FormBuildUtils.HEADER_TEXT.contains(module) - || value.startsWith("#")) - map.put("#" + module + "#", value); - else - map.put("#" + module + "#", "#" + value); - - } else { - map.put("#" + module + "#", FormBuildUtils.getDefaultMap().get("#" + module + "#")); - } - } - } - preview = FormBuildUtils.customiceLayoutBKUSelection(preview, true, false, map, true); - } - - } else { - preview = LanguageHelper.getErrorString("error.bkuformpreview.notpossible"); - - } - - } - catch (Exception e) { - log.warn("BKUSelection Preview can not be generated.", e); - preview = LanguageHelper.getErrorString("error.bkuformpreview.notpossible"); - - } - } - - stream = new ByteArrayInputStream(preview.getBytes()); - - return Constants.STRUTS_SUCCESS; - } - - private String saveOAConfigToDatabase(OnlineApplication dboa, boolean newentry) { - - AuthComponentOA authoa = dboa.getAuthComponentOA(); - if (authoa == null) { - authoa = new AuthComponentOA(); - dboa.setAuthComponentOA(authoa); - } - - if (authUser.isAdmin()) dboa.setIsActive(generalOA.isActive()); - - dboa.setFriendlyName(generalOA.getFriendlyName()); - dboa.setCalculateHPI(generalOA.isCalculateHPI()); - dboa.setRemoveBPKFromAuthBlock(generalOA.isHideBPKAuthBlock()); - - if (authUser.isAdmin()) - dboa.setKeyBoxIdentifier(MOAKeyBoxSelector.fromValue(generalOA.getKeyBoxIdentifier())); - else { - if (newentry) dboa.setKeyBoxIdentifier(MOAKeyBoxSelector.SECURE_SIGNATURE_KEYPAIR); - } - - dboa.setPublicURLPrefix(generalOA.getIdentifier()); - - if (generalOA.isBusinessService() || onlyBusinessService) { - - dboa.setType(Constants.MOA_CONFIG_BUSINESSSERVICE); - - String num = generalOA.getIdentificationNumber().replaceAll(" ", ""); - if (num.startsWith(Constants.IDENIFICATIONTYPE_FN)) { - num = num.substring(Constants.IDENIFICATIONTYPE_FN.length()); - - num = at.gv.egovernment.moa.util.StringUtils.deleteLeadingZeros(num); - - // num = StringUtils.leftPad(num, 7, '0'); - } - - if (num.startsWith(Constants.IDENIFICATIONTYPE_ZVR)) num = num.substring(Constants.IDENIFICATIONTYPE_ZVR.length()); - - if (num.startsWith(Constants.IDENIFICATIONTYPE_ERSB)) num = num.substring(Constants.IDENIFICATIONTYPE_ERSB.length()); - - IdentificationNumber idnumber = new IdentificationNumber(); - idnumber.setValue(Constants.PREFIX_WPBK + generalOA.getIdentificationType() + "+" + num); - idnumber.setType(Constants.BUSINESSSERVICENAMES.get(generalOA.getIdentificationType())); - - authoa.setIdentificationNumber(idnumber); - - } else { - dboa.setType(null); - - if (authUser.isAdmin()) { - if (MiscUtil.isNotEmpty(generalOA.getTarget_admin()) && generalOA.isAdminTarget()) { - dboa.setTarget(generalOA.getTarget_admin()); - dboa.setTargetFriendlyName(generalOA.getTargetFriendlyName()); - - } else { - - String target = generalOA.getTarget(); - - if (MiscUtil.isNotEmpty(generalOA.getTarget_subsector()) && subTargetSet) - dboa.setTarget(target + "-" + generalOA.getTarget_subsector()); - else - dboa.setTarget(target); - - String targetname = TargetValidator.getTargetFriendlyName(target); - if (MiscUtil.isNotEmpty(targetname)) dboa.setTargetFriendlyName(targetname); - - } - - } else { - - if (MiscUtil.isNotEmpty(generalOA.getTarget())) { - - String target = generalOA.getTarget(); - - if (MiscUtil.isNotEmpty(generalOA.getTarget_subsector()) && subTargetSet) - dboa.setTarget(target + "-" + generalOA.getTarget_subsector()); - - else - dboa.setTarget(target); - - String targetname = TargetValidator.getTargetFriendlyName(target); - if (MiscUtil.isNotEmpty(targetname)) dboa.setTargetFriendlyName(targetname); - - } - } - } - - //store BKU-URLs - BKUURLS bkuruls = new BKUURLS(); - authoa.setBKUURLS(bkuruls); - if (authUser.isAdmin()) { - bkuruls.setHandyBKU(generalOA.getBkuHandyURL()); - bkuruls.setLocalBKU(generalOA.getBkuLocalURL()); - bkuruls.setOnlineBKU(generalOA.getBkuOnlineURL()); - } - - TemplatesType templates = authoa.getTemplates(); - if (templates == null) { - templates = new TemplatesType(); - authoa.setTemplates(templates); - } - - //store BKU-selection and send-assertion templates - if (authUser.isAdmin()) { - - if(generalOA.isDeleteBKUTemplate()) - templates.setBKUSelectionTemplate(null); - - if (generalOA.isDeleteSendAssertionTemplate()) - templates.setSendAssertionTemplate(null); - - - if (bkuSelectionForm != null && bkuSelectionForm.size() > 0) { - TransformsInfoType template = new TransformsInfoType(); - - Iterator<String> interator = bkuSelectionForm.keySet().iterator(); - template.setFilename(interator.next()); - template.setTransformation(bkuSelectionForm.get( - template.getFilename())); - - templates.setBKUSelectionTemplate(template); - } - - if (sendAssertionForm != null && sendAssertionForm.size() > 0) { - TransformsInfoType template = new TransformsInfoType(); - - Iterator<String> interator = sendAssertionForm.keySet().iterator(); - template.setFilename(interator.next()); - template.setTransformation(sendAssertionForm.get( - template.getFilename())); - - templates.setSendAssertionTemplate(template); - } - } - - - //store BKU-selection customization - BKUSelectionCustomizationType bkuselectioncustom = templates.getBKUSelectionCustomization(); - if (bkuselectioncustom == null) { - bkuselectioncustom = new BKUSelectionCustomizationType(); - templates.setBKUSelectionCustomization(bkuselectioncustom); - } - - Mandates mandates = new Mandates(); - if (generalOA.isUseMandates()) { - mandates.setProfiles(generalOA.getMandateProfiles()); - - } else { - mandates.setProfiles(new String()); - } - - authoa.setMandates(mandates); - bkuselectioncustom.setMandateLoginButton(MiscUtil.isNotEmpty(generalOA.getMandateProfiles())); - bkuselectioncustom.setOnlyMandateLoginAllowed(formOA.isOnlyMandateAllowed()); - - if (authUser.isAdmin()) { - templates.setAditionalAuthBlockText(generalOA.getAditionalAuthBlockText()); - - List<TemplateType> template = templates.getTemplate(); - if (generalOA.isLegacy()) { - - if (template == null) - template = new ArrayList<TemplateType>(); - else - template.clear(); - - if (MiscUtil.isNotEmpty(generalOA.getSLTemplateURL1())) { - TemplateType el = new TemplateType(); - el.setURL(generalOA.getSLTemplateURL1()); - template.add(el); - } else - template.add(new TemplateType()); - if (MiscUtil.isNotEmpty(generalOA.getSLTemplateURL2())) { - TemplateType el = new TemplateType(); - el.setURL(generalOA.getSLTemplateURL2()); - template.add(el); - }else - template.add(new TemplateType()); - if (MiscUtil.isNotEmpty(generalOA.getSLTemplateURL3())) { - TemplateType el = new TemplateType(); - el.setURL(generalOA.getSLTemplateURL3()); - template.add(el); - }else - template.add(new TemplateType()); - - } else { - if (template != null && template.size() > 0) template.clear(); - } - - bkuselectioncustom.setBackGroundColor(parseColor(formOA.getBackGroundColor())); - bkuselectioncustom.setFrontColor(parseColor(formOA.getFrontColor())); - - bkuselectioncustom.setHeaderBackGroundColor(parseColor(formOA.getHeader_BackGroundColor())); - bkuselectioncustom.setHeaderFrontColor(parseColor(formOA.getHeader_FrontColor())); - bkuselectioncustom.setHeaderText(formOA.getHeader_text()); - - bkuselectioncustom.setButtonBackGroundColor(parseColor(formOA.getButton_BackGroundColor())); - bkuselectioncustom.setButtonBackGroundColorFocus(parseColor(formOA.getButton_BackGroundColorFocus())); - bkuselectioncustom.setButtonFontColor(parseColor(formOA.getButton_FrontColor())); - - if (MiscUtil.isNotEmpty(formOA.getAppletRedirectTarget())) - bkuselectioncustom.setAppletRedirectTarget(formOA.getAppletRedirectTarget()); - - bkuselectioncustom.setFontType(formOA.getFontType()); - - bkuselectioncustom.setAppletHeight(formOA.getApplet_height()); - bkuselectioncustom.setAppletWidth(formOA.getApplet_width()); - - } - - // set default transformation if it is empty - List<TransformsInfoType> transformsInfo = authoa.getTransformsInfo(); - if (transformsInfo == null) { - // TODO: set OA specific transformation if it is required - - } - - OAPVP2 pvp2 = authoa.getOAPVP2(); - if (pvp2 == null) { - pvp2 = new OAPVP2(); - authoa.setOAPVP2(pvp2); - } - - pvp2.setMetadataURL(pvp2OA.getMetaDataURL()); - try { - - if (pvp2OA.getFileUpload() != null) pvp2.setCertificate(pvp2OA.getCertificate()); - - } - catch (CertificateException e) { - log.info("Uploaded Certificate can not be found", e); - return LanguageHelper.getErrorString("validation.pvp2.certificate.notfound"); - } - catch (IOException e) { - log.info("Uploaded Certificate can not be parsed", e); - return LanguageHelper.getErrorString("validation.pvp2.certificate.format"); - } - - OASAML1 saml1 = authoa.getOASAML1(); - if (saml1 == null) { - saml1 = new OASAML1(); - authoa.setOASAML1(saml1); - saml1.setIsActive(false); - } - - if (authUser.isAdmin()) { - saml1.setIsActive(saml1OA.isActive()); - } - - if (saml1.isIsActive() != null && saml1.isIsActive()) { - saml1.setProvideAUTHBlock(saml1OA.isProvideAuthBlock()); - saml1.setProvideCertificate(saml1OA.isProvideCertificate()); - saml1.setProvideFullMandatorData(saml1OA.isProvideFullMandateData()); - saml1.setProvideIdentityLink(saml1OA.isProvideIdentityLink()); - saml1.setProvideStammzahl(saml1OA.isProvideStammZahl()); - saml1.setUseCondition(saml1OA.isUseCondition()); - saml1.setConditionLength(BigInteger.valueOf(saml1OA.getConditionLength())); - // TODO: set sourceID - // saml1.setSourceID(""); - } - - OASSO sso = authoa.getOASSO(); - if (sso == null) { - sso = new OASSO(); - authoa.setOASSO(sso); - sso.setAuthDataFrame(true); - } - sso.setUseSSO(ssoOA.isUseSSO()); - - if (authUser.isAdmin()) sso.setAuthDataFrame(ssoOA.isShowAuthDataFrame()); - - sso.setSingleLogOutURL(ssoOA.getSingleLogOutURL()); - - if (oauth20OA != null) { - log.debug("Saving OAuth 2.0 configuration:"); - OAOAUTH20 oaOAuth20 = authoa.getOAOAUTH20(); - if (oaOAuth20 == null) { - oaOAuth20 = new OAOAUTH20(); - authoa.setOAOAUTH20(oaOAuth20); - } - - oaOAuth20.setOAuthClientId(generalOA.getIdentifier()); - // oaOAuth20.setOAuthClientSecret(oauth20OA.getClientSecret()); - oaOAuth20.setOAuthRedirectUri(oauth20OA.getRedirectUri()); - log.debug("client id: " + oauth20OA.getClientId()); - log.debug("client secret: " + oauth20OA.getClientSecret()); - log.debug("redirect uri:" + oauth20OA.getRedirectUri()); - - oaOAuth20.setOAuthClientSecret((String) request.getSession().getAttribute(Constants.SESSION_OAUTH20SECRET)); - request.getSession().setAttribute(Constants.SESSION_OAUTH20SECRET, null); - - } - - - // fetch stork configuration from database model - OASTORK stork = authoa.getOASTORK(); - if (stork == null) { - // if there is none, create a new one with default values. - stork = new OASTORK(); - authoa.setOASTORK(stork); - stork.setStorkLogonEnabled(false); - } - // transfer the incoming data to the database model - stork.setStorkLogonEnabled(storkOA.isStorkLogonEnabled()); - stork.setQaa(storkOA.getQaa()); - stork.setOAAttributes(storkOA.getAttributes()); - stork.setVidpEnabled(storkOA.isVidpEnabled()); - stork.setAttributeProviders(storkOA.getAttributeProviderPlugins()); - - try { - if (newentry) { - ConfigurationDBUtils.save(dboa); - - if (!authUser.isAdmin()) { - UserDatabase user = ConfigurationDBRead.getUserWithID(authUser.getUserID()); - - List<OnlineApplication> useroas = user.getOnlineApplication(); - if (useroas == null) useroas = new ArrayList<OnlineApplication>(); - - useroas.add(dboa); - ConfigurationDBUtils.saveOrUpdate(user); - } - } - - else - ConfigurationDBUtils.saveOrUpdate(dboa); - - } - catch (MOADatabaseException e) { - log.warn("Online-Application can not be stored.", e); - return LanguageHelper.getErrorString("error.db.oa.store"); - } - - return null; - } - - private String parseColor(String color) { - String value = ""; - - if (MiscUtil.isNotEmpty(color)) { - if (!color.startsWith("#")) - value = "#" + color; - else - value = color; - } - return value; - } - - private void generateUserSpecificConfigurationOptions(UserDatabase userdb) { - - if (userdb.isIsMandateUser() != null && userdb.isIsMandateUser()) { - String bpk = userdb.getBpk(); - if (bpk.startsWith(Constants.IDENIFICATIONTYPE_BASEID_FN) || bpk.startsWith(Constants.IDENIFICATIONTYPE_BASEID_ZVR)) { - - onlyBusinessService = true; - generalOA.setBusinessService(true); - - } - - deaktivededBusinessService = true; - String[] split = bpk.split("\\+"); - generalOA.setIdentificationType(split[1].substring(1)); - - if (bpk.startsWith(Constants.IDENIFICATIONTYPE_BASEID_FN)) - generalOA.setIdentificationNumber(at.gv.egovernment.moa.util.StringUtils.deleteLeadingZeros(split[2])); - else - generalOA.setIdentificationNumber(split[2]); - - } - - } - - public String setGeneralOAConfig() { - - return Constants.STRUTS_SUCCESS; - } - - public String setSAML1OAConfig() { - - return Constants.STRUTS_SUCCESS; - } - - public String setPVP2OAConfig() { - - return Constants.STRUTS_SUCCESS; - } - - public String setSSOOAConfig() { - - return Constants.STRUTS_SUCCESS; - } - - public String setSTORKOAConfig() { - - return Constants.STRUTS_SUCCESS; - } - - // Getter and Setter - public void setServletResponse(HttpServletResponse arg0) { - this.response = arg0; - - } - - public void setServletRequest(HttpServletRequest arg0) { - this.request = arg0; - - } - - public HttpServletRequest getRequest() { - return request; - } - - public void setRequest(HttpServletRequest request) { - this.request = request; - } - - public HttpServletResponse getResponse() { - return response; - } - - public void setResponse(HttpServletResponse response) { - this.response = response; - } - - public OAGeneralConfig getGeneralOA() { - return generalOA; - } - - public void setGeneralOA(OAGeneralConfig generalOA) { - this.generalOA = generalOA; - } - - public OAPVP2Config getPvp2OA() { - return pvp2OA; - } - - public void setPvp2OA(OAPVP2Config pvp2oa) { - pvp2OA = pvp2oa; - } - - public OASAML1Config getSaml1OA() { - return saml1OA; - } - - public void setSaml1OA(OASAML1Config saml1oa) { - saml1OA = saml1oa; - } - - public OASSOConfig getSsoOA() { - return ssoOA; - } - - public void setSsoOA(OASSOConfig ssoOA) { - this.ssoOA = ssoOA; - } - - public OASTORKConfig getStorkOA() { - return storkOA; - } - - public void setStorkOA(OASTORKConfig storkOA) { - this.storkOA = storkOA; - } - - /** - * @param oaidobj - * the oaidobj to set - */ - public void setOaidobj(String oaidobj) { - this.oaidobj = oaidobj; - } - - /** - * @return the authUser - */ - public AuthenticatedUser getAuthUser() { - return authUser; - } - - /** - * @return the newOA - */ - public boolean isNewOA() { - return newOA; - } - - /** - * @param newOA - * the newOA to set - */ - public void setNewOA(boolean newOA) { - this.newOA = newOA; - } - - /** - * @return the nextPage - */ - public String getNextPage() { - return nextPage; - } - - /** - * @return the formID - */ - public String getFormID() { - return formID; - } - - /** - * @param formID - * the formID to set - */ - public void setFormID(String formID) { - this.formID = formID; - } - - /** - * @return the onlyBusinessService - */ - public boolean isOnlyBusinessService() { - return onlyBusinessService; - } - - /** - * @param onlyBusinessService - * the onlyBusinessService to set - */ - public void setOnlyBusinessService(boolean onlyBusinessService) { - this.onlyBusinessService = onlyBusinessService; - } - - /** - * @return the subTargetSet - */ - public boolean isSubTargetSet() { - return subTargetSet; - } - - /** - * @param subTargetSet - * the subTargetSet to set - */ - public void setSubTargetSet(boolean subTargetSet) { - this.subTargetSet = subTargetSet; - } - - /** - * @return the deaktivededBusinessService - */ - public boolean isDeaktivededBusinessService() { - return deaktivededBusinessService; - } - - /** - * @param deaktivededBusinessService - * the deaktivededBusinessService to set - */ - public void setDeaktivededBusinessService(boolean deaktivededBusinessService) { - this.deaktivededBusinessService = deaktivededBusinessService; - } - - /** - * @return the formOA - */ - public FormularCustomization getFormOA() { - return formOA; - } - - /** - * @param formOA - * the formOA to set - */ - public void setFormOA(FormularCustomization formOA) { - this.formOA = formOA; - } - - /** - * @return the stream - */ - public InputStream getStream() { - return stream; - } - - public OAOAuth20Config getOauth20OA() { - return oauth20OA; - } - - public void setOauth20OA(OAOAuth20Config oauth20OA) { - this.oauth20OA = oauth20OA; - } - + + private final Logger log = Logger.getLogger(EditOAAction.class); + + private static final long serialVersionUID = 1L; + + private HttpServletRequest request; + private HttpServletResponse response; + + private AuthenticatedUser authUser; + + private String oaidobj; + private boolean newOA; + private String formID; + + private boolean onlyBusinessService = false; + private boolean onlyStorkService = false; + private boolean subTargetSet = false; + private boolean deaktivededBusinessService = false; + private boolean deactivatedStorkService = false; + private boolean isMetaDataRefreshRequired = false; + + private String nextPage; + + private OAGeneralConfig generalOA = new OAGeneralConfig(); + private OAPVP2Config pvp2OA = new OAPVP2Config(); + private OASAML1Config saml1OA = new OASAML1Config(); + private OASSOConfig ssoOA = new OASSOConfig(); + private OAOAuth20Config oauth20OA = new OAOAuth20Config(); + private OASTORKConfig storkOA = new OASTORKConfig(); + private FormularCustomization formOA = new FormularCustomization(); + + private InputStream stream; + + private Map<String, byte[]> sendAssertionForm = new HashMap<String, byte[]>(); + private Map<String, byte[]> bkuSelectionForm = new HashMap<String, byte[]>(); + + // STRUTS actions + public String inital() { + HttpSession session = request.getSession(); + if (session == null) { + log.info("No http Session found."); + return Constants.STRUTS_ERROR; + } + + Object authUserObj = session.getAttribute(Constants.SESSION_AUTH); + + authUser = (AuthenticatedUser) authUserObj; + + long oaid = -1; + + if (!ValidationHelper.validateOAID(oaidobj)) { + addActionError(LanguageHelper.getErrorString("errors.edit.oa.oaid", request)); + return Constants.STRUTS_ERROR; + } + oaid = Long.valueOf(oaidobj); + + UserDatabase userdb = null; + OnlineApplication onlineapplication = null; + + if (authUser.isAdmin()) + onlineapplication = ConfigurationDBRead.getOnlineApplication(oaid); + + else { + userdb = ConfigurationDBRead.getUserWithID(authUser.getUserID()); + + if (!authUser.isAdmin() && userdb.isIsMailAddressVerified() != null && !userdb.isIsMailAddressVerified()) { + log.info("Online-Applikation managemant disabled. Mail address is not verified."); + addActionError(LanguageHelper.getErrorString("error.editoa.mailverification")); + return Constants.STRUTS_SUCCESS; + } + + // TODO: change to direct Database operation + List<OnlineApplication> oas = userdb.getOnlineApplication(); + for (OnlineApplication oa : oas) { + if (oa.getHjid() == oaid) { + onlineapplication = oa; + break; + } + } + if (onlineapplication == null) { + addActionError(LanguageHelper.getErrorString("errors.edit.oa.oaid", request)); + return Constants.STRUTS_ERROR; + } + } + + generalOA.parse(onlineapplication); + ssoOA.parse(onlineapplication); + saml1OA.parse(onlineapplication); + oauth20OA.parse(onlineapplication); + session.setAttribute(Constants.SESSION_OAUTH20SECRET, this.oauth20OA.getClientSecret()); + + storkOA.parse(onlineapplication); + + Map<String, String> map = new HashMap<String, String>(); + map.putAll(FormBuildUtils.getDefaultMap()); + formOA.parse(onlineapplication, map); + + session.setAttribute(Constants.SESSION_BKUFORMPREVIEW, map); + + List<String> errors = pvp2OA.parse(onlineapplication); + + if (errors.size() > 0) { + for (String el : errors) + addActionError(el); + } + + subTargetSet = MiscUtil.isNotEmpty(generalOA.getTarget_subsector()); + + // set UserSpezific OA Parameters + if (!authUser.isAdmin()) generateUserSpecificConfigurationOptions(userdb); + + ConfigurationDBUtils.closeSession(); + session.setAttribute(Constants.SESSION_OAID, oaid); + + formID = Random.nextRandom(); + session.setAttribute(Constants.SESSION_FORMID, formID); + + newOA = false; + + return Constants.STRUTS_OA_EDIT; + } + + public String newOA() { + log.debug("insert new Online-Application"); + + HttpSession session = request.getSession(); + if (session == null) { + log.info("No http Session found."); + return Constants.STRUTS_ERROR; + } + + session.setAttribute(Constants.SESSION_OAID, null); + nextPage = Constants.STRUTS_RETURNAREA_VALUES.main.name(); + + Object authUserObj = session.getAttribute(Constants.SESSION_AUTH); + + authUser = (AuthenticatedUser) authUserObj; + + UserDatabase userdb = ConfigurationDBRead.getUserWithID(authUser.getUserID()); + + if (!authUser.isAdmin() && userdb.isIsMailAddressVerified() != null && !userdb.isIsMailAddressVerified()) { + log.info("Online-Applikation managemant disabled. Mail address is not verified."); + addActionError(LanguageHelper.getErrorString("error.editoa.mailverification")); + return Constants.STRUTS_SUCCESS; + } + + MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration(); + if (moaidconfig != null) { + DefaultBKUs defaultbkus = moaidconfig.getDefaultBKUs(); + if (defaultbkus != null) { + generalOA.setBkuHandyURL(defaultbkus.getHandyBKU()); + generalOA.setBkuLocalURL(defaultbkus.getLocalBKU()); + generalOA.setBkuOnlineURL(defaultbkus.getOnlineBKU()); + } + } + + // set UserSpezific OA Parameters + if (!authUser.isAdmin()) generateUserSpecificConfigurationOptions(userdb); + + ConfigurationDBUtils.closeSession(); + + newOA = true; + formID = Random.nextRandom(); + session.setAttribute(Constants.SESSION_FORMID, formID); + + session.setAttribute(Constants.SESSION_BKUFORMPREVIEW, null); + + this.oauth20OA.generateClientSecret(); + session.setAttribute(Constants.SESSION_OAUTH20SECRET, this.oauth20OA.getClientSecret()); + + return Constants.STRUTS_OA_EDIT; + } + + public String saveOA() { + HttpSession session = request.getSession(); + if (session == null) { + log.info("No http Session found."); + return Constants.STRUTS_ERROR; + } + + Object authUserObj = session.getAttribute(Constants.SESSION_AUTH); + authUser = (AuthenticatedUser) authUserObj; + + Object formidobj = session.getAttribute(Constants.SESSION_FORMID); + if (formidobj != null && formidobj instanceof String) { + String formid = (String) formidobj; + if (!formid.equals(formID)) { + log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName() + + authUser.getGivenName() + authUser.getUserID()); + return Constants.STRUTS_ERROR; + } + } else { + log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName() + + authUser.getGivenName() + authUser.getUserID()); + return Constants.STRUTS_ERROR; + } + session.setAttribute(Constants.SESSION_FORMID, null); + + UserDatabase userdb = ConfigurationDBRead.getUserWithID(authUser.getUserID()); + if (!authUser.isAdmin() && userdb.isIsMailAddressVerified() != null && !userdb.isIsMailAddressVerified()) { + log.info("Online-Applikation managemant disabled. Mail address is not verified."); + addActionError(LanguageHelper.getErrorString("error.editoa.mailverification")); + return Constants.STRUTS_SUCCESS; + } + + OnlineApplication onlineapplication = null; + List<String> errors = new ArrayList<String>(); + + Object oadbid = request.getSession().getAttribute(Constants.SESSION_OAID); + Long oaid = (long) -1; + + if (oadbid != null) { + try { + oaid = (Long) oadbid; + if (oaid < 0 || oaid > Long.MAX_VALUE) { + addActionError(LanguageHelper.getErrorString("errors.edit.oa.oaid", request)); + return Constants.STRUTS_ERROR; + } + + } catch (Throwable t) { + addActionError(LanguageHelper.getErrorString("errors.edit.oa.oaid", request)); + return Constants.STRUTS_ERROR; + } + } + + // valid DBID and check entry + String oaidentifier = generalOA.getIdentifier(); + if (MiscUtil.isEmpty(oaidentifier)) { + log.info("Empty OA identifier"); + errors.add(LanguageHelper.getErrorString("validation.general.oaidentifier.empty")); + + } else { + + if (!ValidationHelper.validateURL(oaidentifier)) { + log.warn("OnlineapplikationIdentifier is not a valid URL: " + oaidentifier); + errors.add(LanguageHelper.getErrorString("validation.general.oaidentifier.valid", + new Object[]{ValidationHelper.getNotValidOAIdentifierCharacters()})); + } else { + + if (oaid == -1) { + onlineapplication = ConfigurationDBRead.getOnlineApplication(oaidentifier); + newOA = true; + if (onlineapplication != null) { + log.info("The OAIdentifier is not unique"); + errors.add(LanguageHelper.getErrorString("validation.general.oaidentifier.notunique")); + } + + } else { + onlineapplication = ConfigurationDBRead.getOnlineApplication(oaid); + if (!oaidentifier.equals(onlineapplication.getPublicURLPrefix())) { + + if (ConfigurationDBRead.getOnlineApplication(oaidentifier) != null) { + log.info("The OAIdentifier is not unique"); + errors.add(LanguageHelper.getErrorString("validation.general.oaidentifier.notunique")); + } + } + } + } + } + + // set UserSpezific OA Parameters + if (!authUser.isAdmin()) generateUserSpecificConfigurationOptions(userdb); + + // check form + OAGeneralConfigValidation validatior_general = new OAGeneralConfigValidation(); + OAPVP2ConfigValidation validatior_pvp2 = new OAPVP2ConfigValidation(); + OASAML1ConfigValidation validatior_saml1 = new OASAML1ConfigValidation(); + OASSOConfigValidation validatior_sso = new OASSOConfigValidation(); + OASTORKConfigValidation validator_stork = new OASTORKConfigValidation(); + FormularCustomizationValitator validator_form = new FormularCustomizationValitator(); + OAOAUTH20ConfigValidation validatior_oauth20 = new OAOAUTH20ConfigValidation(); + OAFileUploadValidation valiator_fileUpload = new OAFileUploadValidation(); + + errors.addAll(validatior_general.validate(generalOA, authUser.isAdmin())); + errors.addAll(validatior_pvp2.validate(pvp2OA)); + errors.addAll(validatior_saml1.validate(saml1OA, generalOA)); + errors.addAll(validatior_sso.validate(ssoOA, authUser.isAdmin())); + errors.addAll(validator_stork.validate(storkOA)); + errors.addAll(validator_form.validate(formOA)); + errors.addAll(validatior_oauth20.validate(oauth20OA)); + + //validate BKU-selection template + List<String> templateError = valiator_fileUpload.validate(generalOA.getBkuSelectionFileUploadFileName() + , generalOA.getBkuSelectionFileUpload(), "validation.general.bkuselection", bkuSelectionForm); + if (templateError != null && templateError.size() == 0) { + if (bkuSelectionForm != null && bkuSelectionForm.size() > 0) + session.setAttribute(Constants.SESSION_BKUSELECTIONTEMPLATE, bkuSelectionForm); + + else + bkuSelectionForm = (Map<String, byte[]>) session.getAttribute(Constants.SESSION_BKUSELECTIONTEMPLATE); + + } else { + errors.addAll(templateError); + + } + + //validate send-assertion template + templateError = valiator_fileUpload.validate(generalOA.getSendAssertionFileUploadFileName() + , generalOA.getSendAssertionFileUpload(), "validation.general.sendassertion", sendAssertionForm); + if (templateError != null && templateError.size() == 0) { + if (sendAssertionForm != null && sendAssertionForm.size() > 0) + session.setAttribute(Constants.SESSION_SENDASSERTIONTEMPLATE, sendAssertionForm); + + else + sendAssertionForm = (Map<String, byte[]>) session.getAttribute(Constants.SESSION_SENDASSERTIONTEMPLATE); + + } else { + errors.addAll(templateError); + + } + + + // Do not allow SSO in combination with special BKUSelection features + if (ssoOA.isUseSSO() && (formOA.isOnlyMandateAllowed() || !formOA.isShowMandateLoginButton())) { + log.warn("Special BKUSelection features can not be used in combination with SSO"); + errors.add(LanguageHelper.getErrorString("validation.general.bkuselection.specialfeatures.valid")); + } + + if (errors.size() > 0) { + log.info("OAConfiguration with ID " + generalOA.getIdentifier() + " has some errors."); + for (String el : errors) + addActionError(el); + + formID = Random.nextRandom(); + session.setAttribute(Constants.SESSION_FORMID, formID); + return Constants.STRUTS_ERROR_VALIDATION; + + } else { + + boolean newentry = false; + + if (onlineapplication == null) { + onlineapplication = new OnlineApplication(); + newentry = true; + onlineapplication.setIsActive(false); + + if (!authUser.isAdmin()) { + onlineapplication.setIsAdminRequired(true); + + } else + isMetaDataRefreshRequired = true; + + } else { + if (!authUser.isAdmin() && !onlineapplication.getPublicURLPrefix().equals(generalOA.getIdentifier())) { + + onlineapplication.setIsAdminRequired(true); + onlineapplication.setIsActive(false); + log.info("User with ID " + authUser.getUserID() + " change OA-PublicURLPrefix. Reaktivation is required."); + } + + } + + if ((onlineapplication.isIsAdminRequired() == null) + || (authUser.isAdmin() && generalOA.isActive() && onlineapplication.isIsAdminRequired())) { + + onlineapplication.setIsAdminRequired(false); + isMetaDataRefreshRequired = true; + + if (onlineapplication.getHjid() != null) + userdb = ConfigurationDBRead.getUsersWithOADBID(onlineapplication.getHjid()); + + if (userdb != null && !userdb.isIsAdmin()) { + try { + MailHelper.sendUserOnlineApplicationActivationMail(userdb.getGivenname(), userdb.getFamilyname(), + userdb.getInstitut(), onlineapplication.getPublicURLPrefix(), userdb.getMail()); + } catch (ConfigurationException e) { + log.warn("Sending Mail to User " + userdb.getMail() + " failed", e); + } + } + } + + //save OA configuration + String error = saveOAConfigToDatabase(onlineapplication, newentry); + if (MiscUtil.isNotEmpty(error)) { + log.warn("OA configuration can not be stored!"); + addActionError(error); + + formID = Random.nextRandom(); + session.setAttribute(Constants.SESSION_FORMID, formID); + return Constants.STRUTS_ERROR_VALIDATION; + } + + //set metadata reload flag if reload is required + if (pvp2OA.getMetaDataURL() != null) { + + try { + if (isMetaDataRefreshRequired + || !pvp2OA.getMetaDataURL().equals(onlineapplication.getAuthComponentOA().getOAPVP2().getMetadataURL()) + || pvp2OA.getFileUpload() != null + || pvp2OA.isReLoad()) { + + log.debug("Set PVP2 Metadata refresh flag."); + MOAIDConfiguration moaconfig = ConfigurationDBRead.getMOAIDConfiguration(); + moaconfig.setPvp2RefreshItem(new Date()); + ConfigurationDBUtils.saveOrUpdate(moaconfig); + + } + } catch (Throwable e) { + log.info("Found no MetadataURL in OA-Databaseconfig!", e); + } + + } + } + + Object nextPageAttr = session.getAttribute(Constants.SESSION_RETURNAREA); + if (nextPageAttr != null && nextPageAttr instanceof String) { + nextPage = (String) nextPageAttr; + session.setAttribute(Constants.SESSION_RETURNAREA, null); + + } else { + nextPage = Constants.STRUTS_RETURNAREA_VALUES.main.name(); + } + + if (onlineapplication.isIsAdminRequired()) { + int numoas = 0; + int numusers = 0; + + List<OnlineApplication> openOAs = ConfigurationDBRead.getAllNewOnlineApplications(); + if (openOAs != null) numoas = openOAs.size(); + + List<UserDatabase> openUsers = ConfigurationDBRead.getAllNewUsers(); + if (openUsers != null) numusers = openUsers.size(); + try { + + addActionMessage(LanguageHelper.getGUIString("webpages.oaconfig.success.admin", generalOA.getIdentifier(), request)); + + if (numusers > 0 || numoas > 0) MailHelper.sendAdminMail(numoas, numusers); + + } catch (ConfigurationException e) { + log.warn("Sending Mail to Admin failed.", e); + } + + } else + addActionMessage(LanguageHelper.getGUIString("webpages.oaconfig.success", generalOA.getIdentifier(), request)); + + //remove session attributes + session.setAttribute(Constants.SESSION_OAID, null); + session.removeAttribute(Constants.SESSION_BKUSELECTIONTEMPLATE); + session.removeAttribute(Constants.SESSION_SENDASSERTIONTEMPLATE); + + ConfigurationDBUtils.closeSession(); + return Constants.STRUTS_SUCCESS; + } + + public String cancleAndBackOA() { + + HttpSession session = request.getSession(); + if (session == null) { + log.info("No http Session found."); + return Constants.STRUTS_ERROR; + } + + Object nextPageAttr = session.getAttribute(Constants.SESSION_RETURNAREA); + if (nextPageAttr != null && nextPageAttr instanceof String) { + nextPage = (String) nextPageAttr; + session.setAttribute(Constants.SESSION_RETURNAREA, null); + + } else { + nextPage = Constants.STRUTS_RETURNAREA_VALUES.main.name(); + } + + session.setAttribute(Constants.SESSION_OAID, null); + + addActionMessage(LanguageHelper.getGUIString("webpages.oaconfig.cancle", generalOA.getIdentifier(), request)); + + ConfigurationDBUtils.closeSession(); + + return Constants.STRUTS_SUCCESS; + } + + public String deleteOA() { + HttpSession session = request.getSession(); + if (session == null) { + log.info("No http Session found."); + return Constants.STRUTS_ERROR; + } + + Object authUserObj = session.getAttribute(Constants.SESSION_AUTH); + authUser = (AuthenticatedUser) authUserObj; + + Object formidobj = session.getAttribute(Constants.SESSION_FORMID); + if (formidobj != null && formidobj instanceof String) { + String formid = (String) formidobj; + if (!formid.equals(formID)) { + log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName() + + authUser.getGivenName() + authUser.getUserID()); + return Constants.STRUTS_ERROR; + } + } else { + log.warn("FormIDs does not match. Some suspect Form is received from user " + authUser.getFamilyName() + + authUser.getGivenName() + authUser.getUserID()); + return Constants.STRUTS_ERROR; + } + session.setAttribute(Constants.SESSION_FORMID, null); + + Object nextPageAttr = session.getAttribute(Constants.SESSION_RETURNAREA); + if (nextPageAttr != null && nextPageAttr instanceof String) { + nextPage = (String) nextPageAttr; + + } else { + nextPage = Constants.STRUTS_RETURNAREA_VALUES.main.name(); + } + + UserDatabase userdb = ConfigurationDBRead.getUserWithID(authUser.getUserID()); + if (!authUser.isAdmin() && userdb.isIsMailAddressVerified() != null && !userdb.isIsMailAddressVerified()) { + log.info("Online-Applikation managemant disabled. Mail address is not verified."); + addActionError(LanguageHelper.getErrorString("error.editoa.mailverification")); + return Constants.STRUTS_SUCCESS; + } + + String oaidentifier = generalOA.getIdentifier(); + if (MiscUtil.isEmpty(oaidentifier)) { + log.info("Empty OA identifier"); + addActionError(LanguageHelper.getErrorString("validation.general.oaidentifier.empty")); + + formID = Random.nextRandom(); + session.setAttribute(Constants.SESSION_FORMID, formID); + return Constants.STRUTS_ERROR_VALIDATION; + + } else { + if (ValidationHelper.isValidOAIdentifier(oaidentifier)) { + log.warn("IdentificationNumber contains potentail XSS characters: " + oaidentifier); + addActionError(LanguageHelper.getErrorString("validation.general.oaidentifier.valid", + new Object[]{ValidationHelper.getNotValidOAIdentifierCharacters()})); + + formID = Random.nextRandom(); + session.setAttribute(Constants.SESSION_FORMID, formID); + return Constants.STRUTS_ERROR_VALIDATION; + } + } + + OnlineApplication onlineapplication = ConfigurationDBRead.getOnlineApplication(oaidentifier); + request.getSession().setAttribute(Constants.SESSION_OAID, null); + + try { + if (MiscUtil.isNotEmpty(onlineapplication.getAuthComponentOA().getOAPVP2().getMetadataURL())) { + + MOAIDConfiguration moaconfig = ConfigurationDBRead.getMOAIDConfiguration(); + moaconfig.setPvp2RefreshItem(new Date()); + ConfigurationDBUtils.saveOrUpdate(moaconfig); + + } + } catch (Throwable e) { + log.info("Found no MetadataURL in OA-Databaseconfig!", e); + } + + if (ConfigurationDBUtils.delete(onlineapplication)) { + + if (!authUser.isAdmin()) { + UserDatabase user = ConfigurationDBRead.getUserWithID(authUser.getUserID()); + List<OnlineApplication> useroas = user.getOnlineApplication(); + + for (OnlineApplicationType oa : useroas) { + if (oa.getHjid().equals(onlineapplication.getHjid())) { + useroas.remove(oa); + } + } + + try { + ConfigurationDBUtils.saveOrUpdate(user); + + } catch (MOADatabaseException e) { + log.warn("User information can not be updated in database", e); + addActionError(LanguageHelper.getGUIString("error.db.oa.store", request)); + return Constants.STRUTS_ERROR; + } + } + + ConfigurationDBUtils.closeSession(); + + addActionMessage(LanguageHelper.getGUIString("webpages.oaconfig.delete.message", generalOA.getIdentifier(), request)); + + return Constants.STRUTS_SUCCESS; + + } else { + ConfigurationDBUtils.closeSession(); + addActionError(LanguageHelper.getGUIString("webpages.oaconfig.delete.error", generalOA.getIdentifier(), request)); + return Constants.STRUTS_SUCCESS; + } + + } + + public String bkuFramePreview() { + + String preview = null; + + HttpSession session = request.getSession(); + if (session == null) { + log.info("No http Session found."); + preview = LanguageHelper.getErrorString("error.bkuformpreview.notpossible"); + + } else { + InputStream input = null; + + try { + Object mapobj = session.getAttribute(Constants.SESSION_BKUFORMPREVIEW); + if (mapobj != null && mapobj instanceof Map<?, ?>) { + + ConfigurationProvider config = ConfigurationProvider.getInstance(); + String templateURL = config.getConfigRootDir() + ConfigurationProvider.HTMLTEMPLATE_DIR + + ConfigurationProvider.HTMLTEMPLATE_FILE; + + File file = new File(templateURL); + input = new FileInputStream(file); + + String contextpath = config.getMOAIDInstanceURL(); + if (MiscUtil.isEmpty(contextpath)) { + log.info("NO MOA-ID instance URL configurated."); + throw new ConfigurationException("No MOA-ID instance configurated"); + } + + preview = LoginFormBuilder.getTemplate(input); + preview = preview.replace(LoginFormBuilder.CONTEXTPATH, contextpath); + + Map<String, String> map = (Map<String, String>) mapobj; + + request.setCharacterEncoding("UTF-8"); + + String module = request.getParameter(Constants.REQUEST_FORMCUSTOM_MODULE); + String value = request.getParameter(Constants.REQUEST_FORMCUSTOM_VALUE); + + if (value != null) { + String[] query = URLDecoder.decode(request.getQueryString()).split("&"); + value = query[1].substring("value=".length()); + } + + synchronized (map) { + + if (MiscUtil.isNotEmpty(module)) { + if (map.containsKey("#" + module + "#")) { + if (MiscUtil.isNotEmpty(value)) { + if (FormBuildUtils.FONTFAMILY.contains(module) || FormBuildUtils.HEADER_TEXT.contains(module) + || value.startsWith("#")) + map.put("#" + module + "#", value); + else + map.put("#" + module + "#", "#" + value); + + } else { + map.put("#" + module + "#", FormBuildUtils.getDefaultMap().get("#" + module + "#")); + } + } + } + preview = FormBuildUtils.customiceLayoutBKUSelection(preview, true, false, map, true); + } + + } else { + preview = LanguageHelper.getErrorString("error.bkuformpreview.notpossible"); + + } + + } catch (Exception e) { + log.warn("BKUSelection Preview can not be generated.", e); + preview = LanguageHelper.getErrorString("error.bkuformpreview.notpossible"); + + } + } + + stream = new ByteArrayInputStream(preview.getBytes()); + + return Constants.STRUTS_SUCCESS; + } + + private String saveOAConfigToDatabase(OnlineApplication dboa, boolean newentry) { + + AuthComponentOA authoa = dboa.getAuthComponentOA(); + if (authoa == null) { + authoa = new AuthComponentOA(); + dboa.setAuthComponentOA(authoa); + } + + if (authUser.isAdmin()) dboa.setIsActive(generalOA.isActive()); + + dboa.setFriendlyName(generalOA.getFriendlyName()); + dboa.setCalculateHPI(generalOA.isCalculateHPI()); + dboa.setRemoveBPKFromAuthBlock(generalOA.isHideBPKAuthBlock()); + + if (authUser.isAdmin()) + dboa.setKeyBoxIdentifier(MOAKeyBoxSelector.fromValue(generalOA.getKeyBoxIdentifier())); + else { + if (newentry) dboa.setKeyBoxIdentifier(MOAKeyBoxSelector.SECURE_SIGNATURE_KEYPAIR); + } + + dboa.setPublicURLPrefix(generalOA.getIdentifier()); + + if (generalOA.isStorkService() || onlyStorkService) { + dboa.setType(Constants.MOA_CONFIG_STORKSERVICE); + dboa.setStorkSPTargetCountry(generalOA.getStorkSPTargetCountry()); + + + IdentificationNumber idnumber = new IdentificationNumber(); + idnumber.setValue(Constants.PREFIX_STORK + "AT+" + generalOA.getStorkSPTargetCountry()); + idnumber.setType(Constants.BUSINESSSERVICENAMES.get(generalOA.getIdentificationType())); + + authoa.setIdentificationNumber(idnumber); + + } else if (generalOA.isBusinessService() || onlyBusinessService) { + + dboa.setType(Constants.MOA_CONFIG_BUSINESSSERVICE); + + String num = generalOA.getIdentificationNumber().replaceAll(" ", ""); + if (num.startsWith(Constants.IDENIFICATIONTYPE_FN)) { + num = num.substring(Constants.IDENIFICATIONTYPE_FN.length()); + + num = at.gv.egovernment.moa.util.StringUtils.deleteLeadingZeros(num); + + // num = StringUtils.leftPad(num, 7, '0'); + } + + if (num.startsWith(Constants.IDENIFICATIONTYPE_ZVR)) + num = num.substring(Constants.IDENIFICATIONTYPE_ZVR.length()); + + if (num.startsWith(Constants.IDENIFICATIONTYPE_ERSB)) + num = num.substring(Constants.IDENIFICATIONTYPE_ERSB.length()); + + IdentificationNumber idnumber = new IdentificationNumber(); + idnumber.setValue(Constants.PREFIX_WPBK + generalOA.getIdentificationType() + "+" + num); + idnumber.setType(Constants.BUSINESSSERVICENAMES.get(generalOA.getIdentificationType())); + + authoa.setIdentificationNumber(idnumber); + + } else { + dboa.setType(null); + + if (authUser.isAdmin()) { + if (MiscUtil.isNotEmpty(generalOA.getTarget_admin()) && generalOA.isAdminTarget()) { + dboa.setTarget(generalOA.getTarget_admin()); + dboa.setTargetFriendlyName(generalOA.getTargetFriendlyName()); + + } else { + + String target = generalOA.getTarget(); + + if (MiscUtil.isNotEmpty(generalOA.getTarget_subsector()) && subTargetSet) + dboa.setTarget(target + "-" + generalOA.getTarget_subsector()); + else + dboa.setTarget(target); + + String targetname = TargetValidator.getTargetFriendlyName(target); + if (MiscUtil.isNotEmpty(targetname)) dboa.setTargetFriendlyName(targetname); + + } + + } else { + + if (MiscUtil.isNotEmpty(generalOA.getTarget())) { + + String target = generalOA.getTarget(); + + if (MiscUtil.isNotEmpty(generalOA.getTarget_subsector()) && subTargetSet) + dboa.setTarget(target + "-" + generalOA.getTarget_subsector()); + + else + dboa.setTarget(target); + + String targetname = TargetValidator.getTargetFriendlyName(target); + if (MiscUtil.isNotEmpty(targetname)) dboa.setTargetFriendlyName(targetname); + + } + } + } + + //store BKU-URLs + BKUURLS bkuruls = new BKUURLS(); + authoa.setBKUURLS(bkuruls); + if (authUser.isAdmin()) { + bkuruls.setHandyBKU(generalOA.getBkuHandyURL()); + bkuruls.setLocalBKU(generalOA.getBkuLocalURL()); + bkuruls.setOnlineBKU(generalOA.getBkuOnlineURL()); + } + + TemplatesType templates = authoa.getTemplates(); + if (templates == null) { + templates = new TemplatesType(); + authoa.setTemplates(templates); + } + + //store BKU-selection and send-assertion templates + if (authUser.isAdmin()) { + + if (generalOA.isDeleteBKUTemplate()) + templates.setBKUSelectionTemplate(null); + + if (generalOA.isDeleteSendAssertionTemplate()) + templates.setSendAssertionTemplate(null); + + + if (bkuSelectionForm != null && bkuSelectionForm.size() > 0) { + TransformsInfoType template = new TransformsInfoType(); + + Iterator<String> interator = bkuSelectionForm.keySet().iterator(); + template.setFilename(interator.next()); + template.setTransformation(bkuSelectionForm.get( + template.getFilename())); + + templates.setBKUSelectionTemplate(template); + } + + if (sendAssertionForm != null && sendAssertionForm.size() > 0) { + TransformsInfoType template = new TransformsInfoType(); + + Iterator<String> interator = sendAssertionForm.keySet().iterator(); + template.setFilename(interator.next()); + template.setTransformation(sendAssertionForm.get( + template.getFilename())); + + templates.setSendAssertionTemplate(template); + } + } + + + //store BKU-selection customization + BKUSelectionCustomizationType bkuselectioncustom = templates.getBKUSelectionCustomization(); + if (bkuselectioncustom == null) { + bkuselectioncustom = new BKUSelectionCustomizationType(); + templates.setBKUSelectionCustomization(bkuselectioncustom); + } + + Mandates mandates = new Mandates(); + if (generalOA.isUseMandates()) { + mandates.setProfiles(generalOA.getMandateProfiles()); + + } else { + mandates.setProfiles(new String()); + } + + authoa.setMandates(mandates); + bkuselectioncustom.setMandateLoginButton(MiscUtil.isNotEmpty(generalOA.getMandateProfiles())); + bkuselectioncustom.setOnlyMandateLoginAllowed(formOA.isOnlyMandateAllowed()); + + if (authUser.isAdmin()) { + templates.setAditionalAuthBlockText(generalOA.getAditionalAuthBlockText()); + + List<TemplateType> template = templates.getTemplate(); + if (generalOA.isLegacy()) { + + if (template == null) + template = new ArrayList<TemplateType>(); + else + template.clear(); + + if (MiscUtil.isNotEmpty(generalOA.getSLTemplateURL1())) { + TemplateType el = new TemplateType(); + el.setURL(generalOA.getSLTemplateURL1()); + template.add(el); + } else + template.add(new TemplateType()); + if (MiscUtil.isNotEmpty(generalOA.getSLTemplateURL2())) { + TemplateType el = new TemplateType(); + el.setURL(generalOA.getSLTemplateURL2()); + template.add(el); + } else + template.add(new TemplateType()); + if (MiscUtil.isNotEmpty(generalOA.getSLTemplateURL3())) { + TemplateType el = new TemplateType(); + el.setURL(generalOA.getSLTemplateURL3()); + template.add(el); + } else + template.add(new TemplateType()); + + } else { + if (template != null && template.size() > 0) template.clear(); + } + + bkuselectioncustom.setBackGroundColor(parseColor(formOA.getBackGroundColor())); + bkuselectioncustom.setFrontColor(parseColor(formOA.getFrontColor())); + + bkuselectioncustom.setHeaderBackGroundColor(parseColor(formOA.getHeader_BackGroundColor())); + bkuselectioncustom.setHeaderFrontColor(parseColor(formOA.getHeader_FrontColor())); + bkuselectioncustom.setHeaderText(formOA.getHeader_text()); + + bkuselectioncustom.setButtonBackGroundColor(parseColor(formOA.getButton_BackGroundColor())); + bkuselectioncustom.setButtonBackGroundColorFocus(parseColor(formOA.getButton_BackGroundColorFocus())); + bkuselectioncustom.setButtonFontColor(parseColor(formOA.getButton_FrontColor())); + + if (MiscUtil.isNotEmpty(formOA.getAppletRedirectTarget())) + bkuselectioncustom.setAppletRedirectTarget(formOA.getAppletRedirectTarget()); + + bkuselectioncustom.setFontType(formOA.getFontType()); + + bkuselectioncustom.setAppletHeight(formOA.getApplet_height()); + bkuselectioncustom.setAppletWidth(formOA.getApplet_width()); + + } + + // set default transformation if it is empty + List<TransformsInfoType> transformsInfo = authoa.getTransformsInfo(); + if (transformsInfo == null) { + // TODO: set OA specific transformation if it is required + + } + + OAPVP2 pvp2 = authoa.getOAPVP2(); + if (pvp2 == null) { + pvp2 = new OAPVP2(); + authoa.setOAPVP2(pvp2); + } + + pvp2.setMetadataURL(pvp2OA.getMetaDataURL()); + try { + + if (pvp2OA.getFileUpload() != null) pvp2.setCertificate(pvp2OA.getCertificate()); + + } catch (CertificateException e) { + log.info("Uploaded Certificate can not be found", e); + return LanguageHelper.getErrorString("validation.pvp2.certificate.notfound"); + } catch (IOException e) { + log.info("Uploaded Certificate can not be parsed", e); + return LanguageHelper.getErrorString("validation.pvp2.certificate.format"); + } + + OASAML1 saml1 = authoa.getOASAML1(); + if (saml1 == null) { + saml1 = new OASAML1(); + authoa.setOASAML1(saml1); + saml1.setIsActive(false); + } + + if (authUser.isAdmin()) { + saml1.setIsActive(saml1OA.isActive()); + } + + if (saml1.isIsActive() != null && saml1.isIsActive()) { + saml1.setProvideAUTHBlock(saml1OA.isProvideAuthBlock()); + saml1.setProvideCertificate(saml1OA.isProvideCertificate()); + saml1.setProvideFullMandatorData(saml1OA.isProvideFullMandateData()); + saml1.setProvideIdentityLink(saml1OA.isProvideIdentityLink()); + saml1.setProvideStammzahl(saml1OA.isProvideStammZahl()); + saml1.setUseCondition(saml1OA.isUseCondition()); + saml1.setConditionLength(BigInteger.valueOf(saml1OA.getConditionLength())); + // TODO: set sourceID + // saml1.setSourceID(""); + } + + OASSO sso = authoa.getOASSO(); + if (sso == null) { + sso = new OASSO(); + authoa.setOASSO(sso); + sso.setAuthDataFrame(true); + } + sso.setUseSSO(ssoOA.isUseSSO()); + + if (authUser.isAdmin()) sso.setAuthDataFrame(ssoOA.isShowAuthDataFrame()); + + sso.setSingleLogOutURL(ssoOA.getSingleLogOutURL()); + + if (oauth20OA != null) { + log.debug("Saving OAuth 2.0 configuration:"); + OAOAUTH20 oaOAuth20 = authoa.getOAOAUTH20(); + if (oaOAuth20 == null) { + oaOAuth20 = new OAOAUTH20(); + authoa.setOAOAUTH20(oaOAuth20); + } + + oaOAuth20.setOAuthClientId(generalOA.getIdentifier()); + // oaOAuth20.setOAuthClientSecret(oauth20OA.getClientSecret()); + oaOAuth20.setOAuthRedirectUri(oauth20OA.getRedirectUri()); + log.debug("client id: " + oauth20OA.getClientId()); + log.debug("client secret: " + oauth20OA.getClientSecret()); + log.debug("redirect uri:" + oauth20OA.getRedirectUri()); + + oaOAuth20.setOAuthClientSecret((String) request.getSession().getAttribute(Constants.SESSION_OAUTH20SECRET)); + request.getSession().setAttribute(Constants.SESSION_OAUTH20SECRET, null); + + } + + + // fetch stork configuration from database model + OASTORK stork = authoa.getOASTORK(); + if (stork == null) { + // if there is none, create a new one with default values. + stork = new OASTORK(); + authoa.setOASTORK(stork); + stork.setStorkLogonEnabled(false); + } + // transfer the incoming data to the database model + stork.setStorkLogonEnabled(storkOA.isStorkLogonEnabled()); + stork.setQaa(storkOA.getQaa()); + stork.setOAAttributes(storkOA.getAttributes()); + stork.setVidpEnabled(storkOA.isVidpEnabled()); + stork.setAttributeProviders(storkOA.getAttributeProviderPlugins()); + + try { + if (newentry) { + ConfigurationDBUtils.save(dboa); + + if (!authUser.isAdmin()) { + UserDatabase user = ConfigurationDBRead.getUserWithID(authUser.getUserID()); + + List<OnlineApplication> useroas = user.getOnlineApplication(); + if (useroas == null) useroas = new ArrayList<OnlineApplication>(); + + useroas.add(dboa); + ConfigurationDBUtils.saveOrUpdate(user); + } + } else + ConfigurationDBUtils.saveOrUpdate(dboa); + + } catch (MOADatabaseException e) { + log.warn("Online-Application can not be stored.", e); + return LanguageHelper.getErrorString("error.db.oa.store"); + } + + return null; + } + + private String parseColor(String color) { + String value = ""; + + if (MiscUtil.isNotEmpty(color)) { + if (!color.startsWith("#")) + value = "#" + color; + else + value = color; + } + return value; + } + + private void generateUserSpecificConfigurationOptions(UserDatabase userdb) { + + if (userdb.isIsMandateUser() != null && userdb.isIsMandateUser()) { + String bpk = userdb.getBpk(); + if (bpk.startsWith(Constants.IDENIFICATIONTYPE_BASEID_FN) || bpk.startsWith(Constants.IDENIFICATIONTYPE_BASEID_ZVR)) { + onlyBusinessService = true; + generalOA.setBusinessService(true); + } else if (bpk.startsWith(Constants.IDENIFICATIONTYPE_STORK)) { + onlyStorkService = true; + generalOA.setStorkService(true); + } + + deaktivededBusinessService = true; + deactivatedStorkService = true; + String[] split = bpk.split("\\+"); + generalOA.setIdentificationType(split[1].substring(1)); + + if (bpk.startsWith(Constants.IDENIFICATIONTYPE_BASEID_FN)) + generalOA.setIdentificationNumber(at.gv.egovernment.moa.util.StringUtils.deleteLeadingZeros(split[2])); + else + generalOA.setIdentificationNumber(split[2]); + + } + + } + + public String setGeneralOAConfig() { + + return Constants.STRUTS_SUCCESS; + } + + public String setSAML1OAConfig() { + + return Constants.STRUTS_SUCCESS; + } + + public String setPVP2OAConfig() { + + return Constants.STRUTS_SUCCESS; + } + + public String setSSOOAConfig() { + + return Constants.STRUTS_SUCCESS; + } + + public String setSTORKOAConfig() { + + return Constants.STRUTS_SUCCESS; + } + + // Getter and Setter + public void setServletResponse(HttpServletResponse arg0) { + this.response = arg0; + + } + + public void setServletRequest(HttpServletRequest arg0) { + this.request = arg0; + + } + + public HttpServletRequest getRequest() { + return request; + } + + public void setRequest(HttpServletRequest request) { + this.request = request; + } + + public HttpServletResponse getResponse() { + return response; + } + + public void setResponse(HttpServletResponse response) { + this.response = response; + } + + public OAGeneralConfig getGeneralOA() { + return generalOA; + } + + public void setGeneralOA(OAGeneralConfig generalOA) { + this.generalOA = generalOA; + } + + public OAPVP2Config getPvp2OA() { + return pvp2OA; + } + + public void setPvp2OA(OAPVP2Config pvp2oa) { + pvp2OA = pvp2oa; + } + + public OASAML1Config getSaml1OA() { + return saml1OA; + } + + public void setSaml1OA(OASAML1Config saml1oa) { + saml1OA = saml1oa; + } + + public OASSOConfig getSsoOA() { + return ssoOA; + } + + public void setSsoOA(OASSOConfig ssoOA) { + this.ssoOA = ssoOA; + } + + public OASTORKConfig getStorkOA() { + return storkOA; + } + + public void setStorkOA(OASTORKConfig storkOA) { + this.storkOA = storkOA; + } + + /** + * @param oaidobj the oaidobj to set + */ + public void setOaidobj(String oaidobj) { + this.oaidobj = oaidobj; + } + + /** + * @return the authUser + */ + public AuthenticatedUser getAuthUser() { + return authUser; + } + + /** + * @return the newOA + */ + public boolean isNewOA() { + return newOA; + } + + /** + * @param newOA the newOA to set + */ + public void setNewOA(boolean newOA) { + this.newOA = newOA; + } + + /** + * @return the nextPage + */ + public String getNextPage() { + return nextPage; + } + + /** + * @return the formID + */ + public String getFormID() { + return formID; + } + + /** + * @param formID the formID to set + */ + public void setFormID(String formID) { + this.formID = formID; + } + + /** + * @return the onlyBusinessService + */ + public boolean isOnlyBusinessService() { + return onlyBusinessService; + } + + /** + * @param onlyStorkService the onlyStorkService to set + */ + public void setOnlyStorkService(boolean onlyStorkService) { + this.onlyStorkService = onlyStorkService; + } + + /** + * @return the onlyStorkService + */ + public boolean isOnlyStorkService() { + return onlyStorkService; + } + + /** + * @param onlyBusinessService the onlyBusinessService to set + */ + public void setOnlyBusinessService(boolean onlyBusinessService) { + this.onlyBusinessService = onlyBusinessService; + } + + + /** + * @return the subTargetSet + */ + public boolean isSubTargetSet() { + return subTargetSet; + } + + /** + * @param subTargetSet the subTargetSet to set + */ + public void setSubTargetSet(boolean subTargetSet) { + this.subTargetSet = subTargetSet; + } + + /** + * @return the deaktivededBusinessService + */ + public boolean isDeaktivededBusinessService() { + return deaktivededBusinessService; + } + + /** + * @return the deactivatedStorkService + */ + public boolean isDeactivatedStorkService() { + return deactivatedStorkService; + } + + /** + * @param deactivatedStorkService the deactivatedStorkService to set + */ + + public void setDeactivatedStorkService(boolean deactivatedStorkService) { + + this.deactivatedStorkService = deactivatedStorkService; + } + + /** + * @param deaktivededBusinessService the deaktivededBusinessService to set + */ + public void setDeaktivededBusinessService(boolean deaktivededBusinessService) { + this.deaktivededBusinessService = deaktivededBusinessService; + } + + /** + * @return the formOA + */ + public FormularCustomization getFormOA() { + return formOA; + } + + /** + * @param formOA the formOA to set + */ + public void setFormOA(FormularCustomization formOA) { + this.formOA = formOA; + } + + /** + * @return the stream + */ + public InputStream getStream() { + return stream; + } + + public OAOAuth20Config getOauth20OA() { + return oauth20OA; + } + + public void setOauth20OA(OAOAuth20Config oauth20OA) { + this.oauth20OA = oauth20OA; + } + } diff --git a/id/ConfigWebTool/src/main/resources/applicationResources.properties b/id/ConfigWebTool/src/main/resources/applicationResources.properties index 34bf4a8e5..ef52892b3 100644 --- a/id/ConfigWebTool/src/main/resources/applicationResources.properties +++ b/id/ConfigWebTool/src/main/resources/applicationResources.properties @@ -185,7 +185,10 @@ webpages.oaconfig.general.mandate.profiles=Profile webpages.oaconfig.general.mandate.usemandate=Vollmachten (ja/nein) webpages.oaconfig.general.friendlyname=Name der Online-Applikation webpages.oaconfig.general.isbusinessservice=Privatwirtschaftliche Applikation +webpages.oaconfig.general.isstorkservice=Stork Applikation webpages.oaconfig.general.public.header=Öffentlicher Bereich +webpages.oaconfig.general.stork.header=STORK Bereich +webpages.oaconfig.general.stork.countrycode=Landesvorwahl webpages.oaconfig.general.target.friendlyname=Bezeichnung des Bereichs (Frei w\u00E4hlbar) webpages.oaconfig.general.target.admin.checkbox=Anderen Bereich frei definieren webpages.oaconfig.general.target.admin=Bereich (Frei w\u00E4hlbar) diff --git a/id/ConfigWebTool/src/main/webapp/js/common.js b/id/ConfigWebTool/src/main/webapp/js/common.js index fef368b0a..a14a287db 100644 --- a/id/ConfigWebTool/src/main/webapp/js/common.js +++ b/id/ConfigWebTool/src/main/webapp/js/common.js @@ -22,17 +22,33 @@ *******************************************************************************/ function oaBusinessService() { if ($('#OAisbusinessservice').attr('checked') == 'checked') { - - $('#oa_config_businessservice').css('display', "block"); + $('#OAisstorkservice').attr('checked',false); + $('#oa_config_storkservice').css('display', "none"); + $('#oa_config_businessservice').css('display', "block"); $('#oa_config_publicservice').css('display', "none"); } else { - - $('#oa_config_businessservice').css('display', "none"); + $('#oa_config_storkservice').css('display', "none"); + $('#oa_config_businessservice').css('display', "none"); $('#oa_config_publicservice').css('display', "block"); } } +function oaStorkService() { + if ($('#OAisstorkservice').attr('checked') == 'checked') { + $('#OAisbusinessservice').attr('checked',false); + $('#oa_config_storkservice').css('display', "block"); + $('#oa_config_businessservice').css('display', "none"); + $('#oa_config_publicservice').css('display', "none"); + + } else { + $('#oa_config_storkservice').css('display', "none"); + $('#oa_config_businessservice').css('display', "none"); + $('#oa_config_publicservice').css('display', "block"); + + } +} + function oaSSOService() { if ($('#OAuseSSO').attr('checked') == 'checked') { @@ -199,6 +215,7 @@ function userOnLoad() { } function oaOnLoad() { oaBusinessService(); + oaStorkService(); oaSSOService(); oaLegacyService(); oaStork(); diff --git a/id/ConfigWebTool/src/main/webapp/jsp/editOAGeneral.jsp b/id/ConfigWebTool/src/main/webapp/jsp/editOAGeneral.jsp index 5ee1188ae..78ad500ef 100644 --- a/id/ConfigWebTool/src/main/webapp/jsp/editOAGeneral.jsp +++ b/id/ConfigWebTool/src/main/webapp/jsp/editOAGeneral.jsp @@ -59,16 +59,28 @@ key="webpages.oaconfig.general.friendlyname" cssClass="textfield_long"> </s:textfield> - - <s:checkbox name="generalOA.businessService" - value="%{generalOA.businessService}" - labelposition="left" - key="webpages.oaconfig.general.isbusinessservice" - cssClass="checkbox" - onclick="oaBusinessService();" - id="OAisbusinessservice" - disabled="%{isOnlyBusinessService()}"> - </s:checkbox> + + <s:checkbox name="generalOA.businessService" + value="%{generalOA.businessService}" + labelposition="left" + key="webpages.oaconfig.general.isbusinessservice" + cssClass="checkbox" + onclick="oaBusinessService();" + id="OAisbusinessservice" + > + </s:checkbox> + + + <s:checkbox name="generalOA.storkService" + value="%{generalOA.storkService}" + labelposition="left" + key="webpages.oaconfig.general.isstorkservice" + cssClass="checkbox" + onclick="oaStorkService();" + id="OAisstorkservice" + disabled="%{isOnlyStorkService()}"> + </s:checkbox> + </div> <div id="oa_config_businessservice" class="oa_config_block"> @@ -89,6 +101,17 @@ disabled="%{isDeaktivededBusinessService()}"> </s:textfield> </div> + + <div id="oa_config_storkservice" class="oa_config_block"> + <h3><%=LanguageHelper.getGUIString("webpages.oaconfig.general.stork.header", request) %></h3> + <s:textfield name="generalOA.storkSPTargetCountry" + labelposition="left" + key="webpages.oaconfig.general.stork.countrycode" + value="%{generalOA.storkSPTargetCountry}" + cssClass="textfield_middle" + disabled="%{isDeactivatedStorkService()}"> + </s:textfield> + </div> <s:if test="!isOnlyBusinessService()"> <div id="oa_config_publicservice" class="oa_config_block"> diff --git a/id/id.iml b/id/id.iml deleted file mode 100644 index c418d6693..000000000 --- a/id/id.iml +++ /dev/null @@ -1,13 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4"> - <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false"> - <output url="file://$MODULE_DIR$/target/classes" /> - <output-test url="file://$MODULE_DIR$/target/test-classes" /> - <content url="file://$MODULE_DIR$"> - <excludeFolder url="file://$MODULE_DIR$/target" /> - </content> - <orderEntry type="inheritedJdk" /> - <orderEntry type="sourceFolder" forTests="false" /> - </component> -</module> - diff --git a/id/oa/moa-id-oa.iml b/id/oa/moa-id-oa.iml deleted file mode 100644 index 6d9905e25..000000000 --- a/id/oa/moa-id-oa.iml +++ /dev/null @@ -1,61 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4"> - <component name="FacetManager"> - <facet type="web" name="Web"> - <configuration> - <descriptors> - <deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/src/main/webapp/WEB-INF/web.xml" /> - </descriptors> - <webroots> - <root url="file://$MODULE_DIR$/src/main/webapp" relative="/" /> - </webroots> - </configuration> - </facet> - </component> - <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false"> - <output url="file://$MODULE_DIR$/../target/classes" /> - <output-test url="file://$MODULE_DIR$/../target/test-classes" /> - <content url="file://$MODULE_DIR$"> - <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> - <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" /> - <excludeFolder url="file://$MODULE_DIR$/target" /> - </content> - <orderEntry type="inheritedJdk" /> - <orderEntry type="sourceFolder" forTests="false" /> - <orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:jstl:1.2" level="project" /> - <orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:servlet-api:2.4" level="project" /> - <orderEntry type="library" name="Maven: org.opensaml:opensaml:2.6.0" level="project" /> - <orderEntry type="library" name="Maven: org.opensaml:openws:1.5.0" level="project" /> - <orderEntry type="library" name="Maven: org.opensaml:xmltooling:1.4.0" level="project" /> - <orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk15:1.46" level="project" /> - <orderEntry type="library" name="Maven: commons-codec:commons-codec:1.7" level="project" /> - <orderEntry type="library" name="Maven: joda-time:joda-time:2.2" level="project" /> - <orderEntry type="library" name="Maven: ca.juliusdavies:not-yet-commons-ssl:0.3.9" level="project" /> - <orderEntry type="library" name="Maven: commons-httpclient:commons-httpclient:3.1" level="project" /> - <orderEntry type="library" name="Maven: org.apache.santuario:xmlsec:1.5.4" level="project" /> - <orderEntry type="library" scope="RUNTIME" name="Maven: org.apache.xerces:xml-apis:2.10.0" level="project" /> - <orderEntry type="library" scope="RUNTIME" name="Maven: org.apache.xerces:xercesImpl:2.10.0" level="project" /> - <orderEntry type="library" scope="RUNTIME" name="Maven: org.apache.xerces:serializer:2.10.0" level="project" /> - <orderEntry type="library" scope="RUNTIME" name="Maven: xml-resolver:xml-resolver:1.2" level="project" /> - <orderEntry type="library" scope="RUNTIME" name="Maven: xalan:xalan:2.7.1" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:log4j-over-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: commons-collections:commons-collections:3.2.1" level="project" /> - <orderEntry type="library" name="Maven: commons-lang:commons-lang:2.6" level="project" /> - <orderEntry type="library" name="Maven: org.apache.velocity:velocity:1.7" level="project" /> - <orderEntry type="library" name="Maven: org.owasp.esapi:esapi:2.0.1" level="project" /> - <orderEntry type="library" name="Maven: jstl:jstl:1.2" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-simple:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: iaik:commons-iaik:0.7.1" level="project" /> - <orderEntry type="library" name="Maven: log4j:log4j:1.2.14" level="project" /> - <orderEntry type="module" module-name="moa-common" /> - <orderEntry type="library" name="Maven: commons-logging:commons-logging:1.0.4" level="project" /> - <orderEntry type="library" name="Maven: iaik.prod:iaik_jce_full:5.101" level="project" /> - <orderEntry type="library" name="Maven: iaik.prod:iaik_moa:1.5" level="project" /> - <orderEntry type="library" name="Maven: jaxen:jaxen:1.0-FCS" level="project" /> - <orderEntry type="library" name="Maven: saxpath:saxpath:1.0-FCS" level="project" /> - </component> -</module> - diff --git a/id/pom.xml b/id/pom.xml index db4ee137e..bd3344638 100644 --- a/id/pom.xml +++ b/id/pom.xml @@ -24,4 +24,36 @@ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> + <build> + <plugins> + <plugin> + <artifactId>maven-enforcer-plugin</artifactId> + <version>1.1.1</version> + <executions> + <execution> + <id>enforce-banned-dependencies</id> + <goals> + <goal>enforce</goal> + </goals> + <configuration> + <rules> + <bannedDependencies> + <searchTransitive>true</searchTransitive> + <excludes> + <!-- <exclude>commons-logging</exclude> --> + <exclude>org.slf4j:1.5*</exclude> + <exclude>org.slf4j:1.6*</exclude> + <!-- <exclude>org.springframework:2.*</exclude> + <exclude>org.springframework:3.0.*</exclude> --> + </excludes> + </bannedDependencies> + </rules> + <fail>true</fail> + </configuration> + </execution> + </executions> + </plugin> + </plugins> + </build> + </project> diff --git a/id/server/auth/moa-id-auth.iml b/id/server/auth/moa-id-auth.iml index f61dfa171..815c21ef2 100644 --- a/id/server/auth/moa-id-auth.iml +++ b/id/server/auth/moa-id-auth.iml @@ -14,8 +14,8 @@ </facet> </component> <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false"> - <output url="file://$MODULE_DIR$/../../target/classes" /> - <output-test url="file://$MODULE_DIR$/../../target/test-classes" /> + <output url="file://$MODULE_DIR$/target/classes" /> + <output-test url="file://$MODULE_DIR$/target/test-classes" /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" /> <excludeFolder url="file://$MODULE_DIR$/target" /> @@ -23,6 +23,7 @@ <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.6" level="project" /> + <orderEntry type="library" name="Maven: eu.medsea.mimeutil:mime-util:2.1.3" level="project" /> <orderEntry type="library" name="Maven: axis:axis:1.0_IAIK" level="project" /> <orderEntry type="library" name="Maven: org.tuckey:urlrewritefilter:4.0.3" level="project" /> <orderEntry type="module" module-name="moa-spss-lib" /> @@ -53,6 +54,12 @@ <orderEntry type="library" name="Maven: jaxen:jaxen:1.0-FCS" level="project" /> <orderEntry type="library" name="Maven: saxpath:saxpath:1.0-FCS" level="project" /> <orderEntry type="library" name="Maven: joda-time:joda-time:1.6.2" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-simple:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:log4j-over-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: commons-io:commons-io:1.3.2" level="project" /> <orderEntry type="library" name="Maven: iaik.prod:iaik_tsl:1.0" level="project" /> <orderEntry type="library" name="Maven: iaik:iaik_xsect_eval:1.1709142" level="project" /> <orderEntry type="library" name="Maven: iaik:iaik_ecc_signed:2.19" level="project" /> @@ -91,24 +98,9 @@ <orderEntry type="library" name="Maven: org.apache.velocity:velocity:1.7" level="project" /> <orderEntry type="library" name="Maven: org.owasp.esapi:esapi:2.0.1" level="project" /> <orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk16:1.46" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-simple:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:log4j-over-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: commons-io:commons-io:2.2" level="project" /> <orderEntry type="library" name="Maven: eu.stork:oasis-dss-api:1.0.0-SNAPSHOT" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: junit:junit:3.8.1" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.ws:jaxws-rt:2.1.7" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.ws:jaxws-api:2.1" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.messaging.saaj:saaj-impl:1.3.3" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.soap:saaj-api:1.3" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.stream.buffer:streambuffer:0.9" level="project" /> - <orderEntry type="library" name="Maven: org.jvnet.staxex:stax-ex:1.2" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.stream:stax-api:1.0" level="project" /> - <orderEntry type="library" name="Maven: org.codehaus.woodstox:wstx-asl:3.2.3" level="project" /> - <orderEntry type="library" name="Maven: com.sun.org.apache.xml.internal:resolver:20050927" level="project" /> - <orderEntry type="library" name="Maven: org.jvnet:mimepull:1.3" level="project" /> + <orderEntry type="library" name="Maven: eu.medsea.mimeutil:mime-util:2.1.3" level="project" /> <orderEntry type="module" module-name="moa-id-commons" /> <orderEntry type="library" name="Maven: org.hibernate:hibernate-core:4.2.1.Final" level="project" /> <orderEntry type="library" name="Maven: antlr:antlr:2.7.7" level="project" /> @@ -134,12 +126,12 @@ <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-roundtrip:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2_commons:jaxb2-basics-testing:0.6.2" level="project" /> <orderEntry type="library" name="Maven: xmlunit:xmlunit:1.0" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.1" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-persistence:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-customizations:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.springframework:spring:2.0.7" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2.maven2:maven-jaxb2-plugin:0.8.0" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2.maven2:maven-jaxb2-plugin-core:0.8.0" level="project" /> + <orderEntry type="library" name="Maven: com.sun.org.apache.xml.internal:resolver:20050927" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-plugin-api:2.2.1" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-project:2.2.1" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-settings:2.2.1" level="project" /> diff --git a/id/server/auth/pom.xml b/id/server/auth/pom.xml index 987ae1951..c17722df0 100644 --- a/id/server/auth/pom.xml +++ b/id/server/auth/pom.xml @@ -79,8 +79,13 @@ <groupId>MOA.id.server</groupId> <artifactId>moa-id-lib</artifactId> </dependency> - - <!-- transitive dependencies we don't want to include into the war --> + <dependency> + <groupId>eu.stork</groupId> + <artifactId>oasis-dss-api</artifactId> + <version>1.0.0-SNAPSHOT</version> + </dependency> + + <!-- transitive dependencies we don't want to include into the war --> <dependency> <groupId>iaik.prod</groupId> <artifactId>iaik_jce_full</artifactId> diff --git a/id/server/auth/src/main/webapp/WEB-INF/urlrewrite.xml b/id/server/auth/src/main/webapp/WEB-INF/urlrewrite.xml index 59d6d6cce..d6df363c5 100644 --- a/id/server/auth/src/main/webapp/WEB-INF/urlrewrite.xml +++ b/id/server/auth/src/main/webapp/WEB-INF/urlrewrite.xml @@ -68,6 +68,10 @@ <from>^/moa-id-auth/SendPEPSAuthnRequest$</from> <to type="forward">/dispatcher?mod=id_stork2&action=AuthenticationRequest&%{query-string}</to> </rule> + <rule match-type="regex"> + <from>^/moa-id-auth/RetrieveMandate$</from> + <to type="forward">/dispatcher?mod=id_stork2&action=MandateRetrievalRequest&%{query-string}</to> + </rule> <rule match-type="regex"> diff --git a/id/server/idserverlib/moa-id-lib.iml b/id/server/idserverlib/moa-id-lib.iml index cf1b34b4b..47c38c069 100644 --- a/id/server/idserverlib/moa-id-lib.iml +++ b/id/server/idserverlib/moa-id-lib.iml @@ -1,8 +1,8 @@ <?xml version="1.0" encoding="UTF-8"?> <module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false"> - <output url="file://$MODULE_DIR$/../../target/classes" /> - <output-test url="file://$MODULE_DIR$/../../target/test-classes" /> + <output url="file://$MODULE_DIR$/target/classes" /> + <output-test url="file://$MODULE_DIR$/target/test-classes" /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/test/java" isTestSource="true" /> @@ -13,6 +13,7 @@ <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Maven: eu.stork.mw.core:stork-saml-engine:2.0" level="project" /> <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.6" level="project" /> + <orderEntry type="library" name="Maven: eu.medsea.mimeutil:mime-util:2.1.3" level="project" /> <orderEntry type="module" module-name="SamlEngine" /> <orderEntry type="library" name="Maven: eu.stork:Commons:1.2.0" level="project" /> <orderEntry type="library" name="Maven: joda-time:joda-time:2.3" level="project" /> @@ -40,23 +41,10 @@ <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.5" level="project" /> <orderEntry type="library" name="Maven: org.slf4j:log4j-over-slf4j:1.7.5" level="project" /> <orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: commons-io:commons-io:2.2" level="project" /> + <orderEntry type="library" name="Maven: commons-io:commons-io:1.3.2" level="project" /> <orderEntry type="library" name="Maven: eu.stork:oasis-dss-api:1.0.0-SNAPSHOT" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: junit:junit:3.8.1" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.ws:jaxws-rt:2.1.7" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.ws:jaxws-api:2.1" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.bind:jaxb-api:2.2.6" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-impl:2.2.5" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.messaging.saaj:saaj-impl:1.3.3" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.soap:saaj-api:1.3" level="project" /> - <orderEntry type="library" name="Maven: javax.activation:activation:1.1" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.stream.buffer:streambuffer:0.9" level="project" /> - <orderEntry type="library" name="Maven: org.jvnet.staxex:stax-ex:1.2" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.stream:stax-api:1.0" level="project" /> - <orderEntry type="library" name="Maven: org.codehaus.woodstox:wstx-asl:3.2.3" level="project" /> - <orderEntry type="library" name="Maven: stax:stax-api:1.0.1" level="project" /> - <orderEntry type="library" name="Maven: com.sun.org.apache.xml.internal:resolver:20050927" level="project" /> - <orderEntry type="library" name="Maven: org.jvnet:mimepull:1.3" level="project" /> + <orderEntry type="library" name="Maven: eu.medsea.mimeutil:mime-util:2.1.3" level="project" /> <orderEntry type="module" module-name="moa-id-commons" /> <orderEntry type="library" name="Maven: org.hibernate:hibernate-core:4.2.1.Final" level="project" /> <orderEntry type="library" name="Maven: antlr:antlr:2.7.7" level="project" /> @@ -88,12 +76,12 @@ <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-roundtrip:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2_commons:jaxb2-basics-testing:0.6.2" level="project" /> <orderEntry type="library" name="Maven: xmlunit:xmlunit:1.0" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.1" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-persistence:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-customizations:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.springframework:spring:2.0.7" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2.maven2:maven-jaxb2-plugin:0.8.0" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2.maven2:maven-jaxb2-plugin-core:0.8.0" level="project" /> + <orderEntry type="library" name="Maven: com.sun.org.apache.xml.internal:resolver:20050927" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-plugin-api:2.2.1" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-project:2.2.1" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-settings:2.2.1" level="project" /> @@ -111,6 +99,7 @@ <orderEntry type="library" name="Maven: org.apache.maven:maven-plugin-registry:2.2.1" level="project" /> <orderEntry type="library" name="Maven: org.jfrog.maven.annomojo:maven-plugin-anno:1.3.1" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2.maven2:maven-jaxb22-plugin:0.8.0" level="project" /> + <orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-impl:2.2.5" level="project" /> <orderEntry type="library" name="Maven: com.sun.xml.bind:jaxb-xjc:2.2.4-1" level="project" /> <orderEntry type="library" name="Maven: mysql:mysql-connector-java:5.1.25" level="project" /> <orderEntry type="module" module-name="moa-common" scope="TEST" production-on-test="" /> @@ -120,6 +109,7 @@ <orderEntry type="library" name="Maven: org.apache.axis:axis-saaj:1.4" level="project" /> <orderEntry type="library" name="Maven: axis:axis-wsdl4j:1.5.1" level="project" /> <orderEntry type="library" name="Maven: commons-discovery:commons-discovery:0.2" level="project" /> + <orderEntry type="library" name="Maven: javax.activation:activation:1.1" level="project" /> <orderEntry type="library" name="Maven: javax.mail:mail:1.4" level="project" /> <orderEntry type="library" scope="RUNTIME" name="Maven: postgresql:postgresql:7.2" level="project" /> <orderEntry type="library" scope="PROVIDED" name="Maven: javax.servlet:servlet-api:2.4" level="project" /> @@ -145,6 +135,8 @@ <orderEntry type="library" name="Maven: iaik:iaik_ssl:4.4" level="project" /> <orderEntry type="library" name="Maven: iaik:w3c_http:1.0" level="project" /> <orderEntry type="library" name="Maven: org.xerial:sqlite-jdbc:3.7.8-SNAPSHOT" level="project" /> + <orderEntry type="library" name="Maven: stax:stax-api:1.0.1" level="project" /> + <orderEntry type="library" name="Maven: javax.xml.bind:jaxb-api:2.2.6" level="project" /> <orderEntry type="library" name="Maven: iaik.prod:iaik_util:0.23" level="project" /> <orderEntry type="library" name="Maven: iaik.prod:iaik_xsect:1.1709142" level="project" /> <orderEntry type="library" name="Maven: iaik.prod:iaik_jsse:4.4" level="project" /> diff --git a/id/server/idserverlib/pom.xml b/id/server/idserverlib/pom.xml index cca543a26..82a42cb8c 100644 --- a/id/server/idserverlib/pom.xml +++ b/id/server/idserverlib/pom.xml @@ -151,7 +151,33 @@ <!-- should be in the ext directory of the jre -->
<scope>provided</scope>
</dependency>
-
+
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.7.5</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <version>1.7.5</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jcl-over-slf4j</artifactId>
+ <version>1.7.5</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>log4j-over-slf4j</artifactId>
+ <version>1.7.5</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jul-to-slf4j</artifactId>
+ <version>1.7.5</version>
+ </dependency>
<dependency>
<groupId>junit</groupId>
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 ce5aa15c3..22c08b3e0 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 @@ -125,7 +125,7 @@ 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.ApiUtilsException; +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; @@ -138,6 +138,42 @@ 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; +import iaik.asn1.ObjectID; +import iaik.util.logging.Log; +import iaik.x509.X509Certificate; +import iaik.x509.X509ExtensionInitException; +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.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.*; +import org.xml.sax.SAXException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.math.BigInteger; +import java.security.NoSuchAlgorithmException; +import java.security.Principal; +import java.security.cert.CertificateException; +import java.util.*; + +//import java.security.cert.CertificateFactory; +//import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.CreateIdentityLinkResponse; +//import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient; +//import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClientException; /** * API for MOA ID Authentication Service.<br> {@link AuthenticationSession} is @@ -149,148 +185,147 @@ import eu.stork.peps.exceptions.STORKSAMLEngineException; */ public class AuthenticationServer implements MOAIDAuthConstants { - /** single instance */ - private static AuthenticationServer instance; - - /** - * time out in milliseconds used by {@link cleanup} for session store - */ - private long sessionTimeOutCreated = 15 * 60 * 1000; // default 10 minutes - private long sessionTimeOutUpdated = 10 * 60 * 1000; // default 10 minutes - /** - * time out in milliseconds used by {@link cleanup} for authentication data - * store - */ - private long authDataTimeOut = 2 * 60 * 1000; // default 2 minutes - - /** - * Returns the single instance of <code>AuthenticationServer</code>. - * - * @return the single instance of <code>AuthenticationServer</code> - */ - public static AuthenticationServer getInstance() { - if (instance == null) - instance = new AuthenticationServer(); - return instance; - } - - /** - * Constructor for AuthenticationServer. - */ - public AuthenticationServer() { - super(); - } - - - /** - * Processes the beginning of an authentication session. - * <ul> - * <li>Starts an authentication session</li> - * <li>Creates an <code><InfoboxReadRequest></code></li> - * <li>Creates an HTML form for querying the identity link from the security - * layer implementation. <br> - * Form parameters include - * <ul> - * <li>the <code><InfoboxReadRequest></code></li> - * <li>the data URL where the security layer implementation sends it - * response to</li> - * </ul> - * </ul> - * - * @param authURL - * URL of the servlet to be used as data URL - * @param target - * "Geschäftsbereich" of the online application requested - * @param targetFriendlyName - * Friendly name of the target if the target is configured via - * configuration - * @param oaURL - * online application URL requested - * @param bkuURL - * URL of the "Bürgerkartenumgebung" to be used; may be - * <code>null</code>; in this case, the default location will be - * used - * @param useMandate - * Indicates if mandate is used or not - * @param templateURL - * URL providing an HTML template for the HTML form generated - * @param templateMandteURL - * URL providing an HTML template for the HTML form generated - * (for signing in mandates mode) - * @param req - * determines the protocol used - * @param sourceID - * @return HTML form - * @throws AuthenticationException - * @see GetIdentityLinkFormBuilder - * @see InfoboxReadRequestBuilder - */ - public String startAuthentication(AuthenticationSession session, HttpServletRequest req) throws WrongParametersException, - AuthenticationException, ConfigurationException, BuildException { - - if (session == null) { - throw new AuthenticationException("auth.18", new Object[] { }); - } - - //load OnlineApplication configuration - OAAuthParameter oaParam = - AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[] { session.getPublicOAURLPrefix() }); - - //load Template - String template = null; - if (session.getTemplateURL() != null) { - try { - - template = new String(FileUtils.readURL(session.getTemplateURL())); - } catch (IOException ex) { - throw new AuthenticationException("auth.03", new Object[] { - session.getTemplateURL(), ex.toString() }, ex); - } - } - - String infoboxReadRequest = ""; - - String domainIdentifier = AuthConfigurationProvider.getInstance().getSSOTagetIdentifier().trim(); - if (MiscUtil.isEmpty(domainIdentifier) && session.isSsoRequested()) { - //do not use SSO if no Target is set - Log.warn("NO SSO-Target found in configuration. Single Sign-On is deaktivated!"); - session.setSsoRequested(false); - - } - - if (session.isSsoRequested()) { - //load identityLink with SSO Target - boolean isbuisness = false; - - if (domainIdentifier.startsWith(PREFIX_WPBK)) { - - isbuisness = true; - - } else { - isbuisness = false; - - } - - //build ReadInfobox request - infoboxReadRequest = new InfoboxReadRequestBuilder().build( - isbuisness, domainIdentifier); - - } else { - //build ReadInfobox request - infoboxReadRequest = new InfoboxReadRequestBuilder().build( - oaParam.getBusinessService(), oaParam - .getIdentityLinkDomainIdentifier()); - } - - - String dataURL = new DataURLBuilder().buildDataURL( - session.getAuthURL(), REQ_VERIFY_IDENTITY_LINK, session - .getSessionID()); - - //removed in MOAID 2.0 - String pushInfobox = ""; + /** + * single instance + */ + private static AuthenticationServer instance; + + /** + * time out in milliseconds used by {@link cleanup} for session store + */ + private long sessionTimeOutCreated = 15 * 60 * 1000; // default 10 minutes + private long sessionTimeOutUpdated = 10 * 60 * 1000; // default 10 minutes + /** + * time out in milliseconds used by {@link cleanup} for authentication data + * store + */ + private long authDataTimeOut = 2 * 60 * 1000; // default 2 minutes + + /** + * Returns the single instance of <code>AuthenticationServer</code>. + * + * @return the single instance of <code>AuthenticationServer</code> + */ + public static AuthenticationServer getInstance() { + if (instance == null) + instance = new AuthenticationServer(); + return instance; + } + + /** + * Constructor for AuthenticationServer. + */ + public AuthenticationServer() { + super(); + } + + + /** + * Processes the beginning of an authentication session. + * <ul> + * <li>Starts an authentication session</li> + * <li>Creates an <code><InfoboxReadRequest></code></li> + * <li>Creates an HTML form for querying the identity link from the security + * layer implementation. <br> + * Form parameters include + * <ul> + * <li>the <code><InfoboxReadRequest></code></li> + * <li>the data URL where the security layer implementation sends it + * response to</li> + * </ul> + * </ul> + * + * @param authURL URL of the servlet to be used as data URL + * @param target "Geschäftsbereich" of the online application requested + * @param targetFriendlyName Friendly name of the target if the target is configured via + * configuration + * @param oaURL online application URL requested + * @param bkuURL URL of the "Bürgerkartenumgebung" to be used; may be + * <code>null</code>; in this case, the default location will be + * used + * @param useMandate Indicates if mandate is used or not + * @param templateURL URL providing an HTML template for the HTML form generated + * @param templateMandteURL URL providing an HTML template for the HTML form generated + * (for signing in mandates mode) + * @param req determines the protocol used + * @param sourceID + * @return HTML form + * @throws AuthenticationException + * @see GetIdentityLinkFormBuilder + * @see InfoboxReadRequestBuilder + */ + public String startAuthentication(AuthenticationSession session, HttpServletRequest req) throws WrongParametersException, + AuthenticationException, ConfigurationException, BuildException { + + if (session == null) { + throw new AuthenticationException("auth.18", new Object[]{}); + } + + //load OnlineApplication configuration + OAAuthParameter oaParam = + AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + if (oaParam == null) + throw new AuthenticationException("auth.00", new Object[]{session.getPublicOAURLPrefix()}); + + //load Template + String template = null; + if (session.getTemplateURL() != null) { + try { + + template = new String(FileUtils.readURL(session.getTemplateURL())); + } catch (IOException ex) { + throw new AuthenticationException("auth.03", new Object[]{ + session.getTemplateURL(), ex.toString()}, ex); + } + } + + String infoboxReadRequest = ""; + + String domainIdentifier = AuthConfigurationProvider.getInstance().getSSOTagetIdentifier().trim(); + if (MiscUtil.isEmpty(domainIdentifier) && session.isSsoRequested()) { + //do not use SSO if no Target is set + Log.warn("NO SSO-Target found in configuration. Single Sign-On is deaktivated!"); + session.setSsoRequested(false); + + } + + if (session.isSsoRequested()) { + //load identityLink with SSO Target + boolean isbuisness = false; + + if (domainIdentifier.startsWith(PREFIX_WPBK)) { + + isbuisness = true; + + } else { + isbuisness = false; + + } + + //build ReadInfobox request + infoboxReadRequest = new InfoboxReadRequestBuilder().build( + isbuisness, domainIdentifier); + + } else { + + if (oaParam.getStorkService()) + // build stork request + infoboxReadRequest = new InfoboxReadRequestBuilder().buildStorkReadRequest( + oaParam.getIdentityLinkDomainIdentifier()); + else + //build ReadInfobox request + infoboxReadRequest = new InfoboxReadRequestBuilder().build( + oaParam.getBusinessService(), oaParam + .getIdentityLinkDomainIdentifier()); + } + + + String dataURL = new DataURLBuilder().buildDataURL( + session.getAuthURL(), REQ_VERIFY_IDENTITY_LINK, session + .getSessionID()); + + //removed in MOAID 2.0 + String pushInfobox = ""; // VerifyInfoboxParameters verifyInfoboxParameters = oaParam // .getVerifyInfoboxParameters(); @@ -299,1787 +334,1743 @@ public class AuthenticationServer implements MOAIDAuthConstants { // session.setPushInfobox(pushInfobox); // } - //build CertInfo request - String certInfoRequest = new CertInfoVerifyXMLSignatureRequestBuilder() - .build(); - String certInfoDataURL = new DataURLBuilder() - .buildDataURL(session.getAuthURL(), REQ_START_AUTHENTICATION, - session.getSessionID()); - - //get Applet Parameters - String appletwidth = req.getParameter(PARAM_APPLET_WIDTH); - String appletheigth = req.getParameter(PARAM_APPLET_HEIGTH); - appletheigth = StringEscapeUtils.escapeHtml(appletheigth); - appletwidth = StringEscapeUtils.escapeHtml(appletwidth); - - String htmlForm = new GetIdentityLinkFormBuilder().build(template, - session.getBkuURL(), infoboxReadRequest, dataURL, certInfoRequest, - certInfoDataURL, pushInfobox, oaParam, appletheigth, appletwidth); - - return htmlForm; - } - - /** - * Processes an <code><InfoboxReadResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><InfoboxReadResponse></code></li> - * <li>Parses identity link enclosed in - * <code><InfoboxReadResponse></code></li> - * <li>Verifies identity link by calling the MOA SP component</li> - * <li>Checks certificate authority of identity link</li> - * <li>Stores identity link in the session</li> - * <li>Verifies all additional infoboxes returned from the BKU</li> - * <li>Creates an authentication block to be signed by the user</li> - * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> - * containg the authentication block, meant to be returned to the security - * layer implementation</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param infoboxReadResponseParameters - * The parameters from the response returned from the BKU - * including the <code><InfoboxReadResponse></code> - * @return String representation of the - * <code><CreateXMLSignatureRequest></code> - * @throws BKUException - */ - public String verifyIdentityLink(AuthenticationSession session, - Map<String, String> infoboxReadResponseParameters) throws AuthenticationException, - BuildException, ParseException, ConfigurationException, - ValidateException, ServiceException, BKUException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_IDENTITY_LINK, PARAM_SESSIONID }); - - String xmlInfoboxReadResponse = (String) infoboxReadResponseParameters - .get(PARAM_XMLRESPONSE); - - if (isEmpty(xmlInfoboxReadResponse)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_IDENTITY_LINK, PARAM_XMLRESPONSE }); - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - - // check if an identity link was found - // Errorcode 2911 von Trustdesk BKU (nicht spezifikationskonform - // (SL1.2)) - // CharSequence se = "ErrorCode>2911".substring(0); - // boolean b = xmlInfoboxReadResponse.contains(se); - String se = "ErrorCode>2911"; - int b = xmlInfoboxReadResponse.indexOf(se); - if (b != -1) { // no identity link found - Logger - .info("Es konnte keine Personenbindung auf der Karte gefunden werden. Versuche Anmeldung als auslaendische eID."); - return null; - } - // spezifikationsgemaess (SL1.2) Errorcode - se = "ErrorCode>4002"; - // b = xmlInfoboxReadResponse.contains(se); - b = xmlInfoboxReadResponse.indexOf(se); - if (b != -1) { // Unbekannter Infoboxbezeichner - Logger - .info("Unbekannter Infoboxbezeichner. Versuche Anmeldung als auslaendische eID."); - return null; - } - - // parses the <InfoboxReadResponse> - IdentityLink identityLink = new InfoboxReadResponseParser( - xmlInfoboxReadResponse).parseIdentityLink(); - // validates the identity link - IdentityLinkValidator.getInstance().validate(identityLink); - // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP - Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() - .build(identityLink, authConf - .getMoaSpIdentityLinkTrustProfileID()); - - // invokes the call - Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() - .verifyXMLSignature(domVerifyXMLSignatureRequest); - // parses the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( - domVerifyXMLSignatureResponse).parseData(); - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - // if OA is type is business service the manifest validation result has - // to be ignored - boolean ignoreManifestValidationResult = oaParam.getBusinessService() ? true - : false; - - // validates the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponseValidator.getInstance().validate( - verifyXMLSignatureResponse, - authConf.getIdentityLinkX509SubjectNames(), - VerifyXMLSignatureResponseValidator.CHECK_IDENTITY_LINK, - ignoreManifestValidationResult); - - session.setIdentityLink(identityLink); - // now validate the extended infoboxes - - //Removed in MOA-ID 2.0 - //verifyInfoboxes(session, infoboxReadResponseParameters, false); - - return "found!"; - } - - /** - * Processes an <code><InfoboxReadResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><InfoboxReadResponse></code></li> - * <li>Parses identity link enclosed in - * <code><InfoboxReadResponse></code></li> - * <li>Verifies identity link by calling the MOA SP component</li> - * <li>Checks certificate authority of identity link</li> - * <li>Stores identity link in the session</li> - * <li>Verifies all additional infoboxes returned from the BKU</li> - * <li>Creates an authentication block to be signed by the user</li> - * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> - * containg the authentication block, meant to be returned to the security - * layer implementation</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param infoboxReadResponseParameters - * The parameters from the response returned from the BKU - * including the <code><InfoboxReadResponse></code> - * @return String representation of the - * <code><CreateXMLSignatureRequest></code> - */ - public String verifyCertificate(AuthenticationSession session, - X509Certificate certificate) throws AuthenticationException, - BuildException, ParseException, ConfigurationException, - ValidateException, ServiceException, MOAIDException{ - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID }); - - // check if person is a Organwalter - // if true - don't show bPK in AUTH Block - try { - for (ObjectID OWid : MOAIDAuthConstants.OW_LIST) { - if (certificate.getExtension(OWid) != null) { - session.setOW(true); - } - - } - - } catch (X509ExtensionInitException e) { - Logger.warn("Certificate extension is not readable."); - session.setOW(false); - } - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - String returnvalue = getCreateXMLSignatureRequestAuthBlockOrRedirect(session, - authConf, oaParam); - - return returnvalue; - } - - /** - * Processes an <code>Mandate</code> sent by the MIS.<br> - * <ul> - * <li>Validates given <code>Mandate</code></li> - * <li>Verifies Mandate by calling the MOA SP component</li> - * <li>Creates an authentication block to be signed by the user</li> - * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> - * containg the authentication block, meant to be returned to the security - * layer implementation</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param infoboxReadResponseParameters - * The parameters from the response returned from the BKU - * including the <code><InfoboxReadResponse></code> - * @return String representation of the - * <code><CreateXMLSignatureRequest></code> - */ - public void verifyMandate(AuthenticationSession session, MISMandate mandate) - throws AuthenticationException, BuildException, ParseException, - ConfigurationException, ValidateException, ServiceException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - GET_MIS_SESSIONID, PARAM_SESSIONID }); - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - try { - // sets the extended SAML attributes for OID (Organwalter) - setExtendedSAMLAttributeForMandatesOID(session, mandate, oaParam - .getBusinessService()); - - validateExtendedSAMLAttributeForMandates(session, mandate, oaParam.getBusinessService()); - - - } catch (SAXException e) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }, e); - } catch (IOException e) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }, e); - } catch (ParserConfigurationException e) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }, e); - } catch (TransformerException e) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }, e); - } - - } - - /** - * - * @param session - * @param authConf - * @param oaParam - * @return - * @throws ConfigurationException - * @throws BuildException - * @throws ValidateException - */ - public String getCreateXMLSignatureRequestAuthBlockOrRedirect( - AuthenticationSession session, AuthConfigurationProvider authConf, - OAAuthParameter oaParam) throws ConfigurationException, - BuildException, ValidateException { - - // check for intermediate processing of the infoboxes - if (session.isValidatorInputPending()) - return "Redirect to Input Processor"; - - if (authConf == null) - authConf = AuthConfigurationProvider.getInstance(); - if (oaParam == null) - oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - - // builds the AUTH-block - String authBlock = buildAuthenticationBlock(session, oaParam); - - // builds the <CreateXMLSignatureRequest> - List<String> transformsInfos = oaParam.getTransformsInfos(); - if ((transformsInfos == null) || (transformsInfos.size() == 0)) { - // no OA specific transforms specified, use default ones - transformsInfos = authConf.getTransformsInfos(); - } - String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() - .build(authBlock, oaParam.getKeyBoxIdentifier(), - transformsInfos); - return createXMLSignatureRequest; - } - - /** - * Returns an CreateXMLSignatureRequest for signing the ERnP statement.<br> - * <ul> - * <li>Creates an CreateXMLSignatureRequest to be signed by the user</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param cert - * The certificate from the user - * @return String representation of the - * <code><CreateXMLSignatureRequest></code> - */ - public String createXMLSignatureRequestForeignID(AuthenticationSession session, - X509Certificate cert) throws AuthenticationException, - BuildException, ParseException, ConfigurationException, - ValidateException, ServiceException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID }); - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - return getCreateXMLSignatureRequestForeigID(session, authConf, oaParam, - cert); - } - - public String getCreateXMLSignatureRequestForeigID( - AuthenticationSession session, AuthConfigurationProvider authConf, - OAAuthParameter oaParam, X509Certificate cert) - throws ConfigurationException { - - // check for intermediate processing of the infoboxes - if (session.isValidatorInputPending()) - return "Redirect to Input Processor"; - - if (authConf == null) - authConf = AuthConfigurationProvider.getInstance(); - if (oaParam == null) - oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - - Principal subject = cert.getSubjectDN(); - - String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() - .buildForeignID(subject.toString(), oaParam, session); - return createXMLSignatureRequest; - } - - /** - * Processes an <code><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses response enclosed in - * <code><CreateXMLSignatureResponse></code></li> - * <li>Verifies signature by calling the MOA SP component</li> - * <li>Returns the signer certificate</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param createXMLSignatureResponseParameters - * The parameters from the response returned from the BKU - * including the <code><CreateXMLSignatureResponse></code> - * @throws BKUException - */ - public X509Certificate verifyXMLSignature(String sessionID, - Map<String, String> createXMLSignatureResponseParameters) - throws AuthenticationException, BuildException, ParseException, - ConfigurationException, ValidateException, ServiceException, BKUException { - - if (isEmpty(sessionID)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_GET_FOREIGN_ID, PARAM_SESSIONID }); - - String xmlCreateXMLSignatureResponse = (String) createXMLSignatureResponseParameters - .get(PARAM_XMLRESPONSE); - - if (isEmpty(xmlCreateXMLSignatureResponse)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_GET_FOREIGN_ID, PARAM_XMLRESPONSE }); - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - - // parses the <CreateXMLSignatureResponse> - CreateXMLSignatureResponseParser p = new CreateXMLSignatureResponseParser( - xmlCreateXMLSignatureResponse); - CreateXMLSignatureResponse createXMLSignatureResponse = p - .parseResponseDsig(); - - // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP - Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() - .buildDsig(createXMLSignatureResponse, authConf - .getMoaSpAuthBlockTrustProfileID()); - - // invokes the call - Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() - .verifyXMLSignature(domVerifyXMLSignatureRequest); - - // parses the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( - domVerifyXMLSignatureResponse).parseData(); - - return verifyXMLSignatureResponse.getX509certificate(); - - } - - /** - * Processes an <code><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses response enclosed in - * <code><CreateXMLSignatureResponse></code></li> - * <li>Verifies signature by calling the MOA SP component</li> - * <li>Returns the signer certificate</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param readInfoboxResponseParameters - * The parameters from the response returned from the BKU - * including the <code><ReadInfoboxResponse></code> - * @throws BKUException - */ - public X509Certificate getCertificate(String sessionID, - Map<String, String> readInfoboxResponseParameters) throws AuthenticationException, - BuildException, ParseException, ConfigurationException, - ValidateException, ServiceException, BKUException { - - if (isEmpty(sessionID)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID }); - - String xmlReadInfoboxResponse = (String) readInfoboxResponseParameters - .get(PARAM_XMLRESPONSE); - - if (isEmpty(xmlReadInfoboxResponse)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_CERTIFICATE, PARAM_XMLRESPONSE }); - - // parses the <CreateXMLSignatureResponse> - InfoboxReadResponseParser p = new InfoboxReadResponseParser( - xmlReadInfoboxResponse); - X509Certificate cert = p.parseCertificate(); - - return cert; - - } - - /** - * Builds an authentication block <code><saml:Assertion></code> from - * given session data. - * - * @param session - * authentication session - * - * @return <code><saml:Assertion></code> as a String - * - * @throws BuildException - * If an error occurs on serializing an extended SAML attribute - * to be appended to the AUTH-Block. - */ - private String buildAuthenticationBlock(AuthenticationSession session, - OAAuthParameter oaParam) throws BuildException { - - IdentityLink identityLink = session.getIdentityLink(); - String issuer = identityLink.getName(); - String gebDat = identityLink.getDateOfBirth(); - - String identificationValue = null; - String identificationType = null; - - //set empty AuthBlock BPK in case of OW or SSO or bpk is not requested - if (session.isOW() || session.isSsoRequested() || oaParam.isRemovePBKFromAuthBlock()) { - identificationType = ""; - identificationValue = ""; - - } else if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - - if (oaParam.getBusinessService()) { - - String bpkBase64 = new BPKBuilder().buildWBPK(identityLink - .getIdentificationValue(), oaParam.getIdentityLinkDomainIdentifier()); - identificationValue = bpkBase64; - - if (oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_WBPK + "+" )) - identificationType = oaParam.getIdentityLinkDomainIdentifier(); - else - identificationType = Constants.URN_PREFIX_WBPK + "+" + oaParam.getIdentityLinkDomainIdentifier(); - - } else { - String bpkBase64 = new BPKBuilder().buildBPK(identityLink - .getIdentificationValue(), session.getTarget()); - identificationValue = bpkBase64; - identificationType = Constants.URN_PREFIX_CDID + "+" + session.getTarget(); - } - - - } else { - identificationValue = identityLink.getIdentificationValue(); - identificationType = identityLink.getIdentificationType(); - - } - - String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar - .getInstance()); - session.setIssueInstant(issueInstant); - String authURL = session.getAuthURL(); - String target = session.getTarget(); - String targetFriendlyName = session.getTargetFriendlyName(); - - // Bug #485 - // (https://egovlabs.gv.at/tracker/index.php?func=detail&aid=485&group_id=6&atid=105) - // String oaURL = session.getPublicOAURLPrefix(); - - List<ExtendedSAMLAttribute> extendedSAMLAttributes = session.getExtendedSAMLAttributesAUTH(); - - - if (session.isSsoRequested()) { - String oaURL = new String(); - try { - oaURL = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); - - if (MiscUtil.isNotEmpty(oaURL)) - oaURL = oaURL.replaceAll("&", "&"); - - } catch (ConfigurationException e) { - } - String authBlock = new AuthenticationBlockAssertionBuilder() - .buildAuthBlockSSO(issuer, issueInstant, authURL, target, - targetFriendlyName, identificationValue, - identificationType, oaURL, gebDat, - extendedSAMLAttributes, session, oaParam); - return authBlock; - - } else { - String oaURL = session.getPublicOAURLPrefix().replaceAll("&", "&"); - String authBlock = new AuthenticationBlockAssertionBuilder() - .buildAuthBlock(issuer, issueInstant, authURL, target, - targetFriendlyName, identificationValue, - identificationType, oaURL, gebDat, - extendedSAMLAttributes, session, oaParam); - return authBlock; - } - } - - - - /** - * Verifies the infoboxes (except of the identity link infobox) returned by - * the BKU by calling appropriate validator classes. - * - * @param session - * The actual authentication session. - * @param mandate - * The Mandate from the MIS - * - * @throws AuthenticationException - * @throws ConfigurationException - * @throws TransformerException - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - */ - private void validateExtendedSAMLAttributeForMandates( - AuthenticationSession session, MISMandate mandate, - boolean business) - throws ValidateException, ConfigurationException, SAXException, - IOException, ParserConfigurationException, TransformerException { - - ExtendedSAMLAttribute[] extendedSAMLAttributes = addExtendedSamlAttributes( - mandate, business, false); - - int length = extendedSAMLAttributes.length; - for (int i = 0; i < length; i++) { - ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i]; - - verifySAMLAttribute(samlAttribute, i, "MISService", - "MISService"); - - } - } - - /** - * Verifies the infoboxes (except of the identity link infobox) returned by - * the BKU by calling appropriate validator classes. - * - * @param session - * The actual authentication session. - * @param mandate - * The Mandate from the MIS - * - * @throws AuthenticationException - * @throws ConfigurationException - * @throws TransformerException - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - */ - private void setExtendedSAMLAttributeForMandatesOID( - AuthenticationSession session, MISMandate mandate, boolean business) - throws ValidateException, ConfigurationException, SAXException, - IOException, ParserConfigurationException, TransformerException { - - ExtendedSAMLAttribute[] extendedSamlAttributes = addExtendedSamlAttributesOID( - mandate, business); - - AddAdditionalSAMLAttributes(session, extendedSamlAttributes, - "MISService", "MISService"); - - } - - /** - * Adds given SAML Attributes to the current session. They will be appended - * to the final SAML Assertion or the AUTH block. If the attributes are - * already in the list, they will be replaced. - * - * @param session - * The current session - * @param extendedSAMLAttributes - * The SAML attributes to add - * @param identifier - * The infobox identifier for debug purposes - * @param friendlyNam - * The friendly name of the infobox for debug purposes - */ - private static void AddAdditionalSAMLAttributes( - AuthenticationSession session, - ExtendedSAMLAttribute[] extendedSAMLAttributes, String identifier, - String friendlyName) throws ValidateException { - if (extendedSAMLAttributes == null) - return; - List<ExtendedSAMLAttribute> oaAttributes = session.getExtendedSAMLAttributesOA(); - if (oaAttributes == null) - oaAttributes = new Vector<ExtendedSAMLAttribute>(); - List<ExtendedSAMLAttribute> authAttributes = session.getExtendedSAMLAttributesAUTH(); - if (authAttributes == null) - authAttributes = new Vector<ExtendedSAMLAttribute>(); - int length = extendedSAMLAttributes.length; - for (int i = 0; i < length; i++) { - ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i]; - - Object value = verifySAMLAttribute(samlAttribute, i, identifier, - friendlyName); - - if ((value instanceof String) || (value instanceof Element)) { - switch (samlAttribute.getAddToAUTHBlock()) { - case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY: - replaceExtendedSAMLAttribute(authAttributes, samlAttribute); - break; - case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK: - replaceExtendedSAMLAttribute(authAttributes, samlAttribute); - replaceExtendedSAMLAttribute(oaAttributes, samlAttribute); - break; - case ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK: - replaceExtendedSAMLAttribute(oaAttributes, samlAttribute); - break; - default: - Logger - .info("Invalid return value from method \"getAddToAUTHBlock()\" (" - + samlAttribute.getAddToAUTHBlock() - + ") in SAML attribute number " - + (i + 1) - + " for infobox " + identifier); - throw new ValidateException("validator.47", new Object[] { - friendlyName, String.valueOf((i + 1)) }); - } - } else { - Logger - .info("The type of SAML-Attribute number " - + (i + 1) - + " returned from " - + identifier - + "-infobox validator is not valid. Must be either \"java.Lang.String\"" - + " or \"org.w3c.dom.Element\""); - throw new ValidateException("validator.46", new Object[] { - identifier, String.valueOf((i + 1)) }); - } - } - session.setExtendedSAMLAttributesAUTH(authAttributes); - session.setExtendedSAMLAttributesOA(oaAttributes); - } - - /** - * Adds the AUTH block related SAML attributes to the validation result. - * This is needed always before the AUTH block is to be signed, because the - * name of the mandator has to be set - * - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - * @throws TransformerException - */ - - protected static ExtendedSAMLAttribute[] addExtendedSamlAttributes( - MISMandate mandate, boolean business, boolean provideStammzahl) - throws SAXException, IOException, ParserConfigurationException, - TransformerException { - Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>(); - - extendedSamlAttributes.clear(); - - // Name - Element domMandate = mandateToElement(mandate); - Element nameSpaceNode = domMandate.getOwnerDocument().createElement( - "NameSpaceNode"); - nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, - Constants.PD_NS_URI); - nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.MANDATE_POSTFIX, - SZRGWConstants.MANDATE_NS); - - Element mandator = (Element) XPathAPI.selectSingleNode(domMandate, - "//md:Mandate/md:Mandator", nameSpaceNode); - - // Mandate - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_RAW, domMandate, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); - - // (w)bpk - String wbpk = ParepUtils.extractMandatorWbpk(mandator); - if (!ParepUtils.isEmpty(wbpk)) { - if (!ParepUtils.isPhysicalPerson(mandator)) { - String idType = ParepUtils - .extractMandatorIdentificationType(mandator); - if (!ParepUtils.isEmpty(idType) - && idType.startsWith(Constants.URN_PREFIX_BASEID)) { - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_CB_BASE_ID, - ParepUtils.getRegisterString(idType) + ": " + wbpk, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY)); - } - } else if (business) { - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_WBPK, wbpk, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY)); - } - } - - ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes - .size()]; - extendedSamlAttributes.copyInto(ret); - Logger.debug("ExtendedSAML Attributes: " + ret.length); - return ret; - - } - - /** - * Adds the AUTH block related SAML attributes to the validation result. - * This is needed always before the AUTH block is to be signed, because the - * name of the mandator has to be set - * - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - * @throws TransformerException - */ - private static ExtendedSAMLAttribute[] addExtendedSamlAttributesOID( - MISMandate mandate, boolean business) throws SAXException, - IOException, ParserConfigurationException, TransformerException { - - Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>(); - - extendedSamlAttributes.clear(); - - // RepresentationType - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_REPRESENTATIONTYPE, - EXT_SAML_MANDATE_REPRESENTATIONTEXT, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); - - String oid = mandate.getProfRep(); - - if (oid != null) { - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_OID, oid, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); - String oidDescription = mandate.getTextualDescriptionOfOID(); - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION, - oidDescription, SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); - - } - - ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes - .size()]; - extendedSamlAttributes.copyInto(ret); - Logger.debug("ExtendedSAML Attributes: " + ret.length); - return ret; - - } - - /** - * - * @param mandate - * @return - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - */ - private static Element mandateToElement(MISMandate mandate) - throws SAXException, IOException, ParserConfigurationException { - ByteArrayInputStream bais = new ByteArrayInputStream(mandate - .getMandate()); - Document doc = DOMUtils.parseDocumentSimple(bais); - return doc.getDocumentElement(); - } - - protected static void replaceExtendedSAMLAttribute(List<ExtendedSAMLAttribute> attributes, - ExtendedSAMLAttribute samlAttribute) { - if (null == attributes) { - attributes = new Vector<ExtendedSAMLAttribute>(); - } else { - String id = samlAttribute.getName(); - int length = attributes.size(); - for (int i = 0; i < length; i++) { - ExtendedSAMLAttribute att = (ExtendedSAMLAttribute) attributes - .get(i); - if (id.equals(att.getName())) { - // replace attribute - attributes.set(i, samlAttribute); - return; - } - } - attributes.add(samlAttribute); - } - } - - /** - * Processes a <code><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses <code><CreateXMLSignatureResponse></code> for error - * codes</li> - * <li>Parses authentication block enclosed in - * <code><CreateXMLSignatureResponse></code></li> - * <li>Verifies authentication block by calling the MOA SP component</li> - * <li>Creates authentication data</li> - * <li>Creates a corresponding SAML artifact</li> - * <li>Stores authentication data in the authentication data store indexed - * by the SAML artifact</li> - * <li>Deletes authentication session</li> - * <li>Returns the SAML artifact, encoded BASE64</li> - * </ul> - * - * @param sessionID - * session ID of the running authentication session - * @param xmlCreateXMLSignatureReadResponse - * String representation of the - * <code><CreateXMLSignatureResponse></code> - * @return SAML artifact needed for retrieving authentication data, encoded - * BASE64 - * @throws BKUException - */ - public String verifyAuthenticationBlock(AuthenticationSession session, - String xmlCreateXMLSignatureReadResponse) - throws AuthenticationException, BuildException, ParseException, - ConfigurationException, ServiceException, ValidateException, BKUException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID }); - if (isEmpty(xmlCreateXMLSignatureReadResponse)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - // parses <CreateXMLSignatureResponse> - CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser( - xmlCreateXMLSignatureReadResponse).parseResponse(); - - try { - String serializedAssertion = DOMUtils.serializeNode(csresp - .getSamlAssertion()); - 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 }); - } - // validates <CreateXMLSignatureResponse> - if (session.isSsoRequested()) - new CreateXMLSignatureResponseValidator().validateSSO(csresp, session); - else - new CreateXMLSignatureResponseValidator().validate(csresp, session); - - // builds a <VerifyXMLSignatureRequest> for a MOA-SPSS call - List<String> vtids = authConf.getMoaSpAuthBlockVerifyTransformsInfoIDs(); - String tpid = authConf.getMoaSpAuthBlockTrustProfileID(); - Element domVsreq = new VerifyXMLSignatureRequestBuilder().build(csresp, - vtids, tpid); - // debug output - - // invokes the call - Element domVsresp = new SignatureVerificationInvoker() - .verifyXMLSignature(domVsreq); - // debug output - - // parses the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponseParser( - domVsresp).parseData(); - - if (Logger.isTraceEnabled()) { - if (domVsresp != null) { - try { - String xmlVerifyXMLSignatureResponse = DOMUtils - .serializeNode(domVsresp, true); - Logger.trace(new LogMsg(xmlCreateXMLSignatureReadResponse)); - Logger.trace(new LogMsg(xmlVerifyXMLSignatureResponse)); - } catch (Throwable t) { - t.printStackTrace(); - Logger.info(new LogMsg(t.getStackTrace())); - } - } - } - - // validates the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponseValidator.getInstance().validate(vsresp, - null, VerifyXMLSignatureResponseValidator.CHECK_AUTH_BLOCK, - false); - - // Compare AuthBlock Data with information stored in session, especially - // date and time - CreateXMLSignatureResponseValidator.getInstance().validateSigningDateTime(csresp); - - // compares the public keys from the identityLink with the AuthBlock - VerifyXMLSignatureResponseValidator.getInstance().validateCertificate( - vsresp, session.getIdentityLink()); - - // post processing of the infoboxes - Iterator iter = session.getInfoboxValidatorIterator(); - boolean formpending = false; - if (iter != null) { - while (!formpending && iter.hasNext()) { - Vector infoboxValidatorVector = (Vector) iter.next(); - String identifier = (String) infoboxValidatorVector.get(0); - String friendlyName = (String) infoboxValidatorVector.get(1); - InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector - .get(2); - InfoboxValidationResult infoboxValidationResult = null; - try { - infoboxValidationResult = infoboxvalidator.validate(csresp - .getSamlAssertion()); - } catch (ValidateException e) { - Logger.error("Error validating " + identifier + " infobox:" - + e.getMessage()); - throw new ValidateException("validator.44", - new Object[] { friendlyName }); - } - if (!infoboxValidationResult.isValid()) { - Logger.info("Validation of " + identifier - + " infobox failed."); - throw new ValidateException("validator.40", new Object[] { - friendlyName, - infoboxValidationResult.getErrorMessage() }); - } - String form = infoboxvalidator.getForm(); - if (ParepUtils.isEmpty(form)) { - AddAdditionalSAMLAttributes( - session, - infoboxValidationResult.getExtendedSamlAttributes(), - identifier, friendlyName); - } else { - return "Redirect to Input Processor"; - } - } - } - - session.setXMLVerifySignatureResponse(vsresp); - session.setSignerCertificate(vsresp.getX509certificate()); - vsresp.setX509certificate(null); - session.setForeigner(false); - - if (session.getUseMandate()) { - // mandate mode - return null; - - } else { - - 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 implicte stored in changeSessionID!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); - Logger.info("Daten angelegt zu MOASession " + newMOASessionID); - - return newMOASessionID; - } - } - - /** - * Processes a <code><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses <code><CreateXMLSignatureResponse></code> for error - * codes</li> - * <li>Parses authentication block enclosed in - * <code><CreateXMLSignatureResponse></code></li> - * <li>Verifies authentication block by calling the MOA SP component</li> - * <li>Creates authentication data</li> - * <li>Creates a corresponding SAML artifact</li> - * <li>Stores authentication data in the authentication data store indexed - * by the SAML artifact</li> - * <li>Deletes authentication session</li> - * <li>Returns the SAML artifact, encoded BASE64</li> - * </ul> - * - * @param sessionID - * session ID of the running authentication session - * @param xmlCreateXMLSignatureReadResponse - * String representation of the - * <code><CreateXMLSignatureResponse></code> - * @return SAML artifact needed for retrieving authentication data, encoded - * BASE64 - */ - - protected Element createIdentificationBPK(Element mandatePerson, - String baseid, String target) throws BuildException { - Element identificationBpK = mandatePerson.getOwnerDocument() - .createElementNS(Constants.PD_NS_URI, "Identification"); - Element valueBpK = mandatePerson.getOwnerDocument().createElementNS( - Constants.PD_NS_URI, "Value"); - - String bpkBase64 = new BPKBuilder().buildBPK(baseid, target); - valueBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( - bpkBase64)); - Element typeBpK = mandatePerson.getOwnerDocument().createElementNS( - Constants.PD_NS_URI, "Type"); - typeBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( - "urn:publicid:gv.at:cdid+bpk")); - identificationBpK.appendChild(valueBpK); - identificationBpK.appendChild(typeBpK); - - return identificationBpK; - - } - - protected String getBaseId(Element mandatePerson) - throws TransformerException, IOException { - NodeList list = mandatePerson.getElementsByTagNameNS( - Constants.PD_NS_URI, "Identification"); - for (int i = 0; i < list.getLength(); i++) { - Element identification = (Element) list.item(i); - Element type = (Element) identification.getElementsByTagNameNS( - Constants.PD_NS_URI, "Type").item(0); - if (type.getTextContent().compareToIgnoreCase( - "urn:publicid:gv.at:baseid") == 0) { - Element value = (Element) identification - .getElementsByTagNameNS(Constants.PD_NS_URI, "Value") - .item(0); - return value.getTextContent(); - } - } - return null; - - } - - /** - * Gets the foreign authentication data.<br> - * <ul> - * <li>Creates authentication data</li> - * <li>Creates a corresponding SAML artifact</li> - * <li>Stores authentication data in the authentication data store indexed - * by the SAML artifact</li> - * <li>Deletes authentication session</li> - * <li>Returns the SAML artifact, encoded BASE64</li> - * </ul> - * - * @param sessionID - * session ID of the running authentication session - * @return SAML artifact needed for retrieving authentication data, encoded - * BASE64 - */ - public String getForeignAuthenticationData(AuthenticationSession session) - throws AuthenticationException, BuildException, ParseException, - ConfigurationException, ServiceException, ValidateException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID }); - - // post processing of the infoboxes - Iterator iter = session.getInfoboxValidatorIterator(); - boolean formpending = false; - if (iter != null) { - while (!formpending && iter.hasNext()) { - Vector infoboxValidatorVector = (Vector) iter.next(); - String identifier = (String) infoboxValidatorVector.get(0); - String friendlyName = (String) infoboxValidatorVector.get(1); - InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector - .get(2); - InfoboxValidationResult infoboxValidationResult = null; - try { - infoboxValidationResult = infoboxvalidator.validate(session - .getIdentityLink().getSamlAssertion()); - } catch (ValidateException e) { - Logger.error("Error validating " + identifier + " infobox:" - + e.getMessage()); - throw new ValidateException("validator.44", - new Object[] { friendlyName }); - } - if (!infoboxValidationResult.isValid()) { - Logger.info("Validation of " + identifier - + " infobox failed."); - throw new ValidateException("validator.40", new Object[] { - friendlyName, - infoboxValidationResult.getErrorMessage() }); - } - String form = infoboxvalidator.getForm(); - if (ParepUtils.isEmpty(form)) { - AddAdditionalSAMLAttributes( - session, - infoboxValidationResult.getExtendedSamlAttributes(), - identifier, friendlyName); - } else { - return "Redirect to Input Processor"; - } - } - } - - VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponse(); - X509Certificate cert = session.getSignerCertificate(); - vsresp.setX509certificate(cert); - - session.setAuthenticatedUsed(false); - session.setAuthenticated(true); - - - session.setXMLVerifySignatureResponse(vsresp); - session.setSignerCertificate(vsresp.getX509certificate()); - vsresp.setX509certificate(null); - session.setForeigner(true); - - //TODO: regenerate MOASession ID! - return "new Session"; - } - - /** - * Builds the AuthenticationData object together with the corresponding - * <code><saml:Assertion></code> - * - * @param session - * authentication session - * @param verifyXMLSigResp - * VerifyXMLSignatureResponse from MOA-SP - * @param useUTC uses correct UTC time format - * @param useUTC indicates that authenticated citizen is a foreigner - * @param isForeigner indicates whether Austrian (false) or foreigner (true) authenticates - * @return AuthenticationData object - * @throws ConfigurationException - * while accessing configuration data - * @throws BuildException - * while building the <code><saml:Assertion></code> - */ - public static AuthenticationData buildAuthenticationData( - AuthenticationSession session, OAAuthParameter oaParam, String target) - throws ConfigurationException, BuildException { - - IdentityLink identityLink = session.getIdentityLink(); - AuthenticationData authData = new AuthenticationData(); - - VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); - - boolean businessService = oaParam.getBusinessService(); - - authData.setMajorVersion(1); - authData.setMinorVersion(0); - authData.setAssertionID(Random.nextRandom()); - authData.setIssuer(session.getAuthURL()); - - authData.setIssueInstant(DateTimeUtils.buildDateTimeUTC(Calendar - .getInstance())); - - //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO - authData.setIdentificationValue(identityLink.getIdentificationValue()); - authData.setIdentificationType(identityLink.getIdentificationType()); - - authData.setGivenName(identityLink.getGivenName()); - authData.setFamilyName(identityLink.getFamilyName()); - authData.setDateOfBirth(identityLink.getDateOfBirth()); - authData.setQualifiedCertificate(verifyXMLSigResp - .isQualifiedCertificate()); - authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); - authData.setPublicAuthorityCode(verifyXMLSigResp - .getPublicAuthorityCode()); - authData.setBkuURL(session.getBkuURL()); - - try { - - if (session.getUseMandate() && session.isOW()) { - MISMandate mandate = session.getMISMandate(); - authData.setBPK(mandate.getOWbPK()); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); - authData.setIdentityLink(identityLink); - - Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); - - } else { - - if (businessService) { - //since we have foreigner, wbPK is not calculated in BKU - if(identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - - String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); - - if (registerAndOrdNr.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) { - // If domainIdentifier starts with prefix - // "urn:publicid:gv.at:wbpk+"; remove this prefix - registerAndOrdNr = registerAndOrdNr - .substring(AuthenticationSession.REGISTERANDORDNR_PREFIX_.length()); - Logger.debug("Register and ordernumber prefix stripped off; resulting register string: " - + registerAndOrdNr); - } - - String wbpkBase64 = new BPKBuilder().buildWBPK(identityLink.getIdentificationValue(), registerAndOrdNr); - authData.setBPK(wbpkBase64); - authData.setBPKType( Constants.URN_PREFIX_WBPK + "+" + registerAndOrdNr); - - } else { - authData.setBPK(identityLink.getIdentificationValue()); - authData.setBPKType(identityLink.getIdentificationType()); - - } - - Logger.trace("Authenticate user with wbPK " + authData.getBPK()); - - Element idlassertion = session.getIdentityLink().getSamlAssertion(); - //set bpk/wpbk; - Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - prIdentification.getFirstChild().setNodeValue(authData.getBPK()); - //set bkp/wpbk type - Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); - prIdentificationType.getFirstChild().setNodeValue(authData.getBPKType()); - - IdentityLinkAssertionParser idlparser = new IdentityLinkAssertionParser(idlassertion); - IdentityLink idl = idlparser.parseIdentityLink(); - authData.setIdentityLink(idl); - - } else { - - if(identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - // only compute bPK if online application is a public service and we have the Stammzahl - String bpkBase64 = new BPKBuilder().buildBPK(identityLink.getIdentificationValue(), target); - authData.setBPK(bpkBase64); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget()); - } - - Logger.trace("Authenticate user with bPK " + authData.getBPK()); - - authData.setIdentityLink(identityLink); - } - } - - return authData; - - } catch (Throwable ex) { - throw new BuildException("builder.00", new Object[] { - "AuthenticationData", ex.toString() }, ex); - } - } - - /** - * Retrieves a session from the session store. - * - * @param id - * session ID - * @return <code>AuthenticationSession</code> stored with given session ID, - * <code>null</code> if session ID unknown - */ - public static AuthenticationSession getSession(String id) - throws AuthenticationException { - - AuthenticationSession session; - try { - session = AuthenticationSessionStoreage.getSession(id); - - if (session == null) - throw new AuthenticationException("auth.02", new Object[] { id }); - return session; - - } catch (MOADatabaseException e) { - throw new AuthenticationException("parser.04", new Object[] { id }); - } - } - - /** - * Cleans up expired session and authentication data stores. - */ - public void cleanup() { - long now = new Date().getTime(); - - //clean AuthenticationSessionStore - - AuthenticationSessionStoreage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); - - //clean AssertionStore - AssertionStorage assertionstore = AssertionStorage.getInstance(); - assertionstore.clean(now, authDataTimeOut); - - //clean ExeptionStore - DBExceptionStoreImpl exstore = DBExceptionStoreImpl.getStore(); - exstore.clean(now, authDataTimeOut); - - } - - /** - * Sets the sessionTimeOut. - * - * @param seconds - * Time out of the session in seconds - */ - public void setSecondsSessionTimeOutCreated(long seconds) { - sessionTimeOutCreated = seconds * 1000; - } - - public void setSecondsSessionTimeOutUpdated(long seconds) { - sessionTimeOutUpdated = seconds * 1000; - } - - /** - * Sets the authDataTimeOut. - * - * @param seconds - * Time out for signing AuthData in seconds - */ - public void setSecondsAuthDataTimeOut(long seconds) { - authDataTimeOut = seconds * 1000; - } - - /** - * 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; - } - - /** - * Checks the correctness of SAML attributes and returns its value. - * - * @param param - * samlAttribute - * @param i - * the number of the verified attribute for messages - * @param identifier - * the infobox identifier for messages - * @param friendlyname - * the friendly name of the infobox for messages - * @return the SAML attribute value (Element or String) - */ - protected static Object verifySAMLAttribute( - ExtendedSAMLAttribute samlAttribute, int i, String identifier, - String friendlyName) throws ValidateException { - String name = samlAttribute.getName(); - - if (name == null) { - Logger.info("The name of SAML-Attribute number " + (i + 1) - + " returned from " + identifier - + "-infobox validator is null."); - throw new ValidateException("validator.45", new Object[] { - friendlyName, "Name", String.valueOf((i + 1)), "null" }); - } - if (name == "") { - Logger.info("The name of SAML-Attribute number " + (i + 1) - + " returned from " + identifier - + "-infobox validator is empty."); - throw new ValidateException("validator.45", new Object[] { - friendlyName, "Name", String.valueOf((i + 1)), "leer" }); - } - if (samlAttribute.getNameSpace() == null) { - Logger.info("The namespace of SAML-Attribute number " + (i + 1) - + " returned from " + identifier - + "-infobox validator is null."); - throw new ValidateException("validator.45", - new Object[] { friendlyName, "Namespace", - String.valueOf((i + 1)), "null" }); - } - Object value = samlAttribute.getValue(); - if (value == null) { - Logger.info("The value of SAML-Attribute number " + (i + 1) - + " returned from " + identifier - + "-infobox validator is null."); - throw new ValidateException("validator.45", new Object[] { - friendlyName, "Wert", String.valueOf((i + 1)), "null" }); - } - - return value; - } - - /** - * Does the request to the SZR-GW - * @param oaFriendlyName - * @param signature XMLDSIG signature - * @return Identity link assertion - * @throws SZRGWClientException - */ - - public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String gender, String citizenSignature, String represented, String representative, String mandateContent, String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { - - try { - AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); - ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); - - SZRGWClient client = new SZRGWClient(connectionParameters); - - - CreateIdentityLinkRequest request = new CreateIdentityLinkRequest(); - request.setSignature(citizenSignature.getBytes()); - - PEPSData data = new PEPSData(); - data.setDateOfBirth(PEPSDateOfBirth); - data.setFamilyname(PEPSFamilyname); - data.setFirstname(PEPSFirstname); - data.setIdentifier(PEPSIdentifier); - - data.setRepresentative(representative); - data.setRepresented(represented); - data.setMandateContent(mandateContent); - - data.setLegalPersonCanonicalRegisteredAddress(organizationAddress); - data.setLegalPersonTranslatableType(organizationType); - - if(null != mandateContent) { - MISType mis = new MISType(); - - Target targetObject = new Target(); - targetObject.setType(targetType); - targetObject.setValue(targetValue); - mis.setTarget(targetObject); - - mis.setOAFriendlyName(oaFriendlyName); - - Filters filterObject = new Filters(); - MandateIdentifiers mandateIds = new MandateIdentifiers(); - for(String current : filters.split(",")) - mandateIds.getMandateIdentifier().add(current.trim()); - filterObject.setMandateIdentifiers(mandateIds); - mis.setFilters(filterObject); - - request.setMIS(mis); - } - - Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); - CreateIdentityLinkResponse response = client.sentCreateIDLRequest(request , connectionParameters.getUrl()); - return response; - - } - catch (ConfigurationException e) { - Logger.warn(e); - Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null )); - } - - return null; - - } - - /** - * Does the request to the SZR-GW. - * - * @param signature the signature - * @return the identity link - * @throws SZRGWClientException the sZRGW client exception - * @throws ConfigurationException the configuration exception - */ - public CreateIdentityLinkResponse getIdentityLink(Element signature) throws SZRGWClientException, ConfigurationException { - return getIdentityLink(null, null, null, null, XMLHelper.nodeToString(signature)); - } - - /** - * Does the request to the SZR-GW. - * - * @param PEPSIdentifier the pEPS identifier - * @param PEPSFirstname the pEPS firstname - * @param PEPSFamilyname the pEPS familyname - * @param PEPSDateOfBirth the pEPS date of birth - * @param signature XMLDSIG signature - * @return Identity link assertion - * @throws SZRGWClientException the sZRGW client exception - * @throws ConfigurationException the configuration exception - */ - public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String signature) throws SZRGWClientException { - return getIdentityLink(PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, null, signature, null, null, null, null, null, null, null); - } - - /** - * Gets the identity link. - * - * @param citizenSignature the citizen signature - * @param representative the representative - * @param represented the represented - * @param mandate the mandate - * @param organizationAddress the organization address - * @param organizationType the organization type - * @return the identity link - * @throws SZRGWClientException - */ - public CreateIdentityLinkResponse getIdentityLink(String citizenSignature, - String representative, String represented, String mandateContent, - String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { - return getIdentityLink(null, null, null, null, null, - citizenSignature, represented, representative, mandateContent, organizationAddress, - organizationType, targetType, targetValue, oaFriendlyName, filters); - } - - /** - * SZR-GW Client interface. - * - * @param eIdentifier the e identifier - * @param givenName the given name - * @param lastName the last name - * @param dateOfBirth the date of birth - * @param citizenSignature the citizen signature - * @param representative the representative - * @param represented the represented - * @param mandate the mandate - * @return the identity link - * @throws SZRGWClientException the sZRGW client exception - */ - public CreateIdentityLinkResponse getIdentityLink(String eIdentifier, - String givenName, String lastName, String dateOfBirth, String gender, - String citizenSignature, String representative, String represented, - String mandate, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { - return getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, gender, - citizenSignature, representative, represented, mandate, null, - null, targetType, targetValue, oaFriendlyName, filters); - } - - /** - * 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 = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); - if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() }); - - //Start of STORK Processing - STORKConfig storkConfig = AuthConfigurationProvider.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 acsURL = HTTPUtils.getBaseURL(req) + PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; - Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL); - - String providerName= oaParam.getFriendlyName(); - String issuerValue = HTTPUtils.getBaseURL(req); - Logger.debug("Issuer value: " + issuerValue); - - // prepare collection of required attributes - // - attributes for online application - List<OAStorkAttribute> 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 = currentGlobalAttribute.isMandatory(); - break; - } - - newAttribute.setIsRequired(current.isMandatory() || globallyMandatory); - attributeList.add(newAttribute); - } - - // add sign request - PersonalAttribute newAttribute = new PersonalAttribute(); - newAttribute.setName("signedDoc"); - List<String> value = new ArrayList<String>(); - 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); - - - 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"; - - //generate AuthnRquest - STORKAuthnRequest authnRequest = new STORKAuthnRequest(); - authnRequest.setDestination(destination); - authnRequest.setAssertionConsumerServiceURL(acsURL); - authnRequest.setProviderName(providerName); - authnRequest.setIssuer(issuerValue); - authnRequest.setQaa(oaParam.getQaaLevel()); - authnRequest.setSpInstitution(spInstitution); - authnRequest.setCountry(spCountry); - authnRequest.setSpApplication(spApplication); - authnRequest.setSpSector(spSector); - authnRequest.setPersonalAttributeList(attributeList); - - authnRequest.setEIDCrossBorderShare(true); - authnRequest.setEIDCrossSectorShare(true); - authnRequest.setEIDSectorShare(true); - - authnRequest.setCitizenCountryCode(moasession.getCcc()); - - - Logger.debug("STORK AuthnRequest succesfully assembled."); - - STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("outgoing"); - 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); - HttpSession httpSession = req.getSession(); - httpSession.setAttribute("MOA-Session-ID", moasession.getSessionID()); - - - 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("action", destination); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - resp.getOutputStream().write(writer.toString().getBytes()); - } catch (Exception e) { - Logger.error("Error sending STORK SAML AuthnRequest.", e); - httpSession.invalidate(); - throw new MOAIDException("stork.02", new Object[] { destination }); - } - - Logger.info("STORK AuthnRequest successfully successfully prepared for client with target location: " + authnRequest.getDestination()); - } - - private static String generateDssSignRequest(String text, String mimeType, String citizenCountry) { - IdentifierGenerator idGenerator; - try { - idGenerator = new SecureRandomIdentifierGenerator(); - - DocumentType doc = new DocumentType(); - doc.setBase64XML(text.getBytes()); - 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 - * @param signedXML XML signature element - * @return X509Certificate - * @throws CertificateException - */ - public static X509Certificate getCertificateFromXML(Element signedXML) throws CertificateException { - - NodeList nList = signedXML.getElementsByTagNameNS(Constants.DSIG_NS_URI, "X509Certificate"); - - String base64CertString = XMLUtil.getFirstTextValueFromNodeList(nList); - - if (StringUtils.isEmpty(base64CertString)) { - String msg = "XML does not contain a X509Certificate element."; - Logger.error(msg); - throw new CertificateException(msg); - } - - InputStream is = new ByteArrayInputStream(Base64.decode(base64CertString)); - - X509Certificate cert; - try { - cert = new X509Certificate(is); - return cert; - - } catch (Throwable e) { - throw new CertificateException(e); - } - } + //build CertInfo request + String certInfoRequest = new CertInfoVerifyXMLSignatureRequestBuilder() + .build(); + String certInfoDataURL = new DataURLBuilder() + .buildDataURL(session.getAuthURL(), REQ_START_AUTHENTICATION, + session.getSessionID()); + + //get Applet Parameters + String appletwidth = req.getParameter(PARAM_APPLET_WIDTH); + String appletheigth = req.getParameter(PARAM_APPLET_HEIGTH); + appletheigth = StringEscapeUtils.escapeHtml(appletheigth); + appletwidth = StringEscapeUtils.escapeHtml(appletwidth); + + String htmlForm = new GetIdentityLinkFormBuilder().build(template, + session.getBkuURL(), infoboxReadRequest, dataURL, certInfoRequest, + certInfoDataURL, pushInfobox, oaParam, appletheigth, appletwidth); + + return htmlForm; + } + + /** + * Processes an <code><InfoboxReadResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><InfoboxReadResponse></code></li> + * <li>Parses identity link enclosed in + * <code><InfoboxReadResponse></code></li> + * <li>Verifies identity link by calling the MOA SP component</li> + * <li>Checks certificate authority of identity link</li> + * <li>Stores identity link in the session</li> + * <li>Verifies all additional infoboxes returned from the BKU</li> + * <li>Creates an authentication block to be signed by the user</li> + * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> + * containg the authentication block, meant to be returned to the security + * layer implementation</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param infoboxReadResponseParameters The parameters from the response returned from the BKU + * including the <code><InfoboxReadResponse></code> + * @return String representation of the + * <code><CreateXMLSignatureRequest></code> + * @throws BKUException + */ + public String verifyIdentityLink(AuthenticationSession session, + Map<String, String> infoboxReadResponseParameters) throws AuthenticationException, + BuildException, ParseException, ConfigurationException, + ValidateException, ServiceException, BKUException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_IDENTITY_LINK, PARAM_SESSIONID}); + + String xmlInfoboxReadResponse = (String) infoboxReadResponseParameters + .get(PARAM_XMLRESPONSE); + + if (isEmpty(xmlInfoboxReadResponse)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_IDENTITY_LINK, PARAM_XMLRESPONSE}); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + + // check if an identity link was found + // Errorcode 2911 von Trustdesk BKU (nicht spezifikationskonform + // (SL1.2)) + // CharSequence se = "ErrorCode>2911".substring(0); + // boolean b = xmlInfoboxReadResponse.contains(se); + String se = "ErrorCode>2911"; + int b = xmlInfoboxReadResponse.indexOf(se); + if (b != -1) { // no identity link found + Logger + .info("Es konnte keine Personenbindung auf der Karte gefunden werden. Versuche Anmeldung als auslaendische eID."); + return null; + } + // spezifikationsgemaess (SL1.2) Errorcode + se = "ErrorCode>4002"; + // b = xmlInfoboxReadResponse.contains(se); + b = xmlInfoboxReadResponse.indexOf(se); + if (b != -1) { // Unbekannter Infoboxbezeichner + Logger + .info("Unbekannter Infoboxbezeichner. Versuche Anmeldung als auslaendische eID."); + return null; + } + + // parses the <InfoboxReadResponse> + IdentityLink identityLink = new InfoboxReadResponseParser( + xmlInfoboxReadResponse).parseIdentityLink(); + // validates the identity link + IdentityLinkValidator.getInstance().validate(identityLink); + // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP + Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() + .build(identityLink, authConf + .getMoaSpIdentityLinkTrustProfileID()); + + // invokes the call + Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() + .verifyXMLSignature(domVerifyXMLSignatureRequest); + // parses the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( + domVerifyXMLSignatureResponse).parseData(); + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + // if OA is type is business service the manifest validation result has + // to be ignored + boolean ignoreManifestValidationResult = (oaParam.getBusinessService() || oaParam.getStorkService()) ? true + : false; + + // validates the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponseValidator.getInstance().validate( + verifyXMLSignatureResponse, + authConf.getIdentityLinkX509SubjectNames(), + VerifyXMLSignatureResponseValidator.CHECK_IDENTITY_LINK, + ignoreManifestValidationResult); + + session.setIdentityLink(identityLink); + // now validate the extended infoboxes + + //Removed in MOA-ID 2.0 + //verifyInfoboxes(session, infoboxReadResponseParameters, false); + + return "found!"; + } + + /** + * Processes an <code><InfoboxReadResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><InfoboxReadResponse></code></li> + * <li>Parses identity link enclosed in + * <code><InfoboxReadResponse></code></li> + * <li>Verifies identity link by calling the MOA SP component</li> + * <li>Checks certificate authority of identity link</li> + * <li>Stores identity link in the session</li> + * <li>Verifies all additional infoboxes returned from the BKU</li> + * <li>Creates an authentication block to be signed by the user</li> + * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> + * containg the authentication block, meant to be returned to the security + * layer implementation</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param infoboxReadResponseParameters The parameters from the response returned from the BKU + * including the <code><InfoboxReadResponse></code> + * @return String representation of the + * <code><CreateXMLSignatureRequest></code> + */ + public String verifyCertificate(AuthenticationSession session, + X509Certificate certificate) throws AuthenticationException, + BuildException, ParseException, ConfigurationException, + ValidateException, ServiceException, MOAIDException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID}); + + // check if person is a Organwalter + // if true - don't show bPK in AUTH Block + try { + for (ObjectID OWid : MOAIDAuthConstants.OW_LIST) { + if (certificate.getExtension(OWid) != null) { + session.setOW(true); + } + + } + + } catch (X509ExtensionInitException e) { + Logger.warn("Certificate extension is not readable."); + session.setOW(false); + } + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + String returnvalue = getCreateXMLSignatureRequestAuthBlockOrRedirect(session, + authConf, oaParam); + + return returnvalue; + } + + /** + * Processes an <code>Mandate</code> sent by the MIS.<br> + * <ul> + * <li>Validates given <code>Mandate</code></li> + * <li>Verifies Mandate by calling the MOA SP component</li> + * <li>Creates an authentication block to be signed by the user</li> + * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> + * containg the authentication block, meant to be returned to the security + * layer implementation</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param infoboxReadResponseParameters The parameters from the response returned from the BKU + * including the <code><InfoboxReadResponse></code> + * @return String representation of the + * <code><CreateXMLSignatureRequest></code> + */ + public void verifyMandate(AuthenticationSession session, MISMandate mandate) + throws AuthenticationException, BuildException, ParseException, + ConfigurationException, ValidateException, ServiceException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + GET_MIS_SESSIONID, PARAM_SESSIONID}); + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + try { + // sets the extended SAML attributes for OID (Organwalter) + setExtendedSAMLAttributeForMandatesOID(session, mandate, oaParam + .getBusinessService()); + + validateExtendedSAMLAttributeForMandates(session, mandate, oaParam.getBusinessService()); + + + } catch (SAXException e) { + throw new AuthenticationException("auth.16", + new Object[]{GET_MIS_SESSIONID}, e); + } catch (IOException e) { + throw new AuthenticationException("auth.16", + new Object[]{GET_MIS_SESSIONID}, e); + } catch (ParserConfigurationException e) { + throw new AuthenticationException("auth.16", + new Object[]{GET_MIS_SESSIONID}, e); + } catch (TransformerException e) { + throw new AuthenticationException("auth.16", + new Object[]{GET_MIS_SESSIONID}, e); + } + + } + + /** + * @param session + * @param authConf + * @param oaParam + * @return + * @throws ConfigurationException + * @throws BuildException + * @throws ValidateException + */ + public String getCreateXMLSignatureRequestAuthBlockOrRedirect( + AuthenticationSession session, AuthConfigurationProvider authConf, + OAAuthParameter oaParam) throws ConfigurationException, + BuildException, ValidateException { + + // check for intermediate processing of the infoboxes + if (session.isValidatorInputPending()) + return "Redirect to Input Processor"; + + if (authConf == null) + authConf = AuthConfigurationProvider.getInstance(); + if (oaParam == null) + oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + + // builds the AUTH-block + String authBlock = buildAuthenticationBlock(session, oaParam); + + // builds the <CreateXMLSignatureRequest> + List<String> transformsInfos = oaParam.getTransformsInfos(); + if ((transformsInfos == null) || (transformsInfos.size() == 0)) { + // no OA specific transforms specified, use default ones + transformsInfos = authConf.getTransformsInfos(); + } + String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() + .build(authBlock, oaParam.getKeyBoxIdentifier(), + transformsInfos); + return createXMLSignatureRequest; + } + + /** + * Returns an CreateXMLSignatureRequest for signing the ERnP statement.<br> + * <ul> + * <li>Creates an CreateXMLSignatureRequest to be signed by the user</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param cert The certificate from the user + * @return String representation of the + * <code><CreateXMLSignatureRequest></code> + */ + public String createXMLSignatureRequestForeignID(AuthenticationSession session, + X509Certificate cert) throws AuthenticationException, + BuildException, ParseException, ConfigurationException, + ValidateException, ServiceException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID}); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + return getCreateXMLSignatureRequestForeigID(session, authConf, oaParam, + cert); + } + + public String getCreateXMLSignatureRequestForeigID( + AuthenticationSession session, AuthConfigurationProvider authConf, + OAAuthParameter oaParam, X509Certificate cert) + throws ConfigurationException { + + // check for intermediate processing of the infoboxes + if (session.isValidatorInputPending()) + return "Redirect to Input Processor"; + + if (authConf == null) + authConf = AuthConfigurationProvider.getInstance(); + if (oaParam == null) + oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + + Principal subject = cert.getSubjectDN(); + + String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() + .buildForeignID(subject.toString(), oaParam, session); + return createXMLSignatureRequest; + } + + /** + * Processes an <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses response enclosed in + * <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies signature by calling the MOA SP component</li> + * <li>Returns the signer certificate</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param createXMLSignatureResponseParameters The parameters from the response returned from the BKU + * including the <code><CreateXMLSignatureResponse></code> + * @throws BKUException + */ + public X509Certificate verifyXMLSignature(String sessionID, + Map<String, String> createXMLSignatureResponseParameters) + throws AuthenticationException, BuildException, ParseException, + ConfigurationException, ValidateException, ServiceException, BKUException { + + if (isEmpty(sessionID)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_GET_FOREIGN_ID, PARAM_SESSIONID}); + + String xmlCreateXMLSignatureResponse = (String) createXMLSignatureResponseParameters + .get(PARAM_XMLRESPONSE); + + if (isEmpty(xmlCreateXMLSignatureResponse)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_GET_FOREIGN_ID, PARAM_XMLRESPONSE}); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + + // parses the <CreateXMLSignatureResponse> + CreateXMLSignatureResponseParser p = new CreateXMLSignatureResponseParser( + xmlCreateXMLSignatureResponse); + CreateXMLSignatureResponse createXMLSignatureResponse = p + .parseResponseDsig(); + + // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP + Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() + .buildDsig(createXMLSignatureResponse, authConf + .getMoaSpAuthBlockTrustProfileID()); + + // invokes the call + Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() + .verifyXMLSignature(domVerifyXMLSignatureRequest); + + // parses the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( + domVerifyXMLSignatureResponse).parseData(); + + return verifyXMLSignatureResponse.getX509certificate(); + + } + + /** + * Processes an <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses response enclosed in + * <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies signature by calling the MOA SP component</li> + * <li>Returns the signer certificate</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param readInfoboxResponseParameters The parameters from the response returned from the BKU + * including the <code><ReadInfoboxResponse></code> + * @throws BKUException + */ + public X509Certificate getCertificate(String sessionID, + Map<String, String> readInfoboxResponseParameters) throws AuthenticationException, + BuildException, ParseException, ConfigurationException, + ValidateException, ServiceException, BKUException { + + if (isEmpty(sessionID)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID}); + + String xmlReadInfoboxResponse = (String) readInfoboxResponseParameters + .get(PARAM_XMLRESPONSE); + + if (isEmpty(xmlReadInfoboxResponse)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_CERTIFICATE, PARAM_XMLRESPONSE}); + + // parses the <CreateXMLSignatureResponse> + InfoboxReadResponseParser p = new InfoboxReadResponseParser( + xmlReadInfoboxResponse); + X509Certificate cert = p.parseCertificate(); + + return cert; + + } + + /** + * Builds an authentication block <code><saml:Assertion></code> from + * given session data. + * + * @param session authentication session + * @return <code><saml:Assertion></code> as a String + * @throws BuildException If an error occurs on serializing an extended SAML attribute + * to be appended to the AUTH-Block. + */ + private String buildAuthenticationBlock(AuthenticationSession session, + OAAuthParameter oaParam) throws BuildException { + + IdentityLink identityLink = session.getIdentityLink(); + String issuer = identityLink.getName(); + String gebDat = identityLink.getDateOfBirth(); + + String identificationValue = null; + String identificationType = null; + + //set empty AuthBlock BPK in case of OW or SSO or bpk is not requested + if (session.isOW() || session.isSsoRequested() || oaParam.isRemovePBKFromAuthBlock()) { + identificationType = ""; + identificationValue = ""; + + } else if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + + if (oaParam.getBusinessService()) { + + String bpkBase64 = new BPKBuilder().buildWBPK(identityLink + .getIdentificationValue(), oaParam.getIdentityLinkDomainIdentifier()); + identificationValue = bpkBase64; + + if (oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_WBPK + "+")) + identificationType = oaParam.getIdentityLinkDomainIdentifier(); + else + identificationType = Constants.URN_PREFIX_WBPK + "+" + oaParam.getIdentityLinkDomainIdentifier(); + + } else { + String bpkBase64 = new BPKBuilder().buildBPK(identityLink + .getIdentificationValue(), session.getTarget()); + identificationValue = bpkBase64; + identificationType = Constants.URN_PREFIX_CDID + "+" + session.getTarget(); + } + + + } else { + identificationValue = identityLink.getIdentificationValue(); + identificationType = identityLink.getIdentificationType(); + + } + + String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar + .getInstance()); + session.setIssueInstant(issueInstant); + String authURL = session.getAuthURL(); + String target = session.getTarget(); + String targetFriendlyName = session.getTargetFriendlyName(); + + // Bug #485 + // (https://egovlabs.gv.at/tracker/index.php?func=detail&aid=485&group_id=6&atid=105) + // String oaURL = session.getPublicOAURLPrefix(); + + List<ExtendedSAMLAttribute> extendedSAMLAttributes = session.getExtendedSAMLAttributesAUTH(); + + + if (session.isSsoRequested()) { + String oaURL = new String(); + try { + oaURL = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); + + if (MiscUtil.isNotEmpty(oaURL)) + oaURL = oaURL.replaceAll("&", "&"); + + } catch (ConfigurationException e) { + } + String authBlock = new AuthenticationBlockAssertionBuilder() + .buildAuthBlockSSO(issuer, issueInstant, authURL, target, + targetFriendlyName, identificationValue, + identificationType, oaURL, gebDat, + extendedSAMLAttributes, session, oaParam); + return authBlock; + + } else { + String oaURL = session.getPublicOAURLPrefix().replaceAll("&", "&"); + String authBlock = new AuthenticationBlockAssertionBuilder() + .buildAuthBlock(issuer, issueInstant, authURL, target, + targetFriendlyName, identificationValue, + identificationType, oaURL, gebDat, + extendedSAMLAttributes, session, oaParam); + return authBlock; + } + } + + + /** + * Verifies the infoboxes (except of the identity link infobox) returned by + * the BKU by calling appropriate validator classes. + * + * @param session The actual authentication session. + * @param mandate The Mandate from the MIS + * @throws AuthenticationException + * @throws ConfigurationException + * @throws TransformerException + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + */ + private void validateExtendedSAMLAttributeForMandates( + AuthenticationSession session, MISMandate mandate, + boolean business) + throws ValidateException, ConfigurationException, SAXException, + IOException, ParserConfigurationException, TransformerException { + + ExtendedSAMLAttribute[] extendedSAMLAttributes = addExtendedSamlAttributes( + mandate, business, false); + + int length = extendedSAMLAttributes.length; + for (int i = 0; i < length; i++) { + ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i]; + + verifySAMLAttribute(samlAttribute, i, "MISService", + "MISService"); + + } + } + + /** + * Verifies the infoboxes (except of the identity link infobox) returned by + * the BKU by calling appropriate validator classes. + * + * @param session The actual authentication session. + * @param mandate The Mandate from the MIS + * @throws AuthenticationException + * @throws ConfigurationException + * @throws TransformerException + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + */ + private void setExtendedSAMLAttributeForMandatesOID( + AuthenticationSession session, MISMandate mandate, boolean business) + throws ValidateException, ConfigurationException, SAXException, + IOException, ParserConfigurationException, TransformerException { + + ExtendedSAMLAttribute[] extendedSamlAttributes = addExtendedSamlAttributesOID( + mandate, business); + + AddAdditionalSAMLAttributes(session, extendedSamlAttributes, + "MISService", "MISService"); + + } + + /** + * Adds given SAML Attributes to the current session. They will be appended + * to the final SAML Assertion or the AUTH block. If the attributes are + * already in the list, they will be replaced. + * + * @param session The current session + * @param extendedSAMLAttributes The SAML attributes to add + * @param identifier The infobox identifier for debug purposes + * @param friendlyNam The friendly name of the infobox for debug purposes + */ + private static void AddAdditionalSAMLAttributes( + AuthenticationSession session, + ExtendedSAMLAttribute[] extendedSAMLAttributes, String identifier, + String friendlyName) throws ValidateException { + if (extendedSAMLAttributes == null) + return; + List<ExtendedSAMLAttribute> oaAttributes = session.getExtendedSAMLAttributesOA(); + if (oaAttributes == null) + oaAttributes = new Vector<ExtendedSAMLAttribute>(); + List<ExtendedSAMLAttribute> authAttributes = session.getExtendedSAMLAttributesAUTH(); + if (authAttributes == null) + authAttributes = new Vector<ExtendedSAMLAttribute>(); + int length = extendedSAMLAttributes.length; + for (int i = 0; i < length; i++) { + ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i]; + + Object value = verifySAMLAttribute(samlAttribute, i, identifier, + friendlyName); + + if ((value instanceof String) || (value instanceof Element)) { + switch (samlAttribute.getAddToAUTHBlock()) { + case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY: + replaceExtendedSAMLAttribute(authAttributes, samlAttribute); + break; + case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK: + replaceExtendedSAMLAttribute(authAttributes, samlAttribute); + replaceExtendedSAMLAttribute(oaAttributes, samlAttribute); + break; + case ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK: + replaceExtendedSAMLAttribute(oaAttributes, samlAttribute); + break; + default: + Logger + .info("Invalid return value from method \"getAddToAUTHBlock()\" (" + + samlAttribute.getAddToAUTHBlock() + + ") in SAML attribute number " + + (i + 1) + + " for infobox " + identifier); + throw new ValidateException("validator.47", new Object[]{ + friendlyName, String.valueOf((i + 1))}); + } + } else { + Logger + .info("The type of SAML-Attribute number " + + (i + 1) + + " returned from " + + identifier + + "-infobox validator is not valid. Must be either \"java.Lang.String\"" + + " or \"org.w3c.dom.Element\""); + throw new ValidateException("validator.46", new Object[]{ + identifier, String.valueOf((i + 1))}); + } + } + session.setExtendedSAMLAttributesAUTH(authAttributes); + session.setExtendedSAMLAttributesOA(oaAttributes); + } + + /** + * Adds the AUTH block related SAML attributes to the validation result. + * This is needed always before the AUTH block is to be signed, because the + * name of the mandator has to be set + * + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws TransformerException + */ + + protected static ExtendedSAMLAttribute[] addExtendedSamlAttributes( + MISMandate mandate, boolean business, boolean provideStammzahl) + throws SAXException, IOException, ParserConfigurationException, + TransformerException { + Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>(); + + extendedSamlAttributes.clear(); + + // Name + Element domMandate = mandateToElement(mandate); + Element nameSpaceNode = domMandate.getOwnerDocument().createElement( + "NameSpaceNode"); + nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, + Constants.PD_NS_URI); + nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.MANDATE_POSTFIX, + SZRGWConstants.MANDATE_NS); + + Element mandator = (Element) XPathAPI.selectSingleNode(domMandate, + "//md:Mandate/md:Mandator", nameSpaceNode); + + // Mandate + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_RAW, domMandate, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); + + // (w)bpk + String wbpk = ParepUtils.extractMandatorWbpk(mandator); + if (!ParepUtils.isEmpty(wbpk)) { + if (!ParepUtils.isPhysicalPerson(mandator)) { + String idType = ParepUtils + .extractMandatorIdentificationType(mandator); + if (!ParepUtils.isEmpty(idType) + && idType.startsWith(Constants.URN_PREFIX_BASEID)) { + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_CB_BASE_ID, + ParepUtils.getRegisterString(idType) + ": " + wbpk, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY)); + } + } else if (business) { + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_WBPK, wbpk, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY)); + } + } + + ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes + .size()]; + extendedSamlAttributes.copyInto(ret); + Logger.debug("ExtendedSAML Attributes: " + ret.length); + return ret; + + } + + /** + * Adds the AUTH block related SAML attributes to the validation result. + * This is needed always before the AUTH block is to be signed, because the + * name of the mandator has to be set + * + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws TransformerException + */ + private static ExtendedSAMLAttribute[] addExtendedSamlAttributesOID( + MISMandate mandate, boolean business) throws SAXException, + IOException, ParserConfigurationException, TransformerException { + + Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>(); + + extendedSamlAttributes.clear(); + + // RepresentationType + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_REPRESENTATIONTYPE, + EXT_SAML_MANDATE_REPRESENTATIONTEXT, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); + + String oid = mandate.getProfRep(); + + if (oid != null) { + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_OID, oid, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); + String oidDescription = mandate.getTextualDescriptionOfOID(); + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION, + oidDescription, SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); + + } + + ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes + .size()]; + extendedSamlAttributes.copyInto(ret); + Logger.debug("ExtendedSAML Attributes: " + ret.length); + return ret; + + } + + /** + * @param mandate + * @return + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + */ + private static Element mandateToElement(MISMandate mandate) + throws SAXException, IOException, ParserConfigurationException { + ByteArrayInputStream bais = new ByteArrayInputStream(mandate + .getMandate()); + Document doc = DOMUtils.parseDocumentSimple(bais); + return doc.getDocumentElement(); + } + + protected static void replaceExtendedSAMLAttribute(List<ExtendedSAMLAttribute> attributes, + ExtendedSAMLAttribute samlAttribute) { + if (null == attributes) { + attributes = new Vector<ExtendedSAMLAttribute>(); + } else { + String id = samlAttribute.getName(); + int length = attributes.size(); + for (int i = 0; i < length; i++) { + ExtendedSAMLAttribute att = (ExtendedSAMLAttribute) attributes + .get(i); + if (id.equals(att.getName())) { + // replace attribute + attributes.set(i, samlAttribute); + return; + } + } + attributes.add(samlAttribute); + } + } + + /** + * Processes a <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses <code><CreateXMLSignatureResponse></code> for error + * codes</li> + * <li>Parses authentication block enclosed in + * <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies authentication block by calling the MOA SP component</li> + * <li>Creates authentication data</li> + * <li>Creates a corresponding SAML artifact</li> + * <li>Stores authentication data in the authentication data store indexed + * by the SAML artifact</li> + * <li>Deletes authentication session</li> + * <li>Returns the SAML artifact, encoded BASE64</li> + * </ul> + * + * @param sessionID session ID of the running authentication session + * @param xmlCreateXMLSignatureReadResponse String representation of the + * <code><CreateXMLSignatureResponse></code> + * @return SAML artifact needed for retrieving authentication data, encoded + * BASE64 + * @throws BKUException + */ + public String verifyAuthenticationBlock(AuthenticationSession session, + String xmlCreateXMLSignatureReadResponse) + throws AuthenticationException, BuildException, ParseException, + ConfigurationException, ServiceException, ValidateException, BKUException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID}); + if (isEmpty(xmlCreateXMLSignatureReadResponse)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + // parses <CreateXMLSignatureResponse> + CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser( + xmlCreateXMLSignatureReadResponse).parseResponse(); + + try { + String serializedAssertion = DOMUtils.serializeNode(csresp + .getSamlAssertion()); + 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}); + } + // validates <CreateXMLSignatureResponse> + if (session.isSsoRequested()) + new CreateXMLSignatureResponseValidator().validateSSO(csresp, session); + else + new CreateXMLSignatureResponseValidator().validate(csresp, session); + + // builds a <VerifyXMLSignatureRequest> for a MOA-SPSS call + List<String> vtids = authConf.getMoaSpAuthBlockVerifyTransformsInfoIDs(); + String tpid = authConf.getMoaSpAuthBlockTrustProfileID(); + Element domVsreq = new VerifyXMLSignatureRequestBuilder().build(csresp, + vtids, tpid); + // debug output + + // invokes the call + Element domVsresp = new SignatureVerificationInvoker() + .verifyXMLSignature(domVsreq); + // debug output + + // parses the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponseParser( + domVsresp).parseData(); + + if (Logger.isTraceEnabled()) { + if (domVsresp != null) { + try { + String xmlVerifyXMLSignatureResponse = DOMUtils + .serializeNode(domVsresp, true); + Logger.trace(new LogMsg(xmlCreateXMLSignatureReadResponse)); + Logger.trace(new LogMsg(xmlVerifyXMLSignatureResponse)); + } catch (Throwable t) { + t.printStackTrace(); + Logger.info(new LogMsg(t.getStackTrace())); + } + } + } + + // validates the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponseValidator.getInstance().validate(vsresp, + null, VerifyXMLSignatureResponseValidator.CHECK_AUTH_BLOCK, + false); + + // Compare AuthBlock Data with information stored in session, especially + // date and time + CreateXMLSignatureResponseValidator.getInstance().validateSigningDateTime(csresp); + + // compares the public keys from the identityLink with the AuthBlock + VerifyXMLSignatureResponseValidator.getInstance().validateCertificate( + vsresp, session.getIdentityLink()); + + // post processing of the infoboxes + Iterator iter = session.getInfoboxValidatorIterator(); + boolean formpending = false; + if (iter != null) { + while (!formpending && iter.hasNext()) { + Vector infoboxValidatorVector = (Vector) iter.next(); + String identifier = (String) infoboxValidatorVector.get(0); + String friendlyName = (String) infoboxValidatorVector.get(1); + InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector + .get(2); + InfoboxValidationResult infoboxValidationResult = null; + try { + infoboxValidationResult = infoboxvalidator.validate(csresp + .getSamlAssertion()); + } catch (ValidateException e) { + Logger.error("Error validating " + identifier + " infobox:" + + e.getMessage()); + throw new ValidateException("validator.44", + new Object[]{friendlyName}); + } + if (!infoboxValidationResult.isValid()) { + Logger.info("Validation of " + identifier + + " infobox failed."); + throw new ValidateException("validator.40", new Object[]{ + friendlyName, + infoboxValidationResult.getErrorMessage()}); + } + String form = infoboxvalidator.getForm(); + if (ParepUtils.isEmpty(form)) { + AddAdditionalSAMLAttributes( + session, + infoboxValidationResult.getExtendedSamlAttributes(), + identifier, friendlyName); + } else { + return "Redirect to Input Processor"; + } + } + } + + session.setXMLVerifySignatureResponse(vsresp); + session.setSignerCertificate(vsresp.getX509certificate()); + vsresp.setX509certificate(null); + session.setForeigner(false); + + if (session.getUseMandate()) { + // mandate mode + return null; + + } else { + + 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 implicte stored in changeSessionID!!! + String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); + Logger.info("Daten angelegt zu MOASession " + newMOASessionID); + + return newMOASessionID; + } + } + + /** + * Processes a <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses <code><CreateXMLSignatureResponse></code> for error + * codes</li> + * <li>Parses authentication block enclosed in + * <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies authentication block by calling the MOA SP component</li> + * <li>Creates authentication data</li> + * <li>Creates a corresponding SAML artifact</li> + * <li>Stores authentication data in the authentication data store indexed + * by the SAML artifact</li> + * <li>Deletes authentication session</li> + * <li>Returns the SAML artifact, encoded BASE64</li> + * </ul> + * + * @param sessionID session ID of the running authentication session + * @param xmlCreateXMLSignatureReadResponse String representation of the + * <code><CreateXMLSignatureResponse></code> + * @return SAML artifact needed for retrieving authentication data, encoded + * BASE64 + */ + + protected Element createIdentificationBPK(Element mandatePerson, + String baseid, String target) throws BuildException { + Element identificationBpK = mandatePerson.getOwnerDocument() + .createElementNS(Constants.PD_NS_URI, "Identification"); + Element valueBpK = mandatePerson.getOwnerDocument().createElementNS( + Constants.PD_NS_URI, "Value"); + + String bpkBase64 = new BPKBuilder().buildBPK(baseid, target); + valueBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( + bpkBase64)); + Element typeBpK = mandatePerson.getOwnerDocument().createElementNS( + Constants.PD_NS_URI, "Type"); + typeBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( + "urn:publicid:gv.at:cdid+bpk")); + identificationBpK.appendChild(valueBpK); + identificationBpK.appendChild(typeBpK); + + return identificationBpK; + + } + + protected String getBaseId(Element mandatePerson) + throws TransformerException, IOException { + NodeList list = mandatePerson.getElementsByTagNameNS( + Constants.PD_NS_URI, "Identification"); + for (int i = 0; i < list.getLength(); i++) { + Element identification = (Element) list.item(i); + Element type = (Element) identification.getElementsByTagNameNS( + Constants.PD_NS_URI, "Type").item(0); + if (type.getTextContent().compareToIgnoreCase( + "urn:publicid:gv.at:baseid") == 0) { + Element value = (Element) identification + .getElementsByTagNameNS(Constants.PD_NS_URI, "Value") + .item(0); + return value.getTextContent(); + } + } + return null; + + } + + /** + * Gets the foreign authentication data.<br> + * <ul> + * <li>Creates authentication data</li> + * <li>Creates a corresponding SAML artifact</li> + * <li>Stores authentication data in the authentication data store indexed + * by the SAML artifact</li> + * <li>Deletes authentication session</li> + * <li>Returns the SAML artifact, encoded BASE64</li> + * </ul> + * + * @param sessionID session ID of the running authentication session + * @return SAML artifact needed for retrieving authentication data, encoded + * BASE64 + */ + public String getForeignAuthenticationData(AuthenticationSession session) + throws AuthenticationException, BuildException, ParseException, + ConfigurationException, ServiceException, ValidateException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID}); + + // post processing of the infoboxes + Iterator iter = session.getInfoboxValidatorIterator(); + boolean formpending = false; + if (iter != null) { + while (!formpending && iter.hasNext()) { + Vector infoboxValidatorVector = (Vector) iter.next(); + String identifier = (String) infoboxValidatorVector.get(0); + String friendlyName = (String) infoboxValidatorVector.get(1); + InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector + .get(2); + InfoboxValidationResult infoboxValidationResult = null; + try { + infoboxValidationResult = infoboxvalidator.validate(session + .getIdentityLink().getSamlAssertion()); + } catch (ValidateException e) { + Logger.error("Error validating " + identifier + " infobox:" + + e.getMessage()); + throw new ValidateException("validator.44", + new Object[]{friendlyName}); + } + if (!infoboxValidationResult.isValid()) { + Logger.info("Validation of " + identifier + + " infobox failed."); + throw new ValidateException("validator.40", new Object[]{ + friendlyName, + infoboxValidationResult.getErrorMessage()}); + } + String form = infoboxvalidator.getForm(); + if (ParepUtils.isEmpty(form)) { + AddAdditionalSAMLAttributes( + session, + infoboxValidationResult.getExtendedSamlAttributes(), + identifier, friendlyName); + } else { + return "Redirect to Input Processor"; + } + } + } + + VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponse(); + X509Certificate cert = session.getSignerCertificate(); + vsresp.setX509certificate(cert); + + session.setAuthenticatedUsed(false); + session.setAuthenticated(true); + + + session.setXMLVerifySignatureResponse(vsresp); + session.setSignerCertificate(vsresp.getX509certificate()); + vsresp.setX509certificate(null); + session.setForeigner(true); + + //TODO: regenerate MOASession ID! + return "new Session"; + } + + /** + * Builds the AuthenticationData object together with the corresponding + * <code><saml:Assertion></code> + * + * @param session authentication session + * @param verifyXMLSigResp VerifyXMLSignatureResponse from MOA-SP + * @param useUTC uses correct UTC time format + * @param useUTC indicates that authenticated citizen is a foreigner + * @param isForeigner indicates whether Austrian (false) or foreigner (true) authenticates + * @return AuthenticationData object + * @throws ConfigurationException while accessing configuration data + * @throws BuildException while building the <code><saml:Assertion></code> + */ + public static AuthenticationData buildAuthenticationData( + AuthenticationSession session, OAAuthParameter oaParam, String target) + throws ConfigurationException, BuildException { + + IdentityLink identityLink = session.getIdentityLink(); + AuthenticationData authData = new AuthenticationData(); + + VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); + + boolean businessService = oaParam.getBusinessService(); + + authData.setMajorVersion(1); + authData.setMinorVersion(0); + authData.setAssertionID(Random.nextRandom()); + authData.setIssuer(session.getAuthURL()); + + authData.setIssueInstant(DateTimeUtils.buildDateTimeUTC(Calendar + .getInstance())); + + //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO + authData.setIdentificationValue(identityLink.getIdentificationValue()); + authData.setIdentificationType(identityLink.getIdentificationType()); + + authData.setGivenName(identityLink.getGivenName()); + authData.setFamilyName(identityLink.getFamilyName()); + authData.setDateOfBirth(identityLink.getDateOfBirth()); + authData.setQualifiedCertificate(verifyXMLSigResp + .isQualifiedCertificate()); + authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); + authData.setPublicAuthorityCode(verifyXMLSigResp + .getPublicAuthorityCode()); + authData.setBkuURL(session.getBkuURL()); + + try { + + if (session.getUseMandate() && session.isOW()) { + MISMandate mandate = session.getMISMandate(); + authData.setBPK(mandate.getOWbPK()); + authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); + authData.setIdentityLink(identityLink); + + Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); + + } else { + + if (businessService) { + //since we have foreigner, wbPK is not calculated in BKU + if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + + String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); + + if (registerAndOrdNr.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) { + // If domainIdentifier starts with prefix + // "urn:publicid:gv.at:wbpk+"; remove this prefix + registerAndOrdNr = registerAndOrdNr + .substring(AuthenticationSession.REGISTERANDORDNR_PREFIX_.length()); + Logger.debug("Register and ordernumber prefix stripped off; resulting register string: " + + registerAndOrdNr); + } + + String wbpkBase64 = new BPKBuilder().buildWBPK(identityLink.getIdentificationValue(), registerAndOrdNr); + authData.setBPK(wbpkBase64); + authData.setBPKType(Constants.URN_PREFIX_WBPK + "+" + registerAndOrdNr); + + } else { + authData.setBPK(identityLink.getIdentificationValue()); + authData.setBPKType(identityLink.getIdentificationType()); + + } + + Logger.trace("Authenticate user with wbPK " + authData.getBPK()); + + Element idlassertion = session.getIdentityLink().getSamlAssertion(); + //set bpk/wpbk; + Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); + prIdentification.getFirstChild().setNodeValue(authData.getBPK()); + //set bkp/wpbk type + Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); + prIdentificationType.getFirstChild().setNodeValue(authData.getBPKType()); + + IdentityLinkAssertionParser idlparser = new IdentityLinkAssertionParser(idlassertion); + IdentityLink idl = idlparser.parseIdentityLink(); + authData.setIdentityLink(idl); + + } else { + + if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + // only compute bPK if online application is a public service and we have the Stammzahl + String bpkBase64 = new BPKBuilder().buildBPK(identityLink.getIdentificationValue(), target); + authData.setBPK(bpkBase64); + authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget()); + } + + Logger.trace("Authenticate user with bPK " + authData.getBPK()); + + authData.setIdentityLink(identityLink); + } + } + + return authData; + + } catch (Throwable ex) { + throw new BuildException("builder.00", new Object[]{ + "AuthenticationData", ex.toString()}, ex); + } + } + + /** + * Retrieves a session from the session store. + * + * @param id session ID + * @return <code>AuthenticationSession</code> stored with given session ID, + * <code>null</code> if session ID unknown + */ + public static AuthenticationSession getSession(String id) + throws AuthenticationException { + + AuthenticationSession session; + try { + session = AuthenticationSessionStoreage.getSession(id); + + if (session == null) + throw new AuthenticationException("auth.02", new Object[]{id}); + return session; + + } catch (MOADatabaseException e) { + throw new AuthenticationException("parser.04", new Object[]{id}); + } + } + + /** + * Cleans up expired session and authentication data stores. + */ + public void cleanup() { + long now = new Date().getTime(); + + //clean AuthenticationSessionStore + + AuthenticationSessionStoreage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); + + //clean AssertionStore + AssertionStorage assertionstore = AssertionStorage.getInstance(); + assertionstore.clean(now, authDataTimeOut); + + //clean ExeptionStore + DBExceptionStoreImpl exstore = DBExceptionStoreImpl.getStore(); + exstore.clean(now, authDataTimeOut); + + } + + /** + * Sets the sessionTimeOut. + * + * @param seconds Time out of the session in seconds + */ + public void setSecondsSessionTimeOutCreated(long seconds) { + sessionTimeOutCreated = seconds * 1000; + } + + public void setSecondsSessionTimeOutUpdated(long seconds) { + sessionTimeOutUpdated = seconds * 1000; + } + + /** + * Sets the authDataTimeOut. + * + * @param seconds Time out for signing AuthData in seconds + */ + public void setSecondsAuthDataTimeOut(long seconds) { + authDataTimeOut = seconds * 1000; + } + + /** + * 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; + } + + /** + * Checks the correctness of SAML attributes and returns its value. + * + * @param param samlAttribute + * @param i the number of the verified attribute for messages + * @param identifier the infobox identifier for messages + * @param friendlyname the friendly name of the infobox for messages + * @return the SAML attribute value (Element or String) + */ + protected static Object verifySAMLAttribute( + ExtendedSAMLAttribute samlAttribute, int i, String identifier, + String friendlyName) throws ValidateException { + String name = samlAttribute.getName(); + + if (name == null) { + Logger.info("The name of SAML-Attribute number " + (i + 1) + + " returned from " + identifier + + "-infobox validator is null."); + throw new ValidateException("validator.45", new Object[]{ + friendlyName, "Name", String.valueOf((i + 1)), "null"}); + } + if (name == "") { + Logger.info("The name of SAML-Attribute number " + (i + 1) + + " returned from " + identifier + + "-infobox validator is empty."); + throw new ValidateException("validator.45", new Object[]{ + friendlyName, "Name", String.valueOf((i + 1)), "leer"}); + } + if (samlAttribute.getNameSpace() == null) { + Logger.info("The namespace of SAML-Attribute number " + (i + 1) + + " returned from " + identifier + + "-infobox validator is null."); + throw new ValidateException("validator.45", + new Object[]{friendlyName, "Namespace", + String.valueOf((i + 1)), "null"}); + } + Object value = samlAttribute.getValue(); + if (value == null) { + Logger.info("The value of SAML-Attribute number " + (i + 1) + + " returned from " + identifier + + "-infobox validator is null."); + throw new ValidateException("validator.45", new Object[]{ + friendlyName, "Wert", String.valueOf((i + 1)), "null"}); + } + + return value; + } + + /** + * Does the request to the SZR-GW + * + * @param oaFriendlyName + * @param signature XMLDSIG signature + * @return Identity link assertion + * @throws SZRGWClientException + */ + + public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String gender, String citizenSignature, String represented, String representative, String mandateContent, String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { + + try { + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); + + SZRGWClient client = new SZRGWClient(connectionParameters); + + + CreateIdentityLinkRequest request = new CreateIdentityLinkRequest(); + request.setSignature(citizenSignature.getBytes()); + + PEPSData data = new PEPSData(); + data.setDateOfBirth(PEPSDateOfBirth); + data.setFamilyname(PEPSFamilyname); + data.setFirstname(PEPSFirstname); + data.setIdentifier(PEPSIdentifier); + + data.setRepresentative(representative); + data.setRepresented(represented); + data.setMandateContent(mandateContent); + + data.setLegalPersonCanonicalRegisteredAddress(organizationAddress); + data.setLegalPersonTranslatableType(organizationType); + + if (null != mandateContent) { + MISType mis = new MISType(); + + Target targetObject = new Target(); + targetObject.setType(targetType); + targetObject.setValue(targetValue); + mis.setTarget(targetObject); + + mis.setOAFriendlyName(oaFriendlyName); + + Filters filterObject = new Filters(); + MandateIdentifiers mandateIds = new MandateIdentifiers(); + for (String current : filters.split(",")) + mandateIds.getMandateIdentifier().add(current.trim()); + filterObject.setMandateIdentifiers(mandateIds); + mis.setFilters(filterObject); + + request.setMIS(mis); + } + + Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); + CreateIdentityLinkResponse response = client.sentCreateIDLRequest(request, connectionParameters.getUrl()); + return response; + + } catch (ConfigurationException e) { + Logger.warn(e); + Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null)); + } + + return null; + + } + + /** + * Does the request to the SZR-GW. + * + * @param signature the signature + * @return the identity link + * @throws SZRGWClientException the sZRGW client exception + * @throws ConfigurationException the configuration exception + */ + public CreateIdentityLinkResponse getIdentityLink(Element signature) throws SZRGWClientException, ConfigurationException { + return getIdentityLink(null, null, null, null, XMLHelper.nodeToString(signature)); + } + + /** + * Does the request to the SZR-GW. + * + * @param PEPSIdentifier the pEPS identifier + * @param PEPSFirstname the pEPS firstname + * @param PEPSFamilyname the pEPS familyname + * @param PEPSDateOfBirth the pEPS date of birth + * @param signature XMLDSIG signature + * @return Identity link assertion + * @throws SZRGWClientException the sZRGW client exception + * @throws ConfigurationException the configuration exception + */ + public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String signature) throws SZRGWClientException { + return getIdentityLink(PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, null, signature, null, null, null, null, null, null, null); + } + + /** + * Gets the identity link. + * + * @param citizenSignature the citizen signature + * @param representative the representative + * @param represented the represented + * @param mandate the mandate + * @param organizationAddress the organization address + * @param organizationType the organization type + * @return the identity link + * @throws SZRGWClientException + */ + public CreateIdentityLinkResponse getIdentityLink(String citizenSignature, + String representative, String represented, String mandateContent, + String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { + return getIdentityLink(null, null, null, null, null, + citizenSignature, represented, representative, mandateContent, organizationAddress, + organizationType, targetType, targetValue, oaFriendlyName, filters); + } + + /** + * SZR-GW Client interface. + * + * @param eIdentifier the e identifier + * @param givenName the given name + * @param lastName the last name + * @param dateOfBirth the date of birth + * @param citizenSignature the citizen signature + * @param representative the representative + * @param represented the represented + * @param mandate the mandate + * @return the identity link + * @throws SZRGWClientException the sZRGW client exception + */ + public CreateIdentityLinkResponse getIdentityLink(String eIdentifier, + String givenName, String lastName, String dateOfBirth, String gender, + String citizenSignature, String representative, String represented, + String mandate, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { + return getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, gender, + citizenSignature, representative, represented, mandate, null, + null, targetType, targetValue, oaFriendlyName, filters); + } + + /** + * 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 = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); + if (oaParam == null) + throw new AuthenticationException("auth.00", new Object[]{moasession.getPublicOAURLPrefix()}); + + //Start of STORK Processing + STORKConfig storkConfig = AuthConfigurationProvider.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 acsURL = HTTPUtils.getBaseURL(req) + PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; + Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL); + + String providerName = oaParam.getFriendlyName(); + String issuerValue = HTTPUtils.getBaseURL(req); + Logger.debug("Issuer value: " + issuerValue); + + // prepare collection of required attributes + // - attributes for online application + List<OAStorkAttribute> 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 = currentGlobalAttribute.isMandatory(); + break; + } + + newAttribute.setIsRequired(current.isMandatory() || globallyMandatory); + attributeList.add(newAttribute); + } + + // add sign request + PersonalAttribute newAttribute = new PersonalAttribute(); + newAttribute.setName("signedDoc"); + List<String> value = new ArrayList<String>(); + 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); + + + 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"; + + //generate AuthnRquest + STORKAuthnRequest authnRequest = new STORKAuthnRequest(); + authnRequest.setDestination(destination); + authnRequest.setAssertionConsumerServiceURL(acsURL); + authnRequest.setProviderName(providerName); + authnRequest.setIssuer(issuerValue); + authnRequest.setQaa(oaParam.getQaaLevel()); + authnRequest.setSpInstitution(spInstitution); + authnRequest.setCountry(spCountry); + authnRequest.setSpApplication(spApplication); + authnRequest.setSpSector(spSector); + authnRequest.setPersonalAttributeList(attributeList); + + authnRequest.setEIDCrossBorderShare(true); + authnRequest.setEIDCrossSectorShare(true); + authnRequest.setEIDSectorShare(true); + + authnRequest.setCitizenCountryCode(moasession.getCcc()); + + + Logger.debug("STORK AuthnRequest succesfully assembled."); + + STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("outgoing"); + 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); + HttpSession httpSession = req.getSession(); + httpSession.setAttribute("MOA-Session-ID", moasession.getSessionID()); + + + 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("action", destination); + + StringWriter writer = new StringWriter(); + template.merge(context, writer); + + resp.getOutputStream().write(writer.toString().getBytes()); + } catch (Exception e) { + Logger.error("Error sending STORK SAML AuthnRequest.", e); + httpSession.invalidate(); + throw new MOAIDException("stork.02", new Object[]{destination}); + } + + Logger.info("STORK AuthnRequest successfully successfully prepared for client with target location: " + authnRequest.getDestination()); + } + + private static String generateDssSignRequest(String text, String mimeType, String citizenCountry) { + IdentifierGenerator idGenerator; + try { + idGenerator = new SecureRandomIdentifierGenerator(); + + DocumentType doc = new DocumentType(); + doc.setBase64XML(text.getBytes()); + 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 + * + * @param signedXML XML signature element + * @return X509Certificate + * @throws CertificateException + */ + public static X509Certificate getCertificateFromXML(Element signedXML) throws CertificateException { + + NodeList nList = signedXML.getElementsByTagNameNS(Constants.DSIG_NS_URI, "X509Certificate"); + + String base64CertString = XMLUtil.getFirstTextValueFromNodeList(nList); + + if (StringUtils.isEmpty(base64CertString)) { + String msg = "XML does not contain a X509Certificate element."; + Logger.error(msg); + throw new CertificateException(msg); + } + + InputStream is = new ByteArrayInputStream(Base64.decode(base64CertString)); + + X509Certificate cert; + try { + cert = new X509Certificate(is); + return cert; + + } catch (Throwable e) { + throw new CertificateException(e); + } + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java index 828fc78ab..ba347c9e5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java @@ -2,19 +2,19 @@ * Copyright 2014 Federal Chancellery Austria * MOA-ID has been developed in a cooperation between BRZ, the Federal * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * + * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * http://www.osor.eu/eupl/ - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. - * + * * This product combines work with different licenses. See the "NOTICE" text * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works @@ -51,82 +51,143 @@ import at.gv.egovernment.moa.util.Constants; /** * Builder for the <code><InfoboxReadRequest></code> structure * used for requesting the identity link from the security layer implementation. - * + * * @author Paul Ivancsics * @version $Id$ */ public class InfoboxReadRequestBuilder implements Constants { - /** - * Constructor for InfoboxReadRequestBuilder. - */ - public InfoboxReadRequestBuilder() { - } - - - /** - * Builds an <code><InfoboxReadRequest></code>. - * - * @param slVersion12 specifies whether the Security Layer version is - * version 1.2 or not - * @param businessService specifies whether the online application is a - * business service or not - * @param identityLinkDomainIdentifier the identification number of the business - * company; maybe <code>null</code> if the OA - * is a public service; must not be <code>null</code> - * if the OA is a business service - * - * @return <code><InfoboxReadRequest></code> as String - */ - public String build(boolean businessService, String identityLinkDomainIdentifier) { - - String slPrefix; - String slNsDeclaration; - + /** + * Constructor for InfoboxReadRequestBuilder. + */ + public InfoboxReadRequestBuilder() { + } + + + /** + * Builds an <code><InfoboxReadRequest></code>. + * + * @param slVersion12 specifies whether the Security Layer version is + * version 1.2 or not + * @param businessService specifies whether the online application is a + * business service or not + * @param identityLinkDomainIdentifier the identification number of the business + * company; maybe <code>null</code> if the OA + * is a public service; must not be <code>null</code> + * if the OA is a business service + * @return <code><InfoboxReadRequest></code> as String + */ + public String build(boolean businessService, String identityLinkDomainIdentifier) { + + String slPrefix; + String slNsDeclaration; + // if (slVersion12) { - slPrefix = SL12_PREFIX; - slNsDeclaration = SL12_NS_URI; + slPrefix = SL12_PREFIX; + slNsDeclaration = SL12_NS_URI; // } else { // slPrefix = SL10_PREFIX; // slNsDeclaration = SL10_NS_URI; // } - - StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); - sb.append("<"); - sb.append(slPrefix); - sb.append(":InfoboxReadRequest xmlns:"); - sb.append(slPrefix); - sb.append("=\""); - sb.append(slNsDeclaration); - sb.append("\">"); - sb.append("<"); - sb.append(slPrefix); - sb.append(":InfoboxIdentifier>IdentityLink</"); - sb.append(slPrefix); - sb.append(":InfoboxIdentifier>"); - sb.append("<"); - sb.append(slPrefix); - sb.append(":BinaryFileParameters ContentIsXMLEntity=\"true\"/>"); - if (businessService) { - sb.append("<"); - sb.append(slPrefix); - sb.append(":BoxSpecificParameters>"); - sb.append("<"); - sb.append(slPrefix); - sb.append(":IdentityLinkDomainIdentifier>"); - sb.append(identityLinkDomainIdentifier); - sb.append("</sl:IdentityLinkDomainIdentifier>"); - sb.append("</"); - sb.append(slPrefix); - sb.append(":BoxSpecificParameters>"); + + StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":InfoboxReadRequest xmlns:"); + sb.append(slPrefix); + sb.append("=\""); + sb.append(slNsDeclaration); + sb.append("\">"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":InfoboxIdentifier>IdentityLink</"); + sb.append(slPrefix); + sb.append(":InfoboxIdentifier>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":BinaryFileParameters ContentIsXMLEntity=\"true\"/>"); + if (businessService) { + sb.append("<"); + sb.append(slPrefix); + sb.append(":BoxSpecificParameters>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":IdentityLinkDomainIdentifier>"); + sb.append(identityLinkDomainIdentifier); + sb.append("</sl:IdentityLinkDomainIdentifier>"); + sb.append("</"); + sb.append(slPrefix); + sb.append(":BoxSpecificParameters>"); + } + sb.append("</"); + sb.append(slPrefix); + sb.append(":InfoboxReadRequest>"); + + return sb.toString(); + + } + + + /** + * Builds an <code><InfoboxReadRequest></code>. + * + * @param slVersion12 specifies whether the Security Layer version is + * version 1.2 or not + * @param businessService specifies whether the online application is a + * business service or not + * @param identityLinkDomainIdentifier the identification number of the business + * company; maybe <code>null</code> if the OA + * is a public service; must not be <code>null</code> + * if the OA is a business service + * @return <code><InfoboxReadRequest></code> as String + * + */ + public String buildStorkReadRequest(String identityLinkDomainIdentifier) { + + String slPrefix; + String slNsDeclaration; + + slPrefix = SL12_PREFIX; + slNsDeclaration = SL12_NS_URI; + + StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":InfoboxReadRequest xmlns:"); + sb.append(slPrefix); + sb.append("=\""); + sb.append(slNsDeclaration); + sb.append("\">"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":InfoboxIdentifier>IdentityLink</"); + sb.append(slPrefix); + sb.append(":InfoboxIdentifier>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":BinaryFileParameters ContentIsXMLEntity=\"true\"/>"); + + // append box parameters - necessary for stork? + sb.append("<"); + sb.append(slPrefix); + sb.append(":BoxSpecificParameters>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":IdentityLinkDomainIdentifier>"); + sb.append(identityLinkDomainIdentifier); + sb.append("</sl:IdentityLinkDomainIdentifier>"); + sb.append("</"); + sb.append(slPrefix); + sb.append(":BoxSpecificParameters>"); + // end appending box parameters + + sb.append("</"); + sb.append(slPrefix); + sb.append(":InfoboxReadRequest>"); + + return sb.toString(); + } - sb.append("</"); - sb.append(slPrefix); - sb.append(":InfoboxReadRequest>"); - - return sb.toString(); - - } } 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 index 41be2c7e3..f98e5c97b 100644 --- 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 @@ -30,6 +30,7 @@ import java.net.URL; import java.util.ArrayList;
import java.util.List;
+import javax.activation.DataSource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
@@ -66,6 +67,8 @@ 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.profile.DocumentWithSignature;
import eu.stork.oasisdss.profile.SignResponse;
import eu.stork.peps.auth.commons.PEPSUtil;
@@ -202,17 +205,15 @@ public class PEPSConnectorServlet extends AuthServlet { String signatureInfo = authnResponse.getPersonalAttributeList().get("signedDoc").getValue().get(0);
SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(new java.io.StringReader(signatureInfo)));
- List<DocumentWithSignature> doclocations = ApiUtils.findNamedElement(dssSignResponse.getOptionalOutputs(), DocumentWithSignature.class.getSimpleName(), DocumentWithSignature.class);
- // TODO handle multiple docs?
- Logger.debug("trying first doclocation");
- String docUrl = doclocations.get(0).getDocument().getDocumentURL();
- Logger.debug("trying first doclocation successful");
-
// fetch signed doc
- URL url = new URL(docUrl);
- InputStream incomming = url.openStream();
- citizenSignature = IOUtils.toString(incomming);
- incomming.close();
+ DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse);
+ if(ds == null){
+ throw new ApiUtilsException("No datasource found in response");
+ }
+
+ InputStream incoming = ds.getInputStream();
+ citizenSignature = IOUtils.toString(incoming);
+ incoming.close();
JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName());
SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller().unmarshal(IOUtils.toInputStream(citizenSignature))).getValue();
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 index 7e21c6667..2d0a0e367 100644 --- 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 @@ -55,7 +55,12 @@ public class OAParameter { this.businessService = true; else this.businessService = false; - + + if (this.oaType.equals("storkService")) + this.storkService = true; + else + this.storkService = false; + this.publicURLPrefix = oa.getPublicURLPrefix(); this.friendlyName = oa.getFriendlyName(); @@ -81,8 +86,15 @@ public class OAParameter { * if value of {@link #oaType} is "businessService" */ private boolean businessService; - - /** + + /** + * specifies whether the online application is a stork application or not (<code>true</code> + * if value of {@link #oaType} is "storkService" + */ + private boolean storkService; + + + /** * public URL prefix of the online application */ private String publicURLPrefix; @@ -139,5 +151,7 @@ public class OAParameter { public OAOAUTH20 getoAuth20Config() { return oAuth20Config; } + + public boolean getStorkService() { return storkService; } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java index 3af8bcfe5..647c8bb39 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java @@ -491,7 +491,7 @@ public class DispatcherServlet extends AuthServlet{ } } catch (Throwable e) { - Logger.info("An authentication error occous: " + e.getMessage());; + Logger.info("An authentication error occured: " + e.getMessage());; // Try handle module specific, if not possible rethrow if (!info.generateErrorMessage(e, req, resp, protocolRequest)) { throw e; 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 f23e0f599..f660e1b33 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 @@ -34,7 +34,7 @@ import javax.servlet.http.HttpServletResponse; * The class is called whenever the {@link AuthenticationRequest} Action is invoked and checks for missing attributes. * Furthermore, the class can handle direct posts. That is when the class triggers an attribute query which needs user * interaction, redirect to another portal, etc. The redirect will hit here and the class can continue to fetch attributes. - * <p/> + * * TODO how do we treat mandatory and optional attributes? */ public class AttributeCollector implements IAction { @@ -278,7 +278,7 @@ public class AttributeCollector implements IAction { * @see at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { - // this action does not need any authentication. The authentication is already done by the preceding AuthenticationRequest-Action. + // this action does not need any authentication. The authentication is already done by the preceding AuthenticationRequest-Action. return false; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProvider.java index 6fba91fde..d92b0b72f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProvider.java @@ -52,4 +52,5 @@ public interface AttributeProvider { */ public IPersonalAttributeList parse(HttpServletRequest httpReq) throws UnsupportedAttributeException, MOAIDException; + } 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 de079c960..dbeaf94e9 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 @@ -19,9 +19,12 @@ public class AttributeProviderFactory { List<String> result = new ArrayList<String>(); result.add("StorkAttributeRequestProvider"); result.add("EHvdAttributeProvider"); + result.add("SignedDocAttributeRequestProvider"); + result.add("MISAttributeProvider"); - return result; - } + + return result; + } /** * Creates an AttributeProvider object for the given shortname. Returns @@ -35,6 +38,12 @@ public class AttributeProviderFactory { if (shortname.equals("StorkAttributeRequestProvider")) { return new StorkAttributeRequestProvider(url, attributes); } else if(shortname.equals("EHvdAttributeProvider")) { + return new EHvdAttributeProviderPlugin(url); + } else if(shortname.equals("SignedDocAttributeRequestProvider")) { + return new SignedDocAttributeRequestProvider(url); + } else if (shortname.equals("MISAttributeProvider")) { + return new MISAttributeProvider(url); + } else { return new EHvdAttributeProviderPlugin(url, attributes); } else { return null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MISAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MISAttributeProvider.java index 7665bb239..ec38db513 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MISAttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MISAttributeProvider.java @@ -3,6 +3,7 @@ package at.gv.egovernment.moa.id.protocols.stork2; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.logging.Logger; import eu.stork.peps.auth.commons.IPersonalAttributeList; import eu.stork.peps.auth.commons.PersonalAttribute; @@ -13,15 +14,34 @@ import javax.servlet.http.HttpServletResponse; * Implements Attribute Provider for Mandates */ public class MISAttributeProvider implements AttributeProvider { + + String url = null; + + public MISAttributeProvider(String url) { + this.url = url; + } + public IPersonalAttributeList acquire(PersonalAttribute attributes, AuthenticationSession moasession) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException { + Logger.error("Entering MIS for attribute: " + attributes.getName()); + + if (attributes.getName().equals("residencePermit")) { + Logger.error("MIS EXCEPTION: " + attributes.getName()); + //throw new ExternalAttributeRequestRequiredException(this); + } + return null; // } public void performRedirect(String url, String citizenCountyCode, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException { - // + Logger.error("Entering MIS redirect for attribute: " ); + } public IPersonalAttributeList parse(HttpServletRequest httpReq) throws UnsupportedAttributeException, MOAIDException { return null; // } + + public String getName() { + return "MandateProvider"; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java index fa7db82c4..e95cfabe2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java @@ -56,7 +56,7 @@ public class MOASTORKRequest implements IRequest, Serializable { return this.storkAttrQueryRequest; } - public String getOAURL() { + public String getOAURL() { // TODO CHECK IT if (isAuthnRequest) return storkAuthnRequest.getAssertionConsumerServiceURL(); else if (isAttrRequest) diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java new file mode 100644 index 000000000..bad711dbb --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java @@ -0,0 +1,28 @@ +package at.gv.egovernment.moa.id.protocols.stork2; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IRequest; +import com.sun.xml.ws.security.trust.WSTrustConstants; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Processes mandate data after authentication is done in AT + * @author bsuzic + */ +public class MandateRetrievalRequest implements IAction { + public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession moasession) throws MOAIDException { + return null; // + } + + public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { + return true; + } + + public String getDefaultActionName() { + return STORKProtocol.MANDATERETRIEVALREQUEST; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java index 638035008..a361d5f67 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java @@ -31,6 +31,7 @@ public class STORKProtocol implements IModulInfo, MOAIDAuthConstants { public static final String AUTHENTICATIONREQUEST = "AuthenticationRequest"; public static final String ATTRIBUTE_COLLECTOR = "AttributeCollector"; + public static final String MANDATERETRIEVALREQUEST = "MandateRetrievalRequest"; private static HashMap<String, IAction> actions = new HashMap<String, IAction>(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SignedDocAttributeRequestProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SignedDocAttributeRequestProvider.java new file mode 100644 index 000000000..6a8e306a1 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SignedDocAttributeRequestProvider.java @@ -0,0 +1,134 @@ +package at.gv.egovernment.moa.id.protocols.stork2; + +import java.io.StringWriter; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.codec.binary.Base64; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.stork.VelocityProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.StringUtils; + +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.STORKAttrQueryResponse; +import eu.stork.peps.auth.engine.STORKSAMLEngine; +import eu.stork.peps.exceptions.STORKSAMLEngineException; + +/** + * Forwards a signedDoc attribute request to the oasis-dss service instance + */ +public class SignedDocAttributeRequestProvider implements AttributeProvider { + + private PersonalAttribute requestedAttribute; + + /** + * The URL of the service listening for the oasis dss webform post request + */ + private String oasisDssWebFormURL; + + /** + * Instantiates a new signed doc attribute request provider. + * + * @param oasisDssWebFormURL + * the AP location + */ + public SignedDocAttributeRequestProvider(String oasisDssWebFormURL) { + this.oasisDssWebFormURL = oasisDssWebFormURL; + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#acquire(java + * .lang.String) + */ + public IPersonalAttributeList acquire(PersonalAttribute attribute, AuthenticationSession moasession) throws UnsupportedAttributeException, + ExternalAttributeRequestRequiredException { + if(!attribute.getName().equals("signedDoc")){ + throw new UnsupportedAttributeException(); + } + + requestedAttribute = attribute; + + throw new ExternalAttributeRequestRequiredException(this); + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#parse(javax + * .servlet.http.HttpServletRequest) + */ + public IPersonalAttributeList parse(HttpServletRequest httpReq) throws MOAIDException, UnsupportedAttributeException { + Logger.debug("Beginning to extract OASIS-DSS response out of HTTP Request"); + + + STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); + try { + String signResponse = new String(Base64.decodeBase64(httpReq.getParameter("signresponse")), "UTF8"); + List<String> values = new ArrayList<String>(); + values.add(signResponse); + + Logger.debug("Assembling signedDoc attribute"); + PersonalAttribute signedDocAttribute = new PersonalAttribute(requestedAttribute.getName(), requestedAttribute.isRequired(), values, + "Available"); + + // pack and return the result + PersonalAttributeList result = new PersonalAttributeList(); + result.add(signedDocAttribute); + return result; + } catch (UnsupportedEncodingException e) { + Logger.error("Failed to assemble signedDoc attribute"); + throw new MOAIDException("stork.05", null); + } + } + + /* + * (non-Javadoc) + * + * @see + * at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#performRedirect + * (java.lang.String) + */ + public void performRedirect(String url, String citizenCountryCode, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) + 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(); + context.put("signrequest", Base64.encodeBase64String(requestedAttribute.getValue().get(0).getBytes("UTF8"))); + context.put("clienturl", url); + context.put("action", oasisDssWebFormURL); + + StringWriter writer = new StringWriter(); + template.merge(context, writer); + + resp.getOutputStream().write(writer.toString().getBytes()); + } catch (Exception e) { + Logger.error("Error sending STORK SAML AttrRequest.", e); + throw new MOAIDException("stork.11", null); + } + } + +} diff --git a/id/server/idserverlib/src/main/resources/resources/templates/oasis_dss_webform_binding.vm b/id/server/idserverlib/src/main/resources/resources/templates/oasis_dss_webform_binding.vm new file mode 100644 index 000000000..7fcc1bb36 --- /dev/null +++ b/id/server/idserverlib/src/main/resources/resources/templates/oasis_dss_webform_binding.vm @@ -0,0 +1,36 @@ +## +## Velocity Template for OASIS WEBFORM BINDING +## +## Velocity context may contain the following properties +## action - String - the action URL for the form +## signresponse - String - the Base64 encoded SAML Request +## verifyresponse - String - the Base64 encoded SAML Response +## clienturl - String - URL where the USer gets redirected after the signature process + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> + + <body onload="document.forms[0].submit()"> + <noscript> + <p> + <strong>Note:</strong> Since your browser does not support JavaScript, + you must press the Continue button once to proceed. + </p> + </noscript> + + <form action="${action}" method="post"> + <div> + #if($signrequest)<input type="hidden" name="signrequest" value="${signrequest}"/>#end + + #if($verifyrequest)<input type="hidden" name="verifyrequest" value="${verifyrequest}"/>#end + #if($clienturl)<input type="hidden" name="clienturl" value="${clienturl}"/>#end + + </div> + <noscript> + <div> + <input type="submit" value="Continue"/> + </div> + </noscript> + </form> + + </body> +</html>
\ No newline at end of file diff --git a/id/server/moa-id-commons/moa-id-commons.iml b/id/server/moa-id-commons/moa-id-commons.iml index 08d15d746..aeb4ad88c 100644 --- a/id/server/moa-id-commons/moa-id-commons.iml +++ b/id/server/moa-id-commons/moa-id-commons.iml @@ -26,8 +26,8 @@ </facet> </component> <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false"> - <output url="file://$MODULE_DIR$/../../target/classes" /> - <output-test url="file://$MODULE_DIR$/../../target/test-classes" /> + <output url="file://$MODULE_DIR$/target/classes" /> + <output-test url="file://$MODULE_DIR$/target/test-classes" /> <content url="file://$MODULE_DIR$"> <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" /> <sourceFolder url="file://$MODULE_DIR$/src/main/resources/config" type="java-resource" /> @@ -56,6 +56,12 @@ <orderEntry type="library" name="Maven: jaxen:jaxen:1.0-FCS" level="project" /> <orderEntry type="library" name="Maven: saxpath:saxpath:1.0-FCS" level="project" /> <orderEntry type="library" name="Maven: joda-time:joda-time:1.6.2" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-simple:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:log4j-over-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: commons-io:commons-io:1.3.2" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-runtime:0.5.6" level="project" /> <orderEntry type="library" name="Maven: commons-lang:commons-lang:2.2" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2_commons:jaxb2-basics-runtime:0.6.2" level="project" /> @@ -70,10 +76,6 @@ <orderEntry type="library" scope="TEST" name="Maven: junit:junit:3.8.1" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2_commons:jaxb2-basics-testing:0.6.2" level="project" /> <orderEntry type="library" name="Maven: xmlunit:xmlunit:1.0" level="project" /> - <orderEntry type="library" name="Maven: commons-io:commons-io:1.2" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.1" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.6.1" level="project" /> - <orderEntry type="library" name="Maven: log4j:log4j:1.2.14" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-persistence:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-customizations:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.springframework:spring:2.0.7" level="project" /> diff --git a/id/server/moa-id-commons/pom.xml b/id/server/moa-id-commons/pom.xml index 9a3cf4f7c..055a67bf4 100644 --- a/id/server/moa-id-commons/pom.xml +++ b/id/server/moa-id-commons/pom.xml @@ -1,235 +1,260 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <parent> - <groupId>MOA.id</groupId> - <artifactId>moa-id</artifactId> - <version>1.9.98-SNAPSHOT</version> - </parent> - <artifactId>moa-id-commons</artifactId> - <name>moa-id-commons</name> - <groupId>MOA.id.server</groupId> - - <repositories> - <repository> - <id>hyberjaxb</id> - <url>http://repository.highsource.org/maven2/releases/</url> - <releases><enabled>true</enabled></releases> - </repository> - <repository> - <id>JBoss IAIK</id> - <url>http://nexus.iaik.tugraz.at/nexus/content/repositories/nexus/</url> - <!-- <releases><enabled>true</enabled></releases> --> - </repository> - </repositories> - - <dependencies> - <dependency> - <groupId>org.hibernate</groupId> - <artifactId>hibernate-core</artifactId> - <version>4.2.1.Final</version> - </dependency> - <dependency> - <groupId>org.hibernate</groupId> - <artifactId>hibernate-c3p0</artifactId> - <version>4.2.1.Final</version> - </dependency> - <dependency> - <groupId>org.hibernate</groupId> - <artifactId>hibernate-entitymanager</artifactId> - <version>4.2.1.Final</version> - </dependency> - - <dependency> - <groupId>org.apache.commons</groupId> - <artifactId>commons-lang3</artifactId> - <version>3.1</version> - </dependency> - <dependency> - <groupId>MOA</groupId> - <artifactId>moa-common</artifactId> - <type>jar</type> - </dependency> +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + <parent> + <groupId>MOA.id</groupId> + <artifactId>moa-id</artifactId> + <version>1.9.98-SNAPSHOT</version> + </parent> + <artifactId>moa-id-commons</artifactId> + <name>moa-id-commons</name> + <groupId>MOA.id.server</groupId> - <!-- dependency> - <groupId>com.sun.xml.bind</groupId> - <artifactId>jaxb-xjc</artifactId> - <version>2.2.7</version> - </dependency --> - - <dependency> - <groupId>org.hibernate.javax.persistence</groupId> - <artifactId>hibernate-jpa-2.0-api</artifactId> - <version>1.0.1.Final</version> - </dependency> - - <dependency> - <groupId>org.jvnet.hyperjaxb3</groupId> - <artifactId>hyperjaxb3-ejb-runtime</artifactId> - <version>0.5.6</version> - </dependency> - <dependency> - <groupId>org.jvnet.hyperjaxb3</groupId> - <artifactId>maven-hyperjaxb3-plugin</artifactId> - <version>0.5.6</version> -</dependency> - <dependency> - <groupId>mysql</groupId> - <artifactId>mysql-connector-java</artifactId> - <version>5.1.25</version> - </dependency> - </dependencies> - - <build> - <defaultGoal>install</defaultGoal> - - <resources> - <resource> - <directory>src/main/resources/config</directory> - <excludes> - <exclude>**/*.java</exclude> - </excludes> - </resource> - <resource> - <directory>target/generated-sources/xjc</directory> - <excludes> - <exclude>**/*.java</exclude> - </excludes> - </resource> - </resources> - - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.5</source> - <target>1.5</target> - </configuration> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-jar-plugin</artifactId> - <configuration> - <skip>true</skip> - <skipTests>true</skipTests> - <archive> - <addMavenDescriptor>false</addMavenDescriptor> - </archive> - </configuration> - <executions> - <execution> - <goals> - <goal>test-jar</goal> - </goals> - </execution> - </executions> - </plugin> - - <plugin> - <groupId>org.jvnet.hyperjaxb3</groupId> - <artifactId>maven-hyperjaxb3-plugin</artifactId> - <version>0.5.6</version> - <executions> - <execution> - <goals> - <goal>generate</goal> - </goals> - </execution> - </executions> - <configuration> - <extension>true</extension> - <schemaDirectory>src/main/resources/config</schemaDirectory> - <bindingDirectory>src/main/resources/config</bindingDirectory> - <persistenceXml>src/main/resources/config/persistence_template.xml</persistenceXml> - <generatePackage>at.gv.egovernment.moa.id.commons.db.dao.config</generatePackage> - </configuration> - </plugin> - <plugin> - <inherited>true</inherited> - <artifactId>maven-compiler-plugin</artifactId> - <version>2.0.2</version> - <configuration> - <source>1.5</source> - <target>1.5</target> - </configuration> - </plugin> - - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-javadoc-plugin</artifactId> - <version>2.5</version> - <configuration> - <charset>UTF-8</charset> - <docencoding>UTF-8</docencoding> - <quiet>true</quiet> - <author>false</author> - <version>false</version> - <use>true</use> - <excludePackageNames>at.gv.egovernment.moa.spss.server.*;at.gv.egovernment.moa.spss.api.impl.*;at.gv.egovernment.moa.spss.impl.*</excludePackageNames> - <tags> - <tag> - <name>pre</name> - <placement>a</placement> - <head>Preconditions:</head> - </tag> - <tag> - <name>post</name> - <placement>a</placement> - <head>Postconditions:</head> - </tag> - </tags> - <links> - <link>http://java.sun.com/j2se/1.4/docs/api/</link> - <link>http://java.sun.com/j2se/1.5.0/docs/api/</link> - <link>http://logging.apache.org/log4j/docs/api/</link> - </links> - <target>1.5</target> - </configuration> - <executions> - <execution> - <id>generate-javadoc</id> - <phase>package</phase> - <goals> - <goal>jar</goal> - </goals> - </execution> - </executions> - </plugin> - </plugins> - <pluginManagement> - <plugins> - <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> - <plugin> - <groupId>org.eclipse.m2e</groupId> - <artifactId>lifecycle-mapping</artifactId> - <version>1.0.0</version> - <configuration> - <lifecycleMappingMetadata> - <pluginExecutions> - <pluginExecution> - <pluginExecutionFilter> - <groupId> - org.jvnet.hyperjaxb3 - </groupId> - <artifactId> - maven-hyperjaxb3-plugin - </artifactId> - <versionRange> - [0.5.6,) - </versionRange> - <goals> - <goal>generate</goal> - </goals> - </pluginExecutionFilter> - <action> - <ignore></ignore> - </action> - </pluginExecution> - </pluginExecutions> - </lifecycleMappingMetadata> - </configuration> - </plugin> - </plugins> - </pluginManagement> - </build> + <repositories> + <repository> + <id>hyberjaxb</id> + <url>http://repository.highsource.org/maven2/releases/</url> + <releases> + <enabled>true</enabled> + </releases> + </repository> + <repository> + <id>JBoss IAIK</id> + <url>http://nexus.iaik.tugraz.at/nexus/content/repositories/nexus/</url> + <!-- <releases><enabled>true</enabled></releases> --> + </repository> + </repositories> + + <dependencies> + <dependency> + <groupId>org.hibernate</groupId> + <artifactId>hibernate-core</artifactId> + <version>4.2.1.Final</version> + </dependency> + <dependency> + <groupId>org.hibernate</groupId> + <artifactId>hibernate-c3p0</artifactId> + <version>4.2.1.Final</version> + </dependency> + <dependency> + <groupId>org.hibernate</groupId> + <artifactId>hibernate-entitymanager</artifactId> + <version>4.2.1.Final</version> + </dependency> + + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + <version>3.1</version> + </dependency> + <dependency> + <groupId>MOA</groupId> + <artifactId>moa-common</artifactId> + <type>jar</type> + </dependency> + + <!-- dependency> + <groupId>com.sun.xml.bind</groupId> + <artifactId>jaxb-xjc</artifactId> + <version>2.2.7</version> + </dependency --> + + <dependency> + <groupId>org.hibernate.javax.persistence</groupId> + <artifactId>hibernate-jpa-2.0-api</artifactId> + <version>1.0.1.Final</version> + </dependency> + + <dependency> + <groupId>org.jvnet.hyperjaxb3</groupId> + <artifactId>hyperjaxb3-ejb-runtime</artifactId> + <version>0.5.6</version> + <exclusions> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </exclusion> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>org.jvnet.hyperjaxb3</groupId> + <artifactId>maven-hyperjaxb3-plugin</artifactId> + <version>0.5.6</version> + <exclusions> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </exclusion> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + </exclusion> + </exclusions> + </dependency> + <dependency> + <groupId>mysql</groupId> + <artifactId>mysql-connector-java</artifactId> + <version>5.1.25</version> + </dependency> + </dependencies> + + <build> + <defaultGoal>install</defaultGoal> + + <resources> + <resource> + <directory>src/main/resources/config</directory> + <excludes> + <exclude>**/*.java</exclude> + </excludes> + </resource> + <resource> + <directory>target/generated-sources/xjc</directory> + <excludes> + <exclude>**/*.java</exclude> + </excludes> + </resource> + </resources> + + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <source>1.5</source> + <target>1.5</target> + </configuration> + </plugin> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-jar-plugin</artifactId> + <configuration> + <skip>true</skip> + <skipTests>true</skipTests> + <archive> + <addMavenDescriptor>false</addMavenDescriptor> + </archive> + </configuration> + <executions> + <execution> + <goals> + <goal>test-jar</goal> + </goals> + </execution> + </executions> + </plugin> + + <plugin> + <groupId>org.jvnet.hyperjaxb3</groupId> + <artifactId>maven-hyperjaxb3-plugin</artifactId> + <version>0.5.6</version> + <executions> + <execution> + <goals> + <goal>generate</goal> + </goals> + </execution> + </executions> + <configuration> + <extension>true</extension> + <schemaDirectory>src/main/resources/config</schemaDirectory> + <bindingDirectory>src/main/resources/config</bindingDirectory> + <persistenceXml>src/main/resources/config/persistence_template.xml</persistenceXml> + <generatePackage>at.gv.egovernment.moa.id.commons.db.dao.config</generatePackage> + </configuration> + </plugin> + <plugin> + <inherited>true</inherited> + <artifactId>maven-compiler-plugin</artifactId> + <version>2.0.2</version> + <configuration> + <source>1.5</source> + <target>1.5</target> + </configuration> + </plugin> + + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-javadoc-plugin</artifactId> + <version>2.5</version> + <configuration> + <charset>UTF-8</charset> + <docencoding>UTF-8</docencoding> + <quiet>true</quiet> + <author>false</author> + <version>false</version> + <use>true</use> + <excludePackageNames> + at.gv.egovernment.moa.spss.server.*;at.gv.egovernment.moa.spss.api.impl.*;at.gv.egovernment.moa.spss.impl.* + </excludePackageNames> + <tags> + <tag> + <name>pre</name> + <placement>a</placement> + <head>Preconditions:</head> + </tag> + <tag> + <name>post</name> + <placement>a</placement> + <head>Postconditions:</head> + </tag> + </tags> + <links> + <link>http://java.sun.com/j2se/1.4/docs/api/</link> + <link>http://java.sun.com/j2se/1.5.0/docs/api/</link> + <link>http://logging.apache.org/log4j/docs/api/</link> + </links> + <target>1.5</target> + </configuration> + <executions> + <execution> + <id>generate-javadoc</id> + <phase>package</phase> + <goals> + <goal>jar</goal> + </goals> + </execution> + </executions> + </plugin> + </plugins> + <pluginManagement> + <plugins> + <!--This plugin's configuration is used to store Eclipse m2e settings only. It has no influence on the Maven build itself.--> + <plugin> + <groupId>org.eclipse.m2e</groupId> + <artifactId>lifecycle-mapping</artifactId> + <version>1.0.0</version> + <configuration> + <lifecycleMappingMetadata> + <pluginExecutions> + <pluginExecution> + <pluginExecutionFilter> + <groupId> + org.jvnet.hyperjaxb3 + </groupId> + <artifactId> + maven-hyperjaxb3-plugin + </artifactId> + <versionRange> + [0.5.6,) + </versionRange> + <goals> + <goal>generate</goal> + </goals> + </pluginExecutionFilter> + <action> + <ignore></ignore> + </action> + </pluginExecution> + </pluginExecutions> + </lifecycleMappingMetadata> + </configuration> + </plugin> + </plugins> + </pluginManagement> + </build> </project>
\ No newline at end of file diff --git a/id/server/moa-id-commons/src/main/resources/config/moaid_config_2.0.xsd b/id/server/moa-id-commons/src/main/resources/config/moaid_config_2.0.xsd index 845e4fe1f..b7e8f6ff3 100644 --- a/id/server/moa-id-commons/src/main/resources/config/moaid_config_2.0.xsd +++ b/id/server/moa-id-commons/src/main/resources/config/moaid_config_2.0.xsd @@ -11,14 +11,16 @@ <xsd:restriction base="xsd:NMTOKEN"> <xsd:enumeration value="businessService"/> <xsd:enumeration value="publicService"/> - </xsd:restriction> + <xsd:enumeration value="storkService"/> + </xsd:restriction> </xsd:simpleType> </xsd:attribute> <xsd:attribute name="calculateHPI" type="xsd:boolean" use="optional" default="false"/> <xsd:attribute name="friendlyName" type="xsd:string" use="optional"/> <xsd:attribute name="target" type="xsd:string" use="optional"/> <xsd:attribute name="targetFriendlyName" type="xsd:string" use="optional"/> - <xsd:attribute name="removeBPKFromAuthBlock" type="xsd:boolean" use="optional" default="false"/> + <xsd:attribute name="storkSPTargetCountry" type="xsd:string" use="optional"/> + <xsd:attribute name="removeBPKFromAuthBlock" type="xsd:boolean" use="optional" default="false"/> </xsd:extension> </xsd:complexContent> </xsd:complexType> diff --git a/id/server/moa-id.iml b/id/server/moa-id.iml index 567359474..6e02e5944 100644 --- a/id/server/moa-id.iml +++ b/id/server/moa-id.iml @@ -1,13 +1,14 @@ <?xml version="1.0" encoding="UTF-8"?> <module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4"> <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false"> - <output url="file://$MODULE_DIR$/../target/classes" /> - <output-test url="file://$MODULE_DIR$/../target/test-classes" /> + <output url="file://$MODULE_DIR$/target/classes" /> + <output-test url="file://$MODULE_DIR$/target/test-classes" /> <content url="file://$MODULE_DIR$"> <excludeFolder url="file://$MODULE_DIR$/target" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> + <orderEntry type="library" name="Maven: commons-io:commons-io:1.3.2" level="project" /> </component> </module> diff --git a/id/server/mw-messages-api/.classpath b/id/server/mw-messages-api/.classpath index 8b5a9fa96..c15838fd0 100644 --- a/id/server/mw-messages-api/.classpath +++ b/id/server/mw-messages-api/.classpath @@ -6,11 +6,6 @@ <attribute name="maven.pomderived" value="true"/> </attributes> </classpathentry> - <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"> - <attributes> - <attribute name="maven.pomderived" value="true"/> - </attributes> - </classpathentry> <classpathentry kind="src" output="target/test-classes" path="src/test/java"> <attributes> <attribute name="optional" value="true"/> diff --git a/id/server/proxy/moa-id-proxy.iml b/id/server/proxy/moa-id-proxy.iml index 86fa1b292..d0e7de0b2 100644 --- a/id/server/proxy/moa-id-proxy.iml +++ b/id/server/proxy/moa-id-proxy.iml @@ -13,14 +13,15 @@ </facet> </component> <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false"> - <output url="file://$MODULE_DIR$/../../target/classes" /> - <output-test url="file://$MODULE_DIR$/../../target/test-classes" /> + <output url="file://$MODULE_DIR$/target/classes" /> + <output-test url="file://$MODULE_DIR$/target/test-classes" /> <content url="file://$MODULE_DIR$"> <excludeFolder url="file://$MODULE_DIR$/target" /> </content> <orderEntry type="inheritedJdk" /> <orderEntry type="sourceFolder" forTests="false" /> <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.6" level="project" /> + <orderEntry type="library" name="Maven: eu.medsea.mimeutil:mime-util:2.1.3" level="project" /> <orderEntry type="library" name="Maven: axis:axis:1.0_IAIK" level="project" /> <orderEntry type="module" module-name="moa-spss-lib" /> <orderEntry type="library" name="Maven: org.apache.axis:axis-jaxrpc:1.4" level="project" /> @@ -50,6 +51,12 @@ <orderEntry type="library" name="Maven: jaxen:jaxen:1.0-FCS" level="project" /> <orderEntry type="library" name="Maven: saxpath:saxpath:1.0-FCS" level="project" /> <orderEntry type="library" name="Maven: joda-time:joda-time:1.6.2" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:slf4j-simple:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:log4j-over-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.5" level="project" /> + <orderEntry type="library" name="Maven: commons-io:commons-io:1.3.2" level="project" /> <orderEntry type="library" name="Maven: iaik.prod:iaik_tsl:1.0" level="project" /> <orderEntry type="library" name="Maven: iaik:iaik_xsect_eval:1.1709142" level="project" /> <orderEntry type="library" name="Maven: iaik:iaik_ecc_signed:2.19" level="project" /> @@ -88,24 +95,9 @@ <orderEntry type="library" name="Maven: org.apache.velocity:velocity:1.7" level="project" /> <orderEntry type="library" name="Maven: org.owasp.esapi:esapi:2.0.1" level="project" /> <orderEntry type="library" name="Maven: org.bouncycastle:bcprov-jdk16:1.46" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-api:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-simple:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:jcl-over-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:log4j-over-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:jul-to-slf4j:1.7.5" level="project" /> - <orderEntry type="library" name="Maven: commons-io:commons-io:2.2" level="project" /> <orderEntry type="library" name="Maven: eu.stork:oasis-dss-api:1.0.0-SNAPSHOT" level="project" /> <orderEntry type="library" scope="TEST" name="Maven: junit:junit:3.8.1" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.ws:jaxws-rt:2.1.7" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.ws:jaxws-api:2.1" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.messaging.saaj:saaj-impl:1.3.3" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.soap:saaj-api:1.3" level="project" /> - <orderEntry type="library" name="Maven: com.sun.xml.stream.buffer:streambuffer:0.9" level="project" /> - <orderEntry type="library" name="Maven: org.jvnet.staxex:stax-ex:1.2" level="project" /> - <orderEntry type="library" name="Maven: javax.xml.stream:stax-api:1.0" level="project" /> - <orderEntry type="library" name="Maven: org.codehaus.woodstox:wstx-asl:3.2.3" level="project" /> - <orderEntry type="library" name="Maven: com.sun.org.apache.xml.internal:resolver:20050927" level="project" /> - <orderEntry type="library" name="Maven: org.jvnet:mimepull:1.3" level="project" /> + <orderEntry type="library" name="Maven: eu.medsea.mimeutil:mime-util:2.1.3" level="project" /> <orderEntry type="module" module-name="moa-id-commons" /> <orderEntry type="library" name="Maven: org.hibernate:hibernate-core:4.2.1.Final" level="project" /> <orderEntry type="library" name="Maven: antlr:antlr:2.7.7" level="project" /> @@ -131,12 +123,12 @@ <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-roundtrip:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2_commons:jaxb2-basics-testing:0.6.2" level="project" /> <orderEntry type="library" name="Maven: xmlunit:xmlunit:1.0" level="project" /> - <orderEntry type="library" name="Maven: org.slf4j:slf4j-log4j12:1.6.1" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-persistence:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.hyperjaxb3:hyperjaxb3-ejb-schemas-customizations:0.5.6" level="project" /> <orderEntry type="library" name="Maven: org.springframework:spring:2.0.7" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2.maven2:maven-jaxb2-plugin:0.8.0" level="project" /> <orderEntry type="library" name="Maven: org.jvnet.jaxb2.maven2:maven-jaxb2-plugin-core:0.8.0" level="project" /> + <orderEntry type="library" name="Maven: com.sun.org.apache.xml.internal:resolver:20050927" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-plugin-api:2.2.1" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-project:2.2.1" level="project" /> <orderEntry type="library" name="Maven: org.apache.maven:maven-settings:2.2.1" level="project" /> diff --git a/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/CustomAttributeQueryImpl.java b/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/CustomAttributeQueryImpl.java index e485827c8..da6a8ab27 100644 --- a/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/CustomAttributeQueryImpl.java +++ b/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/CustomAttributeQueryImpl.java @@ -50,13 +50,11 @@ public class CustomAttributeQueryImpl extends SubjectQueryImpl implements Custom return Collections.unmodifiableList(children);
}
- @Override
public String getAssertionConsumerServiceURL() {
// TODO Auto-generated method stub
return this.serviceURL;
}
- @Override
public void setAssertionConsumerServiceURL(String newServiceUrl) {
// TODO Auto-generated method stub
this.serviceURL = newServiceUrl;
diff --git a/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignSW.java b/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignSW.java index 4554a9586..6652560bd 100644 --- a/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignSW.java +++ b/id/server/stork2-saml-engine/src/main/java/eu/stork/peps/auth/engine/core/impl/SignSW.java @@ -426,16 +426,16 @@ public class SignSW implements SAMLEngineSignI { final BasicX509Credential entityX509Cred = new BasicX509Credential();
entityX509Cred.setEntityCertificate(cert);
- try {
- cert.checkValidity();
- }
- catch (CertificateExpiredException exp) {
- throw new SAMLEngineException("Certificate expired.");
- }
- catch (CertificateNotYetValidException exp) {
- throw new SAMLEngineException("Certificate not yet valid.");
- }
-
+// try {
+// cert.checkValidity();
+// }
+// catch (CertificateExpiredException exp) {
+// throw new SAMLEngineException("Certificate expired.");
+// }
+// catch (CertificateNotYetValidException exp) {
+// throw new SAMLEngineException("Certificate not yet valid.");
+// }
+//
boolean trusted = false;
for (final Enumeration<String> e = storkOwnKeyStore.aliases(); e.hasMoreElements();)
diff --git a/id/templates/moa-id-templates.iml b/id/templates/moa-id-templates.iml deleted file mode 100644 index 0ecf962d0..000000000 --- a/id/templates/moa-id-templates.iml +++ /dev/null @@ -1,25 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<module org.jetbrains.idea.maven.project.MavenProjectsManager.isMavenModule="true" type="JAVA_MODULE" version="4"> - <component name="FacetManager"> - <facet type="web" name="Web"> - <configuration> - <descriptors> - <deploymentDescriptor name="web.xml" url="file://$MODULE_DIR$/src/main/webapp/WEB-INF/web.xml" /> - </descriptors> - <webroots> - <root url="file://$MODULE_DIR$/src/main/webapp" relative="/" /> - </webroots> - </configuration> - </facet> - </component> - <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_5" inherit-compiler-output="false"> - <output url="file://$MODULE_DIR$/../target/classes" /> - <output-test url="file://$MODULE_DIR$/../target/test-classes" /> - <content url="file://$MODULE_DIR$"> - <excludeFolder url="file://$MODULE_DIR$/target" /> - </content> - <orderEntry type="inheritedJdk" /> - <orderEntry type="sourceFolder" forTests="false" /> - </component> -</module> - |