diff options
Diffstat (limited to 'id/server/modules')
155 files changed, 6771 insertions, 10664 deletions
diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index 11917d0c3..21e7f2027 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -1,10 +1,6 @@ package at.gv.egovernment.moa.id.auth; -import iaik.asn1.ObjectID; -import iaik.x509.X509Certificate; -import iaik.x509.X509ExtensionInitException; - import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -22,6 +18,8 @@ import javax.xml.transform.TransformerException; import org.apache.commons.lang.StringEscapeUtils; import org.apache.xpath.XPathAPI; import org.opensaml.xml.util.Base64; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -29,7 +27,6 @@ import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.AuthenticationBlockAssertionBuilder; import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.builder.CreateXMLSignatureRequestBuilder; @@ -62,8 +59,7 @@ import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.MISMandate; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; @@ -76,6 +72,9 @@ import at.gv.egovernment.moa.util.DateTimeUtils; import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.StringUtils; +import iaik.asn1.ObjectID; +import iaik.x509.X509Certificate; +import iaik.x509.X509ExtensionInitException; /** * API for MOA ID Authentication Service.<br> {@link AuthenticationSession} is @@ -85,24 +84,12 @@ import at.gv.egovernment.moa.util.StringUtils; * @version $Id: AuthenticationServer.java 1273 2012-02-27 14:50:18Z kstranacher * $ */ +@Service("CitizenCardAuthenticationServer") public class AuthenticationServer extends BaseAuthenticationServer { - /** - * single instance - */ - private static AuthenticationServer instance; - - /** - * 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; - } - + @Autowired private MOAReversionLogger revisionsLogger; + @Autowired private AuthConfiguration authConfig; + /** * Constructor for AuthenticationServer. */ @@ -139,13 +126,14 @@ public class AuthenticationServer extends BaseAuthenticationServer { * @param templateMandteURL URL providing an HTML template for the HTML form generated * (for signing in mandates mode) * @param req determines the protocol used + * @param pendingReq * @param sourceID * @return HTML form * @throws AuthenticationException * @see GetIdentityLinkFormBuilder * @see InfoboxReadRequestBuilder */ - public String startAuthentication(AuthenticationSession session, HttpServletRequest req) throws WrongParametersException, + public String startAuthentication(AuthenticationSession session, HttpServletRequest req, IRequest pendingReq) throws WrongParametersException, AuthenticationException, ConfigurationException, BuildException { if (session == null) { @@ -153,40 +141,37 @@ public class AuthenticationServer extends BaseAuthenticationServer { } //load OnlineApplication configuration - OAAuthParameter oaParam = - AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[]{session.getPublicOAURLPrefix()}); + throw new AuthenticationException("auth.00", new Object[]{pendingReq.getOAURL()}); //load Template + String templateURL = pendingReq.getGenericData( + MOAIDAuthConstants.AUTHPROCESS_DATA_SECURITYLAYERTEMPLATE, String.class); String template = null; - if (session.getTemplateURL() != null) { + if (MiscUtil.isNotEmpty(templateURL)) { try { - - template = new String(FileUtils.readURL(session.getTemplateURL())); + template = new String(FileUtils.readURL(templateURL)); + } catch (IOException ex) { throw new AuthenticationException("auth.03", new Object[]{ - session.getTemplateURL(), ex.toString()}, ex); + templateURL, ex.toString()}, ex); + } + + } else { + throw new AuthenticationException("auth.04", new Object[]{ + "SecurityLayerTemplate", "No template definde"}); + } String infoboxReadRequest = ""; - - String domainIdentifier = AuthConfigurationProviderFactory.getInstance().getSSOTagetIdentifier().trim(); - if (MiscUtil.isEmpty(domainIdentifier) && session.isSsoRequested()) { - //do not use SSO if no Target is set - Logger.warn("NO SSO-Target found in configuration. Single Sign-On is deaktivated!"); - session.setSsoRequested(false); - - } - - if (session.isSsoRequested()) { + if (pendingReq.needSingleSignOnFunctionality()) { Logger.info("SSO Login requested"); //load identityLink with SSO Target boolean isbuisness = false; - + String domainIdentifier = authConfig.getSSOTagetIdentifier().trim(); if (domainIdentifier.startsWith(PREFIX_WPBK)) { - isbuisness = true; } else { @@ -207,36 +192,19 @@ public class AuthenticationServer extends BaseAuthenticationServer { } - + //build DataURL for BKU request String dataURL = new DataURLBuilder().buildDataURL( - session.getAuthURL(), REQ_VERIFY_IDENTITY_LINK, session - .getSessionID()); + pendingReq.getAuthURL(), REQ_VERIFY_IDENTITY_LINK, pendingReq.getRequestID()); //removed in MOAID 2.0 String pushInfobox = ""; - // VerifyInfoboxParameters verifyInfoboxParameters = oaParam - // .getVerifyInfoboxParameters(); - // if (verifyInfoboxParameters != null) { - // pushInfobox = verifyInfoboxParameters.getPushInfobox(); - // session.setPushInfobox(pushInfobox); - // } - - //build CertInfo request - //removed in MOA-ID 2.0 - // 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); - //TODO: cleanup before MOA-ID 2.1 release try { String htmlForm = new GetIdentityLinkFormBuilder().build(template, session.getBkuURL(), infoboxReadRequest, dataURL, null, @@ -291,9 +259,6 @@ public class AuthenticationServer extends BaseAuthenticationServer { throw new AuthenticationException("auth.10", new Object[]{ REQ_VERIFY_IDENTITY_LINK, PARAM_XMLRESPONSE}); - AuthConfiguration authConf = AuthConfigurationProviderFactory - .getInstance(); - // check if an identity link was found // Errorcode 2911 von Trustdesk BKU (nicht spezifikationskonform // (SL1.2)) @@ -323,7 +288,7 @@ public class AuthenticationServer extends BaseAuthenticationServer { IdentityLinkValidator.getInstance().validate(identityLink); // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() - .build(identityLink, authConf + .build(identityLink, authConfig .getMoaSpIdentityLinkTrustProfileID(pendingReq.getOnlineApplicationConfiguration().isUseIDLTestTrustStore())); // invokes the call @@ -333,13 +298,12 @@ public class AuthenticationServer extends BaseAuthenticationServer { VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( domVerifyXMLSignatureResponse).parseData(); - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + // validates the <VerifyXMLSignatureResponse> VerifyXMLSignatureResponseValidator.getInstance().validate( verifyXMLSignatureResponse, - authConf.getIdentityLinkX509SubjectNames(), + authConfig.getIdentityLinkX509SubjectNames(), VerifyXMLSignatureResponseValidator.CHECK_IDENTITY_LINK, oaParam); @@ -349,7 +313,7 @@ public class AuthenticationServer extends BaseAuthenticationServer { //Removed in MOA-ID 2.0 //verifyInfoboxes(session, infoboxReadResponseParameters, false); - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_IDL_VALIDATED); return "found!"; @@ -379,15 +343,11 @@ public class AuthenticationServer extends BaseAuthenticationServer { * @return String representation of the * <code><CreateXMLSignatureRequest></code> */ - public String verifyCertificate(AuthenticationSession session, + public void verifyCertificate(AuthenticationSession session, X509Certificate certificate, IRequest pendingReq) 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 { @@ -403,16 +363,6 @@ public class AuthenticationServer extends BaseAuthenticationServer { session.setOW(false); } - AuthConfiguration authConf = AuthConfigurationProviderFactory - .getInstance(); - - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - String returnvalue = getCreateXMLSignatureRequestAuthBlockOrRedirect(session, - authConf, oaParam, pendingReq); - - return returnvalue; } /** @@ -426,6 +376,7 @@ public class AuthenticationServer extends BaseAuthenticationServer { * layer implementation</li> * </ul> * @param pendingReq + * @param pendingReq * * @param sessionID ID of associated authentication session data * @param infoboxReadResponseParameters The parameters from the response returned from the BKU @@ -433,7 +384,7 @@ public class AuthenticationServer extends BaseAuthenticationServer { * @return String representation of the * <code><CreateXMLSignatureRequest></code> */ - public void verifyMandate(AuthenticationSession session, MISMandate mandate) + public void verifyMandate(IRequest pendingReq, AuthenticationSession session, MISMandate mandate) throws AuthenticationException, BuildException, ParseException, ConfigurationException, ValidateException, ServiceException { @@ -441,9 +392,7 @@ public class AuthenticationServer extends BaseAuthenticationServer { throw new AuthenticationException("auth.10", new Object[]{ GET_MIS_SESSIONID, PARAM_SESSIONID}); - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); try { // sets the extended SAML attributes for OID (Organwalter) setExtendedSAMLAttributeForMandatesOID(session, mandate, oaParam @@ -470,8 +419,6 @@ public class AuthenticationServer extends BaseAuthenticationServer { /** * @param session - * @param authConf - * @param oaParam * @param pendingReq * @return * @throws ConfigurationException @@ -479,26 +426,16 @@ public class AuthenticationServer extends BaseAuthenticationServer { * @throws ValidateException */ public String getCreateXMLSignatureRequestAuthBlockOrRedirect( - AuthenticationSession session, AuthConfiguration authConf, - OAAuthParameter oaParam, IRequest pendingReq) throws ConfigurationException, + AuthenticationSession session, IRequest pendingReq) throws ConfigurationException, BuildException, ValidateException { - // // check for intermediate processing of the infoboxes - // if (session.isValidatorInputPending()) - // return "Redirect to Input Processor"; - - if (authConf == null) - authConf = AuthConfigurationProviderFactory.getInstance(); - if (oaParam == null) - oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); // builds the AUTH-block String authBlock = buildAuthenticationBlock(session, oaParam, pendingReq); // builds the <CreateXMLSignatureRequest> - List<String> transformsInfos = authConf.getTransformsInfos(); + List<String> transformsInfos = authConfig.getTransformsInfos(); String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() .build(authBlock, oaParam.getKeyBoxIdentifier(), @@ -511,112 +448,26 @@ public class AuthenticationServer extends BaseAuthenticationServer { * <ul> * <li>Creates an CreateXMLSignatureRequest to be signed by the user</li> * </ul> + * @param pendingReq * * @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, + public String createXMLSignatureRequestForeignID(IRequest pendingReq, X509Certificate cert) throws AuthenticationException, BuildException, ParseException, ConfigurationException, ValidateException, ServiceException { - if (session == null) - throw new AuthenticationException("auth.10", new Object[]{ - REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID}); - - AuthConfiguration authConf = AuthConfigurationProviderFactory - .getInstance(); - - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - return getCreateXMLSignatureRequestForeigID(session, authConf, oaParam, - cert); - } - - public String getCreateXMLSignatureRequestForeigID( - AuthenticationSession session, AuthConfiguration 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 = AuthConfigurationProviderFactory.getInstance(); - if (oaParam == null) - oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - Principal subject = cert.getSubjectDN(); String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() - .buildForeignID(subject.toString(), oaParam, session); + .buildForeignID(subject.toString(), pendingReq); 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}); -// -// AuthConfiguration authConf = AuthConfigurationProviderFactory -// .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> @@ -634,15 +485,11 @@ public class AuthenticationServer extends BaseAuthenticationServer { * including the <code><ReadInfoboxResponse></code> * @throws BKUException */ - public X509Certificate getCertificate(IRequest pendingReq, String sessionID, + public X509Certificate getCertificate(IRequest pendingReq, 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); @@ -655,7 +502,7 @@ public class AuthenticationServer extends BaseAuthenticationServer { xmlReadInfoboxResponse); X509Certificate cert = p.parseCertificate(); - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_CERTIFICATE_VALIDATED); return cert; @@ -673,7 +520,7 @@ public class AuthenticationServer extends BaseAuthenticationServer { * to be appended to the AUTH-Block. */ private String buildAuthenticationBlock(AuthenticationSession session, - OAAuthParameter oaParam, IRequest pendingReq) throws BuildException { + IOAAuthParameters oaParam, IRequest pendingReq) throws BuildException { IdentityLink identityLink = session.getIdentityLink(); String issuer = identityLink.getName(); @@ -682,8 +529,16 @@ public class AuthenticationServer extends BaseAuthenticationServer { String identificationValue = null; String identificationType = null; + //get processing data from pending-request + String authURL = pendingReq.getAuthURL(); + String requestedTarget = pendingReq.getGenericData( + MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, String.class); + String targetFriendlyName = pendingReq.getGenericData( + MOAIDAuthConstants.AUTHPROCESS_DATA_TARGETFRIENDLYNAME, String.class); + + //set empty AuthBlock BPK in case of OW or SSO or bpk is not requested - if (session.isOW() || session.isSsoRequested() || oaParam.isRemovePBKFromAuthBlock()) { + if (session.isOW() || pendingReq.needSingleSignOnFunctionality() || oaParam.isRemovePBKFromAuthBlock()) { identificationType = ""; identificationValue = ""; @@ -700,11 +555,11 @@ public class AuthenticationServer extends BaseAuthenticationServer { else identificationType = Constants.URN_PREFIX_WBPK + "+" + oaParam.getIdentityLinkDomainIdentifier(); - } else { + } else { String bpkBase64 = new BPKBuilder().buildBPK(identityLink - .getIdentificationValue(), session.getTarget()); + .getIdentificationValue(), requestedTarget); identificationValue = bpkBase64; - identificationType = Constants.URN_PREFIX_CDID + "+" + session.getTarget(); + identificationType = Constants.URN_PREFIX_CDID + "+" + requestedTarget; } @@ -714,12 +569,10 @@ public class AuthenticationServer extends BaseAuthenticationServer { } + //set AuthBlock generation time to session 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) @@ -728,22 +581,22 @@ public class AuthenticationServer extends BaseAuthenticationServer { List<ExtendedSAMLAttribute> extendedSAMLAttributes = session.getExtendedSAMLAttributesAUTH(); - if (session.isSsoRequested()) { + if (pendingReq.needSingleSignOnFunctionality()) { String oaURL = pendingReq.getAuthURL(); if (MiscUtil.isNotEmpty(oaURL)) oaURL = oaURL.replaceAll("&", "&"); String authBlock = new AuthenticationBlockAssertionBuilder() - .buildAuthBlockSSO(issuer, issueInstant, authURL, target, + .buildAuthBlockSSO(issuer, issueInstant, authURL, requestedTarget, targetFriendlyName, identificationValue, identificationType, oaURL, gebDat, extendedSAMLAttributes, session, oaParam); return authBlock; - } else { - String oaURL = session.getPublicOAURLPrefix().replaceAll("&", "&"); + } else { + String oaURL = oaParam.getPublicURLPrefix().replaceAll("&", "&"); String authBlock = new AuthenticationBlockAssertionBuilder() - .buildAuthBlock(issuer, issueInstant, authURL, target, + .buildAuthBlock(issuer, issueInstant, authURL, requestedTarget, targetFriendlyName, identificationValue, identificationType, oaURL, gebDat, extendedSAMLAttributes, session, oaParam); @@ -1066,8 +919,6 @@ public class AuthenticationServer extends BaseAuthenticationServer { throw new AuthenticationException("auth.10", new Object[]{ REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); - AuthConfiguration authConf = AuthConfigurationProviderFactory - .getInstance(); // parses <CreateXMLSignatureResponse> CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser( xmlCreateXMLSignatureReadResponse).parseResponse(); @@ -1084,14 +935,15 @@ public class AuthenticationServer extends BaseAuthenticationServer { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); } // validates <CreateXMLSignatureResponse> - if (session.isSsoRequested()) + if (pendingReq.needSingleSignOnFunctionality()) new CreateXMLSignatureResponseValidator().validateSSO(csresp, session, pendingReq); + else new CreateXMLSignatureResponseValidator().validate(csresp, session, pendingReq); // builds a <VerifyXMLSignatureRequest> for a MOA-SPSS call - List<String> vtids = authConf.getMoaSpAuthBlockVerifyTransformsInfoIDs(); - String tpid = authConf.getMoaSpAuthBlockTrustProfileID(pendingReq.getOnlineApplicationConfiguration().isUseAuthBlockTestTestStore()); + List<String> vtids = authConfig.getMoaSpAuthBlockVerifyTransformsInfoIDs(); + String tpid = authConfig.getMoaSpAuthBlockTrustProfileID(pendingReq.getOnlineApplicationConfiguration().isUseAuthBlockTestTestStore()); Element domVsreq = new VerifyXMLSignatureRequestBuilder().build(csresp, vtids, tpid); // debug output @@ -1121,8 +973,7 @@ public class AuthenticationServer extends BaseAuthenticationServer { } } - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); // validates the <VerifyXMLSignatureResponse> VerifyXMLSignatureResponseValidator.getInstance().validate(vsresp, @@ -1163,10 +1014,10 @@ public class AuthenticationServer extends BaseAuthenticationServer { //set QAA Level four in case of card authentifcation session.setQAALevel(PVPConstants.STORK_QAA_1_4); - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_AUTHBLOCK_VALIDATED); - MOAReversionLogger.getInstance().logPersonalInformationEvent(pendingReq, session.getIdentityLink() + revisionsLogger.logPersonalInformationEvent(pendingReq, session.getIdentityLink() ); } diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SimpleNamespaceContext.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/CitizenCardAuthenticationSpringResourceProvider.java index 2c2df3e54..18bf5a1ba 100644 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/SimpleNamespaceContext.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/CitizenCardAuthenticationSpringResourceProvider.java @@ -20,64 +20,44 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. */ -package at.gv.egovernment.moa.id.protocols.stork2; +package at.gv.egovernment.moa.id.auth; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map.Entry; -import java.util.Set; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; -import javax.xml.namespace.NamespaceContext; +import at.gv.egiz.components.spring.api.SpringResourceProvider; /** * @author tlenz * */ -public class SimpleNamespaceContext implements NamespaceContext { - - HashMap<String, String> prefMap = null; - /** - * @param prefMap - */ - SimpleNamespaceContext(HashMap<String, String> prefMap) { - this.prefMap = prefMap; - } +public class CitizenCardAuthenticationSpringResourceProvider implements SpringResourceProvider { /* (non-Javadoc) - * @see javax.xml.namespace.NamespaceContext#getNamespaceURI(java.lang.String) + * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getResourcesToLoad() */ @Override - public String getNamespaceURI(String prefix) { - if (prefMap.containsKey(prefix)) - return prefMap.get(prefix); - else - return null; + public Resource[] getResourcesToLoad() { + ClassPathResource citizenCardAuthConfig = new ClassPathResource("/moaid_citizencard_auth.beans.xml", MOAIDAuthSpringResourceProvider.class); + + return new Resource[] {citizenCardAuthConfig}; } /* (non-Javadoc) - * @see javax.xml.namespace.NamespaceContext#getPrefix(java.lang.String) + * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getPackagesToScan() */ @Override - public String getPrefix(String namespaceURI) { - if (prefMap.containsValue(namespaceURI)) { - Set<Entry<String, String>> set = prefMap.entrySet(); - for (Entry<String, String> el : set) { - if (el.getValue().equals(namespaceURI)) - return el.getKey(); - - } - } - + public String[] getPackagesToScan() { + // TODO Auto-generated method stub return null; } /* (non-Javadoc) - * @see javax.xml.namespace.NamespaceContext#getPrefixes(java.lang.String) + * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getName() */ @Override - public Iterator getPrefixes(String namespaceURI) { - // TODO Auto-generated method stub - return null; + public String getName() { + return "MOA-ID-CitizenCardAuthentication SpringResourceProvider"; } } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java index 760d28d5b..9ae1dc6a7 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/AuthenticationBlockAssertionBuilder.java @@ -52,7 +52,6 @@ import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; @@ -175,7 +174,7 @@ public class AuthenticationBlockAssertionBuilder extends AuthenticationAssertion String gebDat, List<ExtendedSAMLAttribute> extendedSAMLAttributes, AuthenticationSession session, - OAAuthParameter oaParam) + IOAAuthParameters oaParam) throws BuildException { @@ -264,15 +263,9 @@ public class AuthenticationBlockAssertionBuilder extends AuthenticationAssertion String text = ""; - try { - OAAuthParameter oaparam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - if (MiscUtil.isNotEmpty(oaparam.getAditionalAuthBlockText())) { - Logger.debug("Use addional AuthBlock Text from OA=" + oaparam.getPublicURLPrefix()); - text = oaparam.getAditionalAuthBlockText(); - } - - } catch (ConfigurationException e) { - Logger.warn("Addional AuthBlock Text can not loaded from OA!", e); + if (MiscUtil.isNotEmpty(oaParam.getAditionalAuthBlockText())) { + Logger.debug("Use addional AuthBlock Text from OA=" + oaParam.getPublicURLPrefix()); + text = oaParam.getAditionalAuthBlockText(); } String specialText = MessageFormat.format(SPECIAL_TEXT_ATTRIBUTE, @@ -345,25 +338,14 @@ public class AuthenticationBlockAssertionBuilder extends AuthenticationAssertion String oaURL, String gebDat, List<ExtendedSAMLAttribute> extendedSAMLAttributes, - AuthenticationSession session) + AuthenticationSession session, + IOAAuthParameters oaParam) throws BuildException { session.setSAMLAttributeGebeORwbpk(true); String gebeORwbpk = ""; String wbpkNSDeclaration = ""; - - //BZ.., reading OA parameters - OAAuthParameter oaParam; - try { - oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - } catch (ConfigurationException e) { - Logger.error("Error on building AUTH-Block: " + e.getMessage()); - throw new BuildException("builder.00", new Object[] { "AUTH-Block", e.toString()}); - } - //..BZ - - + if (target == null) { // OA is a business application if (!Constants.URN_PREFIX_HPI.equals(identityLinkType)) { @@ -419,14 +401,9 @@ public class AuthenticationBlockAssertionBuilder extends AuthenticationAssertion //..BZ String text = ""; - try { - OAAuthParameter oaparam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - if (MiscUtil.isNotEmpty(oaparam.getAditionalAuthBlockText())) { - Logger.debug("Use addional AuthBlock Text from OA=" + oaparam.getPublicURLPrefix()); - text = oaparam.getAditionalAuthBlockText(); - } - } catch (ConfigurationException e) { - Logger.warn("Addional AuthBlock Text can not loaded from OA!", e); + if (MiscUtil.isNotEmpty(oaParam.getAditionalAuthBlockText())) { + Logger.debug("Use addional AuthBlock Text from OA=" + oaParam.getPublicURLPrefix()); + text = oaParam.getAditionalAuthBlockText(); } String specialText = MessageFormat.format(SPECIAL_TEXT_ATTRIBUTE, diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java index 8b0d906fe..306c871fc 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/SAMLResponseBuilder.java @@ -123,7 +123,8 @@ public class SAMLResponseBuilder implements Constants { statusMessage, StringUtils.removeXMLDeclaration(samlAssertion) }); Element domResponse = DOMUtils.parseDocument(xmlResponse, false, ALL_SCHEMA_LOCATIONS, null).getDocumentElement(); - return domResponse; + return domResponse; + } catch (Throwable ex) { throw new BuildException( diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java deleted file mode 100644 index 5c1b12e0d..000000000 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/builder/StartAuthenticationBuilder.java +++ /dev/null @@ -1,70 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -package at.gv.egovernment.moa.id.auth.builder; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; -import at.gv.egovernment.moa.logging.Logger; - -public class StartAuthenticationBuilder { - - private static StartAuthenticationBuilder instance = null; - - public static StartAuthenticationBuilder getInstance() { - if (instance == null) { - instance = new StartAuthenticationBuilder(); - } - return instance; - } - - - /** - * Depending on the selected citizen's country ({@code moasession.ccc}): - * <ul> - * <li><strong>Either</strong> creates an "IdentityLinkForm" with embedded {@code InfoBoxReadRequest} to be submitted to a citizen card - * environment for reading the subject's IdentityLink</li> - * </ul> - * - * @return The IdentityLinkForm. - */ - public String build(AuthenticationSession moasession, HttpServletRequest req, - HttpServletResponse resp) throws WrongParametersException, MOAIDException { - - if (moasession == null) { - throw new AuthenticationException("auth.18", new Object[] { }); - } - - //normal MOA-ID authentication - Logger.debug("Starting normal MOA-ID authentication"); - - String getIdentityLinkForm = AuthenticationServer.getInstance().startAuthentication(moasession, req); - - return getIdentityLinkForm; - } -} diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java deleted file mode 100644 index 72a7d3ba1..000000000 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/invoke/SignatureVerificationInvoker.java +++ /dev/null @@ -1,142 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egovernment.moa.id.auth.invoke; - -import java.util.Vector; - -import javax.xml.namespace.QName; -import javax.xml.rpc.Call; -import javax.xml.rpc.Service; -import javax.xml.rpc.ServiceFactory; - -import org.apache.axis.message.SOAPBodyElement; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.auth.exception.ServiceException; -import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.spss.api.SignatureVerificationService; -import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureRequestParser; -import at.gv.egovernment.moa.spss.api.xmlbind.VerifyXMLSignatureResponseBuilder; -import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest; -import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse; -import at.gv.egovernment.moa.util.MiscUtil; - -/** - * Invoker of the <code>SignatureVerification</code> web service of MOA-SPSS.<br> - * Either invokes the web service, or calls the corresponding API, depending on configuration data. - * - * @author Stefan Knirsch - * @version $Id$ - */ -public class SignatureVerificationInvoker { - /** This QName Object identifies the SignatureVerification endpoint of the web service */ - private static final QName SERVICE_QNAME = new QName("SignatureVerification"); - - /** - * Method verifyXMLSignature. - * @param request to be sent - * @return Element with the answer - * @throws ServiceException if an error occurs - */ - public Element verifyXMLSignature(Element request) throws ServiceException { - return doCall(SERVICE_QNAME, request); - } - - /** - * Method doCall. - * @param serviceName the name of the service - * @param request the request to be sent - * @return Element the answer - * @throws ServiceException if an error occurs - */ - protected Element doCall(QName serviceName, Element request) throws ServiceException { - ConnectionParameter authConnParam = null; - try { - Service service = ServiceFactory.newInstance().createService(serviceName); - Call call = service.createCall(); - SOAPBodyElement body = new SOAPBodyElement(request); - SOAPBodyElement[] params = new SOAPBodyElement[] { body }; - Vector responses; - SOAPBodyElement response; - - String endPoint; - AuthConfiguration authConfigProvider = AuthConfigurationProviderFactory.getInstance(); - authConnParam = authConfigProvider.getMoaSpConnectionParameter(); - //If the ConnectionParameter do NOT exist, we try to get the api to work.... - if (authConnParam != null && MiscUtil.isNotEmpty(authConnParam.getUrl())) { - Logger.debug("Connecting using auth url: " + authConnParam.getUrl() + ", service " + serviceName.getNamespaceURI() + " : " + serviceName.getLocalPart() + " : "+ serviceName.getPrefix()); - endPoint = authConnParam.getUrl(); - call.setTargetEndpointAddress(endPoint); - responses = (Vector) call.invoke(serviceName, params); - Logger.debug("Got responses: " + responses.size()); // TODO handle axis 302 response when incorrect service url is used - response = (SOAPBodyElement) responses.get(0); - return response.getAsDOM(); - } - else { - SignatureVerificationService svs = SignatureVerificationService.getInstance(); - VerifyXMLSignatureRequest vsrequest = new VerifyXMLSignatureRequestParser().parse(request); - - VerifyXMLSignatureResponse vsresponse = svs.verifyXMLSignature(vsrequest); - Document result = new VerifyXMLSignatureResponseBuilder().build(vsresponse); - - //Logger.setHierarchy("moa.id.auth"); - return result.getDocumentElement(); - } - } - catch (Exception ex) { - if (authConnParam != null) { - throw new ServiceException("service.00", new Object[] { ex.toString()}, ex); - } else { - throw new ServiceException("service.03", new Object[] { ex.toString()}, ex); - } - } - } -} diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/AuthModuleImpl.java index cac7359c7..29118ac17 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthModuleImpl.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/AuthModuleImpl.java @@ -1,5 +1,6 @@ package at.gv.egovernment.moa.id.auth.modules.internal; + import org.apache.commons.lang3.StringUtils; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; @@ -9,7 +10,7 @@ import at.gv.egovernment.moa.id.process.api.ExecutionContext; /** * Module descriptor */ -public class DefaultAuthModuleImpl implements AuthModule { +public class AuthModuleImpl implements AuthModule { @Override public int getPriority() { @@ -19,8 +20,15 @@ public class DefaultAuthModuleImpl implements AuthModule { @Override public String selectProcess(ExecutionContext context) { //select process if BKU is selected and it is no STORK authentication + + boolean performBKUSelection = false; + Object performBKUSelectionObj = context.get("performBKUSelection"); + if (performBKUSelectionObj != null && performBKUSelectionObj instanceof Boolean) + performBKUSelection = (boolean) performBKUSelectionObj; + if (StringUtils.isBlank((String) context.get("ccc")) && - StringUtils.isNotBlank((String) context.get(MOAIDAuthConstants.PARAM_BKU))) + StringUtils.isNotBlank((String) context.get(MOAIDAuthConstants.PARAM_BKU)) && + !performBKUSelection) return "DefaultAuthentication"; else diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java index 7e1bf1fc7..e3afc713b 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CertificateReadRequestTask.java @@ -1,29 +1,25 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.REQ_VERIFY_CERTIFICATE; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang3.BooleanUtils; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.builder.InfoboxReadRequestBuilderCertificate; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; - +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.CitizenCardServletUtils; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; /** @@ -46,53 +42,43 @@ import at.gv.egovernment.moa.logging.Logger; * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ +@Component("CertificateReadRequestTask") public class CertificateReadRequestTask extends AbstractAuthServletTask { @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) throws TaskExecutionException { - - // TODO[branch]: Foreign citizen or mandate mode; respond with IRR for certificates, dataURL = "/VerifyCertificate" - Logger.info("Send InfoboxReadRequest to BKU to get signer certificate."); - - setNoCachingHeaders(resp); + Logger.debug("Send InfoboxReadRequest to BKU to get signer certificate."); + try { + //execute default task initialization + defaultTaskInitialization(req, executionContext); - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("CertificateReadRequestTask", PARAM_SESSIONID, "auth.12"); - } - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - boolean useMandate = session.getUseMandate(); - boolean identityLinkAvailable = BooleanUtils.isTrue((Boolean) executionContext.get("identityLinkAvailable")); - + boolean useMandate = moasession.getUseMandate(); + boolean identityLinkAvailable = BooleanUtils.isTrue((Boolean) executionContext.get("identityLinkAvailable")); if (!identityLinkAvailable && useMandate) { Logger.error("Online-Mandate Mode for foreign citizencs not supported."); throw new AuthenticationException("auth.13", null); } - - // change MOASessionID - AuthenticationSessionStoreage.changeSessionID(session); // create the InfoboxReadRequest to get the certificate String infoboxReadRequest = new InfoboxReadRequestBuilderCertificate().build(true); // build dataurl (to the VerifyCertificateSerlvet) - String dataurl = new DataURLBuilder().buildDataURL(session.getAuthURL(), REQ_VERIFY_CERTIFICATE, - session.getSessionID()); + String dataurl = new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), REQ_VERIFY_CERTIFICATE, + pendingReq.getRequestID()); CitizenCardServletUtils.writeCreateXMLSignatureRequest(resp, infoboxReadRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink", dataurl); } catch (MOAIDException ex) { - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); } catch (IOException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } catch (MOADatabaseException e1) { + throw new TaskExecutionException(pendingReq, e1.getMessage(), e1); } finally { diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java index 307074ee2..cbaaa5ec7 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/CreateIdentityLinkFormTask.java @@ -1,33 +1,24 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; - import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.ObjectUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.advancedlogging.TransactionIDUtils; -import at.gv.egovernment.moa.id.auth.builder.StartAuthenticationBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; -import at.gv.egovernment.moa.id.auth.servlet.GenerateIFrameTemplateServlet; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.StringUtils; /** @@ -62,46 +53,27 @@ import at.gv.egovernment.moa.util.StringUtils; * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ +@Component("CreateIdentityLinkFormTask") public class CreateIdentityLinkFormTask extends AbstractAuthServletTask { + @Autowired @Qualifier("CitizenCardAuthenticationServer") private AuthenticationServer authServer; + @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) - throws TaskExecutionException { - - String moasessionid = StringEscapeUtils.escapeHtml(ObjectUtils.defaultIfNull(req.getParameter(PARAM_SESSIONID), (String) executionContext.get(PARAM_SESSIONID))); - AuthenticationSession moasession = null; + throws TaskExecutionException { try { - - if (MiscUtil.isEmpty(moasessionid)) { - Logger.warn("MOASessionID is empty."); - throw new MOAIDException("auth.18", new Object[] {}); - } - - try { - moasession = AuthenticationSessionStoreage.getSession(moasessionid); + //execute default task initialization + defaultTaskInitialization(req, executionContext); + + //normal MOA-ID authentication + Logger.debug("Starting normal MOA-ID authentication"); + String getIdentityLinkForm = authServer.startAuthentication(moasession, req, pendingReq); - AuthenticationSessionStoreage.changeSessionID(moasession); - executionContext.remove(PARAM_SESSIONID); - - } catch (MOADatabaseException e) { - Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); - throw new MOAIDException("init.04", new Object[] { moasessionid }); - - } catch (Throwable e) { - Logger.info("No HTTP Session found!"); - throw new MOAIDException("auth.18", new Object[] {}); - } - - StartAuthenticationBuilder startauth = StartAuthenticationBuilder.getInstance(); - String getIdentityLinkForm = startauth.build(moasession, req, resp); - - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); if (BooleanUtils.isTrue((Boolean) executionContext.get("useMandate"))) - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_MANDATES_REQUESTED); - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_URL, moasession.getBkuURL()); if (!StringUtils.isEmpty(getIdentityLinkForm)) { @@ -109,21 +81,21 @@ public class CreateIdentityLinkFormTask extends AbstractAuthServletTask { PrintWriter out = new PrintWriter(resp.getOutputStream()); out.print(getIdentityLinkForm); out.flush(); - Logger.debug("Finished GET " + GenerateIFrameTemplateServlet.class); + Logger.debug("Finished GET " + CreateIdentityLinkFormTask.class); } } catch (WrongParametersException ex) { -// handleWrongParameters(ex, req, resp); - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); + } catch (MOAIDException ex) { Logger.info("GetIdentityLink request generation FAILED. Reason:" + ex.getMessage()); - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); } catch (Exception e) { Logger.error("CreateIdentityLinkFormTask has an interal Error.", e); - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java index b729f26e1..204e39b8c 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetForeignIDTask.java @@ -1,6 +1,7 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_XMLRESPONSE; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.REQ_VERIFY_AUTH_BLOCK; import java.io.ByteArrayInputStream; import java.io.IOException; @@ -12,14 +13,13 @@ import javax.servlet.http.HttpServletResponse; import javax.xml.transform.TransformerException; import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse; import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -32,12 +32,8 @@ import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; import at.gv.egovernment.moa.id.client.SZRGWClientException; import at.gv.egovernment.moa.id.client.utils.SZRGWClientUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; @@ -68,16 +64,17 @@ import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ +@Component("GetForeignIDTask") public class GetForeignIDTask extends AbstractAuthServletTask { + @Autowired @Qualifier("CitizenCardAuthenticationServer") private AuthenticationServer authServer; + @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) throws TaskExecutionException { Logger.debug("POST GetForeignIDServlet"); - setNoCachingHeaders(resp); - Map<String, String> parameters; try { @@ -85,41 +82,28 @@ public class GetForeignIDTask extends AbstractAuthServletTask { } catch (FileUploadException | IOException e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); + throw new TaskExecutionException(pendingReq, "Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); } - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - String pendingRequestID = null; - String redirectURL = null; - AuthenticationSession session = null; try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("GetForeignID", PARAM_SESSIONID, "auth.12"); - } + //check if response exists String xmlCreateXMLSignatureResponse = (String) parameters.get(PARAM_XMLRESPONSE); if (!ParamValidatorUtils.isValidXMLDocument(xmlCreateXMLSignatureResponse)) { throw new WrongParametersException("GetForeignID", PARAM_XMLRESPONSE, "auth.12"); + } - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - session = AuthenticationServer.getSession(sessionID); - - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_DATAURL_IP, req.getRemoteHost()); - - // change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - Logger.debug(xmlCreateXMLSignatureResponse); - + + //execute default task initialization + defaultTaskInitialization(req, executionContext); + + CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse) .parseResponseDsig(); try { String serializedAssertion = DOMUtils.serializeNode(csresp.getDsigSignature()); - session.setAuthBlock(serializedAssertion); + moasession.setAuthBlock(serializedAssertion); } catch (TransformerException e) { throw new ParseException("parser.04", new Object[] { REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); @@ -132,13 +116,14 @@ public class GetForeignIDTask extends AbstractAuthServletTask { Element signature = csresp.getDsigSignature(); try { - session.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature)); + moasession.setSignerCertificate(AuthenticationServer.getCertificateFromXML(signature)); + } catch (CertificateException e) { Logger.error("Could not extract certificate from CreateXMLSignatureResponse"); throw new MOAIDException("auth.14", null); } - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_FOREIGN_SZRGW_CONNECTED); // make SZR request to the identity link @@ -152,38 +137,32 @@ public class GetForeignIDTask extends AbstractAuthServletTask { IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(new ByteArrayInputStream( response.getIdentityLink())); IdentityLink identitylink = ilParser.parseIdentityLink(); - session.setIdentityLink(identitylink); + moasession.setIdentityLink(identitylink); // set QAA Level four in case of card authentifcation - session.setQAALevel(PVPConstants.STORK_QAA_1_4); - - AuthenticationServer.getInstance().getForeignAuthenticationData(session); - - // session is implicit stored in changeSessionID!!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + moasession.setQAALevel(PVPConstants.STORK_QAA_1_4); - Logger.info("Changed MOASession " + sessionID + " to Session " + newMOASessionID); - Logger.info("Daten angelegt zu MOASession " + newMOASessionID); + authServer.getForeignAuthenticationData(moasession); - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_FOREIGN_SZRGW_RECEIVED); try { - AuthenticationSessionStoreage.storeSession(session); + authenticatedSessionStorage.storeSession(moasession); + } catch (MOADatabaseException e) { throw new MOAIDException("Session store error", null); } - //put session to context - executionContext.put(PARAM_SESSIONID, session.getSessionID()); + } } catch (MOAIDException ex) { - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); } catch (Exception e) { Logger.error("GetForeignIDServlet has an interal Error.", e); - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java index d85681b40..0a1e3c8f5 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/GetMISSessionIDTask.java @@ -1,7 +1,6 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; -import iaik.pki.PKIException; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.GET_MIS_SESSIONID; import java.security.GeneralSecurityException; import java.util.List; @@ -11,35 +10,25 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.ParserConfigurationException; -import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; - import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.data.MISMandate; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.id.util.SSLUtils; import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; +import iaik.pki.PKIException; /** * Retrieves a mandate from the online mandate issuing service.<p/> @@ -64,64 +53,47 @@ import at.gv.egovernment.moa.util.DOMUtils; * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ +@Component("GetMISSessionIDTask") public class GetMISSessionIDTask extends AbstractAuthServletTask { + @Autowired @Qualifier("CitizenCardAuthenticationServer") private AuthenticationServer authServer; + @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) throws TaskExecutionException { Logger.debug("POST GetMISSessionIDServlet"); - String sessionID = req.getParameter(PARAM_SESSIONID); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - - AuthenticationSession session = null; - String pendingRequestID = null; try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyCertificate", - PARAM_SESSIONID, "auth.12"); - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); + //execute default task initialization + defaultTaskInitialization(req, executionContext); - session = AuthenticationServer.getSession(sessionID); + //get MIS sessionID + String misSessionID = moasession.getMISSessionID(); - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - String misSessionID = session.getMISSessionID(); - - AuthConfiguration authConf = AuthConfigurationProviderFactory - .getInstance(); - ConnectionParameter connectionParameters = authConf + //get mandates from MIS + ConnectionParameter connectionParameters = authConfig .getOnlineMandatesConnectionParameter(); SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory( - AuthConfigurationProviderFactory.getInstance(), + authConfig, connectionParameters); - List<MISMandate> list = MISSimpleClient.sendGetMandatesRequest( connectionParameters.getUrl(), misSessionID, sslFactory); + //check if mandates received if (list == null || list.size() == 0) { Logger.error("Keine Vollmacht gefunden."); throw new AuthenticationException("auth.15", null); } - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_MANDATE_RECEIVED); // for now: list contains only one element MISMandate mandate = (MISMandate) list.get(0); - // TODO[tlenz]: UTF-8 ? - String sMandate = new String(mandate.getMandate()); + String sMandate = new String(mandate.getMandate(), "UTF-8"); if (sMandate == null || sMandate.compareToIgnoreCase("") == 0) { Logger.error("Mandate is empty."); throw new AuthenticationException("auth.15", @@ -136,43 +108,35 @@ public class GetMISSessionIDTask extends AbstractAuthServletTask { null, null).getDocumentElement(); // extract RepresentationType - AuthenticationServer.getInstance().verifyMandate(session, mandate); + authServer.verifyMandate(pendingReq, moasession, mandate); - session.setMISMandate(mandate); + moasession.setMISMandate(mandate); //log mandate specific set of events - MOAReversionLogger.getInstance().logMandateEventSet(pendingReq, mandate); - - String oldsessionID = session.getSessionID(); + revisionsLogger.logMandateEventSet(pendingReq, mandate); + + //Stor MOAsession + authenticatedSessionStorage.storeSession(moasession); - //Session is implicite stored in changeSessionID!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); - Logger.info("Daten angelegt zu MOASession " + newMOASessionID); - - //put session to context - executionContext.put(PARAM_SESSIONID, session.getSessionID()); - - } catch (MOAIDException ex) { - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); } catch (GeneralSecurityException ex) { - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); } catch (PKIException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } catch (SAXException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } catch (ParserConfigurationException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } catch (Exception e) { Logger.error("MISMandateValidation has an interal Error.", e); - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } finally { diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java index 1dd4780f7..54db1d8ff 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/InitializeBKUAuthenticationTask.java @@ -27,22 +27,19 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.auth.parser.StartAuthentificationParameterParser; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; @@ -51,8 +48,11 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author tlenz * */ +@Component("InitializeBKUAuthenticationTask") public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask { + @Autowired StartAuthentificationParameterParser authInitialisationParser; + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @@ -62,19 +62,8 @@ public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask { throws TaskExecutionException { try { - String moasessionid = (String) executionContext.get(MOAIDAuthConstants.PARAM_SESSIONID); - String pendingRequestID = (String) executionContext.get("pendingRequestID"); - - //load pending request - IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID); - if (pendingReq == null) { - Logger.info("No PendingRequest with Id: " + pendingRequestID + " Maybe, a transaction timeout occure."); - throw new MOAIDException("auth.28", new Object[]{pendingRequestID}); - - } - - //load MOASession object - AuthenticationSession moasession = AuthenticationSessionStoreage.getSession(moasessionid); + Logger.info("BKU is selected -> Start BKU communication ..."); + defaultTaskInitialization(request, executionContext); boolean isLegacyRequest = false; Object isLegacyRequestObj = executionContext.get("isLegacyRequest"); @@ -83,21 +72,18 @@ public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask { if (isLegacyRequest) { //parse request parameter into MOASession - Logger.info("Start Authentication Module: " + moasession.getModul() - + " Action: " + moasession.getAction()); + Logger.info("Start Authentication Module: " + pendingReq.requestedModule() + + " Action: " + pendingReq.requestedAction()); - StartAuthentificationParameterParser.parse(executionContext, request, moasession, pendingReq); + authInitialisationParser.parse(executionContext, request, moasession, pendingReq); } else { String bkuid = (String) executionContext.get(MOAIDAuthConstants.PARAM_BKU); String useMandate = (String) executionContext.get(MOAIDAuthConstants.PARAM_USEMANDATE); String ccc = (String) executionContext.get(MOAIDAuthConstants.PARAM_CCC); - - //remove MOASessionID from executionContext because it is not needed any more - - - if (MiscUtil.isEmpty(bkuid) || MiscUtil.isEmpty(moasessionid)) { - Logger.warn("MOASessionID or BKU-type is empty. Maybe an old BKU-selection template is in use."); + + if (MiscUtil.isEmpty(bkuid)) { + Logger.warn("BKU-type is empty. Maybe an old BKU-selection template is in use."); throw new MOAIDException("auth.23", new Object[] {}); } @@ -105,24 +91,24 @@ public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask { IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[] { moasession.getOAURLRequested() }); + throw new AuthenticationException("auth.00", new Object[] { pendingReq.getOAURL() }); else { - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_BKUTYPE_SELECTED, bkuid); //get Target from config or from request in case of SAML 1 String target = null; - if (MiscUtil.isNotEmpty(pendingReq.getTarget()) && - pendingReq.requestedModule().equals("id_saml1")) - target = pendingReq.getTarget(); + if (MiscUtil.isNotEmpty(pendingReq.getGenericData("target", String.class)) && + pendingReq.requestedModule().equals("at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol")) + target = pendingReq.getGenericData("target", String.class); else target = oaParam.getTarget(); String bkuURL = oaParam.getBKUURL(bkuid); if (MiscUtil.isEmpty(bkuURL)) { Logger.info("No OA specific BKU defined. Use BKU from default configuration"); - bkuURL = AuthConfigurationProviderFactory.getInstance().getDefaultBKUURL(bkuid); + bkuURL = authConfig.getDefaultBKUURL(bkuid); } //search for OA specific template @@ -133,13 +119,13 @@ public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask { templateURL = oaTemplateURLList.get(0); } else { - templateURL = AuthConfigurationProviderFactory.getInstance().getSLRequestTemplates(bkuid); + templateURL = authConfig.getSLRequestTemplates(bkuid); } //make url absolut if it is a local url if (MiscUtil.isNotEmpty(templateURL)) templateURL = FileUtils.makeAbsoluteURL(templateURL, - AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir()); + authConfig.getRootConfigFileDir()); if (oaParam.isOnlyMandateAllowed()) useMandate = "true"; @@ -148,25 +134,25 @@ public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask { useMandate = "false"; //parse all OA parameters i - StartAuthentificationParameterParser.parse(moasession, - target, - moasession.getOAURLRequested(), - bkuURL, - templateURL, - useMandate, - ccc, - moasession.getModul(), - moasession.getAction(), - request, - pendingReq); + authInitialisationParser.parse( moasession, + target, + pendingReq.getOAURL(), + bkuURL, + templateURL, + useMandate, + ccc, + request, + pendingReq); } } executionContext.put(MOAIDAuthConstants.PARAM_USEMANDATE, moasession.getUseMandate()); - // make sure moa session has been persisted before running the process + // make sure MOASession and Pending-Request has been persisted before running the process try { - AuthenticationSessionStoreage.storeSession(moasession); + authenticatedSessionStorage.storeSession(moasession); + requestStoreage.storePendingRequest(pendingReq); + } catch (MOADatabaseException e) { Logger.error("Database Error! MOASession is not stored!"); throw new MOAIDException("init.04", new Object[] { @@ -176,11 +162,11 @@ public class InitializeBKUAuthenticationTask extends AbstractAuthServletTask { } catch (MOADatabaseException | MOAIDException e) { Logger.info("Initialize BKUAuthentication FAILED. Reason:" + e.getMessage()); - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } catch (Exception e) { Logger.warn("InitializeBKUAuthentication has an internal error", e); - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java index 49888c136..b9a8fecf6 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareAuthBlockSignatureTask.java @@ -1,28 +1,18 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; - -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.CitizenCardServletUtils; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; /** @@ -45,56 +35,40 @@ import at.gv.egovernment.moa.logging.Logger; * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ +@Component("PrepareAuthBlockSignatureTask") public class PrepareAuthBlockSignatureTask extends AbstractAuthServletTask { + @Autowired @Qualifier("CitizenCardAuthenticationServer") private AuthenticationServer authServer; + @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) throws TaskExecutionException { // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet - Logger.debug("Process IdentityLink"); - - setNoCachingHeaders(resp); + Logger.debug("Process CreateAuthBlock Task"); - String pendingRequestID = null; - try { + //initialize task + defaultTaskInitialization(req, executionContext); - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); - } - - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - // change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - AuthConfiguration authConf = AuthConfigurationProviderFactory.getInstance(); - - String createXMLSignatureRequest = AuthenticationServer.getInstance() - .getCreateXMLSignatureRequestAuthBlockOrRedirect(session, authConf, oaParam, pendingReq); + //build authBlock + String createXMLSignatureRequest = authServer + .getCreateXMLSignatureRequestAuthBlockOrRedirect(moasession, pendingReq); - AuthenticationSessionStoreage.storeSession(session); + //store MOASession + authenticatedSessionStorage.storeSession(moasession); - CitizenCardServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, + //write response + CitizenCardServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, pendingReq, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyIdentityLink"); } catch (MOAIDException ex) { - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); } catch (Exception e) { Logger.error("IdentityLinkValidation has an interal Error.", e); - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } finally { diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java index 099bc085c..f976c0b49 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/PrepareGetMISMandateTask.java @@ -23,17 +23,17 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.GET_MIS_SESSIONID; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; import java.util.List; import javax.net.ssl.SSLSocketFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Component; import org.w3c.dom.Element; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; @@ -44,25 +44,19 @@ import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.SSLUtils; import at.gv.egovernment.moa.id.util.client.mis.simple.MISSessionId; import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.egovernment.moa.util.MiscUtil; /** * @author tlenz * */ +@Component("PrepareGetMISMandateTask") public class PrepareGetMISMandateTask extends AbstractAuthServletTask { /* (non-Javadoc) @@ -75,66 +69,26 @@ public class PrepareGetMISMandateTask extends AbstractAuthServletTask { //mandate Mode try { - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); - - //get Session from context - String moasessionid = (String) executionContext.get(PARAM_SESSIONID); - AuthenticationSession session = null; - if (MiscUtil.isEmpty(moasessionid)) { - Logger.warn("MOASessionID is empty."); - throw new MOAIDException("auth.18", new Object[] {}); - } - - try { - session = AuthenticationSessionStoreage.getSession(moasessionid); - AuthenticationSessionStoreage.changeSessionID(session); - - } catch (MOADatabaseException e) { - Logger.info("MOASession with SessionID=" + moasessionid + " is not found in Database"); - throw new MOAIDException("init.04", new Object[] { moasessionid }); - - } catch (Throwable e) { - Logger.info("No HTTP Session found!"); - throw new MOAIDException("auth.18", new Object[] {}); - - } finally { - executionContext.remove(PARAM_SESSIONID); - - } - - - AuthConfiguration authConf= AuthConfigurationProviderFactory.getInstance(); - ConnectionParameter connectionParameters = authConf.getOnlineMandatesConnectionParameter(); - SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(AuthConfigurationProviderFactory.getInstance(), connectionParameters); + //perform default task initialization + defaultTaskInitialization(request, executionContext); + + ConnectionParameter connectionParameters = authConfig.getOnlineMandatesConnectionParameter(); + SSLSocketFactory sslFactory = SSLUtils.getSSLSocketFactory(authConfig, connectionParameters); // get identitity link as byte[] - Element elem = session.getIdentityLink().getSamlAssertion(); + Element elem = moasession.getIdentityLink().getSamlAssertion(); String s = DOMUtils.serializeNode(elem); //System.out.println("IDL: " + s); byte[] idl = s.getBytes("UTF-8"); - - // redirect url - // build redirect(to the GetMISSessionIdSerlvet) - - //change MOASessionID before MIS request - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - + String redirectURL = new DataURLBuilder().buildDataURL( - session.getAuthURL(), + pendingReq.getAuthURL(), GET_MIS_SESSIONID, - newMOASessionID); + pendingReq.getRequestID()); - String oaURL = session.getOAURLRequested(); IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); - if (oaParam == null) { - oaParam = authConf.getOnlineApplicationParameter(oaURL); - Logger.info("No Service info in PendingRequest --> load service info from configuration"); - - } - List<String> profiles = oaParam.getMandateProfiles(); if (profiles == null) { @@ -143,24 +97,21 @@ public class PrepareGetMISMandateTask extends AbstractAuthServletTask { } String oaFriendlyName = oaParam.getFriendlyName(); - String mandateReferenceValue = session.getMandateReferenceValue(); - byte[] cert = session.getEncodedSignerCertificate(); - byte[] authBlock = session.getAuthBlock().getBytes("UTF-8"); + String mandateReferenceValue = moasession.getMandateReferenceValue(); + byte[] cert = moasession.getEncodedSignerCertificate(); + byte[] authBlock = moasession.getAuthBlock().getBytes("UTF-8"); //TODO: check in case of SSO!!! String targetType = null; - if(oaParam.getBusinessService()) { - String id = oaParam.getIdentityLinkDomainIdentifier(); - if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) - targetType = id; - else - targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_+session.getDomainIdentifier(); + if(oaParam.getBusinessService()){ + targetType = oaParam.getIdentityLinkDomainIdentifier(); } else { targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); + } - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_MANDATE_SERVICE_REQUESTED, mandateReferenceValue); MISSessionId misSessionID = MISSimpleClient.sendSessionIdRequest( @@ -178,20 +129,21 @@ public class PrepareGetMISMandateTask extends AbstractAuthServletTask { if (misSessionID == null) { Logger.error("Fehler bei Anfrage an Vollmachten Service. MIS Session ID ist null."); throw new MISSimpleClientException("Fehler bei Anfrage an Vollmachten Service."); + } String redirectMISGUI = misSessionID.getRedirectURL(); - session.setMISSessionID(misSessionID.getSessiondId()); + moasession.setMISSessionID(misSessionID.getSessiondId()); try { - AuthenticationSessionStoreage.storeSession(session); + authenticatedSessionStorage.storeSession(moasession); } catch (MOADatabaseException | BuildException e) { throw new MOAIDException("Session store error", null); } - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_MANDATE_REDIRECT); response.setStatus(302); @@ -199,7 +151,7 @@ public class PrepareGetMISMandateTask extends AbstractAuthServletTask { Logger.debug("REDIRECT TO: " + redirectMISGUI); } catch (Exception e ) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java index 35104bf3e..b52778577 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyAuthenticationBlockTask.java @@ -1,50 +1,27 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; -import iaik.pki.PKIException; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_XMLRESPONSE; import java.io.IOException; -import java.security.GeneralSecurityException; -import java.util.List; import java.util.Map; -import javax.net.ssl.SSLSocketFactory; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.xml.transform.TransformerException; import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.lang.StringEscapeUtils; -import org.w3c.dom.Element; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MISSimpleClientException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; - -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.ConnectionParameter; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.ModulUtils; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.SSLUtils; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISSessionId; -import at.gv.egovernment.moa.id.util.client.mis.simple.MISSimpleClient; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.DOMUtils; /** * Verifies the signed authentication block (provided as {@code CreateXMLSignatureResponse}).<p/> @@ -79,82 +56,63 @@ import at.gv.egovernment.moa.util.DOMUtils; * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ +@Component("VerifyAuthenticationBlockTask") public class VerifyAuthenticationBlockTask extends AbstractAuthServletTask { + @Autowired @Qualifier("CitizenCardAuthenticationServer") private AuthenticationServer authServer; + @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) throws TaskExecutionException { - - // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyAuthenticationBlockServlet Logger.debug("POST VerifyAuthenticationBlock"); - String pendingRequestID = null; - Map<String, String> parameters; try { parameters = getParameters(req); - } catch (FileUploadException | IOException e) - { + } catch (FileUploadException | IOException e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); - } + throw new TaskExecutionException(pendingReq, "Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); - String sessionID = req.getParameter(PARAM_SESSIONID); - String createXMLSignatureResponse = (String)parameters.get(PARAM_XMLRESPONSE); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - - String redirectURL = null; - try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12"); - if (!ParamValidatorUtils.isValidXMLDocument(createXMLSignatureResponse)) - throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_XMLRESPONSE, "auth.12"); - - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), - pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_DATAURL_IP, req.getRemoteHost()); - - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - AuthenticationServer.getInstance().verifyAuthenticationBlock(pendingReq, session, createXMLSignatureResponse); - - //store all changes in session DAO - AuthenticationSessionStoreage.storeSession(session); - - //put session to context - executionContext.put(PARAM_SESSIONID, session.getSessionID()); - - } + } - catch (MOAIDException ex) { - throw new TaskExecutionException(ex.getMessage(), ex); - + String createXMLSignatureResponse = (String)parameters.get(PARAM_XMLRESPONSE); + + try { + //check if authblock is received + if (!ParamValidatorUtils.isValidXMLDocument(createXMLSignatureResponse)) + throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_XMLRESPONSE, "auth.12"); + + //execute default task initialization + defaultTaskInitialization(req, executionContext); - - } catch (Exception e) { - Logger.error("AuthBlockValidation has an interal Error.", e); - throw new TaskExecutionException(e.getMessage(), e); - - } - + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), + pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_DATAURL_IP, req.getRemoteHost()); - finally { - - } - - + //verify authBlock + authServer.verifyAuthenticationBlock(pendingReq, moasession, createXMLSignatureResponse); + + //store all changes in session DAO + authenticatedSessionStorage.storeSession(moasession); + + } + + catch (MOAIDException ex) { + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); + + } catch (Exception e) { + Logger.error("AuthBlockValidation has an interal Error.", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + + finally { + + } + } } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java index 2734d1027..464c1f3a1 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyCertificateTask.java @@ -1,7 +1,6 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; -import iaik.x509.X509Certificate; +import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.REQ_GET_FOREIGN_ID; import java.io.IOException; import java.util.Map; @@ -10,29 +9,23 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.AuthenticationServer; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; - import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.CitizenCardServletUtils; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; -import at.gv.egovernment.moa.id.util.ServletUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.spss.util.CertificateUtils; +import iaik.x509.X509Certificate; /** * Parses the certificate from {@code InfoBoxReadResponse} (via POST parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_XMLRESPONSE PARAM_XMLRESPONSE}), creates the auth block to be signed and returns a {@code CreateXMLSignatureRequest} for auth block signature.<p/> @@ -59,15 +52,18 @@ import at.gv.egovernment.moa.spss.util.CertificateUtils; * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ +@Component("VerifyCertificateTask") public class VerifyCertificateTask extends AbstractAuthServletTask { + @Autowired @Qualifier("CitizenCardAuthenticationServer") private AuthenticationServer authServer; + @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) throws TaskExecutionException { // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyCertificateServlet - Logger.debug("POST VerifyCertificateServlet"); + Logger.debug("Reveive VerifyCertificate Response"); Map<String, String> parameters; try @@ -76,53 +72,42 @@ public class VerifyCertificateTask extends AbstractAuthServletTask { } catch (FileUploadException | IOException e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); + throw new TaskExecutionException(pendingReq, "Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); } - String sessionID = req.getParameter(PARAM_SESSIONID); - - // escape parameter strings - sessionID = StringEscapeUtils.escapeHtml(sessionID); - AuthenticationSession session = null; try { - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) - throw new WrongParametersException("VerifyCertificate", PARAM_SESSIONID, "auth.12"); - - session = AuthenticationServer.getSession(sessionID); - - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + //execute default task initialization + defaultTaskInitialization(req, executionContext); + + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_DATAURL_IP, req.getRemoteHost()); - //change MOASessionID - sessionID = AuthenticationSessionStoreage.changeSessionID(session); - - X509Certificate cert = AuthenticationServer.getInstance().getCertificate(pendingReq, sessionID, parameters); + //read certificate from response + X509Certificate cert = authServer.getCertificate(pendingReq, parameters); if (cert == null) { Logger.error("Certificate could not be read."); throw new AuthenticationException("auth.14", null); } - - boolean useMandate = session.getUseMandate(); - - if (useMandate) { + + if (moasession.getUseMandate()) { - // verify certificate for OrganWalter - String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyCertificate(session, cert, pendingReq); + // verify certificate for OrganWalter + authServer.verifyCertificate(moasession, cert, pendingReq); + + //create AuthBlock + String createXMLSignatureRequestOrRedirect = + authServer.getCreateXMLSignatureRequestAuthBlockOrRedirect(moasession, pendingReq); try { - AuthenticationSessionStoreage.storeSession(session); + authenticatedSessionStorage.storeSession(moasession); + } catch (MOADatabaseException e) { throw new MOAIDException("session store error", null); } - // TODO[branch]: Mandate; respond with CXSR for authblock signature, dataURL "/VerifyAuthBlock" - CitizenCardServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, session, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate"); + CitizenCardServletUtils.writeCreateXMLSignatureRequestOrRedirect(resp, pendingReq, createXMLSignatureRequestOrRedirect, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "VerifyCertificate"); - } - else { + } else { String countrycode = CertificateUtils.getIssuerCountry(cert); if (countrycode != null) { @@ -133,35 +118,29 @@ public class VerifyCertificateTask extends AbstractAuthServletTask { } // Foreign Identities Modus - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_FOREIGN_FOUND); - String createXMLSignatureRequest = AuthenticationServer.getInstance().createXMLSignatureRequestForeignID(session, cert); + String createXMLSignatureRequest = authServer.createXMLSignatureRequestForeignID(pendingReq, cert); + // build dataurl (to the GetForeignIDSerlvet) String dataurl = new DataURLBuilder().buildDataURL( - session.getAuthURL(), + pendingReq.getAuthURL(), REQ_GET_FOREIGN_ID, - session.getSessionID()); - - try { - AuthenticationSessionStoreage.storeSession(session); - } catch (MOADatabaseException e) { - throw new MOAIDException("session store error", null); - } - - // TODO[branch]: Foreign citizen; respond with CXSR for authblock signature, dataURL "/GetForeignID" + pendingReq.getRequestID()); + CitizenCardServletUtils.writeCreateXMLSignatureRequest(resp, createXMLSignatureRequest, AuthenticationServer.REQ_PROCESS_VALIDATOR_INPUT, "GetForeignID", dataurl); Logger.debug("Send CreateXMLSignatureRequest to BKU"); } } catch (MOAIDException ex) { - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); } catch (Exception e) { Logger.error("CertificateValidation has an interal Error.", e); - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java index 50ef11f27..23e92c0c0 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/internal/tasks/VerifyIdentityLinkTask.java @@ -1,30 +1,22 @@ package at.gv.egovernment.moa.id.auth.modules.internal.tasks; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.*; - import java.io.IOException; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.AuthenticationServer; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; - -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; /** @@ -51,17 +43,16 @@ import at.gv.egovernment.moa.logging.Logger; * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse) * */ +@Component("VerifyIdentityLinkTask") public class VerifyIdentityLinkTask extends AbstractAuthServletTask { + @Autowired @Qualifier("CitizenCardAuthenticationServer") private AuthenticationServer authServer; + @Override public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp) throws TaskExecutionException { - // note: code taken from at.gv.egovernment.moa.id.auth.servlet.VerifyIdentityLinkServlet - - Logger.debug("POST VerifyIdentityLink"); - - setNoCachingHeaders(resp); + Logger.debug("Receive VerifyIdentityLink Response"); Map<String, String> parameters; @@ -69,37 +60,34 @@ public class VerifyIdentityLinkTask extends AbstractAuthServletTask { parameters = getParameters(req); } catch (Exception e) { Logger.error("Parsing mulitpart/form-data request parameters failed: " + e.getMessage()); - throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); + throw new TaskExecutionException(pendingReq, "Parsing mulitpart/form-data request parameters failed", new IOException(e.getMessage())); } try { - - String sessionID = StringEscapeUtils.escapeHtml(req.getParameter(PARAM_SESSIONID)); - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("VerifyIdentityLink", PARAM_SESSIONID, "auth.12"); - } - AuthenticationSession session = AuthenticationServer.getSession(sessionID); - - IRequest pendingReq = RequestStorage.getPendingRequest( - (String) executionContext.get("pendingRequestID")); - MOAReversionLogger.getInstance().logEvent(pendingReq.getOnlineApplicationConfiguration(), + //execute default task initialization + defaultTaskInitialization(req, executionContext); + + revisionsLogger.logEvent(pendingReq.getOnlineApplicationConfiguration(), pendingReq, MOAIDEventConstants.AUTHPROCESS_BKU_DATAURL_IP, req.getRemoteHost()); + + //verify identityLink + boolean identityLinkAvailable = authServer.verifyIdentityLink(pendingReq, moasession, parameters) != null; - boolean identityLinkAvailable = AuthenticationServer.getInstance().verifyIdentityLink(pendingReq, session, parameters) != null; - AuthenticationSessionStoreage.storeSession(session); + //store session + authenticatedSessionStorage.storeSession(moasession); + //set 'identityLink exists' flag to context executionContext.put("identityLinkAvailable", identityLinkAvailable); } catch (ParseException ex) { - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); } catch (MOAIDException ex) { - throw new TaskExecutionException(ex.getMessage(), ex); + throw new TaskExecutionException(pendingReq, ex.getMessage(), ex); } catch (Exception e) { Logger.error("IdentityLinkValidation has an interal Error.", e); - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java deleted file mode 100644 index 7bce406e0..000000000 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/parser/VerifyXMLSignatureResponseParser.java +++ /dev/null @@ -1,211 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/* - * Copyright 2003 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ - - -package at.gv.egovernment.moa.id.auth.parser; - -import iaik.utils.Base64InputStream; -import iaik.x509.X509Certificate; - -import java.io.ByteArrayInputStream; -import java.io.InputStream; - -import org.w3c.dom.Element; - -import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; -import at.gv.egovernment.moa.id.auth.exception.ParseException; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.DOMUtils; -import at.gv.egovernment.moa.util.XPathUtils; - -/** - * Parses a <code><VerifyXMLSignatureResponse></code> returned by - * MOA-SPSS. - * This class implements the Singleton pattern - * - * @author Stefan Knirsch - * @version $Id$ - */ - - -public class VerifyXMLSignatureResponseParser { - // - // XPath namespace prefix shortcuts - // - /** Xpath prefix for reaching MOA Namespaces */ - private static final String MOA = Constants.MOA_PREFIX + ":"; - /** Xpath prefix for reaching DSIG Namespaces */ - private static final String DSIG = Constants.DSIG_PREFIX + ":"; - /** Xpath expression to the root element */ - private static final String ROOT = "/" + MOA + "VerifyXMLSignatureResponse/"; - - /** Xpath expression to the X509SubjectName element */ - private static final String DSIG_SUBJECT_NAME_XPATH = - ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + - DSIG + "X509SubjectName"; - /** Xpath expression to the X509Certificate element */ - private static final String DSIG_X509_CERTIFICATE_XPATH = - ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + - DSIG + "X509Certificate"; - /** Xpath expression to the PublicAuthority element */ - private static final String PUBLIC_AUTHORITY_XPATH = - ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + - MOA + "PublicAuthority"; - /** Xpath expression to the PublicAuthorityCode element */ - private static final String PUBLIC_AUTHORITY_CODE_XPATH = - PUBLIC_AUTHORITY_XPATH + "/" + MOA + "Code"; - /** Xpath expression to the QualifiedCertificate element */ - private static final String QUALIFIED_CERTIFICATE_XPATH = - ROOT + MOA + "SignerInfo/" + DSIG + "X509Data/" + - MOA + "QualifiedCertificate"; - - /** Xpath expression to the SignatureCheckCode element */ - private static final String SIGNATURE_CHECK_CODE_XPATH = - ROOT + MOA + "SignatureCheck/" + MOA + "Code"; - /** Xpath expression to the XMLDSIGManifestCheckCode element */ - private static final String XMLDSIG_MANIFEST_CHECK_CODE_XPATH = - ROOT + MOA + "XMLDSIGManifestCheck/" + MOA + "Code"; - /** Xpath expression to the SignatureManifestCheckCode element */ - private static final String SIGNATURE_MANIFEST_CHECK_CODE_XPATH = - ROOT + MOA + "SignatureManifestCheck/" + MOA + "Code"; - /** Xpath expression to the CertificateCheckCode element */ - private static final String CERTIFICATE_CHECK_CODE_XPATH = - ROOT + MOA + "CertificateCheck/" + MOA + "Code"; - - - /** This is the root element of the XML-Document provided by the Security Layer Card*/ - private Element verifyXMLSignatureResponse; - - /** - * Constructor for VerifyXMLSignatureResponseParser. - * A DOM-representation of the incoming String will be created - * @param xmlResponse <code><InfoboxReadResponse></code> as String - * @throws ParseException on any parsing error - */ - public VerifyXMLSignatureResponseParser(String xmlResponse) throws ParseException{ - try { - InputStream s = new ByteArrayInputStream(xmlResponse.getBytes("UTF-8")); - - verifyXMLSignatureResponse = DOMUtils.parseXmlValidating(s); - } - catch (Throwable t) { - throw new ParseException("parser.01", new Object[] { t.toString() }, t); - } - } - - /** - * Constructor for VerifyXMLSignatureResponseParser. - * A DOM-representation of the incoming Inputstream will be created - * @param xmlResponse <code><InfoboxReadResponse></code> as InputStream - * @throws Exception on any parsing error - */ - public VerifyXMLSignatureResponseParser(InputStream xmlResponse) throws Exception - { - try { - verifyXMLSignatureResponse = DOMUtils.parseXmlValidating(xmlResponse); - } - catch (Throwable t) { - throw new ParseException("parser.01", null, t); - } - } - - /** - * Constructor for VerifyXMLSignatureResponseParser. - * The incoming Element will be used for further operations - * @param xmlResponse <code><InfoboxReadResponse></code> as Element - */ - public VerifyXMLSignatureResponseParser(Element xmlResponse) - { - verifyXMLSignatureResponse =xmlResponse; - - } - - /** - * Parse identity link from <code><InfoboxReadResponse></code> - * @return Identity link - * @throws ParseException on any parsing error - */ - - public VerifyXMLSignatureResponse parseData() throws ParseException { - - VerifyXMLSignatureResponse respData=new VerifyXMLSignatureResponse(); - - try { - - String s = DOMUtils.serializeNode(verifyXMLSignatureResponse); - respData.setXmlDsigSubjectName(XPathUtils.getElementValue(verifyXMLSignatureResponse,DSIG_SUBJECT_NAME_XPATH,"")); - Element e = (Element)XPathUtils.selectSingleNode(verifyXMLSignatureResponse,QUALIFIED_CERTIFICATE_XPATH); - respData.setQualifiedCertificate(e!=null); - - Base64InputStream in = new Base64InputStream(new ByteArrayInputStream(XPathUtils.getElementValue( - verifyXMLSignatureResponse,DSIG_X509_CERTIFICATE_XPATH,"").getBytes("UTF-8")),true); - - respData.setX509certificate(new X509Certificate(in)); - Element publicAuthority = (Element)XPathUtils.selectSingleNode(verifyXMLSignatureResponse,PUBLIC_AUTHORITY_XPATH); - respData.setPublicAuthority(publicAuthority != null); - respData.setPublicAuthorityCode(XPathUtils.getElementValue(verifyXMLSignatureResponse,PUBLIC_AUTHORITY_CODE_XPATH,"")); - respData.setSignatureCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNATURE_CHECK_CODE_XPATH,"")).intValue()); - - String xmlDsigCheckCode = XPathUtils.getElementValue(verifyXMLSignatureResponse,XMLDSIG_MANIFEST_CHECK_CODE_XPATH,null); - if (xmlDsigCheckCode!=null) { - respData.setXmlDSIGManigest(true); - respData.setXmlDSIGManifestCheckCode(new Integer(xmlDsigCheckCode).intValue()); - } else { - respData.setXmlDSIGManigest(false); - } - String signatureManifestCheckCode = XPathUtils.getElementValue(verifyXMLSignatureResponse,SIGNATURE_MANIFEST_CHECK_CODE_XPATH,null); - if (signatureManifestCheckCode != null) { - respData.setSignatureManifestCheckCode(new Integer(signatureManifestCheckCode).intValue()); - } - respData.setCertificateCheckCode(new Integer(XPathUtils.getElementValue(verifyXMLSignatureResponse,CERTIFICATE_CHECK_CODE_XPATH,"")).intValue()); - } - catch (Throwable t) { - throw new ParseException("parser.01", null, t); - } - return respData; - } - - -} diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/servlet/CitizenCardAuthProcessEngineSignalController.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/servlet/CitizenCardAuthProcessEngineSignalController.java new file mode 100644 index 000000000..139be49fe --- /dev/null +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/servlet/CitizenCardAuthProcessEngineSignalController.java @@ -0,0 +1,52 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.servlet; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +/** + * @author tlenz + * + */ +@Controller +public class CitizenCardAuthProcessEngineSignalController extends AbstractProcessEngineSignalController { + + @RequestMapping(value = {"/GetMISSessionID", + "/GetForeignID", + "/VerifyAuthBlock", + "/VerifyCertificate", + "/VerifyIdentityLink" + }, + method = {RequestMethod.POST, RequestMethod.GET}) + public void performCitizenCardAuthentication(HttpServletRequest req, HttpServletResponse resp) throws IOException { + signalProcessManagement(req, resp); + +} +} diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java index 8a9c19c80..5e0a69fd4 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/auth/validator/CreateXMLSignatureResponseValidator.java @@ -56,6 +56,7 @@ import javax.xml.bind.DatatypeConverter; import org.jaxen.SimpleNamespaceContext; import org.w3c.dom.Element; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.AuthenticationBlockAssertionBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse; @@ -66,7 +67,7 @@ import at.gv.egovernment.moa.id.auth.exception.ValidateException; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.TargetToSectorNameMapper; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; @@ -132,10 +133,14 @@ public class CreateXMLSignatureResponseValidator { throws ValidateException { // A3.056: more then one /saml:Assertion/saml:AttributeStatement/saml:Subject/saml:NameIdentifier - - String gbTarget = session.getTarget(); - String oaURL = session.getPublicOAURLPrefix(); - boolean businessService = session.getBusinessService(); + IOAAuthParameters oaParam = pendingReq.getOnlineApplicationConfiguration(); + + String gbTarget = pendingReq.getGenericData( + MOAIDAuthConstants.AUTHPROCESS_DATA_TARGET, String.class); + String targetFriendlyName = pendingReq.getGenericData( + MOAIDAuthConstants.AUTHPROCESS_DATA_TARGETFRIENDLYNAME, String.class); + String oaURL = oaParam.getPublicURLPrefix(); + boolean businessService = oaParam.getBusinessService(); IdentityLink identityLink = session.getIdentityLink(); @@ -227,8 +232,7 @@ public class CreateXMLSignatureResponseValidator { } } if (samlAttribute.getNamespace().equals("http://reference.e-government.gv.at/namespace/moa/20020822#")) { - foundGB = true; - String targetFriendlyName = session.getTargetFriendlyName(); + foundGB = true; String sectorName = TargetToSectorNameMapper.getSectorNameViaTarget(gbTarget); if (StringUtils.isEmpty(sectorName)) { if (targetFriendlyName != null) @@ -293,23 +297,18 @@ public class CreateXMLSignatureResponseValidator { samlSpecialText = samlSpecialText.replaceAll("'", "'"); String text = ""; - try { - OAAuthParameter oaparam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - if (MiscUtil.isNotEmpty(oaparam.getAditionalAuthBlockText())) { - Logger.info("Use addional AuthBlock Text from OA=" + oaparam.getPublicURLPrefix()); - text = oaparam.getAditionalAuthBlockText(); - } - } catch (ConfigurationException e) { - Logger.warn("Addional AuthBlock Text can not loaded from OA!", e); + if (MiscUtil.isNotEmpty(oaParam.getAditionalAuthBlockText())) { + Logger.info("Use addional AuthBlock Text from OA=" + oaParam.getPublicURLPrefix()); + text = oaParam.getAditionalAuthBlockText(); } - - + String specialText = AuthenticationBlockAssertionBuilder.generateSpecialText(text, issuer, identityLink.getDateOfBirth(), issueInstant); if (!samlSpecialText.equals(specialText)) { - throw new ValidateException("validator.67", new Object[] {samlSpecialText, specialText}); + throw new ValidateException("validator.67", new Object[] {samlSpecialText, specialText}); } } else { throw new ValidateException("validator.35", null); + } diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/CitizenCardServletUtils.java b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/CitizenCardServletUtils.java index 276d6a105..36bab9355 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/CitizenCardServletUtils.java +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/java/at/gv/egovernment/moa/id/util/CitizenCardServletUtils.java @@ -53,13 +53,13 @@ import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; -import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.logging.Logger; /** @@ -73,21 +73,21 @@ public class CitizenCardServletUtils extends ServletUtils{ * depending on the requests starting text. * * @param resp The httpServletResponse - * @param session The current AuthenticationSession + * @param pendingReq The current AuthenticationSession * @param createXMLSignatureRequestOrRedirect The request * @param servletGoal The servlet to which the redirect should happen * @param servletName The servlet name for debug purposes * @throws MOAIDException * @throws IOException */ - public static void writeCreateXMLSignatureRequestOrRedirect(HttpServletResponse resp, AuthenticationSession session, String createXMLSignatureRequestOrRedirect, String servletGoal, String servletName) + public static void writeCreateXMLSignatureRequestOrRedirect(HttpServletResponse resp, IRequest pendingReq, String createXMLSignatureRequestOrRedirect, String servletGoal, String servletName) throws MOAIDException, IOException { if (!createXMLSignatureRequestOrRedirect.startsWith("Redirect")) { resp.setStatus(307); String dataURL = new DataURLBuilder().buildDataURL( - session.getAuthURL(), MOAIDAuthConstants.REQ_VERIFY_AUTH_BLOCK, session.getSessionID()); + pendingReq.getAuthURL(), MOAIDAuthConstants.REQ_VERIFY_AUTH_BLOCK, pendingReq.getRequestID()); resp.addHeader("Location", dataURL); //TODO test impact of explicit setting charset with older versions of BKUs (HotSign) @@ -100,7 +100,7 @@ public class CitizenCardServletUtils extends ServletUtils{ Logger.debug("Finished POST " + servletName); } else { - String redirectURL = new DataURLBuilder().buildDataURL(session.getAuthURL(), servletGoal, session.getSessionID()); + String redirectURL = new DataURLBuilder().buildDataURL(pendingReq.getAuthURL(), servletGoal, pendingReq.getRequestID()); resp.setContentType("text/html"); resp.setStatus(302); resp.addHeader("Location", redirectURL); diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider new file mode 100644 index 000000000..2ca8587b6 --- /dev/null +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider @@ -0,0 +1 @@ +at.gv.egovernment.moa.id.auth.CitizenCardAuthenticationSpringResourceProvider
\ No newline at end of file diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.auth.modules.AuthModule b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.auth.modules.AuthModule index 865096055..02b4e5d7c 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.auth.modules.AuthModule +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.auth.modules.AuthModule @@ -1,2 +1,2 @@ # The default moaid process -at.gv.egovernment.moa.id.auth.modules.internal.DefaultAuthModuleImpl +at.gv.egovernment.moa.id.auth.modules.internal.AuthModuleImpl diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml index 6bbaf6ece..74792ed72 100644 --- a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/internal/DefaultAuthentication.process.xml @@ -5,17 +5,17 @@ - National authentication with Austrian Citizen Card and mobile signature with our without mandate. - Legacy authentication for foreign citizens using MOCCA supported signature cards. --> - <pd:Task id="initializeBKUAuthentication" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.InitializeBKUAuthenticationTask" /> - <pd:Task id="createIdentityLinkForm" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.CreateIdentityLinkFormTask" /> - <pd:Task id="verifyIdentityLink" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyIdentityLinkTask" async="true" /> - <pd:Task id="verifyAuthBlock" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyAuthenticationBlockTask" async="true" /> - <pd:Task id="verifyCertificate" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyCertificateTask" async="true" /> - <pd:Task id="getMISMandate" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetMISSessionIDTask" async="true" /> - <pd:Task id="certificateReadRequest" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.CertificateReadRequestTask" /> - <pd:Task id="prepareAuthBlockSignature" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.PrepareAuthBlockSignatureTask" /> - <pd:Task id="prepareGetMISMandate" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.PrepareGetMISMandateTask" /> - <pd:Task id="finalizeAuthentication" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.FinalizeAuthenticationTask" /> - <pd:Task id="getForeignID" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetForeignIDTask" async="true" /> + <pd:Task id="initializeBKUAuthentication" class="InitializeBKUAuthenticationTask" /> + <pd:Task id="createIdentityLinkForm" class="CreateIdentityLinkFormTask" /> + <pd:Task id="verifyIdentityLink" class="VerifyIdentityLinkTask" async="true" /> + <pd:Task id="verifyAuthBlock" class="VerifyAuthenticationBlockTask" async="true" /> + <pd:Task id="verifyCertificate" class="VerifyCertificateTask" async="true" /> + <pd:Task id="getMISMandate" class="GetMISSessionIDTask" async="true" /> + <pd:Task id="certificateReadRequest" class="CertificateReadRequestTask" /> + <pd:Task id="prepareAuthBlockSignature" class="PrepareAuthBlockSignatureTask" /> + <pd:Task id="prepareGetMISMandate" class="PrepareGetMISMandateTask" /> + <pd:Task id="finalizeAuthentication" class="FinalizeAuthenticationTask" /> + <pd:Task id="getForeignID" class="GetForeignIDTask" async="true" /> <!-- Process is triggered either by GenerateIFrameTemplateServlet (upon bku selection) or by AuthenticationManager (upon legacy authentication start using legacy parameters. --> <pd:StartEvent id="start" /> diff --git a/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/moaid_citizencard_auth.beans.xml b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/moaid_citizencard_auth.beans.xml new file mode 100644 index 000000000..b0ab11a11 --- /dev/null +++ b/id/server/modules/moa-id-modul-citizencard_authentication/src/main/resources/moaid_citizencard_auth.beans.xml @@ -0,0 +1,57 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + <bean id="CitizenCardAuthenticationServer" + class="at.gv.egovernment.moa.id.auth.AuthenticationServer"/> + + +<!-- Authentication Process Tasks --> + <bean id="InitializeBKUAuthenticationTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.InitializeBKUAuthenticationTask" + scope="prototype"/> + + <bean id="CreateIdentityLinkFormTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.CreateIdentityLinkFormTask" + scope="prototype"/> + + <bean id="VerifyIdentityLinkTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyIdentityLinkTask" + scope="prototype"/> + + <bean id="CertificateReadRequestTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.CertificateReadRequestTask" + scope="prototype"/> + + <bean id="VerifyCertificateTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyCertificateTask" + scope="prototype"/> + + <bean id="PrepareAuthBlockSignatureTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.PrepareAuthBlockSignatureTask" + scope="prototype"/> + + <bean id="VerifyAuthenticationBlockTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.VerifyAuthenticationBlockTask" + scope="prototype"/> + + <bean id="PrepareGetMISMandateTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.PrepareGetMISMandateTask" + scope="prototype"/> + + <bean id="GetMISSessionIDTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetMISSessionIDTask" + scope="prototype"/> + + <bean id="GetForeignIDTask" + class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.GetForeignIDTask" + scope="prototype"/> + +</beans>
\ No newline at end of file diff --git a/id/server/modules/moa-id-module-eIDAS/pom.xml b/id/server/modules/moa-id-module-eIDAS/pom.xml new file mode 100644 index 000000000..b43efac9e --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/pom.xml @@ -0,0 +1,111 @@ +<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.server.modules</groupId> + <artifactId>moa-id-modules</artifactId> + <version>${moa-id-version}</version> + </parent> + <artifactId>moa-id-module-eIDAS</artifactId> + <name>MOA-ID eIDAS Module</name> + <description>Inbound / outbound implemention of eIDAS protocol for MOA-ID</description> + + <properties> + <repositoryPath>${basedir}/../../../../repository</repositoryPath> + + <eidas-commons.version>eidas.1.0</eidas-commons.version> + <eidas-saml-engine.version>eidas.1.0</eidas-saml-engine.version> + + </properties> + + <dependencies> + <dependency> + <groupId>org.springframework</groupId> + <artifactId>spring-test</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + + <!-- eidas Commons --> + <dependency> + <groupId>eu.eidas</groupId> + <artifactId>eidas-commons</artifactId> + <version>${eidas-commons.version}</version> + <!--scope>provided</scope--> + <exclusions> + <exclusion> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + </exclusion> + <exclusion> + <artifactId>log4j-over-slf4j</artifactId> + <groupId>org.slf4j</groupId> + </exclusion> + </exclusions> + </dependency> + + <!-- eidas SAML Engine --> + <dependency> + <groupId>eu.eidas</groupId> + <artifactId>saml-engine</artifactId> + <version>${eidas-saml-engine.version}</version> + <scope>compile</scope> + <exclusions> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-simple</artifactId> + </exclusion> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>jcl-over-slf4j</artifactId> + </exclusion> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-api</artifactId> + </exclusion> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>jul-to-slf4j</artifactId> + </exclusion> + <exclusion> + <groupId>org.slf4j</groupId> + <artifactId>log4j-over-slf4j</artifactId> + </exclusion> + <exclusion> + <groupId>xalan</groupId> + <artifactId>serializer</artifactId> + </exclusion> + <exclusion> + <groupId>xalan</groupId> + <artifactId>xalan</artifactId> + </exclusion> + <exclusion> + <groupId>xerces</groupId> + <artifactId>xercesImpl</artifactId> + </exclusion> + <exclusion> + <groupId>xml-resolver</groupId> + <artifactId>xml-resolver</artifactId> + </exclusion> + <exclusion> + <groupId>xml-apis</groupId> + <artifactId>xml-apis</artifactId> + </exclusion> + </exclusions> + </dependency> + + <dependency> + <groupId>org.bouncycastle</groupId> + <artifactId>bcprov-jdk15on</artifactId> + <version>1.52</version> + <!-- <scope>provided</scope> --> + </dependency> + + + </dependencies> + +</project>
\ No newline at end of file diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/Constants.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/Constants.java new file mode 100644 index 000000000..909b29fab --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/Constants.java @@ -0,0 +1,84 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas; + +/** + * @author tlenz + * + */ +public class Constants { + + public static final String eIDAS_SAML_ENGINE_NAME = "default"; + public static final String SSLSOCKETFACTORYNAME = "eIDASMetadataSSLSocketFactory"; + + //default keys for eIDAS SAML-engine configuration + public static final String eIDAS_SAML_ENGINE_NAME_ID_BASICCONFIG = "SamlEngineConf"; + public static final String eIDAS_SAML_ENGINE_NAME_ID_SIGNATURECONFIG = "SignatureConf"; + public static final String eIDAS_SAML_ENGINE_NAME_ID_ENCRYPTIONCONFIG = "EncryptionConf"; + public static final String eIDAS_SAML_ENGINE_NAME_ID_CLASS = "class"; + + //default implementations for eIDAS SAML-engine functionality + public static final String SAML_SIGNING_IMPLENTATION = "eu.eidas.auth.engine.core.impl.SignSW"; + public static final String SAML_ENCRYPTION_IMPLENTATION = "at.gv.egovernment.moa.id.auth.modules.eidas.config.ModifiedEncryptionSW"; + + //configuration property keys + public static final String CONIG_PROPS_EIDAS_PREFIX="moa.id.protocols.eIDAS"; + public static final String CONIG_PROPS_EIDAS_SAMLENGINE="samlengine"; + public static final String CONIG_PROPS_EIDAS_SAMLENGINE_PREFIX=CONIG_PROPS_EIDAS_PREFIX + "." + CONIG_PROPS_EIDAS_SAMLENGINE; + public static final String CONIG_PROPS_EIDAS_SAMLENGINE_BASIC_CONFIGFILE = CONIG_PROPS_EIDAS_SAMLENGINE_PREFIX + ".config.file"; + public static final String CONIG_PROPS_EIDAS_SAMLENGINE_SIGN="sign"; + public static final String CONIG_PROPS_EIDAS_SAMLENGINE_ENCRYPT="enc"; + public static final String CONIG_PROPS_EIDAS_SAMLENGINE_SIGN_CONFIGFILE = CONIG_PROPS_EIDAS_SAMLENGINE_PREFIX + "." + + CONIG_PROPS_EIDAS_SAMLENGINE_SIGN + ".config.file"; + public static final String CONIG_PROPS_EIDAS_SAMLENGINE_ENC_CONFIGFILE = CONIG_PROPS_EIDAS_SAMLENGINE_PREFIX + "." + + CONIG_PROPS_EIDAS_SAMLENGINE_ENCRYPT + ".config.file"; + public static final String CONIG_PROPS_EIDAS_METADATA_VALIDATION_TRUSTSTORE = CONIG_PROPS_EIDAS_PREFIX + ".metadata.validation.truststore"; + + //timeouts and clock skews + public static final long CONFIG_PROPS_SKEWTIME = 2 * 60 * 1000; //2 minutes skew time for response validation + public static final int CONFIG_PROPS_METADATA_SOCKED_TIMEOUT = 20 * 1000; //20 seconds metadata socked timeout + public static final long CONFIG_PROPS_METADATA_GARBAGE_TIMEOUT = 7 * 24 * 60 * 60 * 1000; //remove unused eIDAS metadata after 7 days + + //eIDAS attribute names + public static final String eIDAS_ATTR_PERSONALIDENTIFIER = "PersonIdentifier"; + public static final String eIDAS_ATTR_DATEOFBIRTH = "DateOfBirth"; + public static final String eIDAS_ATTR_CURRENTGIVENNAME = "CurrentGivenName"; + public static final String eIDAS_ATTR_CURRENTFAMILYNAME = "CurrentFamilyName"; + + //http endpoint descriptions + public static final String eIDAS_HTTP_ENDPOINT_SP_POST = "/eidas/sp/post"; + public static final String eIDAS_HTTP_ENDPOINT_SP_REDIRECT = "/eidas/sp/redirect"; + public static final String eIDAS_HTTP_ENDPOINT_IDP_POST = "/eidas/idp/post"; + public static final String eIDAS_HTTP_ENDPOINT_IDP_REDIRECT = "/eidas/idp/redirect"; + public static final String eIDAS_HTTP_ENDPOINT_METADATA = "/eidas/metadata"; + + //Event-Codes for Revisionslog + public static final int eIDAS_REVERSIONSLOG_METADATA = 3400; + public static final int eIDAS_REVERSIONSLOG_IDP_AUTHREQUEST = 3401; + public static final int eIDAS_REVERSIONSLOG_IDP_AUTHRESPONSE = 3402; + public static final int eIDAS_REVERSIONSLOG_SP_AUTHREQUEST= 3403; + public static final int eIDAS_REVERSIONSLOG_SP_AUTHRESPONSE= 3404; + + public static final String eIDAS_GENERIC_REQ_DATA_COUNTRY = "country"; + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/MOAIDCertificateManagerConfigurationImpl.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/MOAIDCertificateManagerConfigurationImpl.java new file mode 100644 index 000000000..9b634ff4d --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/MOAIDCertificateManagerConfigurationImpl.java @@ -0,0 +1,118 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.config; + +import java.util.HashMap; +import java.util.Map; + +import at.gv.egovernment.moa.logging.Logger; + +import eu.eidas.config.ConfigurationException; +import eu.eidas.samlengineconfig.AbstractCertificateConfigurationManager; +import eu.eidas.samlengineconfig.EngineInstance; +import eu.eidas.samlengineconfig.SamlEngineConfiguration; +import eu.eidas.samlengineconfig.impl.SamlEngineConfigurationImpl; + +/** + * @author tlenz + * + */ +public class MOAIDCertificateManagerConfigurationImpl extends + AbstractCertificateConfigurationManager { + + private SamlEngineConfiguration samlEngineConfiguration =null; + + @Override + public boolean isActive() { + return true; + } + + /** + * + */ + public MOAIDCertificateManagerConfigurationImpl() { + try { + initalizeConfiguration(); + + } catch (at.gv.egovernment.moa.id.config.ConfigurationException e) { + Logger.error("eIDAS SAML-engine initialization FAILED", e); + + } + } + + + /* (non-Javadoc) + * @see eu.eidas.samlengineconfig.CertificateConfigurationManager#addConfiguration(java.lang.String, java.lang.String, java.util.Map, boolean) + */ + @Override + public void addConfiguration(String paramString1, String paramString2, + Map<String, String> paramMap, boolean paramBoolean) { + throw new ConfigurationException("","not yet implemented"); + + } + + /* (non-Javadoc) + * @see eu.eidas.samlengineconfig.CertificateConfigurationManager#getInstance(java.lang.String) + */ + @Override + public EngineInstance getInstance(String paramString) { + return getConfiguration().get(paramString); + + } + + /* (non-Javadoc) + * @see eu.eidas.samlengineconfig.CertificateConfigurationManager#getConfiguration() + */ + @Override + public Map<String, EngineInstance> getConfiguration() { + if(samlEngineConfiguration == null){ + try { + initalizeConfiguration(); + + } catch (at.gv.egovernment.moa.id.config.ConfigurationException e) { + Logger.error("eIDAS SAML-engine initialization FAILED", e); + + } + + } + + return samlEngineConfiguration==null?new HashMap<String, EngineInstance>():((MOAeIDASSAMLEngineConfigurationImpl) samlEngineConfiguration).getInstanceMap(); + + } + + + /** + * Initialize eIDAS SAML-engine from MOA-ID configuration + * @throws at.gv.egovernment.moa.id.config.ConfigurationException + * + */ + private void initalizeConfiguration() throws at.gv.egovernment.moa.id.config.ConfigurationException { + //initialize configuration + MOAeIDASSAMLEngineConfigurationImpl tmp = new MOAeIDASSAMLEngineConfigurationImpl(); + tmp.initialize(); + + //set initialized configuration + samlEngineConfiguration = tmp; + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/MOAeIDASSAMLEngineConfigurationImpl.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/MOAeIDASSAMLEngineConfigurationImpl.java new file mode 100644 index 000000000..584910ea5 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/MOAeIDASSAMLEngineConfigurationImpl.java @@ -0,0 +1,268 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.config; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; +import at.gv.egovernment.moa.id.auth.modules.eidas.exceptions.EIDASEngineConfigurationException; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.FileUtils; +import at.gv.egovernment.moa.util.MiscUtil; + +import eu.eidas.samlengineconfig.BinaryParameter; +import eu.eidas.samlengineconfig.ConfigurationParameter; +import eu.eidas.samlengineconfig.EngineInstance; +import eu.eidas.samlengineconfig.InstanceConfiguration; +import eu.eidas.samlengineconfig.PropsParameter; +import eu.eidas.samlengineconfig.SamlEngineConfiguration; + +/** + * @author tlenz + * + */ +public class MOAeIDASSAMLEngineConfigurationImpl extends + SamlEngineConfiguration { + + private static final String KEYSTORE_PATH="keystorePath"; + private static final String METADATA_KEYSTORE_PATH="metadata.keystorePath"; + private static final String ENCRYPTION_ACTIVATION="encryptionActivation"; + private static final String[] BINARY_PARAMETERS={KEYSTORE_PATH, ENCRYPTION_ACTIVATION,METADATA_KEYSTORE_PATH}; + + public List<EngineInstance> getInstances(){ + return super.getInstances(); + } + + @Override + public void setInstances(List<EngineInstance> engineInstances) { + super.setInstances(engineInstances); + + } + + public Map<String, EngineInstance> getInstanceMap() { + Map<String, EngineInstance> result = new HashMap<String, EngineInstance>(); + for(EngineInstance instance:getInstances()) { + + result.put(instance.getName(), instance); + } + + return result; + } + + //initialize + public void initialize() throws ConfigurationException { + //create an eIDAS SAML-engine instance + EngineInstance engineInst = new EngineInstance(); + engineInst.setName(Constants.eIDAS_SAML_ENGINE_NAME); + List<InstanceConfiguration> engineConfigs = new ArrayList<InstanceConfiguration>(); + + + //add configurations + + //add basic eIDAS SAML-engine configuration + MOAeIDASSAMLInstanceConfigurationImpl samlBaseConfig = new MOAeIDASSAMLInstanceConfigurationImpl(); + samlBaseConfig.setName(Constants.eIDAS_SAML_ENGINE_NAME_ID_BASICCONFIG); + samlBaseConfig.addParameter(loadConfigurationFromExternalFile(Constants.CONIG_PROPS_EIDAS_SAMLENGINE_BASIC_CONFIGFILE)); + engineConfigs.add(samlBaseConfig); + + //add signing eIDAS SAML-engine configuration + MOAeIDASSAMLInstanceConfigurationImpl samlSignConfig = new MOAeIDASSAMLInstanceConfigurationImpl(); + samlSignConfig.setName(Constants.eIDAS_SAML_ENGINE_NAME_ID_SIGNATURECONFIG); + samlSignConfig.addParameter(Constants.eIDAS_SAML_ENGINE_NAME_ID_CLASS, + Constants.SAML_SIGNING_IMPLENTATION); + + //TODO: load signing keys directly from MOA-ID configuration in finale version + samlSignConfig.addParameter(loadConfigurationFromExternalFile(Constants.CONIG_PROPS_EIDAS_SAMLENGINE_SIGN_CONFIGFILE)); + engineConfigs.add(samlSignConfig); + + //add encryption eIDAS SAML-engine configuration + MOAeIDASSAMLInstanceConfigurationImpl samlEncConfig = new MOAeIDASSAMLInstanceConfigurationImpl(); + samlEncConfig.setName(Constants.eIDAS_SAML_ENGINE_NAME_ID_ENCRYPTIONCONFIG); + samlEncConfig.addParameter(Constants.eIDAS_SAML_ENGINE_NAME_ID_CLASS, + Constants.SAML_ENCRYPTION_IMPLENTATION); + + //TODO: load encryption keys directly from MOA-ID configuration in finale version + samlEncConfig.addParameter(loadConfigurationFromExternalFile(Constants.CONIG_PROPS_EIDAS_SAMLENGINE_ENC_CONFIGFILE)); + engineConfigs.add(samlEncConfig); + + engineInst.setConfigurations(engineConfigs); + super.addInstance(engineInst); + + } + + /** + * Load an external eIDAS SAML-engine configuration file, which is referenced from MOA-ID configuration + * + * @param key Configuration key, which is used in property based MOA-ID configuration file + * @return eIDAS SAML-engine configuration object + * @throws ConfigurationException + */ + + private ConfigurationParameter loadConfigurationFromExternalFile(String key) throws ConfigurationException { + String configFile = + AuthConfigurationProviderFactory.getInstance().getBasicMOAIDConfiguration(key); + if (MiscUtil.isEmpty(configFile)) { + Logger.warn("No eIDAS SAML-engine configuration key: " + + key + " found in MOA-ID properties configuration file."); + //throw new EIDASEngineConfigurationException("No eIDAS SAML-engine configuration property.", null); + return null; + } + + Properties inputProps = loadPropsFromXml(configFile); + return buildPropsParameter(inputProps, configFile); + + } + + + private PropsParameter buildPropsParameter(Properties inputProps, String fileName) throws EIDASEngineConfigurationException { + PropsParameter outputProps = new PropsParameter(); + outputProps.setFileName(fileName); + + //original eIDAS SAML-engine use this identifier + outputProps.setName("fileConfiguration"); + + outputProps.setValue(inputProps); + + //post-process special parameters + for(String key:BINARY_PARAMETERS) { + Object keystorePath = inputProps.get(key); + if (keystorePath != null) { + if (keystorePath instanceof String && + isBinaryParameter((String)keystorePath) ) { + BinaryParameter bp = new BinaryParameter(); + bp.setValue(loadBinaryFile(keystorePath.toString())); + bp.setName(key); + bp.setUrl(keystorePath.toString()); + inputProps.put(key, bp); + + } else { + Logger.warn("eIDAS SAML-engine keyStore parameter has an unsuspected type. +" + + "(Type: " + keystorePath.toString() + ")"); + + } + } + } + + return outputProps; + } + + private boolean isBinaryParameter(String parameter) { + if (MiscUtil.isNotEmpty(parameter)) { + String absoluteConfigFile; + try { + absoluteConfigFile = FileUtils.makeAbsoluteURL( + parameter, + AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir()); + File file = new File(new URL(absoluteConfigFile).toURI()); + return file.exists(); + + } catch (ConfigurationException | MalformedURLException | URISyntaxException e) { + Logger.warn("Binary eIDAS SAML-engine configuration parameter: " + + parameter + " is not loadable."); + + } + + } + + return false; + + } + + private byte[] loadBinaryFile(String fileName) throws EIDASEngineConfigurationException{ + InputStream is = null; + byte data[]=null; + try { + String absoluteConfigFile = FileUtils.makeAbsoluteURL( + fileName, + AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir()); + + File file = new File(new URL(absoluteConfigFile).toURI()); + is = new FileInputStream(file); + data=new byte[is.available()]; + is.read(data); + + } catch (ConfigurationException | URISyntaxException | IOException e) { + throw new EIDASEngineConfigurationException("eIDAS SAML-engine configuration FAILED", null, e); + + } finally { + if (is != null) + try { + is.close(); + + } catch (IOException e) { + Logger.warn("eIDAS SAML-engine configuration is not closeable.", e); + + } + + } + + return data; + + } + + private Properties loadPropsFromXml(String configFile) throws EIDASEngineConfigurationException { + Properties props = new Properties(); + InputStream is = null; + try { + String absoluteConfigFile = FileUtils.makeAbsoluteURL( + configFile, + AuthConfigurationProviderFactory.getInstance().getRootConfigFileDir()); + + File file = new File(new URL(absoluteConfigFile).toURI()); + is = new FileInputStream(file); + props.loadFromXML(is); + + } catch (ConfigurationException | URISyntaxException | IOException e) { + throw new EIDASEngineConfigurationException("eIDAS SAML-engine configuration FAILED", null, e); + + } finally { + if (is != null) + try { + is.close(); + + } catch (IOException e) { + Logger.warn("eIDAS SAML-engine configuration is not closeable.", e); + + } + + } + + return props; + + } + + +} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/MOAeIDASSAMLInstanceConfigurationImpl.java index 096f223d7..dccd39905 100644 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/MOAeIDASSAMLInstanceConfigurationImpl.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * Copyright 2014 Federal Chancellery Austria * MOA-ID has been developed in a cooperation between BRZ, the Federal * Chancellery Austria - ICT staff unit, and Graz University of Technology. @@ -19,35 +19,42 @@ * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.config; -import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider; +import java.util.ArrayList; +import java.util.List; -public class ExternalAttributeRequestRequiredException extends Exception { - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = 5207631348933518908L; - - /** The ap. */ - private AttributeProvider ap; +import eu.eidas.samlengineconfig.ConfigurationParameter; +import eu.eidas.samlengineconfig.InstanceConfiguration; +import eu.eidas.samlengineconfig.StringParameter; - /** - * Instantiates a new external attribute request required exception. - * - * @param provider the provider - */ - public ExternalAttributeRequestRequiredException(AttributeProvider provider) { - ap = provider; - } +/** + * @author tlenz + * + */ +public class MOAeIDASSAMLInstanceConfigurationImpl extends + InstanceConfiguration { - /** - * Gets the ap that caused the exception. - * - * @return the ap - */ - public AttributeProvider getAp() { - return ap; + public void addParameter(ConfigurationParameter param) { + if (param != null) { + List<ConfigurationParameter> paramList = super.getParameters(); + if (paramList == null) { + paramList = new ArrayList<ConfigurationParameter>(); + super.setParameters(paramList); + + } + + paramList.add(param); + } } - + + public void addParameter(String key, String value) { + StringParameter param = new StringParameter(); + param.setName(key); + param.setValue(value); + addParameter(param); + + } + } diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/ModifiedEncryptionSW.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/ModifiedEncryptionSW.java new file mode 100644 index 000000000..bdd8c8e72 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/config/ModifiedEncryptionSW.java @@ -0,0 +1,29 @@ +package at.gv.egovernment.moa.id.auth.modules.eidas.config; + +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.logging.Logger; +import eu.eidas.auth.engine.core.impl.EncryptionSW; + +/** + * This encryption module asks the moa configuration on whether to encrypt the response or not. In doubt, encryption is enforced. + */ +public class ModifiedEncryptionSW extends EncryptionSW { + + @Override + public boolean isEncryptionEnable(String countryCode) { + // - encrypt if so configured + try { + AuthConfiguration moaconfig = AuthConfigurationProviderFactory.getInstance(); + Boolean useEncryption = moaconfig.getStorkConfig().getCPEPS(countryCode).isXMLSignatureSupported(); + Logger.info(useEncryption ? "using encryption" : "do not use encrpytion"); + return useEncryption; + } catch(NullPointerException | ConfigurationException e) { + Logger.warn("failed to gather information about encryption for countryCode " + countryCode + " - thus, enabling encryption"); + if(Logger.isDebugEnabled()) + e.printStackTrace(); + return true; + } + } +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/eIDASAuthenticationModulImpl.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/eIDASAuthenticationModulImpl.java new file mode 100644 index 000000000..7b044522c --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/eIDASAuthenticationModulImpl.java @@ -0,0 +1,72 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas; + +import org.apache.commons.lang3.StringUtils; + +import at.gv.egovernment.moa.id.auth.modules.AuthModule; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; + +/** + * @author tlenz + * + */ +public class eIDASAuthenticationModulImpl implements AuthModule { + + private int priority = 1; + + @Override + public int getPriority() { + return priority; + } + + /** + * Sets the priority of this module. Default value is {@code 0}. + * @param priority The priority. + */ + public void setPriority(int priority) { + this.priority = priority; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#selectProcess(at.gv.egovernment.moa.id.process.api.ExecutionContext) + */ + @Override + public String selectProcess(ExecutionContext context) { + if (StringUtils.isNotBlank((String) context.get("ccc")) || + StringUtils.isNotBlank((String) context.get("CCC"))) + return "eIDASAuthentication"; + else + return null; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getProcessDefinitions() + */ + @Override + public String[] getProcessDefinitions() { + return new String[] { "classpath:at/gv/egovernment/moa/id/auth/modules/eidas/eIDAS.Authentication.process.xml" }; + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/eIDASAuthenticationSpringResourceProvider.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/eIDASAuthenticationSpringResourceProvider.java new file mode 100644 index 000000000..384516711 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/eIDASAuthenticationSpringResourceProvider.java @@ -0,0 +1,29 @@ +package at.gv.egovernment.moa.id.auth.modules.eidas; + +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; + +import at.gv.egiz.components.spring.api.SpringResourceProvider; +import at.gv.egovernment.moa.id.auth.MOAIDAuthSpringResourceProvider; + +public class eIDASAuthenticationSpringResourceProvider implements SpringResourceProvider { + + @Override + public String getName() { + return "MOA-ID eIDAS-Authentication SpringResourceProvider"; + } + + @Override + public String[] getPackagesToScan() { + // TODO Auto-generated method stub + return null; + } + + @Override + public Resource[] getResourcesToLoad() { + ClassPathResource eIDASAuthConfig = new ClassPathResource("/moaid_eidas_auth.beans.xml", MOAIDAuthSpringResourceProvider.class); + + return new Resource[] {eIDASAuthConfig}; + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/eIDASSignalServlet.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/eIDASSignalServlet.java new file mode 100644 index 000000000..2c0f1cf8c --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/eIDASSignalServlet.java @@ -0,0 +1,106 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas; + +import java.io.IOException; + +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.gv.egovernment.moa.id.auth.servlet.AbstractProcessEngineSignalController; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +@Controller +public class eIDASSignalServlet extends AbstractProcessEngineSignalController { + + public eIDASSignalServlet() { + super(); + Logger.debug("Registering servlet " + getClass().getName() + + " with mappings '/eidas/sp/post' and '/eidas/sp/redirect'."); + + } + + @RequestMapping(value = { "/eidas/sp/post", + "/eidas/sp/redirect" + }, + method = {RequestMethod.POST, RequestMethod.GET}) + public void performCitizenCardAuthentication(HttpServletRequest req, HttpServletResponse resp) throws IOException { + signalProcessManagement(req, resp); + } + + @Override + /** + * Protocol specific implementation to get the pending-requestID + * from http request object + * + * @param request The http Servlet-Request object + * @return The Pending-request id + * + */ + public String getPendingRequestId(HttpServletRequest request) { + String sessionId = super.getPendingRequestId(request); + + try { + + // use SAML2 relayState + if (sessionId == null) { + sessionId = StringEscapeUtils.escapeHtml(request.getParameter("RelayState")); + } + + // take from InResponseTo attribute of SAMLResponse + if (sessionId == null) { + String base64SamlToken = request.getParameter("SAMLResponse"); + if (base64SamlToken != null && false) { +// byte[] samlToken = Base64Utils.decode(base64SamlToken, false); +// Document samlResponse = parseDocument(new ByteArrayInputStream(samlToken)); +// +// XPath xPath = XPathFactory.newInstance().newXPath(); +// SimpleNamespaceContext nsContext = new SimpleNamespaceContext(); +// nsContext.bindNamespaceUri("saml2p", "urn:oasis:names:tc:SAML:2.0:protocol"); +// xPath.setNamespaceContext(nsContext); +// XPathExpression expression = xPath.compile("string(/saml2p:Response/@InResponseTo)"); +// sessionId = (String) expression.evaluate(samlResponse, XPathConstants.STRING); +// sessionId = StringEscapeUtils.escapeHtml(StringUtils.trimToNull(sessionId)); + } else { + Logger.warn("No parameter 'SAMLResponse'. Unable to retrieve MOA session id."); + } + } + + } catch (Exception e) { + Logger.warn("Unable to retrieve moa session id.", e); + } + + return sessionId; + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/engine/MOAeIDASChainingMetadataProvider.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/engine/MOAeIDASChainingMetadataProvider.java new file mode 100644 index 000000000..965abcde1 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/engine/MOAeIDASChainingMetadataProvider.java @@ -0,0 +1,370 @@ +package at.gv.egovernment.moa.id.auth.modules.eidas.engine; + +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 java.util.Map.Entry; +import java.util.Timer; + +import javax.net.ssl.SSLHandshakeException; +import javax.xml.namespace.QName; + +import org.apache.commons.httpclient.MOAHttpClient; +import org.apache.commons.httpclient.params.HttpClientParams; +import org.opensaml.saml2.metadata.EntitiesDescriptor; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.provider.ChainingMetadataProvider; +import org.opensaml.saml2.metadata.provider.HTTPMetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataFilter; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.saml2.metadata.provider.ObservableMetadataProvider; +import org.opensaml.xml.XMLObject; + +import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; +import at.gv.egovernment.moa.id.commons.ex.MOAHttpProtocolSocketFactoryException; +import at.gv.egovernment.moa.id.commons.utils.MOAHttpProtocolSocketFactory; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing; +import at.gv.egovernment.moa.id.config.auth.MOAGarbageCollector; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SchemaValidationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.filter.SignatureValidationException; +import at.gv.egovernment.moa.id.saml2.MetadataFilterChain; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; +import eu.eidas.auth.engine.AbstractSAMLEngine; + +public class MOAeIDASChainingMetadataProvider implements ObservableMetadataProvider, IGarbageCollectorProcessing { + + private static MOAeIDASChainingMetadataProvider instance = null; + private static Object mutex = new Object(); + + private MetadataProvider internalProvider; + private Map<String, Date> lastAccess = null; + + + public static MOAeIDASChainingMetadataProvider getInstance() { + if (instance == null) { + synchronized (mutex) { + if (instance == null) { + instance = new MOAeIDASChainingMetadataProvider(); + MOAGarbageCollector.addModulForGarbageCollection(instance); + } + } + } + return instance; + } + + + private MOAeIDASChainingMetadataProvider() { + internalProvider = new ChainingMetadataProvider(); + lastAccess = new HashMap<String, Date>(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IGarbageCollectorProcessing#runGarbageCollector() + */ + @Override + public void runGarbageCollector() { + if (!lastAccess.isEmpty()) { + Date now = new Date(); + Date expioredate = new Date(now.getTime() - + Constants.CONFIG_PROPS_METADATA_GARBAGE_TIMEOUT); + Logger.debug("Starting eIDAS Metadata garbag collection (Expioredate:" + + expioredate + ")"); + + List<String> expiredEntities = new ArrayList<String>(); + + Iterator<Entry<String, Date>> lastAccessInterator = lastAccess.entrySet().iterator(); + while(lastAccessInterator.hasNext()) { + Entry<String, Date> element = lastAccessInterator.next(); + if (element.getValue().before(expioredate)) { + Logger.debug("Remove unused eIDAS Metadate: " + element.getKey()); + expiredEntities.add(element.getKey()); + + } + } + + if (!expiredEntities.isEmpty()) { + ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; + + //get all actually loaded metadata providers + Map<String, HTTPMetadataProvider> loadedproviders = getAllActuallyLoadedProviders(); + + for (String expired : expiredEntities) { + if (loadedproviders.containsKey(expired)) { + HTTPMetadataProvider provider = loadedproviders.get(expired); + + //destroy metadata provider + provider.destroy(); + + //remove from map + loadedproviders.remove(expired); + + /*OpenSAML ChainingMetadataProvider can not remove a MetadataProvider (UnsupportedOperationException) + *The ChainingMetadataProvider use internal a unmodifiableList to hold all registrated MetadataProviders.*/ + //chainProvider.removeMetadataProvider(provider); + Logger.info("Remove not used eIDAS MetadataProvider " + expired + + " after timeout."); + + } else + Logger.warn("eIDAS metadata for EntityID: " + expired + + " is marked as unsed, but no loaded metadata provider is found."); + + } + + try { + synchronized (chainProvider) { + chainProvider.setProviders(new ArrayList<MetadataProvider>(loadedproviders.values())); + + emitChangeEvent(); + } + + } catch (MetadataProviderException e) { + Logger.warn("ReInitalize eIDASA MetaDataProvider is not possible! MOA-ID Instance has to be restarted manualy", e); + + } + } + } + } + + + + private HTTPMetadataProvider createNewHTTPMetaDataProvider(String metadataURL) { + HTTPMetadataProvider httpProvider = null; + Timer timer= null; + MOAHttpClient httpClient = null; + try { + AuthConfiguration authConfig = AuthConfigurationProviderFactory.getInstance(); + + httpClient = new MOAHttpClient(); + + HttpClientParams httpClientParams = new HttpClientParams(); + httpClientParams.setSoTimeout(Constants.CONFIG_PROPS_METADATA_SOCKED_TIMEOUT); + httpClient.setParams(httpClientParams); + + if (metadataURL.startsWith("https:")) { + try { + MOAHttpProtocolSocketFactory protoSocketFactory = new MOAHttpProtocolSocketFactory( + Constants.SSLSOCKETFACTORYNAME, + authConfig.getCertstoreDirectory(), + authConfig.getTrustedCACertificates(), + null, + AuthConfiguration.DEFAULT_X509_CHAININGMODE, + authConfig.isTrustmanagerrevoationchecking()); + + httpClient.setCustomSSLTrustStore(metadataURL, protoSocketFactory); + + } catch (MOAHttpProtocolSocketFactoryException e) { + Logger.warn("MOA SSL-TrustStore can not initialized. Use default Java TrustStore."); + + } + } + + timer = new Timer(); + httpProvider = new HTTPMetadataProvider(timer, httpClient, + metadataURL); + httpProvider.setParserPool(AbstractSAMLEngine.getNewBasicSecuredParserPool()); + httpProvider.setRequireValidMetadata(true); + httpProvider.setMinRefreshDelay(1000*60*15); //15 minutes + httpProvider.setMaxRefreshDelay(1000*60*60*24); //24 hours + //httpProvider.setRefreshDelayFactor(0.1F); + + //add Metadata filters + MetadataFilterChain filter = new MetadataFilterChain(); + filter.addFilter(new MOAeIDASMetadataSignatureFilter( + authConfig.getBasicMOAIDConfiguration(Constants.CONIG_PROPS_EIDAS_METADATA_VALIDATION_TRUSTSTORE))); + httpProvider.setMetadataFilter(filter); + + httpProvider.initialize(); + + return httpProvider; + + } catch (Throwable e) { + if (e.getCause() != null && e.getCause().getCause() instanceof SSLHandshakeException) { + Logger.warn("SSL-Server certificate for metadata " + + metadataURL + " not trusted.", e); + + } if (e.getCause() != null && e.getCause().getCause() instanceof SignatureValidationException) { + Logger.warn("Signature verification for metadata" + + metadataURL + " FAILED.", e); + + } if (e.getCause() != null && e.getCause().getCause() instanceof SchemaValidationException) { + Logger.warn("Schema validation for metadata " + + metadataURL + " FAILED.", e); + } + + Logger.error( + "Failed to add Metadata file for " + + metadataURL + "[ " + + e.getMessage() + " ]", e); + + if (httpProvider != null) { + Logger.debug("Destroy failed Metadata provider"); + httpProvider.destroy(); + } + + if (timer != null) { + Logger.debug("Destroy Timer."); + timer.cancel(); + } + + + } + + return null; + } + + private Map<String, HTTPMetadataProvider> getAllActuallyLoadedProviders() { + Map<String, HTTPMetadataProvider> loadedproviders = new HashMap<String, HTTPMetadataProvider>(); + ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; + + //make a Map of all actually loaded HTTPMetadataProvider + List<MetadataProvider> providers = chainProvider.getProviders(); + for (MetadataProvider provider : providers) { + if (provider instanceof HTTPMetadataProvider) { + HTTPMetadataProvider httpprovider = (HTTPMetadataProvider) provider; + loadedproviders.put(httpprovider.getMetadataURI(), httpprovider); + + } + } + + return loadedproviders; + } + + public boolean refreshMetadataProvider(String metadataURL) { + try { + if (MiscUtil.isNotEmpty(metadataURL)) { + Map<String, HTTPMetadataProvider> actuallyLoadedProviders = getAllActuallyLoadedProviders(); + + // check if MetadataProvider is actually loaded + if (actuallyLoadedProviders.containsKey(metadataURL)) { + actuallyLoadedProviders.get(metadataURL).refresh(); + Logger.info("eIDAS metadata for " + + metadataURL + " is refreshed."); + return true; + + } else { + //load new Metadata Provider + ChainingMetadataProvider chainProvider = (ChainingMetadataProvider) internalProvider; + HTTPMetadataProvider newMetadataProvider = createNewHTTPMetaDataProvider(metadataURL); + chainProvider.addMetadataProvider(newMetadataProvider); + + emitChangeEvent(); + Logger.info("eIDAS metadata for " + + metadataURL + " is added."); + return true; + + } + + } else + Logger.debug("Can not refresh eIDAS metadata: NO eIDAS metadata URL."); + + } catch (MetadataProviderException e) { + Logger.warn("Refresh eIDAS metadata for " + + metadataURL + " FAILED.", e); + + } + + return false; + + } + + + public boolean requireValidMetadata() { + return internalProvider.requireValidMetadata(); + } + + public void setRequireValidMetadata(boolean requireValidMetadata) { + internalProvider.setRequireValidMetadata(requireValidMetadata); + } + + public MetadataFilter getMetadataFilter() { + return internalProvider.getMetadataFilter(); + } + + public void setMetadataFilter(MetadataFilter newFilter) + throws MetadataProviderException { + internalProvider.setMetadataFilter(newFilter); + } + + public XMLObject getMetadata() throws MetadataProviderException { + return internalProvider.getMetadata(); + } + + public EntitiesDescriptor getEntitiesDescriptor(String entitiesID) + throws MetadataProviderException { + Logger.warn("eIDAS metadata not support 'EntitiesDescriptor' elements!"); + return null; + + } + + public EntityDescriptor getEntityDescriptor(String entityID) + throws MetadataProviderException { + EntityDescriptor entityDesc = null; + try { + entityDesc = internalProvider.getEntityDescriptor(entityID); + if (entityDesc == null) { + Logger.debug("Can not find eIDAS metadata for entityID: " + entityID + + " Start refreshing process ..."); + if (refreshMetadataProvider(entityID)) + entityDesc = internalProvider.getEntityDescriptor(entityID); + + } else { + if (!entityDesc.isValid()) + if (refreshMetadataProvider(entityID)) + entityDesc = internalProvider.getEntityDescriptor(entityID); + + } + + + } catch (MetadataProviderException e) { + Logger.debug("Can not find eIDAS metadata for entityID: " + entityID + + " Start refreshing process ..."); + if (refreshMetadataProvider(entityID)) + entityDesc = internalProvider.getEntityDescriptor(entityID); + + } + + if (entityDesc != null) + lastAccess.put(entityID, new Date()); + + return entityDesc; + } + + public List<RoleDescriptor> getRole(String entityID, QName roleName) + throws MetadataProviderException { + return internalProvider.getRole(entityID, roleName); + } + + public RoleDescriptor getRole(String entityID, QName roleName, + String supportedProtocol) throws MetadataProviderException { + return internalProvider.getRole(entityID, roleName, supportedProtocol); + } + + /* (non-Javadoc) + * @see org.opensaml.saml2.metadata.provider.ObservableMetadataProvider#getObservers() + */ + @Override + public List<Observer> getObservers() { + return ((ChainingMetadataProvider) internalProvider).getObservers(); + } + + protected void emitChangeEvent() { + if ((getObservers() == null) || (getObservers().size() == 0)) { + return; + } + + List<Observer> tempObserverList = new ArrayList<Observer>(getObservers()); + for (ObservableMetadataProvider.Observer observer : tempObserverList) + if (observer != null) + observer.onEvent(this); + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/engine/MOAeIDASMetadataProviderDecorator.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/engine/MOAeIDASMetadataProviderDecorator.java new file mode 100644 index 000000000..e3ae5c046 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/engine/MOAeIDASMetadataProviderDecorator.java @@ -0,0 +1,120 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.engine; + +import java.security.KeyStore; + +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.IDPSSODescriptor; +import org.opensaml.saml2.metadata.RoleDescriptor; +import org.opensaml.saml2.metadata.SPSSODescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProvider; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; + +import eu.eidas.auth.engine.EIDASSAMLEngine; +import eu.eidas.auth.engine.metadata.MetadataProcessorI; +import eu.eidas.engine.exceptions.SAMLEngineException; + +/** + * @author tlenz + * + */ +public class MOAeIDASMetadataProviderDecorator implements MetadataProcessorI { + + private MetadataProvider metadataprovider = null; + + /** + * + */ + public MOAeIDASMetadataProviderDecorator(MetadataProvider metadataprovider) { + this.metadataprovider = metadataprovider; + + } + + /* (non-Javadoc) + * @see eu.eidas.auth.engine.metadata.MetadataProcessorI#getEntityDescriptor(java.lang.String) + */ + @Override + public EntityDescriptor getEntityDescriptor(String url) + throws SAMLEngineException { + try { + return this.metadataprovider.getEntityDescriptor(url); + + } catch (MetadataProviderException e) { + throw new SAMLEngineException("eIDAS Metadata processing FAILED.", e); + + } + } + + /* (non-Javadoc) + * @see eu.eidas.auth.engine.metadata.MetadataProcessorI#getSPSSODescriptor(java.lang.String) + */ + @Override + public SPSSODescriptor getSPSSODescriptor(String url) + throws SAMLEngineException { + return getFirstRoleDescriptor(getEntityDescriptor(url), SPSSODescriptor.class); + + } + + /* (non-Javadoc) + * @see eu.eidas.auth.engine.metadata.MetadataProcessorI#getIDPSSODescriptor(java.lang.String) + */ + @Override + public IDPSSODescriptor getIDPSSODescriptor(String url) + throws SAMLEngineException { + return getFirstRoleDescriptor(getEntityDescriptor(url), IDPSSODescriptor.class); + + } + + /* (non-Javadoc) + * @see eu.eidas.auth.engine.metadata.MetadataProcessorI#checkValidMetadataSignature(java.lang.String, eu.eidas.auth.engine.EIDASSAMLEngine) + */ + @Override + public void checkValidMetadataSignature(String url, EIDASSAMLEngine engine) + throws SAMLEngineException { + //Do nothing, because metadata signature is already validated during + //metadata provider initialization + + } + + /* (non-Javadoc) + * @see eu.eidas.auth.engine.metadata.MetadataProcessorI#checkValidMetadataSignature(java.lang.String, java.security.KeyStore) + */ + @Override + public void checkValidMetadataSignature(String url, KeyStore trustStore) + throws SAMLEngineException { + //Do nothing, because metadata signature is already validated during + //metadata provider initialization + + } + + protected <T extends RoleDescriptor> T getFirstRoleDescriptor(EntityDescriptor entityDescriptor, final Class<T> clazz){ + for(RoleDescriptor rd:entityDescriptor.getRoleDescriptors()){ + if(clazz.isInstance(rd)){ + return (T)rd; + } + } + return null; + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/engine/MOAeIDASMetadataSignatureFilter.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/engine/MOAeIDASMetadataSignatureFilter.java new file mode 100644 index 000000000..c9f3e5bcd --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/engine/MOAeIDASMetadataSignatureFilter.java @@ -0,0 +1,132 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.engine; + +import java.io.IOException; +import java.io.StringWriter; + +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.provider.FilterException; +import org.opensaml.saml2.metadata.provider.MetadataFilter; +import org.opensaml.xml.XMLObject; + +import at.gv.egovernment.moa.id.auth.builder.SignatureVerificationUtils; +import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; +import at.gv.egovernment.moa.id.auth.exception.BuildException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +public class MOAeIDASMetadataSignatureFilter implements MetadataFilter { + + private String trustProfileID = null; + + /** + * + */ + public MOAeIDASMetadataSignatureFilter(String trustProfileID) { + this.trustProfileID = trustProfileID; + + } + + + /* (non-Javadoc) + * @see org.opensaml.saml2.metadata.provider.MetadataFilter#doFilter(org.opensaml.xml.XMLObject) + */ + @Override + public void doFilter(XMLObject metadata) throws FilterException { + if (metadata instanceof EntityDescriptor) { + if (((EntityDescriptor) metadata).isSigned()) { + EntityDescriptor entityDes = (EntityDescriptor) metadata; + //check signature; + try { + Transformer transformer = TransformerFactory.newInstance() + .newTransformer(); + StringWriter sw = new StringWriter(); + StreamResult sr = new StreamResult(sw); + DOMSource source = new DOMSource(metadata.getDOM()); + transformer.transform(source, sr); + sw.close(); + String metadataXML = sw.toString(); + + SignatureVerificationUtils sigVerify = + new SignatureVerificationUtils(); + VerifyXMLSignatureResponse result = sigVerify.verify( + metadataXML.getBytes(), trustProfileID); + + //check signature-verification result + if (result.getSignatureCheckCode() != 0) { + Logger.warn("eIDAS Metadata signature-verification FAILED!" + + " Metadata: " + entityDes.getEntityID() + + " StatusCode:" + result.getSignatureCheckCode()); + throw new FilterException("eIDAS Metadata signature-verification FAILED!" + + " Metadata: " + entityDes.getEntityID() + + " StatusCode:" + result.getSignatureCheckCode()); + + } + + if (result.getCertificateCheckCode() != 0) { + Logger.warn("eIDAS Metadata certificate-verification FAILED!" + + " Metadata: " + entityDes.getEntityID() + + " StatusCode:" + result.getCertificateCheckCode()); + throw new FilterException("eIDAS Metadata certificate-verification FAILED!" + + " Metadata: " + entityDes.getEntityID() + + " StatusCode:" + result.getCertificateCheckCode()); + + } + + + } catch (MOAIDException | TransformerFactoryConfigurationError | TransformerException | IOException e) { + Logger.error("eIDAS Metadata verification has an interal error.", e); + throw new FilterException("eIDAS Metadata verification has an interal error." + + " Message:" + e.getMessage()); + + } + + + } else { + Logger.warn("eIDAS Metadata root-element MUST be signed."); + throw new FilterException("eIDAS Metadata root-element MUST be signed.'"); + + } + + } else { + Logger.warn("eIDAS Metadata root-element is not of type 'EntityDescriptor'"); + throw new FilterException("eIDAS Metadata root-element is not of type 'EntityDescriptor'"); + + } + + } + +} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/exceptions/EIDASEngineConfigurationException.java index 79641d085..98bc559d2 100644 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKException.java +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/exceptions/EIDASEngineConfigurationException.java @@ -1,64 +1,60 @@ -/******************************************************************************* +/* * Copyright 2014 Federal Chancellery Austria * MOA-ID has been developed in a cooperation between BRZ, the Federal * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * + * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * http://www.osor.eu/eupl/ - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. - * + * * This product combines work with different licenses. See the "NOTICE" text * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/** - * */ -package at.gv.egovernment.moa.id.auth.stork; +package at.gv.egovernment.moa.id.auth.modules.eidas.exceptions; +import at.gv.egovernment.moa.id.config.ConfigurationException; /** - * Exception thrown if error occurs in STORK processing - * @author bzwattendorfer + * @author tlenz * */ -public class STORKException extends Exception{ +public class EIDASEngineConfigurationException extends ConfigurationException { /** * */ private static final long serialVersionUID = 1L; - - public STORKException() { - super(); - + + /** + * @param messageId + * @param parameters + * @param wrapped + */ + public EIDASEngineConfigurationException(String messageId, + Object[] parameters, Throwable wrapped) { + super(messageId, parameters, wrapped); } - public STORKException(String message, Throwable cause) { - super(message, cause); - + /** + * @param string + * @param object + */ + public EIDASEngineConfigurationException(String string, Object[] object) { + super(string, object); } - public STORKException(String message) { - super(message); - - } - public STORKException(Throwable cause) { - super(cause); - - } + - - } diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/exceptions/EIDASEngineException.java index 123d32af4..95690bbeb 100644 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKPVPUtilits.java +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/exceptions/EIDASEngineException.java @@ -20,30 +20,26 @@ * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. */ -package at.gv.egovernment.moa.id.protocols.stork2; +package at.gv.egovernment.moa.id.auth.modules.eidas.exceptions; -import java.util.Arrays; -import java.util.List; /** * @author tlenz * */ -public class STORKPVPUtilits { - - public static final List<String> attributesRequirePVPAuthentication = - Arrays.asList("ECApplicationRole", "MSOrganization"); - - - - public static boolean performAuthenticationOnNationalIDP(MOASTORKRequest moastorkRequest) { - for (String el : attributesRequirePVPAuthentication) { - if (moastorkRequest.getPersonalAttributeList().containsKey(el)) { - return true; - - } - } - return false; +public class EIDASEngineException extends Exception { + + /** + * @param string + * @param e + */ + public EIDASEngineException(String string, Throwable e) { + super(string, e); } - + + /** + * + */ + private static final long serialVersionUID = 1559812927427153879L; + } diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/UnsupportedAttributeException.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/exceptions/eIDASAttributeException.java index 31b9c9c0a..7840ae2e6 100644 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/UnsupportedAttributeException.java +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/exceptions/eIDASAttributeException.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * Copyright 2014 Federal Chancellery Austria * MOA-ID has been developed in a cooperation between BRZ, the Federal * Chancellery Austria - ICT staff unit, and Graz University of Technology. @@ -19,11 +19,20 @@ * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.exceptions; -public class UnsupportedAttributeException extends Exception { +/** + * @author tlenz + * + */ +public class eIDASAttributeException extends Exception { - private static final long serialVersionUID = -7720066381435378111L; + private static final long serialVersionUID = 1L; + + public eIDASAttributeException(String message) { + super(message); + + } } diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/CreateIdentityLinkTask.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/CreateIdentityLinkTask.java new file mode 100644 index 000000000..515ce2913 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/CreateIdentityLinkTask.java @@ -0,0 +1,163 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.tasks; + +import java.io.IOException; +import java.io.InputStream; +import java.text.ParseException; +import java.text.SimpleDateFormat; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; + +import org.springframework.stereotype.Component; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.xml.sax.SAXException; + +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; +import at.gv.egovernment.moa.id.auth.data.IdentityLink; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; +import at.gv.egovernment.moa.id.auth.modules.eidas.exceptions.eIDASAttributeException; +import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.egovernment.moa.util.XPathUtils; +import eu.eidas.auth.commons.IPersonalAttributeList; + +/** + * @author tlenz + * + */ +@Component("CreateIdentityLinkTask") +public class CreateIdentityLinkTask extends AbstractAuthServletTask { + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, + HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try{ + defaultTaskInitialization(request, executionContext); + + //get eIDAS attributes from MOA-Session + IPersonalAttributeList eIDASAttributes = moasession.getGenericDataFromSession( + AuthenticationSessionStorageConstants.eIDAS_ATTRIBUTELIST, + IPersonalAttributeList.class); + + IdentityLink identityLink = null; + + //connect SZR-Gateway + //TODO: implement SZR-Gateway communication!!!! + if(true) { + + // create fake IdL + // - fetch IdL template from resources + InputStream s = CreateIdentityLinkTask.class.getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml"); + Element idlTemplate = DOMUtils.parseXmlValidating(s); + + identityLink = new IdentityLinkAssertionParser(idlTemplate).parseIdentityLink(); + + // replace data + Element idlassertion = identityLink.getSamlAssertion(); + + // - set bpk/wpbk; + Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); + if(!eIDASAttributes.containsKey(Constants.eIDAS_ATTR_PERSONALIDENTIFIER)) + throw new eIDASAttributeException("PersonalIdentifier is missing"); + String eIdentifier = eIDASAttributes.get(Constants.eIDAS_ATTR_PERSONALIDENTIFIER).getValue().get(0); + prIdentification.getFirstChild().setNodeValue(eIdentifier); + + // - set last name + Node prFamilyName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH); + if(!eIDASAttributes.containsKey(Constants.eIDAS_ATTR_CURRENTFAMILYNAME)) + throw new eIDASAttributeException("currentFamilyName is missing"); + String familyName = eIDASAttributes.get(Constants.eIDAS_ATTR_CURRENTFAMILYNAME).getValue().get(0); + prFamilyName.getFirstChild().setNodeValue(familyName); + + // - set first name + Node prGivenName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH); + if(!eIDASAttributes.containsKey(Constants.eIDAS_ATTR_CURRENTGIVENNAME)) + throw new eIDASAttributeException("currentGivenName is missing"); + String givenName = eIDASAttributes.get(Constants.eIDAS_ATTR_CURRENTGIVENNAME).getValue().get(0); + prGivenName.getFirstChild().setNodeValue(givenName); + + // - set date of birth + Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH); + if(!eIDASAttributes.containsKey(Constants.eIDAS_ATTR_DATEOFBIRTH)) + throw new eIDASAttributeException("dateOfBirth is missing"); + String dateOfBirth = eIDASAttributes.get(Constants.eIDAS_ATTR_DATEOFBIRTH).getValue().get(0); + dateOfBirth = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(dateOfBirth)); + prDateOfBirth.getFirstChild().setNodeValue(dateOfBirth); + + identityLink = new IdentityLinkAssertionParser(idlassertion).parseIdentityLink(); + + //resign IDL + IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance(); + Element resignedilAssertion = identitylinkresigner.resignIdentityLink(identityLink.getSamlAssertion(), authConfig.getStorkFakeIdLResigningKey()); + identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink(); + + } else { + //contact SZR Gateway + Logger.debug("Starting connecting SZR Gateway"); + + //TODO:!!!!!! + + } + + Logger.debug("SZR communication was successfull"); + + if (identityLink == null) { + Logger.error("SZR Gateway did not return an identity link."); + throw new MOAIDException("stork.10", null); + } + + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_PEPS_IDL_RECEIVED); + moasession.setForeigner(true); + moasession.setIdentityLink(identityLink); + moasession.setBkuURL("Not applicable (eIDASAuthentication)"); + + //store MOA-session to database + authenticatedSessionStorage.storeSession(moasession); + + } catch (ParseException | MOAIDException | MOADatabaseException | ParserConfigurationException | SAXException | IOException e) { + throw new TaskExecutionException(pendingReq, "IdentityLink generation for foreign person FAILED.", e); + + } catch (eIDASAttributeException e) { + throw new TaskExecutionException(pendingReq, "Minimum required eIDAS attributeset not found.", e); + + } + + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/GenerateAuthnRequestTask.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/GenerateAuthnRequestTask.java new file mode 100644 index 000000000..2156720e8 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/GenerateAuthnRequestTask.java @@ -0,0 +1,191 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.tasks; + +import java.io.IOException; +import java.io.StringWriter; +import java.util.Collection; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.springframework.stereotype.Component; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; +import at.gv.egovernment.moa.id.auth.modules.eidas.exceptions.EIDASEngineException; +import at.gv.egovernment.moa.id.auth.modules.eidas.utils.SAMLEngineUtils; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.config.stork.CPEPS; +import at.gv.egovernment.moa.id.config.stork.StorkAttribute; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.util.VelocityProvider; +import at.gv.egovernment.moa.logging.Logger; +import eu.eidas.auth.commons.EIDASAuthnRequest; +import eu.eidas.auth.commons.EIDASUtil; +import eu.eidas.auth.commons.EidasLoaCompareType; +import eu.eidas.auth.commons.EidasLoaLevels; +import eu.eidas.auth.commons.IPersonalAttributeList; +import eu.eidas.auth.commons.PersonalAttribute; +import eu.eidas.auth.commons.PersonalAttributeList; +import eu.eidas.auth.engine.EIDASSAMLEngine; +import eu.eidas.auth.engine.core.eidas.SPType; +import eu.eidas.engine.exceptions.EIDASSAMLEngineException; + +/** + * @author tlenz + * + */ +@Component("GenerateAuthnRequestTask") +public class GenerateAuthnRequestTask extends AbstractAuthServletTask { + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, + HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + + try{ + //get service-provider configuration + IOAAuthParameters oaConfig = pendingReq.getOnlineApplicationConfiguration(); + + // get target country + String citizenCountryCode = (String) executionContext.get(MOAIDAuthConstants.PARAM_CCC); + + if (StringUtils.isEmpty(citizenCountryCode)) { + // illegal state; task should not have been executed without a selected country + throw new AuthenticationException("stork.22", new Object[] { pendingReq.getRequestID() }); + } + + CPEPS cpeps = authConfig.getStorkConfig().getCPEPS(citizenCountryCode); + if(null == cpeps) { + Logger.error("PEPS unknown for country", new Object[] {citizenCountryCode}); + throw new AuthenticationException("Unknown PEPS for citizen country '{}'", new Object[] {citizenCountryCode}); + } + Logger.debug("Found eIDaS Node/C-PEPS configuration for citizen of country: " + citizenCountryCode); + String destination = cpeps.getPepsURL().toString().split(";")[1].trim(); // FIXME convenience for metadata url and assertion destination + String metadataUrl = cpeps.getPepsURL().toString().split(";")[0].trim(); + + // assemble requested attributes + Collection<StorkAttribute> attributesFromConfig = oaConfig.getRequestedSTORKAttributes(); + + // - prepare attribute list + IPersonalAttributeList pAttList = new PersonalAttributeList(); + + // - fill container + for (StorkAttribute current : attributesFromConfig) { + PersonalAttribute newAttribute = new PersonalAttribute(); + newAttribute.setName(current.getName()); + + boolean globallyMandatory = false; + for (StorkAttribute currentGlobalAttribute : authConfig.getStorkConfig().getStorkAttributes()) + if (current.getName().equals(currentGlobalAttribute.getName())) { + globallyMandatory = BooleanUtils.isTrue(currentGlobalAttribute.getMandatory()); + break; + } + + newAttribute.setIsRequired(current.getMandatory() || globallyMandatory); + pAttList.add(newAttribute); + } + + EIDASSAMLEngine engine = SAMLEngineUtils.createSAMLEngine(); + + //build eIDAS AuthnRequest + EIDASAuthnRequest authnRequest = new EIDASAuthnRequest(); + authnRequest.setProviderName(pendingReq.getAuthURL()); + authnRequest.setPersonalAttributeList(pAttList); + + authnRequest.setIssuer(pendingReq.getAuthURL() + Constants.eIDAS_HTTP_ENDPOINT_METADATA); + + authnRequest.setDestination(destination); + authnRequest.setEidasNameidFormat(EIDASAuthnRequest.NAMEID_FORMAT_UNSPECIFIED); + authnRequest.setEidasLoA(EidasLoaLevels.LOW.stringValue()); + authnRequest.setEidasLoACompareType(EidasLoaCompareType.MINIMUM.stringValue()); + authnRequest.setSPType(SPType.DEFAULT_VALUE); + + engine.initRequestedAttributes(pAttList); + authnRequest = engine.generateEIDASAuthnRequest(authnRequest); + + //encode AuthnRequest + byte[] token = authnRequest.getTokenSaml(); + String SAMLRequest = EIDASUtil.encodeSAMLToken(token); + + + //send + try { + VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); + Template template = velocityEngine.getTemplate("/resources/templates/eidas_postbinding_template.vm"); + VelocityContext context = new VelocityContext(); + + String actionType = "SAMLRequest"; + context.put(actionType, SAMLRequest); + Logger.debug("Encoded " + actionType + " original: " + SAMLRequest); + + context.put("RelayState", pendingReq.getRequestID()); + + Logger.debug("Using assertion consumer url as action: " + destination); + context.put("action", destination); + + Logger.debug("Starting template merge"); + StringWriter writer = new StringWriter(); + + Logger.debug("Doing template merge"); + template.merge(context, writer); + Logger.debug("Template merge done"); + + Logger.debug("Sending html content: " + writer.getBuffer().toString()); + + response.setContentType("text/html;charset=UTF-8"); + response.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8")); + + } catch (IOException e) { + Logger.error("Velocity IO error: " + e.getMessage()); + throw new MOAIDException("stork.15", null); // TODO + } catch (Exception e) { + Logger.error("Velocity general error: " + e.getMessage()); + throw new MOAIDException("stork.15", null); // TODO + } + + }catch (EIDASSAMLEngineException e){ + Logger.error("eIDAS AuthnRequest generation FAILED.", e); + throw new TaskExecutionException(pendingReq, "eIDAS AuthnRequest generation FAILED.", + new EIDASEngineException("Could not generate token for Saml Request", e)); + + } catch (EIDASEngineException | MOAIDException e) { + throw new TaskExecutionException(pendingReq, "eIDAS AuthnRequest generation FAILED.", e); + + } + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/ReceiveAuthnResponseTask.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/ReceiveAuthnResponseTask.java new file mode 100644 index 000000000..dea9e675e --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/tasks/ReceiveAuthnResponseTask.java @@ -0,0 +1,90 @@ +package at.gv.egovernment.moa.id.auth.modules.eidas.tasks; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.stereotype.Component; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; +import at.gv.egovernment.moa.id.auth.modules.eidas.exceptions.EIDASEngineException; +import at.gv.egovernment.moa.id.auth.modules.eidas.utils.MOAPersonalAttributeList; +import at.gv.egovernment.moa.id.auth.modules.eidas.utils.SAMLEngineUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; +import eu.eidas.auth.commons.EIDASAuthnResponse; +import eu.eidas.auth.commons.EIDASUtil; +import eu.eidas.auth.engine.EIDASSAMLEngine; +import eu.eidas.engine.exceptions.EIDASSAMLEngineException; + +@Component("ReceiveAuthnResponseTask") +public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { + + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) throws TaskExecutionException { + + try{ + //get SAML Response + String base64SamlToken = request.getParameter("SAMLResponse"); + if (MiscUtil.isEmpty(base64SamlToken)) { + Logger.warn("No eIDAS SAMLReponse found in http request."); + throw new MOAIDException("HTTP request includes no eIDAS SAML-Response element.", null); + + } + + //get MOASession + defaultTaskInitialization(request, executionContext); + + //decode SAML response + byte[] decSamlToken = EIDASUtil.decodeSAMLToken(base64SamlToken); + + //get eIDAS SAML-engine + EIDASSAMLEngine engine = SAMLEngineUtils.createSAMLEngine(); + + //validate SAML token + EIDASAuthnResponse samlResp = engine.validateEIDASAuthnResponse(decSamlToken, + request.getRemoteHost(), Constants.CONFIG_PROPS_SKEWTIME); + + boolean encryptedResponse=engine.isEncryptedSamlResponse(decSamlToken); + if (encryptedResponse) { + Logger.info("Received encrypted eIDAS SAML-Response."); + //TODO: check if additional decryption operation is required + + } + + //MOA-ID specific response validation + //TODO: implement MOA-ID specific response validation + + //update MOA-Session data with received information + Logger.debug("Store eIDAS response information into MOA-session."); + moasession.setQAALevel(samlResp.getAssuranceLevel()); + + moasession.setGenericDataToSession( + AuthenticationSessionStorageConstants.eIDAS_ATTRIBUTELIST, + new MOAPersonalAttributeList(samlResp.getPersonalAttributeList())); + + moasession.setGenericDataToSession( + AuthenticationSessionStorageConstants.eIDAS_RESPONSE, + decSamlToken); + + //store MOA-session to database + authenticatedSessionStorage.storeSession(moasession); + + }catch (EIDASSAMLEngineException e) { + Logger.error("eIDAS AuthnRequest generation FAILED.", e); + throw new TaskExecutionException(pendingReq, "eIDAS Response processing FAILED.", + new EIDASEngineException("Could not validate eIDAS response", e)); + + } catch (EIDASEngineException | MOAIDException | MOADatabaseException e) { + throw new TaskExecutionException(pendingReq, "eIDAS Response processing FAILED.", e); + + } + + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/utils/MOAOrderedAttributeIterator.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/utils/MOAOrderedAttributeIterator.java new file mode 100644 index 000000000..573163af0 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/utils/MOAOrderedAttributeIterator.java @@ -0,0 +1,66 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.utils; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +import at.gv.egovernment.moa.logging.Logger; + +import eu.eidas.auth.commons.PersonalAttribute; +import eu.eidas.auth.commons.PersonalAttributeList; + + +/** + * @author tlenz + * + */ +public class MOAOrderedAttributeIterator implements Iterator<PersonalAttribute> { + + private MOAPersonalAttributeList pal; + private Iterator<String> keyIterator; + + public MOAOrderedAttributeIterator(MOAPersonalAttributeList palArg) { + this.pal = palArg; + keyIterator = palArg.getInsertOrder().iterator(); + } + + @Override + public boolean hasNext() { + return keyIterator.hasNext(); + } + + @Override + public PersonalAttribute next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + return pal.get(keyIterator.next()); + } + + @Override + public void remove() { + Logger.error("Not implemented"); + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/utils/MOAPersonalAttributeList.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/utils/MOAPersonalAttributeList.java new file mode 100644 index 000000000..5cc100b70 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/utils/MOAPersonalAttributeList.java @@ -0,0 +1,343 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.utils; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.StringTokenizer; +import java.util.concurrent.ConcurrentHashMap; + +import org.apache.commons.lang.StringUtils; + +import at.gv.egovernment.moa.logging.Logger; + +import eu.eidas.auth.commons.AttributeConstants; +import eu.eidas.auth.commons.AttributeUtil; +import eu.eidas.auth.commons.EIDASErrors; +import eu.eidas.auth.commons.EIDASParameters; +import eu.eidas.auth.commons.EIDASUtil; +import eu.eidas.auth.commons.EIDASValues; +import eu.eidas.auth.commons.IPersonalAttributeList; +import eu.eidas.auth.commons.PersonalAttribute; +import eu.eidas.auth.commons.exceptions.InternalErrorEIDASException; + +/** + * @author tlenz + * + */ +public final class MOAPersonalAttributeList extends + ConcurrentHashMap<String, PersonalAttribute> implements IPersonalAttributeList { + + /** + * + */ + private static final long serialVersionUID = -4488124133022713089L; + + public MOAPersonalAttributeList(IPersonalAttributeList eIDASAttributeList) { + super(); + Iterator<PersonalAttribute> element = eIDASAttributeList.iterator(); + while(element.hasNext()) + add(element.next()); + + } + + /** + * Hash with the latest fetched attribute name alias. + */ + private Map<String, Integer> latestAttrAlias = + new HashMap<String, Integer>(); + + /** + * Hash with mapping number of alias or the attribute name. + */ + private Map<String, Integer> attrAliasNumber = + new HashMap<String, Integer>(); + private List<String> insertOrder = new ArrayList<String>(); + + /** + * Obtain the insertOrder Collection + * + * @return defensive copy of the collection + */ + List<String> getInsertOrder() { + return Collections.unmodifiableList(this.insertOrder); + } + + /** + * Default constructor. + */ + public MOAPersonalAttributeList() { + super(); + + } + + /** + * Constructor with initial capacity for the PersonalAttributeList size. + * + * @param capacity The initial capacity for the PersonalAttributeList. + */ + public MOAPersonalAttributeList(final int capacity) { + super(capacity); + } + + /** + * {@inheritDoc} + */ + public Iterator<PersonalAttribute> iterator() { + return new MOAOrderedAttributeIterator(this); + } + + /** + * {@inheritDoc} + */ + public PersonalAttribute get(final Object key) { + String attrName = (String) key; + + if (this.latestAttrAlias == null) + this.latestAttrAlias = new HashMap<String, Integer>(); + + if (this.attrAliasNumber == null) + this.attrAliasNumber = new HashMap<String, Integer>(); + + if (this.latestAttrAlias.containsKey(key)) { + attrName = attrName + this.latestAttrAlias.get(key); + } else { + if (this.attrAliasNumber.containsKey(key)) { + this.latestAttrAlias.put(attrName, this.attrAliasNumber.get(key)); + } + } + return super.get(attrName); + } + + /** + * {@inheritDoc} + */ + public void add(final PersonalAttribute value) { + if (value != null) { + this.put(value.getName(), value); + } + } + + /** + * {@inheritDoc} + */ + public PersonalAttribute put(final String key, final PersonalAttribute val) { + if (StringUtils.isNotEmpty(key) && val != null) { + // Validate if attribute name already exists! + String attrAlias = key; + if (this.containsKey(attrAlias)) { + if (this.attrAliasNumber == null) + this.attrAliasNumber = new HashMap<String, Integer>(); + if (!val.isEmptyValue() && StringUtils.isNumeric(val.getValue().get(0))) { + final String attrValue = val.getValue().get(0); + attrAlias = key + attrValue; + this.attrAliasNumber.put(key, Integer.valueOf(attrValue)); + } else { + final PersonalAttribute attr = super.get(key); + if (!attr.isEmptyValue() + && StringUtils.isNumeric(attr.getValue().get(0))) { + attrAlias = key + attr.getValue().get(0); + super.put(key, (PersonalAttribute) attr); + this.attrAliasNumber.put(key, null); + } + } + } else { + if (insertOrder == null) + insertOrder = new ArrayList<String>(); + + insertOrder.add(key); + } + return super.put(attrAlias, val); + } else { + return null; + } + } + + @Override + public PersonalAttribute remove(Object key) { + insertOrder.remove(key); + return super.remove(key); + } + + /** + * {@inheritDoc} + */ + public void populate(final String attrList) { + final StringTokenizer strToken = + new StringTokenizer(attrList, EIDASValues.ATTRIBUTE_SEP.toString()); + + while (strToken.hasMoreTokens()) { + final PersonalAttribute persAttr = new PersonalAttribute(); + String[] tuples = + strToken.nextToken().split(EIDASValues.ATTRIBUTE_TUPLE_SEP.toString(), + AttributeConstants.NUMBER_TUPLES.intValue()); + + // Convert to the new format if needed! + tuples = convertFormat(tuples); + + if (AttributeUtil.hasValidTuples(tuples)) { + final int attrValueIndex = + AttributeConstants.ATTR_VALUE_INDEX.intValue(); + final String tmpAttrValue = + tuples[attrValueIndex].substring(1, + tuples[attrValueIndex].length() - 1); + final String[] vals = + tmpAttrValue.split(EIDASValues.ATTRIBUTE_VALUE_SEP.toString()); + + persAttr.setName(tuples[AttributeConstants.ATTR_NAME_INDEX.intValue()]); + persAttr.setIsRequired(Boolean + .valueOf(tuples[AttributeConstants.ATTR_TYPE_INDEX.intValue()])); + // check if it is a complex value + if (tuples[AttributeConstants.ATTR_NAME_INDEX.intValue()] + .equals(EIDASParameters.COMPLEX_ADDRESS_VALUE.toString())) { + persAttr.setComplexValue(createComplexValue(vals)); + } else { + persAttr.setValue(createValues(vals)); + } + + if (tuples.length == AttributeConstants.NUMBER_TUPLES.intValue()) { + persAttr.setStatus(tuples[AttributeConstants.ATTR_STATUS_INDEX + .intValue()]); + } + this.put(tuples[AttributeConstants.ATTR_NAME_INDEX.intValue()], + persAttr); + + } else { + Logger.info("BUSINESS EXCEPTION : Invalid personal attribute list tuples"); + } + + } + } + + /** + * Returns a copy of this <tt>IPersonalAttributeList</tt> instance. + * + * @return The copy of this IPersonalAttributeList. + */ + public Object clone() { + try { + MOAPersonalAttributeList theClone= (MOAPersonalAttributeList)super.clone(); + theClone.insertOrder=new ArrayList<String>(insertOrder); + return theClone; + + } catch (CloneNotSupportedException e) { + throw new InternalErrorEIDASException( + EIDASUtil.getConfig(EIDASErrors.INTERNAL_ERROR.errorCode()), + EIDASUtil.getConfig(EIDASErrors.INTERNAL_ERROR.errorMessage()), e); + } + } + + /** + * Creates a string in the following format. + * + * attrName:attrType:[attrValue1,attrValue2=attrComplexValue]:attrStatus; + * + * @return {@inheritDoc} + */ + @Override + public String toString() { + final StringBuilder strBuilder = new StringBuilder(); + final Iterator<String> iteratorInsertOrder = insertOrder.iterator(); + while (iteratorInsertOrder.hasNext()) { + String key = iteratorInsertOrder.next(); + final PersonalAttribute attr = get(key); + strBuilder.append(attr.toString()); + if (isNumberAlias(key)) { + strBuilder.append(get(key).toString()); + } + } + return strBuilder.toString(); + } + + /** + * Validates and creates the attribute's complex values. + * + * @param values The complex values. + * @return The {@link Map} with the complex values. + * @see Map + */ + private Map<String, String> createComplexValue(final String[] values) { + final Map<String, String> complexValue = new HashMap<String, String>(); + for (final String val : values) { + final String[] tVal = val.split("="); + if (StringUtils.isNotEmpty(val) && tVal.length == 2) { + complexValue.put(tVal[0], AttributeUtil.unescape(tVal[1])); + } + } + return complexValue; + } + + /** + * Validates and creates the attribute values. + * + * @param vals The attribute values. + * @return The {@link List} with the attribute values. + * @see List + */ + private List<String> createValues(final String[] vals) { + final List<String> values = new ArrayList<String>(); + for (final String val : vals) { + if (StringUtils.isNotEmpty(val)) { + values.add(AttributeUtil.unescape(val)); + } + } + return values; + } + + ////////////////// + /** + * Converts the attribute tuple (attrName:attrType...) to the new format. + * + * @param tuples The attribute tuples to convert. + * @return The attribute tuples in the new format. + */ + private String[] convertFormat(final String[] tuples) { + final String[] newFormatTuples = + new String[AttributeConstants.NUMBER_TUPLES.intValue()]; + if (tuples != null) { + System.arraycopy(tuples, 0, newFormatTuples, 0, tuples.length); + + for (int i = tuples.length; i < newFormatTuples.length; i++) { + if (i == AttributeConstants.ATTR_VALUE_INDEX.intValue()) { + newFormatTuples[i] = "[]"; + } else { + newFormatTuples[i] = ""; + } + } + } + return newFormatTuples; + } + + public boolean isNumberAlias(String key) { + return this.attrAliasNumber.containsKey(key); + } + + + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/utils/SAMLEngineUtils.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/utils/SAMLEngineUtils.java new file mode 100644 index 000000000..8e46f0ef1 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/auth/modules/eidas/utils/SAMLEngineUtils.java @@ -0,0 +1,71 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.eidas.utils; + +import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; +import at.gv.egovernment.moa.id.auth.modules.eidas.config.MOAIDCertificateManagerConfigurationImpl; +import at.gv.egovernment.moa.id.auth.modules.eidas.engine.MOAeIDASChainingMetadataProvider; +import at.gv.egovernment.moa.id.auth.modules.eidas.engine.MOAeIDASMetadataProviderDecorator; +import at.gv.egovernment.moa.id.auth.modules.eidas.exceptions.EIDASEngineException; +import at.gv.egovernment.moa.logging.Logger; +import eu.eidas.auth.engine.EIDASSAMLEngine; +import eu.eidas.engine.exceptions.EIDASSAMLEngineException; +import eu.eidas.samlengineconfig.CertificateConfigurationManager; + +/** + * @author tlenz + * + */ +public class SAMLEngineUtils { + + private static EIDASSAMLEngine eIDASEngine = null; + + public static synchronized EIDASSAMLEngine createSAMLEngine() throws EIDASEngineException{ + + if (eIDASEngine == null) { + try { + //get eIDAS SAMLengine configuration from MOA-ID configuration + CertificateConfigurationManager configManager = new MOAIDCertificateManagerConfigurationImpl(); + + //initial eIDAS SAMLengine + EIDASSAMLEngine engine = EIDASSAMLEngine.createSAMLEngine(Constants.eIDAS_SAML_ENGINE_NAME, + configManager); + + //set Metadata managment to eIDAS SAMLengine + engine.setMetadataProcessor( + new MOAeIDASMetadataProviderDecorator( + MOAeIDASChainingMetadataProvider.getInstance())); + + eIDASEngine = engine; + + } catch (EIDASSAMLEngineException e) { + Logger.error("eIDAS SAMLengine initialization FAILED!", e); + throw new EIDASEngineException("eIDAS SAMLengine initialization FAILED!", e); + + } + } + + return eIDASEngine; + } + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASData.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASData.java new file mode 100644 index 000000000..3c33b8d58 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASData.java @@ -0,0 +1,88 @@ +package at.gv.egovernment.moa.id.protocols.eidas; + +import java.util.Collection; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; + +import at.gv.egovernment.moa.id.auth.modules.eidas.utils.MOAPersonalAttributeList; +import at.gv.egovernment.moa.id.moduls.RequestImpl; +import eu.eidas.auth.commons.EIDASAuthnRequest; + +@Component("EIDASData") +@Scope(value = BeanDefinition.SCOPE_PROTOTYPE) +public class EIDASData extends RequestImpl { + + /** The Constant serialVersionUID. */ + private static final long serialVersionUID = 8765755670214923910L; + + /** The attributes requested by the eIDaS. */ + private MOAPersonalAttributeList attributes; + + /** The incoming eIDaS SAML2 AuthnRequest. */ + private EIDASAuthnRequest authnRequest; + + /** The ip address of the requester. */ + private String remoteIPAddress; + + @Override + public Collection<String> getRequestedAttributes() { + // TODO Auto-generated method stub + return null; + } + + /** + * Gets the eidas requested attributes. + * + * @return the requested attributes + */ + public MOAPersonalAttributeList getEidasRequestedAttributes() { + return (MOAPersonalAttributeList) attributes.clone(); + } + + /** + * Sets the eidas requested attributes. + * + * @param personalAttributeList the requested attributes + */ + public void setEidasRequestedAttributes(MOAPersonalAttributeList personalAttributeList) { + attributes = personalAttributeList; + } + + /** + * Gets the eidas request. + * + * @return the eidas request + */ + public EIDASAuthnRequest getEidasRequest() { + return authnRequest; + } + + /** + * Sets the eidas request. + * + * @param request the new eidas request + */ + public void setEidasRequest(EIDASAuthnRequest request) { + authnRequest = request; + } + + /** + * Gets the remote address. + * + * @return the remote address + */ + public String getRemoteAddress() { + return remoteIPAddress; + } + + /** + * Sets the remote address. + * + * @param remoteIP the new remote address + */ + public void setRemoteAddress(String remoteIP) { + remoteIPAddress = remoteIP; + } +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASProtocol.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASProtocol.java new file mode 100644 index 000000000..4caa6700a --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EIDASProtocol.java @@ -0,0 +1,190 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.protocols.eidas; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; +import at.gv.egovernment.moa.id.auth.modules.eidas.utils.MOAPersonalAttributeList; +import at.gv.egovernment.moa.id.auth.modules.eidas.utils.SAMLEngineUtils; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; +import eu.eidas.auth.commons.EIDASAuthnRequest; +import eu.eidas.auth.commons.EIDASUtil; +import eu.eidas.auth.engine.EIDASSAMLEngine; + +/** + * eIDAS Protocol Support for outbound authentication + * + * @author tlenz + */ +public class EIDASProtocol extends AbstractAuthProtocolModulController { + + public static final String NAME = EIDASProtocol.class.getName(); + public static final String PATH = "eidas"; + + public String getName() { + return NAME; + } + + public String getPath() { + return PATH; + } + + //eIDAS metadata end-point + @RequestMapping(value = "/eidas/metadata", method = {RequestMethod.GET}) + public void eIDASMetadataRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException { + + //create pendingRequest object + EIDASData pendingReq = applicationContext.getBean(EIDASData.class); + pendingReq.initialize(req); + pendingReq.setModule(NAME); + pendingReq.setNeedAuthentication(false); + pendingReq.setAuthenticated(false); + + revisionsLogger.logEvent( + pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), + MOAIDEventConstants.TRANSACTION_IP, + req.getRemoteAddr()); + + + EidasMetaDataRequest metadataAction = applicationContext.getBean(EidasMetaDataRequest.class); + metadataAction.processRequest(pendingReq, + req, resp, null); + + revisionsLogger.logEvent( + pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), + Constants.eIDAS_REVERSIONSLOG_METADATA); + } + + + //PVP2.x IDP POST-Binding end-point + @RequestMapping(value = "/eidas/ColleagueRequest", method = {RequestMethod.POST}) + public void PVPIDPPostRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException, IOException { + + //create pending-request object + EIDASData pendingReq = applicationContext.getBean(EIDASData.class); + pendingReq.initialize(req); + pendingReq.setModule(NAME); + + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); + revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_CREATED, pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent( + pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), + MOAIDEventConstants.TRANSACTION_IP, + req.getRemoteAddr()); + + //preProcess eIDAS request + preProcess(req, resp, pendingReq); + + revisionsLogger.logEvent(pendingReq, Constants.eIDAS_REVERSIONSLOG_IDP_AUTHREQUEST); + + //AuthnRequest needs authentication + pendingReq.setNeedAuthentication(true); + + //set protocol action, which should be executed after authentication + pendingReq.setAction(eIDASAuthenticationRequest.class.getName()); + + //switch to session authentication + performAuthentication(req, resp, pendingReq); + } + + /* + First request step - send it to BKU selection for user authentication. After the user credentials + and other info are obtained, in the second step the request will be processed and the user redirected + */ + public void preProcess(HttpServletRequest request, HttpServletResponse response, EIDASData pendingReq) throws MOAIDException { + + Logger.info("received an eIDaS request"); + + //get SAML Response and decode it + String base64SamlToken = request.getParameter("SAMLRequest"); + if (MiscUtil.isEmpty(base64SamlToken)) { + Logger.warn("No eIDAS SAMLRequest found in http request."); + throw new MOAIDException("HTTP request includes no eIDAS SAML-Request element.", null); + } + byte[] decSamlToken = EIDASUtil.decodeSAMLToken(base64SamlToken); + + try { + //get eIDAS SAML-engine + EIDASSAMLEngine engine = SAMLEngineUtils.createSAMLEngine(); + + //validate SAML token + EIDASAuthnRequest samlReq = engine.validateEIDASAuthnRequest(decSamlToken); + + // - memorize remote ip + pendingReq.setRemoteAddress(request.getRemoteAddr()); + + // - memorize country code of target country + pendingReq.setGenericDataToSession( + Constants.eIDAS_GENERIC_REQ_DATA_COUNTRY, samlReq.getCountry()); + + // - memorize requested attributes + pendingReq.setEidasRequestedAttributes(new MOAPersonalAttributeList(samlReq.getPersonalAttributeList())); + + // - memorize whole request + samlReq.setPersonalAttributeList(pendingReq.getEidasRequestedAttributes()); // circumvent non-serializable eidas personal attribute list + pendingReq.setEidasRequest(samlReq); + + // - memorize OA url + pendingReq.setOAURL(samlReq.getIssuer()); + + // - memorize OA config + OAAuthParameter oaConfig = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(pendingReq.getOAURL()); + if (oaConfig == null) + throw new AuthenticationException("stork.12", new Object[]{pendingReq.getOAURL()}); + pendingReq.setOnlineApplicationConfiguration(oaConfig); + + } catch(Exception e) { + Logger.error("error in preprocessing step", e); + throw new MOAIDException("error in preprocessing step", null); + + } + } + + public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) throws Throwable { + return false; + } + + public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) { + return false; + } +} + + diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EidasMetaDataRequest.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EidasMetaDataRequest.java new file mode 100644 index 000000000..4e34902e2 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/EidasMetaDataRequest.java @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright 2015 e-SENS project + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be + * approved by the European Commission - subsequent versions of + * the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: http://ec.europa.eu/idabc/eupl + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + *******************************************************************************/ +package at.gv.egovernment.moa.id.protocols.eidas; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; +import at.gv.egovernment.moa.id.auth.modules.eidas.exceptions.EIDASEngineException; +import at.gv.egovernment.moa.id.auth.modules.eidas.utils.SAMLEngineUtils; +import at.gv.egovernment.moa.id.data.IAuthData; +import at.gv.egovernment.moa.id.data.SLOInformationInterface; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IRequest; +import eu.eidas.auth.engine.EIDASSAMLEngine; +import eu.eidas.auth.engine.metadata.MetadataConfigParams; +import eu.eidas.auth.engine.metadata.MetadataGenerator; +import eu.eidas.engine.exceptions.SAMLEngineException; + + +/** + * First version to provide some valid metadata to an asking eIDaS node + */ +@Service("EidasMetaDataRequest") +public class EidasMetaDataRequest implements IAction { + private Logger logger = org.slf4j.LoggerFactory.getLogger(EidasMetaDataRequest.class); + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.data.IAuthData) + */ + @Override + public SLOInformationInterface processRequest(IRequest req, + HttpServletRequest httpReq, HttpServletResponse httpResp, + IAuthData authData) throws MOAIDException { + + try { + logger.debug("EidasMetaDataServlet GET"); + + String pubURLPrefix = req.getAuthURL(); + + String metadata_url = pubURLPrefix + Constants.eIDAS_HTTP_ENDPOINT_METADATA; + + String sp_return_url = pubURLPrefix + Constants.eIDAS_HTTP_ENDPOINT_SP_POST; + String metaData = generateMetadata(metadata_url, sp_return_url); + + logger.trace(metaData); + + httpResp.setContentType(MediaType.TEXT_XML.getType()); + httpResp.getWriter().print(metaData); + httpResp.flushBuffer(); + } catch (Exception e) { + e.printStackTrace(); + } + + + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.moduls.IAction#needAuthentication(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, + HttpServletResponse httpResp) { + return false; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() + */ + @Override + public String getDefaultActionName() { + return "eIDAS-Metadata Action"; + + } + + public String generateMetadata(String metadata_url, String sp_return_url) throws SAMLEngineException, EIDASEngineException{ + String metadata="invalid metadata"; + + EIDASSAMLEngine engine = SAMLEngineUtils.createSAMLEngine(); + + MetadataGenerator generator = new MetadataGenerator(); + MetadataConfigParams mcp=new MetadataConfigParams(); + generator.setConfigParams(mcp); + generator.initialize(engine); + mcp.setEntityID(metadata_url); + + generator.addSPRole(); + String returnUrl = sp_return_url; + mcp.setAssertionConsumerUrl(returnUrl); + + generator.addIDPRole(); + mcp.setAssuranceLevel("http://eidas.europa.eu/LoA/substantial"); // TODO make configurable + + metadata = generator.generateMetadata(); + return metadata; + } +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/eIDASAuthenticationRequest.java b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/eIDASAuthenticationRequest.java new file mode 100644 index 000000000..d75d4b1b9 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/java/at/gv/egovernment/moa/id/protocols/eidas/eIDASAuthenticationRequest.java @@ -0,0 +1,185 @@ +/******************************************************************************* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + *******************************************************************************/ +package at.gv.egovernment.moa.id.protocols.eidas; + +import java.io.StringWriter; +import java.text.SimpleDateFormat; +import java.util.Map.Entry; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; +import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.eidas.Constants; +import at.gv.egovernment.moa.id.auth.modules.eidas.engine.MOAeIDASChainingMetadataProvider; +import at.gv.egovernment.moa.id.auth.modules.eidas.engine.MOAeIDASMetadataProviderDecorator; +import at.gv.egovernment.moa.id.auth.modules.eidas.utils.MOAPersonalAttributeList; +import at.gv.egovernment.moa.id.auth.modules.eidas.utils.SAMLEngineUtils; +import at.gv.egovernment.moa.id.data.IAuthData; +import at.gv.egovernment.moa.id.data.SLOInformationInterface; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.util.VelocityProvider; +import at.gv.egovernment.moa.logging.Logger; +import eu.eidas.auth.commons.EIDASAuthnResponse; +import eu.eidas.auth.commons.EIDASStatusCode; +import eu.eidas.auth.commons.EIDASUtil; +import eu.eidas.auth.commons.PersonalAttribute; +import eu.eidas.auth.engine.EIDASSAMLEngine; +import eu.eidas.auth.engine.metadata.MetadataUtil; + + +/** + * Second request step - after authentication of the user is done and moasession obtained, + * process request and forward the user further to PEPS and/or other entities + * + * @author tlenz + */ + +@Service("eIDASAuthenticationRequest") +public class eIDASAuthenticationRequest implements IAction { + + @Autowired protected MOAReversionLogger revisionsLogger; + + @Override + public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { + EIDASData eidasRequest; + if(req instanceof EIDASData) + eidasRequest = (EIDASData) req; + else + throw new MOAIDException("got wrong IRequest type. is: {}, should be: {}", new String[] {req.getClass().toString(), EIDASData.class.toString()}); + + + // gather attributes + MOAPersonalAttributeList resultingAttributeList = (MOAPersonalAttributeList) eidasRequest.getEidasRequestedAttributes().clone(); + + for(Entry<String, PersonalAttribute> current : resultingAttributeList.entrySet()) { + String newValue = ""; + + // TODO make use of proper builder + switch(current.getKey()) { + case Constants.eIDAS_ATTR_DATEOFBIRTH: newValue = new SimpleDateFormat("YYYY-MM-dd").format(authData.getDateOfBirth()); break; + case Constants.eIDAS_ATTR_CURRENTFAMILYNAME: newValue = authData.getFamilyName();break; + case Constants.eIDAS_ATTR_CURRENTGIVENNAME: newValue = authData.getGivenName();break; + case Constants.eIDAS_ATTR_PERSONALIDENTIFIER: newValue = new BPKBuilder().buildStorkeIdentifier(authData.getIdentificationType(), authData.getIdentificationValue(), + eidasRequest.getGenericData(Constants.eIDAS_GENERIC_REQ_DATA_COUNTRY, String.class)); break; + } + + if("".equals(newValue)) + current.getValue().setStatus(EIDASStatusCode.STATUS_NOT_AVAILABLE.toString()); + else { + current.getValue().getValue().clear(); + current.getValue().getValue().add(newValue); + current.getValue().setStatus(EIDASStatusCode.STATUS_AVAILABLE.toString()); + } + } + + // construct eIDaS response + EIDASAuthnResponse response = new EIDASAuthnResponse(); + response.setPersonalAttributeList(resultingAttributeList); + + // - create metadata url + String pubURLPrefix = req.getAuthURL(); + String metadata_url = pubURLPrefix + Constants.eIDAS_HTTP_ENDPOINT_METADATA; + response.setIssuer(metadata_url); + + response.setAssuranceLevel(authData.getEIDASQAALevel()); + + String token = null; + try { + EIDASSAMLEngine engine = SAMLEngineUtils.createSAMLEngine(); + + // encryption is done by the SamlEngine, i.e. by the module we provide in the config + // but we need to set the appropriate request issuer + engine.setRequestIssuer(eidasRequest.getEidasRequest().getIssuer()); + + // check if we have the destination available, supply it if not + if(null == eidasRequest.getEidasRequest().getAssertionConsumerServiceURL()) { + String assertionConsumerUrl = MetadataUtil.getAssertionUrlFromMetadata( + new MOAeIDASMetadataProviderDecorator(MOAeIDASChainingMetadataProvider.getInstance()), + engine, + eidasRequest.getEidasRequest()); + eidasRequest.getEidasRequest().setAssertionConsumerServiceURL(assertionConsumerUrl); + } + + response = engine.generateEIDASAuthnResponse(eidasRequest.getEidasRequest(), response, eidasRequest.getRemoteAddress(), true); + + + token = EIDASUtil.encodeSAMLToken(response.getTokenSaml()); + } catch(Exception e) { + e.printStackTrace(); + } + + revisionsLogger.logEvent(req, Constants.eIDAS_REVERSIONSLOG_IDP_AUTHREQUEST); + + // send the response + try { + VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); + Template template = velocityEngine.getTemplate("/resources/templates/stork2_postbinding_template.html"); + VelocityContext context = new VelocityContext(); + + context.put("SAMLResponse", token); + Logger.debug("SAMLResponse original: " + token); + + Logger.debug("Putting assertion consumer url as action: " + eidasRequest.getEidasRequest().getAssertionConsumerServiceURL()); + context.put("action", eidasRequest.getEidasRequest().getAssertionConsumerServiceURL()); + Logger.trace("Starting template merge"); + StringWriter writer = new StringWriter(); + + Logger.trace("Doing template merge"); + template.merge(context, writer); + Logger.trace("Template merge done"); + + Logger.trace("Sending html content : " + new String(writer.getBuffer())); + + httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8")); + httpResp.setContentType(MediaType.TEXT_HTML.getType()); + + } catch (Exception e) { + Logger.error("Velocity error: " + e.getMessage()); + } + + return null; + } + + @Override + public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { + return true; + } + + @Override + public String getDefaultActionName() { + return "eIDAS_AuthnRequest"; + } + + +} diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider b/id/server/modules/moa-id-module-eIDAS/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider new file mode 100644 index 000000000..cd2416a91 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider @@ -0,0 +1 @@ +at.gv.egovernment.moa.id.auth.modules.eidas.eIDASAuthenticationSpringResourceProvider
\ No newline at end of file diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/resources/at/gv/egovernment/moa/id/auth/modules/eidas/eIDAS.Authentication.process.xml b/id/server/modules/moa-id-module-eIDAS/src/main/resources/at/gv/egovernment/moa/id/auth/modules/eidas/eIDAS.Authentication.process.xml new file mode 100644 index 000000000..4ff64e76d --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/resources/at/gv/egovernment/moa/id/auth/modules/eidas/eIDAS.Authentication.process.xml @@ -0,0 +1,18 @@ +<?xml version="1.0" encoding="UTF-8"?> +<pd:ProcessDefinition id="eIDASAuthentication" xmlns:pd="http://reference.e-government.gv.at/namespace/moa/process/definition/v1"> + + + <pd:Task id="createAuthnRequest" class="GenerateAuthnRequestTask" /> + <pd:Task id="receiveAuthnResponse" class="ReceiveAuthnResponseTask" async="true" /> + <pd:Task id="finalizeAuthentication" class="FinalizeAuthenticationTask" /> + <pd:Task id="generateIdentityLink" class="CreateIdentityLinkTask" /> + + <pd:StartEvent id="start" /> + <pd:Transition from="start" to="createAuthnRequest" /> + <pd:Transition from="createAuthnRequest" to="receiveAuthnResponse" /> + <pd:Transition from="receiveAuthnResponse" to="generateIdentityLink" /> + <pd:Transition from="generateIdentityLink" to="finalizeAuthentication" /> + <pd:Transition from="finalizeAuthentication" to="end" /> + <pd:EndEvent id="end" /> + +</pd:ProcessDefinition> diff --git a/id/server/modules/module-stork/src/main/resources/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml b/id/server/modules/moa-id-module-eIDAS/src/main/resources/at/gv/egovernment/moa/id/auth/modules/eidas/eIDAS.authmodule.beans.xml index 2e924bdd0..0e1b60fe7 100644 --- a/id/server/modules/module-stork/src/main/resources/at/gv/egovernment/moa/id/auth/modules/stork/STORK.authmodule.beans.xml +++ b/id/server/modules/moa-id-module-eIDAS/src/main/resources/at/gv/egovernment/moa/id/auth/modules/eidas/eIDAS.authmodule.beans.xml @@ -1,14 +1,14 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:context="http://www.springframework.org/schema/context"
+<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd - http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
-
- <context:annotation-config />
-
- <bean id="storkAuthModule" class="at.gv.egovernment.moa.id.auth.modules.stork.STORKAuthModuleImpl">
- <property name="priority" value="0" />
- </bean>
-
-</beans>
+ http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> + + <context:annotation-config /> + + <bean id="eIDASAuthModule" class="at.gv.egovernment.moa.id.auth.modules.eidas.eIDASAuthenticationModulImpl"> + <property name="priority" value="1" /> + </bean> + +</beans> diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/resources/moaid_eidas_auth.beans.xml b/id/server/modules/moa-id-module-eIDAS/src/main/resources/moaid_eidas_auth.beans.xml new file mode 100644 index 000000000..a3f5042a1 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/resources/moaid_eidas_auth.beans.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + +<!-- Authentication Process Tasks --> + <bean id="GenerateAuthnRequestTask" + class="at.gv.egovernment.moa.id.auth.modules.eidas.tasks.GenerateAuthnRequestTask" + scope="prototype"/> + + <bean id="ReceiveAuthnResponseTask" + class="at.gv.egovernment.moa.id.auth.modules.eidas.tasks.ReceiveAuthnResponseTask" + scope="prototype"/> + + <bean id="CreateIdentityLinkTask" + class="at.gv.egovernment.moa.id.auth.modules.eidas.tasks.CreateIdentityLinkTask" + scope="prototype"/> + +</beans>
\ No newline at end of file diff --git a/id/server/modules/moa-id-module-eIDAS/src/main/resources/resources/templates/eidas_postbinding_template.vm b/id/server/modules/moa-id-module-eIDAS/src/main/resources/resources/templates/eidas_postbinding_template.vm new file mode 100644 index 000000000..3bd225b00 --- /dev/null +++ b/id/server/modules/moa-id-module-eIDAS/src/main/resources/resources/templates/eidas_postbinding_template.vm @@ -0,0 +1,41 @@ +## +## Velocity Template for SAML 2 HTTP-POST binding +## +## Velocity context may contain the following properties +## action - String - the action URL for the form +## RelayState - String - the relay state for the message +## SAMLRequest - String - the Base64 encoded SAML Request +## SAMLResponse - String - the Base64 encoded SAML Response +## Contains target attribute to delegate PEPS authentication out of iFrame + +<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> + <head> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> + </head> + + <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" target="_top"> + <div> + #if($RelayState)<input type="hidden" name="RelayState" value="${RelayState}"/>#end + + #if($SAMLRequest)<input type="hidden" name="SAMLRequest" value="${SAMLRequest}"/>#end + + #if($SAMLResponse)<input type="hidden" name="SAMLResponse" value="${SAMLResponse}"/>#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/modules/module-stork/src/main/resources/resources/xmldata/fakeIdL_IdL_template.xml b/id/server/modules/moa-id-module-eIDAS/src/main/resources/resources/xmldata/fakeIdL_IdL_template.xml index 09084a34f..09084a34f 100644 --- a/id/server/modules/module-stork/src/main/resources/resources/xmldata/fakeIdL_IdL_template.xml +++ b/id/server/modules/moa-id-module-eIDAS/src/main/resources/resources/xmldata/fakeIdL_IdL_template.xml diff --git a/id/server/modules/moa-id-module-openID/pom.xml b/id/server/modules/moa-id-module-openID/pom.xml index 080d5ae0b..030cd32a0 100644 --- a/id/server/modules/moa-id-module-openID/pom.xml +++ b/id/server/modules/moa-id-module-openID/pom.xml @@ -73,6 +73,12 @@ </exclusions> </dependency> + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + <version>19.0</version> + </dependency> + <!-- <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java index bb180d8e9..1f9d9e3a0 100644 --- a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java +++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java @@ -27,14 +27,12 @@ import java.util.List; import org.apache.commons.lang.StringUtils; -import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder; -import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.oauth20.Pair; -import at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20AuthRequest; import at.gv.egovernment.moa.id.protocols.builder.attributes.BPKAttributeBuilder; import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDAuthBlock; import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDCcsURL; @@ -46,6 +44,8 @@ import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDSectorForIDAttri import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDSignerCertificate; import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDSourcePIN; import at.gv.egovernment.moa.id.protocols.builder.attributes.EIDSourcePINType; +import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator; import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateLegalPersonFullNameAttributeBuilder; import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateLegalPersonSourcePinAttributeBuilder; import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateLegalPersonSourcePinTypeAttributeBuilder; @@ -59,13 +59,12 @@ import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateProfRepDescA import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateProfRepOIDAttributeBuilder; import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateReferenceValueAttributeBuilder; import at.gv.egovernment.moa.id.protocols.builder.attributes.MandateTypeAttributeBuilder; +import at.gv.egovernment.moa.id.protocols.oauth20.Pair; +import at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20AuthRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAttributeBuilder; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.logging.Logger; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; - public final class OAuth20AttributeBuilder { private OAuth20AttributeBuilder() { @@ -207,7 +206,7 @@ public final class OAuth20AttributeBuilder { } private static void addAttibutes(final List<IAttributeBuilder> builders, final JsonObject jsonObject, - final OAAuthParameter oaParam, final IAuthData authData, OAuth20AuthRequest oAuthRequest) { + final IOAAuthParameters oaParam, final IAuthData authData, OAuth20AuthRequest oAuthRequest) { for (IAttributeBuilder b : builders) { try { //TODO: better solution requires more refactoring :( @@ -230,33 +229,33 @@ public final class OAuth20AttributeBuilder { } public static void addScopeOpenId(final JsonObject jsonObject, - final OAAuthParameter oaParam, final IAuthData authData, + final IOAAuthParameters oaParam, final IAuthData authData, final OAuth20AuthRequest oAuthRequest) { addAttibutes(buildersOpenId, jsonObject, oaParam, authData, oAuthRequest); } public static void addScopeProfile(final JsonObject jsonObject, - final OAAuthParameter oaParam, final IAuthData authData) { + final IOAAuthParameters oaParam, final IAuthData authData) { addAttibutes(buildersProfile, jsonObject, oaParam, authData, null); } public static void addScopeEID(final JsonObject jsonObject, - final OAAuthParameter oaParam, final IAuthData authData) { + final IOAAuthParameters oaParam, final IAuthData authData) { addAttibutes(buildersEID, jsonObject, oaParam, authData, null); } public static void addScopeEIDGov(final JsonObject jsonObject, - final OAAuthParameter oaParam, final IAuthData authData) { + final IOAAuthParameters oaParam, final IAuthData authData) { addAttibutes(buildersEIDGov, jsonObject, oaParam, authData, null); } public static void addScopeMandate(final JsonObject jsonObject, - final OAAuthParameter oaParam, final IAuthData authData) { + final IOAAuthParameters oaParam, final IAuthData authData) { addAttibutes(buildersMandate, jsonObject, oaParam, authData, null); } public static void addScopeSTORK(final JsonObject jsonObject, - final OAAuthParameter oaParam, final IAuthData authData) { + final IOAAuthParameters oaParam, final IAuthData authData) { addAttibutes(buildersSTORK, jsonObject, oaParam, authData, null); } diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java index d2636c259..d08a3b4f0 100644 --- a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java +++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OpenIdNonceAttribute.java @@ -23,11 +23,10 @@ package at.gv.egovernment.moa.id.protocols.oauth20.attributes; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20AuthRequest; import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder; import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeGenerator; +import at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20AuthRequest; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.util.MiscUtil; @@ -42,7 +41,7 @@ public class OpenIdNonceAttribute implements IAttributeBuilder { return g.buildStringAttribute(this.getName(), "", null); } - public <ATT> ATT build(OAAuthParameter oaParam, IAuthData authData, OAuth20AuthRequest oAuthRequest, + public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, OAuth20AuthRequest oAuthRequest, IAttributeGenerator<ATT> g) throws AttributeException { if (MiscUtil.isNotEmpty(oAuthRequest.getNonce())) return g.buildStringAttribute(this.getName(), "", oAuthRequest.getNonce()); diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java index 88e26da76..e7594954b 100644 --- a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java +++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthAction.java @@ -30,11 +30,13 @@ import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationImpl; import at.gv.egovernment.moa.id.data.SLOInformationInterface; @@ -51,28 +53,31 @@ import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorE import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuth20SignatureUtil; import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthJsonToken; import at.gv.egovernment.moa.id.protocols.oauth20.json.OAuthSigner; -import at.gv.egovernment.moa.id.storage.AssertionStorage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; +@Service("OAuth20AuthAction") class OAuth20AuthAction implements IAction { + @Autowired protected MOAReversionLogger revisionsLogger; + @Autowired protected ITransactionStorage transactionStorage; + public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { OAuth20AuthRequest oAuthRequest = (OAuth20AuthRequest) req; String responseType = oAuthRequest.getResponseType(); - MOAReversionLogger.getInstance().logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_OPENIDCONNECT_AUTHREQUEST); + revisionsLogger.logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_OPENIDCONNECT_AUTHREQUEST); String code = Random.nextRandom(); try { String accessToken = UUID.randomUUID().toString(); - - Logger.debug("Stored session with id: " + code); + + Logger.debug("Build OAuth20SessionObject from authenticationData."); OAuth20SessionObject o = new OAuth20SessionObject(); if (responseType.equals(OAuth20Constants.RESPONSE_CODE)) { o.setScope(oAuthRequest.getScope()); @@ -86,8 +91,9 @@ class OAuth20AuthAction implements IAction { throw new OAuth20ResponseTypeException(); } - // store data in oath session - AssertionStorage.getInstance().put(code, o); + // store data in oath session + + transactionStorage.put(code, o); Logger.debug("Saved OAuth20SessionObject in session with id: " + code); @@ -113,8 +119,8 @@ class OAuth20AuthAction implements IAction { Logger.warn("An error occur during OpenID-Connect idToken generation.", e); //remove OAuthSessionObject if it already exists - if (AssertionStorage.getInstance().containsKey(code)) { - AssertionStorage.getInstance().remove(code); + if (transactionStorage.containsKey(code)) { + transactionStorage.remove(code); } if (e instanceof OAuth20Exception) { @@ -147,7 +153,7 @@ class OAuth20AuthAction implements IAction { private Pair<String, String> buildIdToken(String scope, OAuth20AuthRequest oAuthRequest, IAuthData authData) throws MOAIDException, SignatureException { - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(oAuthRequest.getOAURL()); + IOAAuthParameters oaParam = oAuthRequest.getOnlineApplicationConfiguration(); OAuthSigner signer = OAuth20SignatureUtil.loadSigner(authData.getIssuer()); OAuthJsonToken token = new OAuthJsonToken(signer); diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java index e5d8db873..055d14ef3 100644 --- a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java +++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20AuthRequest.java @@ -22,18 +22,21 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.oauth20.protocol; +import java.util.Collection; import java.util.HashMap; -import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; -import org.opensaml.saml2.core.Attribute; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util; import at.gv.egovernment.moa.id.protocols.oauth20.attributes.OAuth20AttributeBuilder; @@ -42,19 +45,24 @@ import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ResponseTypeException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; -import at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder; import at.gv.egovernment.moa.logging.Logger; +@Component("OAuth20AuthRequest") +@Scope(value = BeanDefinition.SCOPE_PROTOTYPE) public class OAuth20AuthRequest extends OAuth20BaseRequest { /** * @param req * @throws ConfigurationException */ - public OAuth20AuthRequest(HttpServletRequest req) - throws ConfigurationException { - super(req); + public OAuth20AuthRequest() { + super(); + + //AuthnRequest needs authentication + this.setNeedAuthentication(true); + + //set protocol action, which should be executed after authentication + this.setAction(OAuth20AuthAction.class.getName()); } private static final long serialVersionUID = 1L; @@ -201,43 +209,36 @@ public class OAuth20AuthRequest extends OAuth20BaseRequest { * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes() */ @Override - public List<Attribute> getRequestedAttributes() { + public Collection<String> getRequestedAttributes() { Map<String, String> reqAttr = new HashMap<String, String>(); for (String el : PVP2XProtocol.DEFAULTREQUESTEDATTRFORINTERFEDERATION) reqAttr.put(el, ""); - try { - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(getOAURL()); - - for (String s : scope.split(" ")) { - if (s.equalsIgnoreCase("profile")) { - for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuildersprofile()) - reqAttr.put(el.getName(), ""); + for (String s : scope.split(" ")) { + if (s.equalsIgnoreCase("profile")) { + for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuildersprofile()) + reqAttr.put(el.getName(), ""); - } else if (s.equalsIgnoreCase("eID")) { - for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuilderseid()) - reqAttr.put(el.getName(), ""); - - } else if (s.equalsIgnoreCase("eID_gov")) { - for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuilderseidgov()) - reqAttr.put(el.getName(), ""); - - } else if (s.equalsIgnoreCase("mandate")) { - for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuildersmandate()) - reqAttr.put(el.getName(), ""); - - } else if (s.equalsIgnoreCase("stork")) { - for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuildersstork()) - reqAttr.put(el.getName(), ""); - - } + } else if (s.equalsIgnoreCase("eID")) { + for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuilderseid()) + reqAttr.put(el.getName(), ""); + + } else if (s.equalsIgnoreCase("eID_gov")) { + for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuilderseidgov()) + reqAttr.put(el.getName(), ""); + + } else if (s.equalsIgnoreCase("mandate")) { + for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuildersmandate()) + reqAttr.put(el.getName(), ""); + + } else if (s.equalsIgnoreCase("stork")) { + for (IAttributeBuilder el :OAuth20AttributeBuilder.getBuildersstork()) + reqAttr.put(el.getName(), ""); + } - - return AttributQueryBuilder.buildSAML2AttributeList(oa, reqAttr.keySet().iterator()); - - } catch (ConfigurationException e) { - Logger.error("Load configuration for OA " + getOAURL() + " FAILED", e); - return null; } + + //return attributQueryBuilder.buildSAML2AttributeList(this.getOnlineApplicationConfiguration(), reqAttr.keySet().iterator()); + return reqAttr.keySet(); } } diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java index 5fcac0b2f..4eae5ac3b 100644 --- a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java +++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20BaseRequest.java @@ -38,7 +38,6 @@ import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; -import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidRequestException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20OANotSupportedException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; @@ -49,11 +48,7 @@ abstract class OAuth20BaseRequest extends RequestImpl { private static final long serialVersionUID = 1L; protected Set<String> allowedParameters = new HashSet<String>(); - - public OAuth20BaseRequest(HttpServletRequest req) throws ConfigurationException { - super(req); - } - + protected String getParam(final HttpServletRequest request, final String name, final boolean isNeeded) throws OAuth20Exception { String param = request.getParameter(name); Logger.debug("Reading param " + name + " from HttpServletRequest with value " + param); @@ -81,7 +76,6 @@ abstract class OAuth20BaseRequest extends RequestImpl { if (oaParam == null) { throw new OAuth20WrongParameterException(OAuth20Constants.PARAM_CLIENT_ID); } - this.setTarget(oaParam.getTarget()); if (StringUtils.isEmpty(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTSECRET)) || StringUtils.isEmpty(oaParam.getConfigurationValue(MOAIDConfigurationConstants.SERVICE_PROTOCOLS_OPENID_CLIENTID)) @@ -120,29 +114,4 @@ abstract class OAuth20BaseRequest extends RequestImpl { protected abstract void populateSpecialParameters(final HttpServletRequest request) throws OAuth20Exception; - public static OAuth20BaseRequest newInstance(final String action, final HttpServletRequest request, String sessionId, String transactionId) throws OAuth20Exception { - OAuth20BaseRequest res; - try { - if (action.equals(OAuth20Protocol.AUTH_ACTION)) { - res = new OAuth20AuthRequest(request); - - } else if (action.equals(OAuth20Protocol.TOKEN_ACTION)) { - res = new OAuth20TokenRequest(request); - - } else { - throw new OAuth20InvalidRequestException(); - } - - } catch (ConfigurationException e) { - Logger.warn(e.getMessage()); - throw new OAuth20InvalidRequestException(); - - } - - res.setAction(action); - res.setModule(OAuth20Protocol.NAME); - - res.populateParameters(request); - return res; - } } diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java index 70c29359e..b29d33a8d 100644 --- a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java +++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20Protocol.java @@ -1,6 +1,8 @@ package at.gv.egovernment.moa.id.protocols.oauth20.protocol; +import java.io.IOException; import java.net.URLEncoder; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -9,12 +11,19 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.google.gson.JsonObject; +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IModulInfo; +import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Constants; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20Exception; @@ -23,11 +32,8 @@ import at.gv.egovernment.moa.id.util.ErrorResponseUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -import com.google.gson.JsonObject; - -import java.util.Arrays; - -public class OAuth20Protocol implements IModulInfo { +@Controller +public class OAuth20Protocol extends AbstractAuthProtocolModulController { public static final String NAME = OAuth20Protocol.class.getName(); public static final String PATH = "id_oauth20"; @@ -40,14 +46,7 @@ public class OAuth20Protocol implements IModulInfo { PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, PVPConstants.BPK_NAME }); - - private static HashMap<String, IAction> actions = new HashMap<String, IAction>(); - - static { - actions.put(AUTH_ACTION, new OAuth20AuthAction()); - actions.put(TOKEN_ACTION, new OAuth20TokenAction()); - } - + public String getName() { return NAME; } @@ -56,42 +55,83 @@ public class OAuth20Protocol implements IModulInfo { return PATH; } - public IAction getAction(String action) { - return actions.get(action); - } - - /* - * (non-Javadoc) - * @see - * at.gv.egovernment.moa.id.moduls.IModulInfo#preProcess(javax.servlet.http.HttpServletRequest, - * javax.servlet.http.HttpServletResponse, java.lang.String) + /** + * */ - public IRequest preProcess(HttpServletRequest request, HttpServletResponse resp, String action, - String sessionId, String transactionId) throws MOAIDException { - // validation is done inside creation - OAuth20BaseRequest res = OAuth20BaseRequest.newInstance(action, request, sessionId, transactionId); - Logger.debug("Created: " + res); - return res; + public OAuth20Protocol() { + super(); + Logger.debug("Registering servlet " + getClass().getName() + + " with mappings '/oauth2/auth' and '/oauth2/token'."); } - /* - * (non-Javadoc) - * @see - * at.gv.egovernment.moa.id.moduls.IModulInfo#canHandleRequest(javax.servlet.http.HttpServletRequest - * , javax.servlet.http.HttpServletResponse) - */ - public IAction canHandleRequest(HttpServletRequest request, HttpServletResponse response) { - if (!StringUtils.isEmpty(request.getParameter("action"))) { - if (request.getParameter("action").equals(AUTH_ACTION)) { - return getAction(AUTH_ACTION); - } else if (request.getParameter("action").equals(TOKEN_ACTION)) { - return getAction(TOKEN_ACTION); - } + //OpenID Connect auth request + @RequestMapping(value = "/oauth2/auth", method = {RequestMethod.POST, RequestMethod.GET}) + public void openIDConnectAuthRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException, IOException { + if (!authConfig.getAllowedProtocols().isOAUTHActive()) { + Logger.info("OpenID-Connect is deaktivated!"); + throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }); + + } + + OAuth20AuthRequest pendingReq = applicationContext.getBean(OAuth20AuthRequest.class); + try { + pendingReq.initialize(req); + pendingReq.setModule(OAuth20Protocol.NAME); + pendingReq.populateParameters(req); + + } catch (OAuth20Exception e) { + Logger.info("OpenID-Connect request has a validation error: " + e.getMessage()); + throw new InvalidProtocolRequestException(e.getMessage(), null); + } - return null;// getAction(AUTH_ACTION); + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); + revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_CREATED, pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent( + pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), + MOAIDEventConstants.TRANSACTION_IP, + req.getRemoteAddr()); + + //process request + performAuthentication(req, resp, (RequestImpl)pendingReq); + } + //openID Connect tokken request + @RequestMapping(value = "/oauth2/token", method = {RequestMethod.POST, RequestMethod.GET}) + public void OpenIDConnectTokkenRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException, IOException { + if (!authConfig.getAllowedProtocols().isOAUTHActive()) { + Logger.info("OpenID-Connect is deaktivated!"); + throw new ProtocolNotActiveException("auth.22", new java.lang.Object[] { NAME }); + + } + + OAuth20TokenRequest pendingReq = applicationContext.getBean(OAuth20TokenRequest.class); + try { + pendingReq.initialize(req); + pendingReq.setModule(OAuth20Protocol.NAME); + pendingReq.populateParameters(req); + + } catch (OAuth20Exception e) { + Logger.info("OpenID-Connect request has a validation error: " + e.getMessage()); + throw new InvalidProtocolRequestException(e.getMessage(), null); + + } + + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); + revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_CREATED, pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent( + pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), + MOAIDEventConstants.TRANSACTION_IP, + req.getRemoteAddr()); + + //process request + performAuthentication(req, resp, (RequestImpl)pendingReq); + + } + /* * (non-Javadoc) * @see at.gv.egovernment.moa.id.moduls.IModulInfo#generateErrorMessage(java.lang.Throwable, diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java index 2238a25e1..bb0126a7b 100644 --- a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java +++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenAction.java @@ -26,6 +26,11 @@ package at.gv.egovernment.moa.id.protocols.oauth20.protocol; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import com.google.gson.JsonObject; + import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -38,13 +43,15 @@ import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20Util; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20ServerErrorException; import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20UnauthorizedClientException; -import at.gv.egovernment.moa.id.storage.AssertionStorage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.logging.Logger; -import com.google.gson.JsonObject; - +@Service("OAuth20TokenAction") class OAuth20TokenAction implements IAction { + @Autowired protected MOAReversionLogger revisionsLogger; + @Autowired protected ITransactionStorage transactionStorage; + public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { @@ -53,13 +60,13 @@ class OAuth20TokenAction implements IAction { try { OAuth20TokenRequest oAuthRequest = (OAuth20TokenRequest) req; - MOAReversionLogger.getInstance().logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_OPENIDCONNECT_TOKENREQUEST); + revisionsLogger.logEvent(req, MOAIDEventConstants.AUTHPROTOCOL_OPENIDCONNECT_TOKENREQUEST); try { Logger.debug("Loaded OAuth20SessionObject from session: " + oAuthRequest.getCode()); auth20SessionObject = - AssertionStorage.getInstance().get(oAuthRequest.getCode(), OAuth20SessionObject.class); + transactionStorage.get(oAuthRequest.getCode(), OAuth20SessionObject.class); } catch (MOADatabaseException e) { throw new OAuth20UnauthorizedClientException(); @@ -97,7 +104,7 @@ class OAuth20TokenAction implements IAction { // destroy session for clean up Logger.debug("Going to destroy session: " + auth20SessionObject.getCode()); - AssertionStorage.getInstance().remove(auth20SessionObject.getCode()); + transactionStorage.remove(auth20SessionObject.getCode()); } } diff --git a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java index abfe4ce15..75fbb4120 100644 --- a/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java +++ b/id/server/modules/moa-id-module-openID/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/protocol/OAuth20TokenRequest.java @@ -22,11 +22,13 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.oauth20.protocol; -import java.util.List; +import java.util.Collection; import javax.servlet.http.HttpServletRequest; -import org.opensaml.saml2.core.Attribute; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; import at.gv.egovernment.moa.id.commons.config.MOAIDConfigurationConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; @@ -39,15 +41,21 @@ import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20InvalidGrant import at.gv.egovernment.moa.id.protocols.oauth20.exceptions.OAuth20WrongParameterException; import at.gv.egovernment.moa.logging.Logger; +@Component("OAuth20TokenRequest") +@Scope(value = BeanDefinition.SCOPE_PROTOTYPE) class OAuth20TokenRequest extends OAuth20BaseRequest { /** * @param req * @throws ConfigurationException */ - public OAuth20TokenRequest(HttpServletRequest req) - throws ConfigurationException { - super(req); + public OAuth20TokenRequest() { + super(); + //AuthnRequest needs authentication + this.setNeedAuthentication(false); + + //set protocol action, which should be executed after authentication + this.setAction(OAuth20TokenAction.class.getName()); } private static final long serialVersionUID = 1L; @@ -160,7 +168,7 @@ class OAuth20TokenRequest extends OAuth20BaseRequest { * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes() */ @Override - public List<Attribute> getRequestedAttributes() { + public Collection<String> getRequestedAttributes() { return null; } } diff --git a/id/server/modules/moa-id-module-openID/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo b/id/server/modules/moa-id-module-openID/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo deleted file mode 100644 index b653c91c3..000000000 --- a/id/server/modules/moa-id-module-openID/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo +++ /dev/null @@ -1 +0,0 @@ -at.gv.egovernment.moa.id.protocols.oauth20.protocol.OAuth20Protocol
\ No newline at end of file diff --git a/id/server/modules/moa-id-module-pvp2/.gitignore b/id/server/modules/moa-id-module-pvp2/.gitignore new file mode 100644 index 000000000..b83d22266 --- /dev/null +++ b/id/server/modules/moa-id-module-pvp2/.gitignore @@ -0,0 +1 @@ +/target/ diff --git a/id/server/modules/moa-id-module-pvp2/pom.xml b/id/server/modules/moa-id-module-pvp2/pom.xml new file mode 100644 index 000000000..0a71e27ce --- /dev/null +++ b/id/server/modules/moa-id-module-pvp2/pom.xml @@ -0,0 +1,11 @@ +<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.server.modules</groupId> + <artifactId>moa-id-modules</artifactId> + <version>${moa-id-version}</version> + </parent> + <artifactId>moa-id-module-pvp2</artifactId> + <name>PVP2 Module</name> + <description>PVP2.x authentication modul for MOA-ID-Auth</description> +</project>
\ No newline at end of file diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferAuthenticationData.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferAuthenticationData.java index a93412b11..b9ab4f307 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferAuthenticationData.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferAuthenticationData.java @@ -28,10 +28,11 @@ import java.util.List; import org.w3c.dom.Element; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAuthnRequest; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.IdentityLink; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.data.AuthenticationRole; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.MISMandate; @@ -44,9 +45,12 @@ import at.gv.egovernment.moa.logging.Logger; public class SSOTransferAuthenticationData implements IAuthData { private AuthenticationSession authSession = null; + boolean isIDPPrivateService = true; - public SSOTransferAuthenticationData(AuthenticationSession authSession) { + public SSOTransferAuthenticationData(AuthConfiguration authConfig, AuthenticationSession authSession) throws ConfigurationException { this.authSession = authSession; + String domainIdentifier = authConfig.getSSOTagetIdentifier().trim(); + isIDPPrivateService = domainIdentifier.startsWith(MOAIDAuthConstants.PREFIX_WPBK); } @@ -74,7 +78,7 @@ public class SSOTransferAuthenticationData implements IAuthData { */ @Override public boolean isBusinessService() { - return this.authSession.getBusinessService(); + return this.isIDPPrivateService; } /* (non-Javadoc) @@ -358,28 +362,20 @@ public class SSOTransferAuthenticationData implements IAuthData { } /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.IAuthData#getStorkAuthnRequest() + * @see at.gv.egovernment.moa.id.data.IAuthData#getEIDASQAALevel() */ @Override - public STORKAuthnRequest getStorkAuthnRequest() { + public String getEIDASQAALevel() { // TODO Auto-generated method stub return null; } - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.IAuthData#getStorkAuthnResponse() - */ - @Override - public String getStorkAuthnResponse() { - // TODO Auto-generated method stub - return null; - } /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.data.IAuthData#getStorkAttributes() + * @see at.gv.egovernment.moa.id.data.IAuthData#getGenericData(java.lang.String, java.lang.Class) */ @Override - public IPersonalAttributeList getStorkAttributes() { + public <T> T getGenericData(String key, Class<T> clazz) { // TODO Auto-generated method stub return null; } diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferOnlineApplication.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferOnlineApplication.java index 9b5005a61..4ba2e1a01 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferOnlineApplication.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/data/SSOTransferOnlineApplication.java @@ -441,4 +441,13 @@ public class SSOTransferOnlineApplication implements IOAAuthParameters { return null; } + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.config.auth.IOAAuthParameters#isRemovePBKFromAuthBlock() + */ + @Override + public boolean isRemovePBKFromAuthBlock() { + // TODO Auto-generated method stub + return false; + } + } diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferServlet.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferServlet.java new file mode 100644 index 000000000..d33b157e0 --- /dev/null +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferServlet.java @@ -0,0 +1,201 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.ssotransfer.servlet; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.velocity.VelocityContext; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.google.gson.JsonObject; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.ssotransfer.SSOTransferConstants; +import at.gv.egovernment.moa.id.auth.modules.ssotransfer.utils.GUIUtils; +import at.gv.egovernment.moa.id.auth.modules.ssotransfer.utils.SSOContainerUtils; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; +import at.gv.egovernment.moa.id.moduls.SSOManager; +import at.gv.egovernment.moa.id.storage.IAuthenticationSessionStoreage; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; +import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.Base64Utils; +import at.gv.egovernment.moa.util.MiscUtil; +import net.glxn.qrgen.QRCode; +import net.glxn.qrgen.image.ImageType; + + + +/** + * @author tlenz + * + */ +//@WebServlet(name = "SSOTransferGUI", value = "/TransferSSOSession") +@Controller +public class SSOTransferServlet{ + + private static final long transmisionTimeOut = 90 * 1000; // default 90 secundes + + @Autowired SSOManager ssomanager; + @Autowired IAuthenticationSessionStoreage authenticationSessionStorage; + @Autowired SSOContainerUtils ssoTransferUtils; + @Autowired ITransactionStorage transactionStorage; + + public SSOTransferServlet() { + super(); + Logger.debug("Registering servlet " + getClass().getName() + + " with mapping {'/TransferSSOSession','/TransmitSSOSession'}."); + } + + @RequestMapping(value = { "/TransmitSSOSession" + }, + method = {RequestMethod.GET}) + public void transferToPhone(HttpServletRequest req, HttpServletResponse resp) throws IOException { + Object tokenObj = req.getParameter(SSOTransferConstants.REQ_PARAM_TOKEN); + if (tokenObj != null && tokenObj instanceof String) { + String token = (String)tokenObj; + try { + String signedEncSession = transactionStorage.get(token, String.class, transmisionTimeOut); + if (MiscUtil.isNotEmpty(signedEncSession)) { + resp.setContentType("text/html;charset=UTF-8"); + PrintWriter out = new PrintWriter(resp.getOutputStream()); + out.print(signedEncSession); + out.flush(); + + } else { + Logger.info("Servlet " + getClass().getName() + " receive a token:" + + token + ", which references an empty data object."); + resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Empty data object."); + + } + + } catch (MOADatabaseException e) { + Logger.info("Servlet " + getClass().getName() + " receive a token:" + + token + ", which is UNKNOWN."); + resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Transfer token is UNKOWN:"); + + + } catch (AuthenticationException e) { + Logger.info("Servlet " + getClass().getName() + " receive a token:" + + token + ", which has a timeout."); + resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Single Sign-On session transfer token is not valid any more."); + + } + + } else { + Logger.info("Servlet " + getClass().getName() + " receive a NOT valid request."); + resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Request not valid."); + + } + + + } + + + @RequestMapping(value = { "/TransferSSOSession" + }, + method = {RequestMethod.GET}) + public void transferSSOSessionGUI(HttpServletRequest req, HttpServletResponse resp) throws IOException { + //search SSO session + String ssoid = ssomanager.getSSOSessionID(req); + + VelocityContext context = new VelocityContext(); + + try { + if (ssomanager.isValidSSOSession(ssoid, null)) { + Object createQRObj = req.getParameter(SSOTransferConstants.REQ_PARAM_GENERATE_QR); + if (createQRObj != null && createQRObj instanceof Integer) { + + + + } else { + //create first step of SSO Transfer GUI + String authURL = HTTPUtils.extractAuthURLFromRequest(req); + if (!AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(). + contains(authURL)) { + Logger.warn("Requested URL is not allowed.");; + resp.sendError(500, "Requested URL is not allowed."); + + } + + String moaSessionID = authenticationSessionStorage.getMOASessionSSOID(ssoid); + if (MiscUtil.isNotEmpty(moaSessionID)) { + AuthenticationSession authSession = authenticationSessionStorage.getSession(moaSessionID); + if(authSession != null) { + Date now = new Date(); + String encodedSSOContainer = ssoTransferUtils.generateSignedAndEncryptedSSOContainer(authURL, authSession, now); + + String token = Random.nextRandom(); + transactionStorage.put(token, encodedSSOContainer); + + String containerURL = authURL + + SSOTransferConstants.SERVLET_SSOTRANSFER_TO_SMARTPHONE + + "?"+ SSOTransferConstants.REQ_PARAM_TOKEN + "=" + token; + + JsonObject qrResult = new JsonObject(); + qrResult.addProperty(SSOTransferConstants.SSOCONTAINER_KEY_TYPE, + SSOTransferConstants.SSOCONTAINER_VALUE_TYPE_PERSIST); + qrResult.addProperty(SSOTransferConstants.SSOCONTAINER_KEY_URL, containerURL); + + ByteArrayOutputStream qrStream = + QRCode.from(qrResult.toString()).to(ImageType.GIF).withSize(300, 300).stream(); + String base64EncodedImage = Base64Utils.encode(qrStream.toByteArray()); + context.put("QRImage", base64EncodedImage); + + context.put("successMsg", "Scan the QR-Code with your <i>SSO-Transfer App</i> to start the transfer operation."); + + GUIUtils.printSSOTransferGUI(context, resp); + + } + } + } + + } else { + context.put("errorMsg", + "No active Single Sign-On session found! SSO Session transfer is not possible."); + GUIUtils.printSSOTransferGUI(context, resp); + } + + } catch (MOAIDException | MOADatabaseException e) { + e.printStackTrace(); + resp.sendError(500, e.getMessage()); + + } + + } + + +} diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferSignalServlet.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferSignalServlet.java index b82417ae6..b53916338 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferSignalServlet.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/servlet/SSOTransferSignalServlet.java @@ -24,37 +24,33 @@ package at.gv.egovernment.moa.id.auth.modules.ssotransfer.servlet; import java.io.IOException; -import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import at.gv.egovernment.moa.id.auth.servlet.ProcessEngineSignalServlet; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.gv.egovernment.moa.id.auth.servlet.AbstractProcessEngineSignalController; import at.gv.egovernment.moa.logging.Logger; /** * @author tlenz * */ -@WebServlet(urlPatterns = { "/SSOTransferSignalEndpoint" }, loadOnStartup = 1) -public class SSOTransferSignalServlet extends ProcessEngineSignalServlet { - - private static final long serialVersionUID = 8372275858647807149L; - +@Controller +public class SSOTransferSignalServlet extends AbstractProcessEngineSignalController { public SSOTransferSignalServlet() { super(); Logger.debug("Registering servlet " + getClass().getName() + " with mappings '/SSOTransferEndpoint'."); } - protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - Logger.debug("Receive http-POST request."); - super.doPost(req, resp); - - } - - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - Logger.debug("Receive http-GET request."); - super.doPost(req, resp); + @RequestMapping(value = { "/SSOTransferSignalEndpoint" + }, + method = {RequestMethod.POST, RequestMethod.GET}) + public void performSSOTransfer(HttpServletRequest req, HttpServletResponse resp) throws IOException { + signalProcessManagement(req, resp); + } } diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/task/InitializeRestoreSSOSessionTask.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/task/InitializeRestoreSSOSessionTask.java index 67566afe5..e84c60ec5 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/task/InitializeRestoreSSOSessionTask.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/task/InitializeRestoreSSOSessionTask.java @@ -22,32 +22,27 @@ */ package at.gv.egovernment.moa.id.auth.modules.ssotransfer.task; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; - import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; +import org.springframework.stereotype.Component; -import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.auth.modules.ssotransfer.utils.GUIUtils; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; /** * @author tlenz * */ +@Component("InitializeRestoreSSOSessionTask") public class InitializeRestoreSSOSessionTask extends AbstractAuthServletTask { /* (non-Javadoc) @@ -67,27 +62,17 @@ public class InitializeRestoreSSOSessionTask extends AbstractAuthServletTask { response.sendError(500, "Requested URL is not allowed."); } - - String sessionID = (String) executionContext.get(PARAM_SESSIONID); - String pendingRequestID = (String) executionContext.get("pendingRequestID"); - - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("CreateStorkAuthRequestFormTask", PARAM_SESSIONID, "auth.12"); - } - AuthenticationSession moasession = BaseAuthenticationServer.getSession(sessionID); - IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID); - - VelocityContext context = GUIUtils.buildSSOTransferGUI(authURL, moasession); + + VelocityContext context = GUIUtils.buildSSOTransferGUI(authURL, pendingReq.getRequestID()); GUIUtils.printSSOTransferGUI(context, response); } catch (WrongParametersException | AuthenticationException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } catch (Exception e) { Logger.error(this.getClass().getName() + " has an interal Error.", e); - throw new TaskExecutionException(this.getClass().getName() + " has an interal Error.", e); + throw new TaskExecutionException(pendingReq, this.getClass().getName() + " has an interal Error.", e); } diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/task/RestoreSSOSessionTask.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/task/RestoreSSOSessionTask.java index 006b27167..6ba29fe3a 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/task/RestoreSSOSessionTask.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/task/RestoreSSOSessionTask.java @@ -22,8 +22,6 @@ */ package at.gv.egovernment.moa.id.auth.modules.ssotransfer.task; -import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID; - import java.io.BufferedReader; import java.io.IOException; @@ -34,15 +32,13 @@ import org.apache.commons.lang3.BooleanUtils; import org.apache.velocity.VelocityContext; import org.joda.time.DateTime; import org.opensaml.saml2.core.Response; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; import at.gv.egovernment.moa.id.auth.modules.ssotransfer.SSOTransferConstants; @@ -50,13 +46,9 @@ import at.gv.egovernment.moa.id.auth.modules.ssotransfer.utils.GUIUtils; import at.gv.egovernment.moa.id.auth.modules.ssotransfer.utils.SSOContainerUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.process.api.ExecutionContext; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; -import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; @@ -64,8 +56,11 @@ import at.gv.egovernment.moa.util.MiscUtil; * @author tlenz * */ +@Component("RestoreSSOSessionTask") public class RestoreSSOSessionTask extends AbstractAuthServletTask { + @Autowired SSOContainerUtils ssoTransferUtils; + /* (non-Javadoc) * @see at.gv.egovernment.moa.id.process.springweb.MoaIdTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @@ -78,21 +73,8 @@ public class RestoreSSOSessionTask extends AbstractAuthServletTask { StringBuffer sb = new StringBuffer(); String receivedPostMessage = null; - AuthenticationSession moasession = null; - IRequest pendingReq = null; String authURL =null; - try { - String sessionID = (String) request.getParameter(PARAM_SESSIONID); - String pendingRequestID = (String) executionContext.get("pendingRequestID"); - - // check parameter - if (!ParamValidatorUtils.isValidSessionID(sessionID)) { - throw new WrongParametersException("RestoreSSOSessionTask", PARAM_SESSIONID, "auth.12"); - - } - moasession = BaseAuthenticationServer.getSession(sessionID); - pendingReq = RequestStorage.getPendingRequest(pendingRequestID); - + try { BufferedReader reader = request.getReader(); String line = null; while ((line = reader.readLine()) != null) { @@ -104,11 +86,19 @@ public class RestoreSSOSessionTask extends AbstractAuthServletTask { } catch (IOException e) { Logger.warn("Received POST-message produce an ERROR.", e); - } catch (WrongParametersException | AuthenticationException e) { - throw new TaskExecutionException(e.getMessage(), e); - } + //session is valid --> load MOASession object + try { + defaultTaskInitialization(request, executionContext); + + } catch (MOAIDException | MOADatabaseException e1) { + Logger.error("Database Error! MOASession is not stored!"); + throw new TaskExecutionException(pendingReq, "Load MOASession FAILED.", e1); + + } + + if (MiscUtil.isNotEmpty(receivedPostMessage)) { Logger.debug("Receive POST-Message data. Start data-validation process ... "); try { @@ -125,12 +115,14 @@ public class RestoreSSOSessionTask extends AbstractAuthServletTask { if (PVPConfiguration.getInstance().getIDPPublicPath().contains(entityID)) { // stored SSO session data is from this IDP - start local session reconstruction - Response ssoInformation = SSOContainerUtils.validateReceivedSSOContainer(sessionBlob); - SSOContainerUtils.parseSSOContainerToMOASessionDataObject(pendingReq, moasession, ssoInformation); + Response ssoInformation = ssoTransferUtils.validateReceivedSSOContainer(sessionBlob); + + //transfer SSO Assertion into MOA-Session + ssoTransferUtils.parseSSOContainerToMOASessionDataObject(pendingReq, moasession, ssoInformation); // store MOASession into database try { - AuthenticationSessionStoreage.storeSession(moasession); + authenticatedSessionStorage.storeSession(moasession); } catch (MOADatabaseException e) { Logger.error("Database Error! MOASession is not stored!"); @@ -151,7 +143,7 @@ public class RestoreSSOSessionTask extends AbstractAuthServletTask { } catch (Exception e) { Logger.error("Parse reveived JSON data-object " + sb.toString() + " FAILED!", e); - throw new TaskExecutionException("JSON data is not parseable.", e); + throw new TaskExecutionException(pendingReq, "JSON data is not parseable.", e); } @@ -170,7 +162,7 @@ public class RestoreSSOSessionTask extends AbstractAuthServletTask { DateTime moaSessionCreated = new DateTime(moasession.getSessionCreated().getTime()); if (moaSessionCreated.plusMinutes(3).isBeforeNow()) { Logger.warn("No SSO session-container received. Stop authentication process after time-out."); - throw new TaskExecutionException("No SSO container received from smartphone app.", null); + throw new TaskExecutionException(pendingReq, "No SSO container received from smartphone app.", null); } else { Logger.debug("No restored SSO session found --> Wait a few minutes and check again."); @@ -187,11 +179,11 @@ public class RestoreSSOSessionTask extends AbstractAuthServletTask { } - context = GUIUtils.buildSSOTransferGUI(authURL, moasession); + context = GUIUtils.buildSSOTransferGUI(authURL, pendingReq.getRequestID()); GUIUtils.printSSOTransferGUI(context, response); } catch (IOException | MOAIDException e) { - throw new TaskExecutionException(e.getMessage(), e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); } diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/GUIUtils.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/GUIUtils.java index 310b8a813..ee7a397aa 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/GUIUtils.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/GUIUtils.java @@ -40,7 +40,6 @@ import org.apache.velocity.app.VelocityEngine; import com.google.gson.JsonObject; import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.modules.ssotransfer.SSOTransferConstants; import at.gv.egovernment.moa.id.config.ConfigurationException; @@ -61,11 +60,10 @@ public class GUIUtils { public static final int REFESH_TIMEOUT = 5 * 1000; //5 sec - public static VelocityContext buildSSOTransferGUI(String authURL, AuthenticationSession moasession) throws ConfigurationException, IOException { - String token = moasession.getSessionID(); + public static VelocityContext buildSSOTransferGUI(String authURL, String pendingReqID) throws ConfigurationException, IOException { String containerURL = authURL + SSOTransferConstants.SERVLET_SSOTRANSFER_FROM_SMARTPHONE - + "?" + MOAIDAuthConstants.PARAM_SESSIONID + "=" + token; + + "?" + MOAIDAuthConstants.PARAM_TARGET_PENDINGREQUESTID + "=" + pendingReqID; JsonObject qrResult = new JsonObject(); qrResult.addProperty(SSOTransferConstants.SSOCONTAINER_KEY_TYPE, diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/SSOContainerUtils.java b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/SSOContainerUtils.java index 861dcbf58..7c8a86f73 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/SSOContainerUtils.java +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/java/at/gv/egovernment/moa/id/auth/modules/ssotransfer/utils/SSOContainerUtils.java @@ -79,6 +79,8 @@ import org.opensaml.xml.signature.SignatureException; import org.opensaml.xml.signature.SignatureValidator; import org.opensaml.xml.signature.Signer; import org.opensaml.xml.validation.ValidationException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; @@ -93,6 +95,7 @@ import at.gv.egovernment.moa.id.auth.modules.ssotransfer.data.SSOTransferAuthent import at.gv.egovernment.moa.id.auth.modules.ssotransfer.data.SSOTransferOnlineApplication; import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; @@ -104,8 +107,9 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion.PVP2AssertionB import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionAttributeExtractorExeption; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoCredentialsException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.SAMLRequestNotSignedException; -import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.IDPCredentialProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.AssertionAttributeExtractor; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; @@ -119,9 +123,9 @@ import iaik.x509.X509Certificate; * @author tlenz * */ +@Service("SSOContainerUtils") public class SSOContainerUtils { public static final List<String> REQUIRED_ATTRIBUTES; - static { List<String> tmp = new ArrayList<String>(); tmp.add(PVPConstants.EID_AUTH_BLOCK_NAME); @@ -140,15 +144,13 @@ public class SSOContainerUtils { REQUIRED_ATTRIBUTES = Collections.unmodifiableList(tmp); } - public static void parseSSOContainerToMOASessionDataObject(IRequest pendingReq, AuthenticationSession moasession, Response ssoInformation) throws AssertionAttributeExtractorExeption, ConfigurationException { + @Autowired IDPCredentialProvider credentials; + @Autowired SAMLVerificationEngine samlVerificationEngine; + @Autowired AuthConfiguration authConfig; + + public void parseSSOContainerToMOASessionDataObject(IRequest pendingReq, AuthenticationSession moasession, Response ssoInformation) throws AssertionAttributeExtractorExeption, ConfigurationException { AssertionAttributeExtractor attributeExtractor = new AssertionAttributeExtractor(ssoInformation); - String authServiceURL = pendingReq.getAuthURL(); - if (authServiceURL.endsWith("/")) - moasession.setAuthURL(authServiceURL); - else - moasession.setAuthURL(authServiceURL + "/"); - //TODO: maybe change to correct URL //set dummy BKU URLx moasession.setBkuURL("http://egiz.gv.at/sso_session-transfer_app"); @@ -248,7 +250,7 @@ public class SSOContainerUtils { } - public static Response validateReceivedSSOContainer(String signedEncryptedContainer) throws IOException, XMLParserException, UnmarshallingException, MOAIDException { + public Response validateReceivedSSOContainer(String signedEncryptedContainer) throws IOException, XMLParserException, UnmarshallingException, MOAIDException { byte[] base64decodedContainer = Base64Utils.decode(signedEncryptedContainer, false); final BasicParserPool ppMgr = new BasicParserPool(); @@ -276,7 +278,7 @@ public class SSOContainerUtils { throw new SAMLRequestNotSignedException(e); } - Credential credential = CredentialProvider.getIDPAssertionSigningCredential(); + Credential credential = credentials.getIDPAssertionSigningCredential(); if (credential == null) { throw new NoCredentialsException("moaID IDP"); } @@ -293,7 +295,7 @@ public class SSOContainerUtils { if (ssoContainer.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { //validate PVP 2.1 assertion - SAMLVerificationEngine.validateAssertion(ssoContainer, false); + samlVerificationEngine.validateAssertion(ssoContainer, false, credentials.getIDPAssertionEncryptionCredential()); return ssoContainer; } else { @@ -311,7 +313,7 @@ public class SSOContainerUtils { } - public static String generateSignedAndEncryptedSSOContainer(String authURL, + public String generateSignedAndEncryptedSSOContainer(String authURL, AuthenticationSession authSession, Date date) { try { String entityID = authURL; @@ -342,7 +344,7 @@ public class SSOContainerUtils { String sessionIndex = SAML2Utils.getSecureIdentifier(); - IAuthData authData = new SSOTransferAuthenticationData(authSession); + IAuthData authData = new SSOTransferAuthenticationData(authConfig, authSession); Assertion assertion = PVP2AssertionBuilder.buildGenericAssertion( authURL, @@ -376,7 +378,7 @@ public class SSOContainerUtils { return null; } - private static String buildSSOContainerObject(String authURL, Assertion assertion, DateTime date) throws ConfigurationException, EncryptionException, CredentialsNotAvailableException, SecurityException, ParserConfigurationException, MarshallingException, SignatureException, TransformerFactoryConfigurationError, TransformerException, IOException { + private String buildSSOContainerObject(String authURL, Assertion assertion, DateTime date) throws ConfigurationException, EncryptionException, CredentialsNotAvailableException, SecurityException, ParserConfigurationException, MarshallingException, SignatureException, TransformerFactoryConfigurationError, TransformerException, IOException { Response authResponse = SAML2Utils.createSAMLObject(Response.class); Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); @@ -396,7 +398,7 @@ public class SSOContainerUtils { authResponse.setStatus(SAML2Utils.getSuccessStatus()); //encrypt container - X509Credential encryptionCredentials = CredentialProvider.getIDPAssertionEncryptionCredential(); + X509Credential encryptionCredentials = credentials.getIDPAssertionEncryptionCredential(); EncryptionParameters dataEncParams = new EncryptionParameters(); dataEncParams.setAlgorithm(PVPConstants.DEFAULT_SYM_ENCRYPTION_METHODE); @@ -422,9 +424,9 @@ public class SSOContainerUtils { //sign container - Credential signingCredential = CredentialProvider.getIDPAssertionSigningCredential(); - Signature signature = CredentialProvider - .getIDPSignature(signingCredential); + Credential signingCredential = credentials.getIDPAssertionSigningCredential(); + Signature signature = AbstractCredentialProvider.getIDPSignature(signingCredential); + SecurityHelper.prepareSignatureParams(signature, signingCredential, null, null); authResponse.setSignature(signature); diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/resources/at/gv/egovernment/moa/id/auth/modules/ssotransfer/SSOTransfer.authmodule.beans.xml b/id/server/modules/moa-id-module-ssoTransfer/src/main/resources/at/gv/egovernment/moa/id/auth/modules/ssotransfer/SSOTransfer.authmodule.beans.xml index 1a8709e15..349b3afb0 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/resources/at/gv/egovernment/moa/id/auth/modules/ssotransfer/SSOTransfer.authmodule.beans.xml +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/resources/at/gv/egovernment/moa/id/auth/modules/ssotransfer/SSOTransfer.authmodule.beans.xml @@ -11,4 +11,27 @@ <property name="priority" value="1" /> </bean> + <bean id="SSOContainerUtils" + class="at.gv.egovernment.moa.id.auth.modules.ssotransfer.utils.SSOContainerUtils"/> + + + <bean id="SSOTransferSignalServlet" + class="at.gv.egovernment.moa.id.auth.modules.ssotransfer.servlet.SSOTransferSignalServlet"/> + + + <bean id="SSOTransferServlet" + class="at.gv.egovernment.moa.id.auth.modules.ssotransfer.servlet.SSOTransferServlet"/> + + +<!-- Federated Authentication Process Tasks --> + <bean id="RestoreSSOSessionTask" + class="at.gv.egovernment.moa.id.auth.modules.ssotransfer.task.RestoreSSOSessionTask" + scope="prototype"/> + + <bean id="InitializeRestoreSSOSessionTask" + class="at.gv.egovernment.moa.id.auth.modules.ssotransfer.task.InitializeRestoreSSOSessionTask" + scope="prototype"/> + + + </beans> diff --git a/id/server/modules/moa-id-module-ssoTransfer/src/main/resources/at/gv/egovernment/moa/id/auth/modules/ssotransfer/SSOTransferAuthentication.process.xml b/id/server/modules/moa-id-module-ssoTransfer/src/main/resources/at/gv/egovernment/moa/id/auth/modules/ssotransfer/SSOTransferAuthentication.process.xml index 07d746e39..e7d98c8c8 100644 --- a/id/server/modules/moa-id-module-ssoTransfer/src/main/resources/at/gv/egovernment/moa/id/auth/modules/ssotransfer/SSOTransferAuthentication.process.xml +++ b/id/server/modules/moa-id-module-ssoTransfer/src/main/resources/at/gv/egovernment/moa/id/auth/modules/ssotransfer/SSOTransferAuthentication.process.xml @@ -4,9 +4,9 @@ <!-- STORK authentication both with C-PEPS supporting xml signatures and with C-PEPS not supporting xml signatures. --> - <pd:Task id="initializeRestoreSSOSessionTask" class="at.gv.egovernment.moa.id.auth.modules.ssotransfer.task.InitializeRestoreSSOSessionTask" /> - <pd:Task id="restoreSSOSessionTask" class="at.gv.egovernment.moa.id.auth.modules.ssotransfer.task.RestoreSSOSessionTask" async="true" /> - <pd:Task id="finalizeAuthentication" class="at.gv.egovernment.moa.id.auth.modules.internal.tasks.FinalizeAuthenticationTask" /> + <pd:Task id="initializeRestoreSSOSessionTask" class="InitializeRestoreSSOSessionTask" /> + <pd:Task id="restoreSSOSessionTask" class="RestoreSSOSessionTask" async="true" /> + <pd:Task id="finalizeAuthentication" class="FinalizeAuthenticationTask" /> <!-- Process is triggered either by GenerateIFrameTemplateServlet (upon bku selection) or by AuthenticationManager (upon legacy authentication start using legacy parameters. --> <pd:StartEvent id="start" /> diff --git a/id/server/modules/moa-id-modules-federated_authentication/pom.xml b/id/server/modules/moa-id-modules-federated_authentication/pom.xml new file mode 100644 index 000000000..7e8ac86af --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/pom.xml @@ -0,0 +1,24 @@ +<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.server.modules</groupId> + <artifactId>moa-id-modules</artifactId> + <version>${moa-id-version}</version> + </parent> + <artifactId>moa-id-modules-federated_authentication</artifactId> + <description>PVP2 ServiceProvider implementation for federated authentication</description> + + <name>MOA ID-Module Federated-Authentication</name> + + <properties> + <repositoryPath>${basedir}/../../../../repository</repositoryPath> + </properties> + + <dependencies> + <dependency> + <groupId>MOA.id.server</groupId> + <artifactId>moa-id-lib</artifactId> + </dependency> + </dependencies> + +</project>
\ No newline at end of file diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/FederatedAuthConstants.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/FederatedAuthConstants.java new file mode 100644 index 000000000..e2f851132 --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/FederatedAuthConstants.java @@ -0,0 +1,50 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth; + +/** + * @author tlenz + * + */ +public class FederatedAuthConstants { + + public static final int METADATA_VALIDUNTIL_IN_HOURS = 24; + + public static final String ENDPOINT_POST = "/sp/federated/post"; + public static final String ENDPOINT_REDIRECT = "/sp/federated/redirect"; + public static final String ENDPOINT_METADATA = "/sp/federated/metadata"; + + public static final String CONFIG_PROPS_PREFIX = "modules.federatedAuth."; + public static final String CONFIG_PROPS_KEYSTORE = CONFIG_PROPS_PREFIX + "keystore.path"; + public static final String CONFIG_PROPS_KEYSTOREPASSWORD = CONFIG_PROPS_PREFIX + "keystore.password"; + public static final String CONFIG_PROPS_SIGN_METADATA_KEY_PASSWORD = CONFIG_PROPS_PREFIX + "metadata.sign.password"; + public static final String CONFIG_PROPS_SIGN_METADATA_ALIAS_PASSWORD = CONFIG_PROPS_PREFIX + "metadata.sign.alias"; + public static final String CONFIG_PROPS_SIGN_SIGNING_KEY_PASSWORD = CONFIG_PROPS_PREFIX + "request.sign.password"; + public static final String CONFIG_PROPS_SIGN_SIGNING_ALIAS_PASSWORD = CONFIG_PROPS_PREFIX + "request.sign.alias"; + public static final String CONFIG_PROPS_ENCRYPTION_KEY_PASSWORD = CONFIG_PROPS_PREFIX + "response.encryption.password"; + public static final String CONFIG_PROPS_ENCRYPTION_ALIAS_PASSWORD = CONFIG_PROPS_PREFIX + "response.encryption.alias"; + + public static final String CONFIG_DEFAULT_QAA_STORK_LEVEL = "http://www.stork.gov.eu/1.0/citizenQAALevel/4"; + public static final String CONFIG_DEFAULT_QAA_SECCLASS_LEVEL = "http://www.ref.gv.at/ns/names/agiz/pvp/secclass/0-3"; + +} diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/FederatedAuthenticationModuleImpl.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/FederatedAuthenticationModuleImpl.java new file mode 100644 index 000000000..6abc60c46 --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/FederatedAuthenticationModuleImpl.java @@ -0,0 +1,68 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.modules.AuthModule; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; + +/** + * @author tlenz + * + */ +public class FederatedAuthenticationModuleImpl implements AuthModule { + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getPriority() + */ + @Override + public int getPriority() { + // TODO Auto-generated method stub + return 0; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#selectProcess(at.gv.egovernment.moa.id.process.api.ExecutionContext) + */ + @Override + public String selectProcess(ExecutionContext context) { + //select interfederation authentication if PERFORM_INTERFEDERATION_AUTH flag is set + Object performfedAuthObj = context.get(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH); + if (performfedAuthObj != null && performfedAuthObj instanceof Boolean) { + if ((boolean) performfedAuthObj) + return "SSOfederationAuthentication"; + + } + + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AuthModule#getProcessDefinitions() + */ + @Override + public String[] getProcessDefinitions() { + return new String[] { "classpath:at/gv/egovernment/moa/id/auth/modules/federatedauth/federated.Authentication.process.xml" }; + } + +} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAgeAttributBuilder.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/FederatedAuthenticationSpringResourceProvider.java index dff93139c..91d56ebed 100644 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAgeAttributBuilder.java +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/FederatedAuthenticationSpringResourceProvider.java @@ -1,4 +1,4 @@ -/******************************************************************************* +/* * Copyright 2014 Federal Chancellery Austria * MOA-ID has been developed in a cooperation between BRZ, the Federal * Chancellery Austria - ICT staff unit, and Graz University of Technology. @@ -19,31 +19,45 @@ * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth; -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; +import org.springframework.core.io.ClassPathResource; +import org.springframework.core.io.Resource; -public class STORKAgeAttributBuilder implements IPVPAttributeBuilder { +import at.gv.egiz.components.spring.api.SpringResourceProvider; - public String getName() { - return STORKConstants.AGE_NAME; - } +/** + * @author tlenz + * + */ +public class FederatedAuthenticationSpringResourceProvider implements SpringResourceProvider { - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { + /* (non-Javadoc) + * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getResourcesToLoad() + */ + @Override + public Resource[] getResourcesToLoad() { + ClassPathResource federationAuthConfig = new ClassPathResource("/moaid_federated_auth.beans.xml", FederatedAuthenticationSpringResourceProvider.class); - return g.buildStringAttribute(STORKConstants.AGE_FRIENDLYNAME, STORKConstants.AGE_NAME, - STORKAttributHelper.getAttribut(STORKConstants.AGE_NAME, authData)); - + return new Resource[] {federationAuthConfig}; } - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.AGE_FRIENDLYNAME, STORKConstants.AGE_NAME); + /* (non-Javadoc) + * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getPackagesToScan() + */ + @Override + public String[] getPackagesToScan() { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see at.gv.egiz.components.spring.api.SpringResourceProvider#getName() + */ + @Override + public String getName() { + return "MOA-ID Auth-module 'SSO Interfederation'"; } } diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthMetadataConfiguration.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthMetadataConfiguration.java new file mode 100644 index 000000000..29b6ea18b --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthMetadataConfiguration.java @@ -0,0 +1,281 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth.config; + +import java.util.Arrays; +import java.util.List; + +import org.opensaml.saml2.core.Attribute; +import org.opensaml.saml2.core.NameIDType; +import org.opensaml.saml2.metadata.ContactPerson; +import org.opensaml.saml2.metadata.Organization; +import org.opensaml.saml2.metadata.RequestedAttribute; +import org.opensaml.xml.security.credential.Credential; + +import at.gv.egovernment.moa.id.auth.modules.federatedauth.FederatedAuthConstants; +import at.gv.egovernment.moa.id.auth.modules.federatedauth.utils.FederatedAuthCredentialProvider; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +public class FederatedAuthMetadataConfiguration implements IPVPMetadataBuilderConfiguration { + + + private static final int VALIDUNTIL_IN_HOURS = 24; + + private String authURL; + private FederatedAuthCredentialProvider credentialProvider; + + public FederatedAuthMetadataConfiguration(String authURL, FederatedAuthCredentialProvider credentialProvider) { + this.authURL = authURL; + this.credentialProvider = credentialProvider; + + } + + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataValidUntil() + */ + @Override + public int getMetadataValidUntil() { + return FederatedAuthConstants.METADATA_VALIDUNTIL_IN_HOURS; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildEntitiesDescriptorAsRootElement() + */ + @Override + public boolean buildEntitiesDescriptorAsRootElement() { + return false; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildIDPSSODescriptor() + */ + @Override + public boolean buildIDPSSODescriptor() { + return false; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#buildSPSSODescriptor() + */ + @Override + public boolean buildSPSSODescriptor() { + return true; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityIDPostfix() + */ + @Override + public String getEntityID() { + return authURL + FederatedAuthConstants.ENDPOINT_METADATA; + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEntityFriendlyName() + */ + @Override + public String getEntityFriendlyName() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getContactPersonInformation() + */ + @Override + public List<ContactPerson> getContactPersonInformation() { + try { + return PVPConfiguration.getInstance().getIDPContacts(); + + } catch (ConfigurationException e) { + Logger.warn("Can not load Metadata entry: Contect Person", e); + return null; + + } + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getOrgansiationInformation() + */ + @Override + public Organization getOrgansiationInformation() { + try { + return PVPConfiguration.getInstance().getIDPOrganisation(); + + } catch (ConfigurationException e) { + Logger.warn("Can not load Metadata entry: Organisation", e); + return null; + + } + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getMetadataSigningCredentials() + */ + @Override + public Credential getMetadataSigningCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPMetaDataSigningCredential(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getRequestorResponseSigningCredentials() + */ + @Override + public Credential getRequestorResponseSigningCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPAssertionSigningCredential(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getEncryptionCredentials() + */ + @Override + public Credential getEncryptionCredentials() throws CredentialsNotAvailableException { + return credentialProvider.getIDPAssertionEncryptionCredential(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSOPostBindingURL() + */ + @Override + public String getIDPWebSSOPostBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPWebSSORedirectBindingURL() + */ + @Override + public String getIDPWebSSORedirectBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLOPostBindingURL() + */ + @Override + public String getIDPSLOPostBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPSLORedirectBindingURL() + */ + @Override + public String getIDPSLORedirectBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServicePostBindingURL() + */ + @Override + public String getSPAssertionConsumerServicePostBindingURL() { + return authURL + FederatedAuthConstants.ENDPOINT_POST; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAssertionConsumerServiceRedirectBindingURL() + */ + @Override + public String getSPAssertionConsumerServiceRedirectBindingURL() { + return authURL + FederatedAuthConstants.ENDPOINT_REDIRECT; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOPostBindingURL() + */ + @Override + public String getSPSLOPostBindingURL() { + return authURL + FederatedAuthConstants.ENDPOINT_POST; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLORedirectBindingURL() + */ + @Override + public String getSPSLORedirectBindingURL() { + return authURL + FederatedAuthConstants.ENDPOINT_REDIRECT; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPSLOSOAPBindingURL() + */ + @Override + public String getSPSLOSOAPBindingURL() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleAttributes() + */ + @Override + public List<Attribute> getIDPPossibleAttributes() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getIDPPossibleNameITTypes() + */ + @Override + public List<String> getIDPPossibleNameITTypes() { + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPRequiredAttributes() + */ + @Override + public List<RequestedAttribute> getSPRequiredAttributes() { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.builder.AbstractPVPMetadataBuilder#getSPAllowedNameITTypes() + */ + @Override + public List<String> getSPAllowedNameITTypes() { + return Arrays.asList(NameIDType.PERSISTENT, + NameIDType.TRANSIENT, + NameIDType.UNSPECIFIED); + + } + +} diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthnRequestBuilderConfiguration.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthnRequestBuilderConfiguration.java new file mode 100644 index 000000000..eca5c7649 --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/config/FederatedAuthnRequestBuilderConfiguration.java @@ -0,0 +1,161 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth.config; + +import org.opensaml.saml2.core.AuthnContextComparisonTypeEnumeration; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.xml.security.credential.Credential; + +import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation; + +/** + * @author tlenz + * + */ +public class FederatedAuthnRequestBuilderConfiguration implements IPVPAuthnRequestBuilderConfiguruation { + + private boolean isPassive; + private String SPEntityID; + private String QAA_Level; + private EntityDescriptor idpEntity; + private Credential signCred; + + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#isPassivRequest() + */ + @Override + public Boolean isPassivRequest() { + return this.isPassive; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getAssertionConsumerServiceId() + */ + @Override + public Integer getAssertionConsumerServiceId() { + return 0; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getEntityID() + */ + @Override + public String getSPEntityID() { + return this.SPEntityID; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getNameIDPolicy() + */ + @Override + public String getNameIDPolicyFormat() { + return NameID.TRANSIENT; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getNameIDPolicy() + */ + @Override + public boolean getNameIDPolicyAllowCreation() { + return true; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getAuthnContextClassRef() + */ + @Override + public String getAuthnContextClassRef() { + return this.QAA_Level; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getAuthnContextComparison() + */ + @Override + public AuthnContextComparisonTypeEnumeration getAuthnContextComparison() { + return AuthnContextComparisonTypeEnumeration.MINIMUM; + } + + /** + * @param isPassive the isPassive to set + */ + public void setPassive(boolean isPassive) { + this.isPassive = isPassive; + } + + /** + * @param sPEntityID the sPEntityID to set + */ + public void setSPEntityID(String sPEntityID) { + SPEntityID = sPEntityID; + } + + /** + * @param qAA_Level the qAA_Level to set + */ + public void setQAA_Level(String qAA_Level) { + QAA_Level = qAA_Level; + } + + /** + * @param idpEntity the idpEntity to set + */ + public void setIdpEntity(EntityDescriptor idpEntity) { + this.idpEntity = idpEntity; + } + + /** + * @param signCred the signCred to set + */ + public void setSignCred(Credential signCred) { + this.signCred = signCred; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getAuthnRequestSigningCredential() + */ + @Override + public Credential getAuthnRequestSigningCredential() { + return this.signCred; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getIDPEntityDescriptor() + */ + @Override + public EntityDescriptor getIDPEntityDescriptor() { + return this.idpEntity; + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPAuthnRequestBuilderConfiguruation#getSubjectNameID() + */ + @Override + public String getSubjectNameID() { + return null; + } + + +} diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/controller/FederatedAuthMetadataController.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/controller/FederatedAuthMetadataController.java new file mode 100644 index 000000000..c06800079 --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/controller/FederatedAuthMetadataController.java @@ -0,0 +1,97 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth.controller; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.gv.egovernment.moa.id.auth.modules.federatedauth.FederatedAuthConstants; +import at.gv.egovernment.moa.id.auth.modules.federatedauth.config.FederatedAuthMetadataConfiguration; +import at.gv.egovernment.moa.id.auth.modules.federatedauth.utils.FederatedAuthCredentialProvider; +import at.gv.egovernment.moa.id.auth.servlet.AbstractController; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPMetadataBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.config.IPVPMetadataBuilderConfiguration; +import at.gv.egovernment.moa.id.util.HTTPUtils; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +@Controller +public class FederatedAuthMetadataController extends AbstractController { + + @Autowired PVPMetadataBuilder metadatabuilder; + @Autowired AuthConfiguration authConfig; + @Autowired FederatedAuthCredentialProvider credentialProvider; + + public FederatedAuthMetadataController() { + super(); + Logger.debug("Registering servlet " + getClass().getName() + + " with mappings '" + FederatedAuthConstants.ENDPOINT_METADATA + + "'."); + + } + + @RequestMapping(value = "/sp/federated/metadata", + method = {RequestMethod.GET}) + public void getSPMetadata(HttpServletRequest req, HttpServletResponse resp) throws IOException { + //check PublicURL prefix + try { + String authURL = HTTPUtils.extractAuthURLFromRequest(req); + if (!authConfig.getPublicURLPrefix().contains(authURL)) { + resp.sendError(HttpServletResponse.SC_FORBIDDEN, "No valid request URL"); + return; + + } else { + //initialize metadata builder configuration + IPVPMetadataBuilderConfiguration metadataConfig = + new FederatedAuthMetadataConfiguration(authURL, credentialProvider); + + //build metadata + String xmlMetadata = metadatabuilder.buildPVPMetadata(metadataConfig); + + //write response + resp.setContentType("text/xml"); + resp.getOutputStream().write(xmlMetadata.getBytes("UTF-8")); + resp.getOutputStream().close(); + + } + + } catch (Exception e) { + Logger.warn("Build federated-authentication PVP metadata FAILED.", e); + handleErrorNoRedirect(e, req, resp, false); + + } + + } + +} diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/controller/FederatedAuthSignalController.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/controller/FederatedAuthSignalController.java new file mode 100644 index 000000000..431ed5ef1 --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/controller/FederatedAuthSignalController.java @@ -0,0 +1,67 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth.controller; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang3.StringEscapeUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import at.gv.egovernment.moa.id.auth.modules.federatedauth.FederatedAuthConstants; +import at.gv.egovernment.moa.id.auth.servlet.AbstractProcessEngineSignalController; +import at.gv.egovernment.moa.logging.Logger; + +/** + * @author tlenz + * + */ +@Controller +public class FederatedAuthSignalController extends AbstractProcessEngineSignalController { + + public FederatedAuthSignalController() { + super(); + Logger.debug("Registering servlet " + getClass().getName() + + " with mappings '" + FederatedAuthConstants.ENDPOINT_POST + + "' and '" + FederatedAuthConstants.ENDPOINT_REDIRECT + "'."); + + } + + @RequestMapping(value = { "/sp/federated/post", + "/sp/federated/redirect" + }, + method = {RequestMethod.POST, RequestMethod.GET}) + public void performCitizenCardAuthentication(HttpServletRequest req, HttpServletResponse resp) throws IOException { + signalProcessManagement(req, resp); + + } + + public String getPendingRequestId(HttpServletRequest request) { + return StringEscapeUtils.escapeHtml4(request.getParameter("RelayState")); + + } +} diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/CreateAuthnRequestTask.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/CreateAuthnRequestTask.java new file mode 100644 index 000000000..2e134713b --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/CreateAuthnRequestTask.java @@ -0,0 +1,220 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth.tasks; + +import java.lang.reflect.InvocationTargetException; +import java.security.NoSuchAlgorithmException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.ws.message.encoder.MessageEncodingException; +import org.opensaml.xml.security.SecurityException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.auth.modules.federatedauth.FederatedAuthConstants; +import at.gv.egovernment.moa.id.auth.modules.federatedauth.config.FederatedAuthnRequestBuilderConfiguration; +import at.gv.egovernment.moa.id.auth.modules.federatedauth.utils.FederatedAuthCredentialProvider; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; +import at.gv.egovernment.moa.id.protocols.pvp2x.builder.PVPAuthnRequestBuilder; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestBuildException; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; +import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +@Component("CreateFederatedAuthnRequestTask") +public class CreateAuthnRequestTask extends AbstractAuthServletTask { + + @Autowired PVPAuthnRequestBuilder authnReqBuilder; + @Autowired FederatedAuthCredentialProvider credential; + + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + try{ + // get IDP entityID + String idpEntityID = pendingReq.getGenericData(RequestImpl.DATAID_INTERFEDERATIOIDP_URL, String.class); + + if (MiscUtil.isEmpty(idpEntityID)) { + Logger.info("Interfederation not possible -> not inderfederation IDP EntityID found!"); + throw new TaskExecutionException(pendingReq, "Interfederation not possible", new MOAIDException("No inderfederation-IDP EntityID found.", null)); + + } + + //load IDP configuration from MOA-ID Configuration + OAAuthParameter idpConfig = authConfig.getOnlineApplicationParameter(idpEntityID); + //validate IDP + if (!idpConfig.isInderfederationIDP() || !idpConfig.isInboundSSOInterfederationAllowed()) { + Logger.info("Requested interfederation IDP " + idpEntityID + " is not valid for interfederation."); + Logger.debug("isInderfederationIDP:" + String.valueOf(idpConfig.isInderfederationIDP()) + + " isInboundSSOAllowed:" + String.valueOf(idpConfig.isInboundSSOInterfederationAllowed())); + + handleAuthnRequestBuildProblem(executionContext, idpConfig, "sp.pvp2.01", new Object[]{idpEntityID}); + + return; + + } + + //load IDP SAML2 entitydescriptor + EntityDescriptor idpEntity = MOAMetadataProvider.getInstance(). + getEntityDescriptor(idpEntityID); + if (idpEntity == null) { + Logger.warn("Requested IDP " + idpEntityID + + " has no valid metadata or metadata is not found"); + + handleAuthnRequestBuildProblem(executionContext, idpConfig, "sp.pvp2.02", new Object[]{idpEntityID}); + return; + + } + + //setup AuthnRequestBuilder configuration + FederatedAuthnRequestBuilderConfiguration authnReqConfig = new FederatedAuthnRequestBuilderConfiguration(); + authnReqConfig.setIdpEntity(idpEntity); + authnReqConfig.setPassive(idpConfig.isPassivRequestUsedForInterfederation()); + authnReqConfig.setSignCred(credential.getIDPAssertionSigningCredential()); + authnReqConfig.setSPEntityID(pendingReq.getAuthURL() + FederatedAuthConstants.ENDPOINT_METADATA); + authnReqConfig.setQAA_Level(evaluateRequiredQAALevel()); + + //build and transmit AuthnRequest + authnReqBuilder.buildAuthnRequest(pendingReq, authnReqConfig , response); + + } catch (MOAIDException | MetadataProviderException e) { + throw new TaskExecutionException(pendingReq, "Build PVP2.1 AuthnRequest for SSO inderfederation FAILED.", e); + + } catch (MessageEncodingException | NoSuchAlgorithmException | SecurityException e) { + Logger.error("Build PVP2.1 AuthnRequest for SSO inderfederation FAILED", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } catch (Exception e) { + Logger.error("Build PVP2.1 AuthnRequest for SSO inderfederation FAILED", e); + throw new TaskExecutionException(pendingReq, e.getMessage(), e); + + } + } + + /** + * @param executionContext + * @param idpConfig + * @param message + * @param objects + * @throws AuthnRequestBuildException + */ + private void handleAuthnRequestBuildProblem(ExecutionContext executionContext, OAAuthParameter idpConfig, String msgCode, Object[] objects) throws AuthnRequestBuildException { + + if (idpConfig.isPerformLocalAuthenticationOnInterfederationError()) { + Logger.info("Switch to local authentication on this IDP ... "); + + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, true); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION, true); + + executionContext.remove(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH); + + } else { + throw new AuthnRequestBuildException(msgCode, objects); + + } + + } + + private String evaluateRequiredQAALevel() { + IOAAuthParameters sp = pendingReq.getOnlineApplicationConfiguration(); + + //check if STORK protocol module is in ClassPath + Object storkRequst = null; + Integer storkSecClass = null; + try { + storkRequst = Class.forName("at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest").newInstance(); + if (storkRequst != null && + pendingReq.getClass().isInstance(storkRequst)) { + Object storkAuthnRequest = pendingReq.getClass().getMethod("getStorkAuthnRequest", null).invoke(pendingReq, null); + storkSecClass = (Integer) storkAuthnRequest.getClass().getMethod("getQaa", null).invoke(storkAuthnRequest, null); + + } + + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | java.lang.SecurityException ex) { + + + } + + if (sp != null && sp.isSTORKPVPGateway()){ + //use PVP SecClass instead of STORK QAA level + String secClass = null; + if (storkRequst != null && + pendingReq.getClass().isInstance(storkRequst)) { + + try { + secClass = PVPtoSTORKMapper.getInstance().mapToSecClass( + PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass)); + + } catch (Exception e) { + Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4", e); + + } + } + + if (MiscUtil.isNotEmpty(secClass)) + return secClass; + else + return FederatedAuthConstants.CONFIG_DEFAULT_QAA_SECCLASS_LEVEL; + + } else { + if (storkRequst != null && pendingReq.getClass().isInstance(storkRequst)) { + //use requested QAA level from STORK request + try { + String qaaLevel = PVPConstants.STORK_QAA_PREFIX + String.valueOf(storkSecClass); + Logger.debug("Use STORK-QAA level " + qaaLevel + " from STORK request"); + return qaaLevel; + + + } catch (Exception e) { + Logger.warn("Read STORK-QAA level FAILED with an exception.", e); + + } + } + Logger.warn("STORK-QAA level can not read from STORK request. Use default QAA 4"); + return FederatedAuthConstants.CONFIG_DEFAULT_QAA_STORK_LEVEL; + + } + } + +} diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/ReceiveAuthnResponseTask.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/ReceiveAuthnResponseTask.java new file mode 100644 index 000000000..49f9782ae --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/tasks/ReceiveAuthnResponseTask.java @@ -0,0 +1,225 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth.tasks; + +import java.io.IOException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.transform.TransformerException; + +import org.opensaml.saml2.core.Response; +import org.opensaml.saml2.core.StatusCode; +import org.opensaml.ws.message.decoder.MessageDecodingException; +import org.opensaml.xml.io.MarshallingException; +import org.opensaml.xml.security.SecurityException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; +import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask; +import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException; +import at.gv.egovernment.moa.id.auth.modules.federatedauth.utils.FederatedAuthCredentialProvider; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.moduls.RequestImpl; +import at.gv.egovernment.moa.id.moduls.SSOManager; +import at.gv.egovernment.moa.id.process.api.ExecutionContext; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IDecoder; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; +import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AssertionValidationExeption; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnResponseValidationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.messages.InboundMessage; +import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialsNotAvailableException; +import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; +import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; +import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; + +/** + * @author tlenz + * + */ +@Component("ReceiveFederatedAuthnResponseTask") +public class ReceiveAuthnResponseTask extends AbstractAuthServletTask { + + @Autowired SAMLVerificationEngine samlVerificationEngine; + @Autowired FederatedAuthCredentialProvider credentialProvider; + @Autowired SSOManager ssoManager; + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask#execute(at.gv.egovernment.moa.id.process.api.ExecutionContext, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) + */ + @Override + public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response) + throws TaskExecutionException { + InboundMessage msg = null; + + try { + + IDecoder decoder = null; + //select Response Binding + if (request.getMethod().equalsIgnoreCase("POST")) { + decoder = new PostBinding(); + Logger.trace("Receive PVP Response from federated IDP, by using POST-Binding."); + + } else if (request.getMethod().equalsIgnoreCase("GET")) { + decoder = new RedirectBinding(); + Logger.trace("Receive PVP Response from federated IDP, by using Redirect-Binding."); + + } else { + Logger.warn("Receive PVP Response, but Binding (" + + request.getMethod() + ") is not supported."); + throw new AuthnResponseValidationException("sp.pvp2.03", null); + + } + + //decode PVP response object + msg = (InboundMessage) decoder.decode(request, response, true); + + if (MiscUtil.isEmpty(msg.getEntityID())) { + throw new InvalidProtocolRequestException("sp.pvp2.04", new Object[] {}); + + } + + //validate response signature + if(!msg.isVerified()) { + samlVerificationEngine.verify(msg, TrustEngineFactory.getSignatureKnownKeysTrustEngine()); + msg.setVerified(true); + + } + + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROTOCOL_PVP_REQUEST_AUTHRESPONSE); + + //validate assertion + MOAResponse processedMsg = preProcessAuthResponse((MOAResponse) msg); + + //store valid assertion into pending-request + pendingReq.setGenericDataToSession(RequestImpl.DATAID_INTERFEDERATIOIDP_RESPONSE, processedMsg); + + //update MOASession with federation information + authenticatedSessionStorage.createInterfederatedSession(pendingReq, true); + + //store pending-request + requestStoreage.storePendingRequest(pendingReq); + + //write log entries + revisionsLogger.logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_INTERFEDERATION_REVEIVED); + Logger.info("Receive a valid assertion from IDP " + msg.getEntityID()); + + } catch (MessageDecodingException | SecurityException e) { + String samlRequest = request.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID PVP Response from federated IDP: " + samlRequest, e); + throw new TaskExecutionException(pendingReq, "Receive INVALID PVP Response from federated IDP", e); + + } catch (IOException | MarshallingException | TransformerException e) { + Logger.warn("Processing PVP response from federated IDP FAILED.", e); + throw new TaskExecutionException(pendingReq, "Processing PVP response from federated IDP FAILED.", e); + + } catch (CredentialsNotAvailableException e) { + Logger.error("PVP response decrytion FAILED. No credential found.", e); + throw new TaskExecutionException(pendingReq, "PVP response decrytion FAILED. No credential found.", e); + + } catch (AssertionValidationExeption | AuthnResponseValidationException e) { + Logger.info("PVP response validation FAILED. Msg:" + e.getMessage()); + if (msg != null) { + OAAuthParameter idpConfig = authConfig.getOnlineApplicationParameter(msg.getEntityID()); + + //remove federated IDP from SSO session if exists + ssoManager.removeInterfederatedSSOIDP(msg.getEntityID(), request); + + //select next step + handleAuthnResponseValidationProblem(executionContext, idpConfig, e); + + } else + throw new TaskExecutionException(pendingReq, "PVP response validation FAILED.", e); + + } catch (Exception e) { + + + } + + } + + /** + * @param executionContext + * @param idpConfig + * @param message + * @param objects + * @throws TaskExecutionException + * @throws Throwable + */ + private void handleAuthnResponseValidationProblem(ExecutionContext executionContext, OAAuthParameter idpConfig, Throwable e) throws TaskExecutionException { + + if (idpConfig != null && idpConfig.isPerformLocalAuthenticationOnInterfederationError()) { + Logger.info("Switch to local authentication on this IDP ... "); + + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_REQUIRELOCALAUTHENTICATION, true); + executionContext.put(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_BKUSELECTION, true); + + executionContext.remove(MOAIDAuthConstants.PROCESSCONTEXT_PERFORM_INTERFEDERATION_AUTH); + + } else { + throw new TaskExecutionException(pendingReq, "PVP response validation FAILED.", e); + + } + + } + + /** + * PreProcess AuthResponse and Assertion + * @param msg + * @throws TransformerException + * @throws MarshallingException + * @throws IOException + * @throws CredentialsNotAvailableException + * @throws AssertionValidationExeption + * @throws AuthnResponseValidationException + */ + private MOAResponse preProcessAuthResponse(MOAResponse msg) throws IOException, MarshallingException, TransformerException, AssertionValidationExeption, CredentialsNotAvailableException, AuthnResponseValidationException { + Logger.debug("Start PVP21 assertion processing... "); + Response samlResp = (Response) msg.getResponse(); + + // check SAML2 response status-code + if (samlResp.getStatus().getStatusCode().getValue().equals(StatusCode.SUCCESS_URI)) { + //validate PVP 2.1 assertion + samlVerificationEngine.validateAssertion(samlResp, true, credentialProvider.getIDPAssertionEncryptionCredential()); + + msg.setSAMLMessage(SAML2Utils.asDOMDocument(samlResp).getDocumentElement()); + return msg; + + } else { + Logger.info("Receive StatusCode " + samlResp.getStatus().getStatusCode().getValue() + + " from federated IDP."); + throw new AuthnResponseValidationException("sp.pvp2.04", + new Object[]{samlResp.getIssuer().getValue(), samlResp.getStatus().getStatusCode().getValue()}); + + } + + } + +} diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/utils/FederatedAuthCredentialProvider.java b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/utils/FederatedAuthCredentialProvider.java new file mode 100644 index 000000000..1168250ad --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/java/at/gv/egovernment/moa/id/auth/modules/federatedauth/utils/FederatedAuthCredentialProvider.java @@ -0,0 +1,123 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.auth.modules.federatedauth.utils; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import at.gv.egovernment.moa.id.auth.modules.federatedauth.FederatedAuthConstants; +import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; +import at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider; +import at.gv.egovernment.moa.util.FileUtils; + +/** + * @author tlenz + * + */ +@Service("FederatedAuthCredentialProvider") +public class FederatedAuthCredentialProvider extends AbstractCredentialProvider { + + @Autowired AuthConfiguration authConfig; + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getKeyStoreFilePath() + */ + @Override + public String getKeyStoreFilePath() { + return FileUtils.makeAbsoluteURL( + authConfig.getBasicMOAIDConfiguration(FederatedAuthConstants.CONFIG_PROPS_KEYSTORE), + authConfig.getRootConfigFileDir()); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getKeyStorePassword() + */ + @Override + public String getKeyStorePassword() { + return authConfig.getBasicMOAIDConfiguration(FederatedAuthConstants.CONFIG_PROPS_KEYSTOREPASSWORD).trim(); + + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getMetadataKeyAlias() + */ + @Override + public String getMetadataKeyAlias() { + return authConfig.getBasicMOAIDConfiguration( + FederatedAuthConstants.CONFIG_PROPS_SIGN_METADATA_ALIAS_PASSWORD).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getMetadataKeyPassword() + */ + @Override + public String getMetadataKeyPassword() { + return authConfig.getBasicMOAIDConfiguration( + FederatedAuthConstants.CONFIG_PROPS_SIGN_METADATA_KEY_PASSWORD).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getSignatureKeyAlias() + */ + @Override + public String getSignatureKeyAlias() { + return authConfig.getBasicMOAIDConfiguration( + FederatedAuthConstants.CONFIG_PROPS_SIGN_SIGNING_ALIAS_PASSWORD).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getSignatureKeyPassword() + */ + @Override + public String getSignatureKeyPassword() { + return authConfig.getBasicMOAIDConfiguration( + FederatedAuthConstants.CONFIG_PROPS_SIGN_SIGNING_KEY_PASSWORD).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getEncryptionKeyAlias() + */ + @Override + public String getEncryptionKeyAlias() { + return authConfig.getBasicMOAIDConfiguration( + FederatedAuthConstants.CONFIG_PROPS_ENCRYPTION_ALIAS_PASSWORD).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getEncryptionKeyPassword() + */ + @Override + public String getEncryptionKeyPassword() { + return authConfig.getBasicMOAIDConfiguration( + FederatedAuthConstants.CONFIG_PROPS_ENCRYPTION_KEY_PASSWORD).trim(); + } + + /* (non-Javadoc) + * @see at.gv.egovernment.moa.id.protocols.pvp2x.signer.AbstractCredentialProvider#getCredentialName() + */ + @Override + public String getFriendlyName() { + return "FederatedAuth-SP"; + } + +} diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider b/id/server/modules/moa-id-modules-federated_authentication/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider new file mode 100644 index 000000000..28e4ae944 --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/resources/META-INF/services/at.gv.egiz.components.spring.api.SpringResourceProvider @@ -0,0 +1 @@ +at.gv.egovernment.moa.id.auth.modules.federatedauth.FederatedAuthenticationSpringResourceProvider
\ No newline at end of file diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/federatedauth/federated.Authentication.process.xml b/id/server/modules/moa-id-modules-federated_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/federatedauth/federated.Authentication.process.xml new file mode 100644 index 000000000..c5c491ff8 --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/resources/at/gv/egovernment/moa/id/auth/modules/federatedauth/federated.Authentication.process.xml @@ -0,0 +1,26 @@ +<?xml version="1.0" encoding="UTF-8"?> +<pd:ProcessDefinition id="SSOfederationAuthentication" xmlns:pd="http://reference.e-government.gv.at/namespace/moa/process/definition/v1"> + + + <pd:Task id="createInterfederationAuthnRequest" class="CreateFederatedAuthnRequestTask" /> + <pd:Task id="receiveInterfederationAuthnResponse" class="ReceiveFederatedAuthnResponseTask" async="true" /> + <pd:Task id="finalizeAuthentication" class="FinalizeAuthenticationTask" /> + <pd:Task id="restartAuthProzessManagement" class="RestartAuthProzessManagement"/> + + <pd:StartEvent id="start" /> + + <pd:Transition from="start" to="createInterfederationAuthnRequest" /> + + <!-- Switch to local authentication --> + <pd:Transition from="createInterfederationAuthnRequest" to="restartAuthProzessManagement" conditionExpression="ctx['requireLocalAuthentication']"/> + <pd:Transition from="receiveInterfederationAuthnResponse" to="restartAuthProzessManagement" conditionExpression="ctx['requireLocalAuthentication']"/> + <pd:Transition from="restartAuthProzessManagement" to="end" /> + + <!-- Perform federated authentication --> + <pd:Transition from="createInterfederationAuthnRequest" to="receiveInterfederationAuthnResponse"/> + <pd:Transition from="receiveInterfederationAuthnResponse" to="finalizeAuthentication"/> + <pd:Transition from="finalizeAuthentication" to="end" /> + + <pd:EndEvent id="end" /> + +</pd:ProcessDefinition>
\ No newline at end of file diff --git a/id/server/modules/moa-id-modules-federated_authentication/src/main/resources/moaid_federated_auth.beans.xml b/id/server/modules/moa-id-modules-federated_authentication/src/main/resources/moaid_federated_auth.beans.xml new file mode 100644 index 000000000..4933504f0 --- /dev/null +++ b/id/server/modules/moa-id-modules-federated_authentication/src/main/resources/moaid_federated_auth.beans.xml @@ -0,0 +1,36 @@ +<?xml version="1.0" encoding="UTF-8"?> +<beans xmlns="http://www.springframework.org/schema/beans" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns:context="http://www.springframework.org/schema/context" + xmlns:tx="http://www.springframework.org/schema/tx" + xmlns:aop="http://www.springframework.org/schema/aop" + xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd + http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd + http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd + http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> + + +<!-- Federated authentication services --> + <bean id="FederatedAuthCredentialProvider" + class="at.gv.egovernment.moa.id.auth.modules.federatedauth.utils.FederatedAuthCredentialProvider"/> + + <bean id="FederatedAuthMetadataController" + class="at.gv.egovernment.moa.id.auth.modules.federatedauth.controller.FederatedAuthMetadataController"/> + + <bean id="FederatedAuthModule" + class="at.gv.egovernment.moa.id.auth.modules.federatedauth.FederatedAuthenticationModuleImpl"/> + + <bean id="FederatedAuthSignalController" + class="at.gv.egovernment.moa.id.auth.modules.federatedauth.controller.FederatedAuthSignalController"/> + + +<!-- Federated Authentication Process Tasks --> + <bean id="CreateFederatedAuthnRequestTask" + class="at.gv.egovernment.moa.id.auth.modules.federatedauth.tasks.CreateAuthnRequestTask" + scope="prototype"/> + + <bean id="ReceiveFederatedAuthnResponseTask" + class="at.gv.egovernment.moa.id.auth.modules.federatedauth.tasks.ReceiveAuthnResponseTask" + scope="prototype"/> + +</beans>
\ No newline at end of file diff --git a/id/server/modules/moa-id-modules-saml1/pom.xml b/id/server/modules/moa-id-modules-saml1/pom.xml index 9c43ae277..256fb4af2 100644 --- a/id/server/modules/moa-id-modules-saml1/pom.xml +++ b/id/server/modules/moa-id-modules-saml1/pom.xml @@ -8,7 +8,6 @@ <groupId>MOA.id.server.modules</groupId> <artifactId>moa-id-module-saml1</artifactId> - <version>${moa-id-version}</version> <packaging>jar</packaging> <name>MOA ID-Module SAML1</name> @@ -24,7 +23,18 @@ <artifactId>moa-id-lib</artifactId> <scope>test</scope> <type>test-jar</type> - <version>3.0.3-Snapshot</version> + </dependency> + + <dependency> + <groupId>MOA.id.server</groupId> + <artifactId>moa-id-lib</artifactId> + </dependency> + + <!-- Only for development to use SAML1 protocol + SAML1 is removed from official OPB release --> + <dependency> + <groupId>MOA.id.server.modules</groupId> + <artifactId>moa-id-module-eIDAS</artifactId> </dependency> <dependency> @@ -38,6 +48,18 @@ <groupId>MOA.id.server.modules</groupId> <artifactId>moa-id-modul-citizencard_authentication</artifactId> </dependency> + + <dependency> + <groupId>MOA.id.server.modules</groupId> + <artifactId>moa-id-module-eIDAS</artifactId> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>test</scope> + </dependency> + </dependencies> diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java index d4e73690f..61a73335c 100644 --- a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java +++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java @@ -27,12 +27,15 @@ import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.auth.data.AuthenticationSessionStorageConstants; import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.servlet.RedirectServlet; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.data.IAuthData; import at.gv.egovernment.moa.id.data.SLOInformationImpl; import at.gv.egovernment.moa.id.data.SLOInformationInterface; @@ -40,9 +43,13 @@ import at.gv.egovernment.moa.id.moduls.IAction; import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.URLEncoder; +import eu.eidas.auth.commons.IPersonalAttributeList; +@Service("SAML1_GetArtifactAction") public class GetArtifactAction implements IAction { + @Autowired private SAML1AuthenticationServer saml1server; + public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData obj) throws AuthenticationException { @@ -65,14 +72,14 @@ public class GetArtifactAction implements IAction { } try { - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(oaURL); - - SAML1AuthenticationServer saml1server = SAML1AuthenticationServer.getInstace(); - + IOAAuthParameters oaParam = req.getOnlineApplicationConfiguration(); + // add other stork attributes to MOA assertion if available - if(null != authData.getStorkAttributes()) { - List<ExtendedSAMLAttribute> moaExtendedSAMLAttibutes = SAML1AuthenticationServer.addAdditionalSTORKAttributes(authData.getStorkAttributes()); + IPersonalAttributeList storkAttributes = authData.getGenericData( + AuthenticationSessionStorageConstants.STORK_ATTRIBUTELIST, + IPersonalAttributeList.class); + if(null != storkAttributes) { + List<ExtendedSAMLAttribute> moaExtendedSAMLAttibutes = saml1server.addAdditionalSTORKAttributes(storkAttributes); authData.getExtendedSAMLAttributesOA().addAll(moaExtendedSAMLAttibutes); Logger.info("MOA assertion assembled and SAML Artifact generated."); } @@ -83,7 +90,8 @@ public class GetArtifactAction implements IAction { String url = req.getAuthURL() + "/RedirectServlet"; url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(oaURL, "UTF-8")); if (!oaParam.getBusinessService()) - url = addURLParameter(url, MOAIDAuthConstants.PARAM_TARGET, URLEncoder.encode(req.getTarget(), "UTF-8")); + url = addURLParameter(url, MOAIDAuthConstants.PARAM_TARGET, + URLEncoder.encode(req.getGenericData(SAML1Protocol.REQ_DATA_TARGET, String.class), "UTF-8")); url = addURLParameter(url, MOAIDAuthConstants.PARAM_SAMLARTIFACT, URLEncoder.encode(samlArtifactBase64, "UTF-8")); url = httpResp.encodeRedirectURL(url); @@ -95,7 +103,7 @@ public class GetArtifactAction implements IAction { String redirectURL = oaURL; if (!oaParam.getBusinessService()) { redirectURL = addURLParameter(redirectURL, MOAIDAuthConstants.PARAM_TARGET, - URLEncoder.encode(req.getTarget(), "UTF-8")); + URLEncoder.encode(req.getGenericData(SAML1Protocol.REQ_DATA_TARGET, String.class), "UTF-8")); } diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java index 2b4aaf458..fc5837e51 100644 --- a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java +++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetAuthenticationDataService.java @@ -46,19 +46,39 @@ package at.gv.egovernment.moa.id.protocols.saml1; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.StringWriter; import java.util.Calendar; -import org.apache.axis.AxisFault; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import org.w3c.dom.Element; import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; import at.gv.egovernment.moa.id.auth.builder.SAMLResponseBuilder; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.auth.servlet.AbstractController; import at.gv.egovernment.moa.id.util.ErrorResponseUtils; +import at.gv.egovernment.moa.id.util.HTTPUtils; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.id.util.Random; +import at.gv.egovernment.moa.id.util.VelocityProvider; +import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Constants; import at.gv.egovernment.moa.util.DOMUtils; import at.gv.egovernment.moa.util.DateTimeUtils; @@ -67,147 +87,262 @@ import at.gv.egovernment.moa.util.XPathUtils; /** * Web service for picking up authentication data created in the MOA-ID Auth component. * - * @author Paul Ivancsics - * @version $Id: GetAuthenticationDataService.java 1233 2012-01-26 21:59:33Z kstranacher $ - * @see at.gv.egovernment.moa.id.auth.AuthenticationServer#getAuthenticationData + * This getAssertion WebService implementations a hacked solution to integrate SAML1 into + * the new Spring based MOA-ID implementation. + * + * @deprecated + * It is too bad about the time to implement a better solution, + * since SAML1 is deprecated MOA-ID >= 2.0.0 + * + * @author tlenz */ -public class GetAuthenticationDataService implements Constants { +@Controller +public class GetAuthenticationDataService extends AbstractController implements Constants { - /** - * Constructor for GetAuthenticationDataService. - */ - public GetAuthenticationDataService() { - super(); - } + @Autowired private SAML1AuthenticationServer saml1AuthServer; + + private static final String PARAM_WSDL="wsdl"; + private static final String PARAM_XSD="xsd"; + + private static final String TEMPLATE_PLAIN_INFO="plain_info.vm"; + private static final String TEMPLATE_WSDL="wsdl/MOA-ID-1.x.vm"; + private static final String TEMPLATE_XSD="wsdl/MOA-SPSS-1.2.vm"; + private static final String TEMPLATE_SOAP_ERROR="soap_error.vm"; + private static final String TEMPLATE_SOAP_SUCCESS="soap_success.vm"; + + private static final String SERVICE_ENDPOINT = "/services/GetAuthenticationData"; + + private static final String CONTEXT_ENDPOINT = "endpoint"; + private static final String CONTEXT_ERROR = "error"; + + private static final String CONTEXT_SOAP_RESPONSEID = "responseID"; + private static final String CONTEXT_SOAP_REQUESTEID = "requestID"; + private static final String CONTEXT_SOAP_ISSUEINSTANT = "issueInstant"; + private static final String CONTEXT_SOAP_ERRORMESSAGE = "errorMsg"; + private static final String CONTEXT_SOAP_STATUSCODE = "statusCode"; + private static final String CONTEXT_SOAP_ASSERTION = "assertion"; + + @RequestMapping(value = "/services/GetAuthenticationData", method = {RequestMethod.POST}) + public void getAuthenticationData(HttpServletRequest req, HttpServletResponse resp) + throws IOException { + InputStream is = null; + VelocityContext context = new VelocityContext(); + try { + is = req.getInputStream(); + Element soapReq = DOMUtils.parseXmlNonValidating(is); - /** - * Takes a <code>lt;samlp:Request></code> containing a - * <code>SAML artifact</code> and returns the corresponding - * authentication data <code>lt;saml:Assertion></code> - * (obtained from the <code>AuthenticationServer</code>), - * enclosed in a <code>lt;samlp:Response></code>. - * <br/>Bad requests are mapped into various <code>lt;samlp:StatusCode></code>s, - * possibly containing enclosed sub-<code>lt;samlp:StatusCode></code>s. - * The status codes are defined in the SAML specification. - * - * @param requests request elements of type <code>lt;samlp:Request></code>; - * only 1 request element is allowed - * @return response element of type <code>lt;samlp:Response></code>, - * packed into an <code>Element[]</code> - * @throws AxisFault thrown when an error occurs in assembling the - * <code>lt;samlp:Response></code> - */ - public Element[] Request(Element[] requests) - throws AxisFault { - - Element request = requests[0]; - Element[] responses = new Element[1]; + //process request + Element soapResp = processRequest(soapReq); + + String respString = DOMUtils.serializeNode(soapResp, true); + + resp.setContentType("text/xml;charset=UTF-8"); + context.put(CONTEXT_SOAP_ASSERTION, respString); + evaluateTemplate(context, resp, TEMPLATE_SOAP_SUCCESS); + + } catch (ParserConfigurationException | SAXException | IOException | TransformerException e) { + Logger.error("SAML1 GetAuthenticationData receive a non-valid request.", e); + resp.setContentType("text/xml;charset=UTF-8"); + + context.put(CONTEXT_SOAP_ISSUEINSTANT, DateTimeUtils.buildDateTimeUTC(Calendar.getInstance())); + context.put(CONTEXT_SOAP_RESPONSEID, Random.nextRandom()); + context.put(CONTEXT_SOAP_STATUSCODE, "samlp:Requester"); + context.put(CONTEXT_SOAP_ERRORMESSAGE, e.getMessage()); + + evaluateTemplate(context, resp, TEMPLATE_SOAP_ERROR); + + } catch (SAML1AssertionResponseBuildException e) { + Logger.error("SAML1 GetAuthenticationData response build failed..", e); + resp.setContentType("text/xml;charset=UTF-8"); + + context.put(CONTEXT_SOAP_ISSUEINSTANT, e.getIssueInstant()); + context.put(CONTEXT_SOAP_REQUESTEID, e.getRequestID()); + context.put(CONTEXT_SOAP_RESPONSEID, e.getResponseID()); + context.put(CONTEXT_SOAP_STATUSCODE, "samlp:Responder"); + context.put(CONTEXT_SOAP_ERRORMESSAGE, e.getMessage()); + + evaluateTemplate(context, resp, TEMPLATE_SOAP_ERROR); + + } finally { + try { + if (is != null) + is.close(); + + } catch (Exception e) { + + } + } + } + + @RequestMapping(value = "/services/GetAuthenticationData", method = {RequestMethod.GET}) + public void getAuthenticationDataWSDL(HttpServletRequest req, HttpServletResponse resp) + throws Exception { + String wsdl_param = req.getParameter(PARAM_WSDL); + String xsd_param = req.getParameter(PARAM_XSD); + + String fullServiceEndPoint = HTTPUtils.extractAuthURLFromRequest(req) + SERVICE_ENDPOINT; + + VelocityContext context = new VelocityContext(); + context.put(CONTEXT_ENDPOINT, fullServiceEndPoint); + + if (wsdl_param != null) { + //print wsdl + resp.setContentType("text/xml;charset=UTF-8"); + evaluateTemplate(context, resp, TEMPLATE_WSDL); + + } else if (xsd_param != null){ + //print xsd + resp.setContentType("text/xml;charset=UTF-8"); + evaluateTemplate(context, resp, TEMPLATE_XSD); + + } else { + //print plain info + resp.setContentType("text/html;charset=UTF-8"); + evaluateTemplate(context, resp, TEMPLATE_PLAIN_INFO); + + } + + } + + private Element processRequest(Element soapReq) throws ParserConfigurationException, IOException, SAXException, TransformerException, SAML1AssertionResponseBuildException { String requestID = ""; String statusCode = ""; String subStatusCode = null; String statusMessageCode = null; String statusMessage = null; String samlAssertion = ""; - if (requests.length > 1) { - // more than 1 request given as parameter - statusCode = "samlp:Requester"; - subStatusCode = "samlp:TooManyResponses"; - statusMessageCode = "1201"; - } + Element responses; + + //select soap-body element + NodeList saml1ReqList = soapReq.getElementsByTagNameNS(soapReq.getNamespaceURI(), "Body");; + if (saml1ReqList.getLength() != 1) { + saml1ReqList = soapReq.getElementsByTagNameNS(soapReq.getNamespaceURI(), "body");; + if (saml1ReqList.getLength() != 1) { + throw new SAXException("No unique 'soap-env:Body' element."); + + } + } + + //get first child from body --> should be the SAML1 Request element + Element saml1Req; + if (saml1ReqList.item(0).getFirstChild() instanceof Element) + saml1Req = (Element) saml1ReqList.item(0).getFirstChild(); + else { - try { - DOMUtils.validateElement(request, ALL_SCHEMA_LOCATIONS, null); - NodeList samlArtifactList = XPathUtils.selectNodeList(request, "samlp:AssertionArtifact"); - if (samlArtifactList.getLength() == 0) { - // no SAML artifact given in request - statusCode = "samlp:Requester"; - statusMessageCode = "1202"; - } - else if (samlArtifactList.getLength() > 1) { - // too many SAML artifacts given in request - statusCode = "samlp:Requester"; - subStatusCode = "samlp:TooManyResponses"; - statusMessageCode = "1203"; - } + throw new SAXException("First child of 'soap-env:Body' element has a wrong type."); - else { - Element samlArtifactElem = (Element)samlArtifactList.item(0); - requestID = request.getAttribute("RequestID"); - String samlArtifact = DOMUtils.getText(samlArtifactElem); - SAML1AuthenticationServer saml1server = SAML1AuthenticationServer.getInstace(); + } + + //validate the SAML1 request element, which we selected above + DOMUtils.validateElement(saml1Req, ALL_SCHEMA_LOCATIONS, null); + + //parse inforamtion from SAML1 request + try { + NodeList samlArtifactList = XPathUtils.selectNodeList(saml1Req, "samlp:AssertionArtifact"); + if (samlArtifactList.getLength() == 0) { + // no SAML artifact given in request + statusCode = "samlp:Requester"; + statusMessageCode = "1202"; + + } else if (samlArtifactList.getLength() > 1) { + // too many SAML artifacts given in request + statusCode = "samlp:Requester"; + subStatusCode = "samlp:TooManyResponses"; + statusMessageCode = "1203"; + + } else { + Element samlArtifactElem = (Element)samlArtifactList.item(0); + requestID = saml1Req.getAttribute("RequestID"); + String samlArtifact = DOMUtils.getText(samlArtifactElem); + + try { + samlAssertion = saml1AuthServer.getSaml1AuthenticationData(samlArtifact); + + // success + statusCode = "samlp:Success"; + statusMessageCode = "1200"; + } catch (ClassCastException ex) { try { + Throwable error = saml1AuthServer.getErrorResponse(samlArtifact); + statusCode = "samlp:Responder"; + + ErrorResponseUtils errorUtils = ErrorResponseUtils.getInstance(); + + if (error instanceof MOAIDException) { + statusMessageCode = ((MOAIDException)error).getMessageId(); + statusMessage = StringEscapeUtils.escapeXml(((MOAIDException)error).getMessage()); - samlAssertion = saml1server.getSaml1AuthenticationData(samlArtifact); - - // success - statusCode = "samlp:Success"; - statusMessageCode = "1200"; - } - - catch (ClassCastException ex) { - - try { - Throwable error = saml1server.getErrorResponse(samlArtifact); - statusCode = "samlp:Responder"; - - ErrorResponseUtils errorUtils = ErrorResponseUtils.getInstance(); + } else { + statusMessage = StringEscapeUtils.escapeXml(error.getMessage()); - if (error instanceof MOAIDException) { - statusMessageCode = ((MOAIDException)error).getMessageId(); - statusMessage = StringEscapeUtils.escapeXml(((MOAIDException)error).getMessage()); - - } else { - statusMessage = StringEscapeUtils.escapeXml(error.getMessage()); - } - subStatusCode = errorUtils.getResponseErrorCode(error); - - } catch (Exception e) { - //no authentication data for given SAML artifact - statusCode = "samlp:Requester"; - subStatusCode = "samlp:ResourceNotRecognized"; - statusMessage = ex.toString(); - } - - } - - catch (AuthenticationException ex) { + } + subStatusCode = errorUtils.getResponseErrorCode(error); + + } catch (Exception e) { //no authentication data for given SAML artifact statusCode = "samlp:Requester"; subStatusCode = "samlp:ResourceNotRecognized"; statusMessage = ex.toString(); } + + } catch (AuthenticationException ex) { + //no authentication data for given SAML artifact + statusCode = "samlp:Requester"; + subStatusCode = "samlp:ResourceNotRecognized"; + statusMessage = ex.toString(); } } - catch (Throwable t) { - // invalid request format - statusCode = "samlp:Requester"; - statusMessageCode = "1204"; - } + + + } catch (Throwable t) { + // invalid request format + statusCode = "samlp:Requester"; + statusMessageCode = "1204"; + + } + + String responseID = Random.nextRandom(); + String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar.getInstance()); + + try { + if (statusMessage == null) + statusMessage = MOAIDMessageProvider.getInstance().getMessage(statusMessageCode, null); + responses = new SAMLResponseBuilder().build( + responseID, requestID, issueInstant, statusCode, subStatusCode, statusMessage, samlAssertion); + return responses; + + } catch (Throwable e) { + throw new SAML1AssertionResponseBuildException(responseID, issueInstant, + requestID, "1299", e.getMessage(), e); + + } } + + + private void evaluateTemplate(VelocityContext context, HttpServletResponse httpResp, String templateURL) throws IOException { + InputStream is = null; + try { + is = Thread.currentThread() + .getContextClassLoader() + .getResourceAsStream(templateURL); + + VelocityEngine engine = VelocityProvider.getClassPathVelocityEngine(); + BufferedReader reader = new BufferedReader(new InputStreamReader(is )); + StringWriter writer = new StringWriter(); + engine.evaluate(context, writer, "SAML1 GetAuthenticationData", reader); + httpResp.getOutputStream().write(writer.toString().getBytes("UTF-8")); + + } catch (Exception e) { + Logger.error("SAML1 GetAuthenticationData has an error:", e); + throw new IOException(e); + + } finally { + if (is != null) + is.close(); + + } - try { - String responseID = Random.nextRandom(); - String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar.getInstance()); - - if (statusMessage == null) - statusMessage = MOAIDMessageProvider.getInstance().getMessage(statusMessageCode, null); - responses[0] = new SAMLResponseBuilder().build( - responseID, requestID, issueInstant, statusCode, subStatusCode, statusMessage, samlAssertion); - - } - catch (MOAIDException e) { - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - throw fault; - } - catch (Throwable t) { - MOAIDException e = new MOAIDException("1299", null, t); - AxisFault fault = AxisFault.makeFault(e); - fault.setFaultDetail(new Element[] { e.toErrorResponse()}); - throw fault; - } - return responses; - } - + } } + diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AssertionResponseBuildException.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AssertionResponseBuildException.java new file mode 100644 index 000000000..0c06a94df --- /dev/null +++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AssertionResponseBuildException.java @@ -0,0 +1,86 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.saml1; + +/** + * @author tlenz + * + */ +public class SAML1AssertionResponseBuildException extends Exception { + + private static final long serialVersionUID = -394698807368683821L; + + private String responseID; + private String issueInstant; + private String requestID; + private String errorCode; + + /** + * @param responseID + * @param issueInstant + * @param requestID + * @param string + * @param message + */ + public SAML1AssertionResponseBuildException(String responseID, String issueInstant, String requestID, String errorCode, + String errorMsg, Throwable throwable) { + super(errorMsg, throwable); + + this.requestID = requestID; + this.issueInstant = issueInstant; + this.responseID = responseID; + this.errorCode = errorCode; + } + + /** + * @return the responseID + */ + public String getResponseID() { + return responseID; + } + + /** + * @return the issueInstant + */ + public String getIssueInstant() { + return issueInstant; + } + + /** + * @return the requestID + */ + public String getRequestID() { + return requestID; + } + + /** + * @return the errorCode + */ + public String getErrorCode() { + return errorCode; + } + + + + +} diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java index 04e50baac..5eb39880e 100644 --- a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java +++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java @@ -35,6 +35,8 @@ import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import org.apache.commons.lang3.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; import org.w3c.dom.Element; import org.xml.sax.SAXException; @@ -56,12 +58,11 @@ import at.gv.egovernment.moa.id.auth.parser.SAMLArtifactParser; import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters; import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -//import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; +import at.gv.egovernment.moa.id.storage.ITransactionStorage; import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; @@ -74,22 +75,14 @@ import at.gv.util.xsd.persondata.IdentificationType.Value; import at.gv.util.xsd.persondata.PersonNameType; import at.gv.util.xsd.persondata.PersonNameType.FamilyName; import at.gv.util.xsd.persondata.PhysicalPersonType; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PersonalAttribute; +import eu.eidas.auth.commons.IPersonalAttributeList; +import eu.eidas.auth.commons.PersonalAttribute; +//import at.gv.egovernment.moa.id.util.IdentityLinkReSigner; +@Service("SAML1AuthenticationServer") public class SAML1AuthenticationServer extends AuthenticationServer { - - private static SAML1AuthenticationServer instance; - - public static SAML1AuthenticationServer getInstace() { - if (instance == null) - instance = new SAML1AuthenticationServer(); - return instance; - } - - private static AssertionStorage authenticationDataStore = AssertionStorage.getInstance(); - + @Autowired private ITransactionStorage authenticationDataStore; /** * time out in milliseconds used by {@link cleanup} for authentication data @@ -107,20 +100,23 @@ public class SAML1AuthenticationServer extends AuthenticationServer { samlArtifact, ex.toString() }); } Throwable error = null; - //synchronized (authenticationDataStore) { - try { - error = authenticationDataStore - .get(samlArtifact, Throwable.class); + try { + error = authenticationDataStore + .get(samlArtifact, Throwable.class); - authenticationDataStore.remove(samlArtifact); - - } catch (MOADatabaseException e) { + if (error == null) { Logger.error("Assertion not found for SAML Artifact: " + samlArtifact); throw new AuthenticationException("1206", new Object[] { samlArtifact }); + } + + authenticationDataStore.remove(samlArtifact); + + } catch (MOADatabaseException e) { + Logger.error("Assertion not found for SAML Artifact: " + samlArtifact); + throw new AuthenticationException("1206", new Object[] { samlArtifact }); + } - //} - return error; } @@ -129,7 +125,7 @@ public class SAML1AuthenticationServer extends AuthenticationServer { * @param iPersonalAttributeList STORK attribute list * @return */ - public static List<ExtendedSAMLAttribute> addAdditionalSTORKAttributes(IPersonalAttributeList iPersonalAttributeList) { + public List<ExtendedSAMLAttribute> addAdditionalSTORKAttributes(IPersonalAttributeList iPersonalAttributeList) { List<ExtendedSAMLAttribute> moaExtendedSAMLAttributeList = new Vector<ExtendedSAMLAttribute>(); if(null == iPersonalAttributeList) @@ -177,22 +173,24 @@ public class SAML1AuthenticationServer extends AuthenticationServer { throw new AuthenticationException("1205", new Object[] { samlArtifact, ex.toString() }); } - String authData = null; - //synchronized (authenticationDataStore) { - // System.out.println("assertionHandle: " + assertionHandle); - - try { - authData = authenticationDataStore - .get(samlArtifact, String.class, authDataTimeOut); + String authData = null; + try { + authData = authenticationDataStore + .get(samlArtifact, String.class, authDataTimeOut); - } catch (MOADatabaseException e) { + if (authData == null) { Logger.error("Assertion not found for SAML Artifact: " + samlArtifact); throw new AuthenticationException("1206", new Object[] { samlArtifact }); - } - //} + + } - authenticationDataStore.remove(samlArtifact); + } catch (MOADatabaseException e) { + Logger.error("Assertion not found for SAML Artifact: " + samlArtifact); + throw new AuthenticationException("1206", new Object[] { samlArtifact }); + } + + authenticationDataStore.remove(samlArtifact); Logger.debug("Assertion delivered for SAML Artifact: " + samlArtifact); return authData; @@ -210,7 +208,7 @@ public class SAML1AuthenticationServer extends AuthenticationServer { return samlArtifact; } - public String BuildSAMLArtifact(OAAuthParameter oaParam, + public String BuildSAMLArtifact(IOAAuthParameters oaParam, SAML1AuthenticationData authData, String sourceID) throws ConfigurationException, BuildException, AuthenticationException { @@ -435,7 +433,7 @@ public class SAML1AuthenticationServer extends AuthenticationServer { } - private String generateMandateDate(OAAuthParameter oaParam, AuthenticationData authData + private String generateMandateDate(IOAAuthParameters oaParam, AuthenticationData authData ) throws AuthenticationException, BuildException, ParseException, ConfigurationException, ServiceException, ValidateException { diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java index 6573270e4..1b1815b44 100644 --- a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java +++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java @@ -22,18 +22,20 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.saml1; +import java.io.IOException; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringEscapeUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants; -import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger; -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.exception.InvalidProtocolRequestException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ProtocolNotActiveException; @@ -42,17 +44,30 @@ import at.gv.egovernment.moa.id.auth.servlet.RedirectServlet; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IModulInfo; import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.id.protocols.AbstractAuthProtocolModulController; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLEncoder; -public class SAML1Protocol extends MOAIDAuthConstants implements IModulInfo { +/** + * SAML1 authentication protocol implementation + * + * @deprecated + * @author tlenz + * + */ + +@Controller +public class SAML1Protocol extends AbstractAuthProtocolModulController { + @Autowired private SAML1AuthenticationServer saml1AuthServer; + + public static final String REQ_DATA_SOURCEID = "saml1_sourceID"; + public static final String REQ_DATA_TARGET = "saml1_target"; + public static final String NAME = SAML1Protocol.class.getName(); public static final String PATH = "id_saml1"; @@ -72,24 +87,6 @@ public class SAML1Protocol extends MOAIDAuthConstants implements IModulInfo { PVPConstants.EID_SOURCE_PIN_TYPE_NAME }); - private static HashMap<String, IAction> actions = new HashMap<String, IAction>(); - - static { - - actions.put(GETARTIFACT, new GetArtifactAction()); - - instance = new SAML1Protocol(); - } - - private static SAML1Protocol instance = null; - - public static SAML1Protocol getInstance() { - if (instance == null) { - instance = new SAML1Protocol(); - } - return instance; - } - public String getName() { return NAME; } @@ -98,92 +95,131 @@ public class SAML1Protocol extends MOAIDAuthConstants implements IModulInfo { return PATH; } - public IRequest preProcess(HttpServletRequest request, - HttpServletResponse response, String action, - String sessionId, String transactionId) throws MOAIDException { - SAML1RequestImpl config = new SAML1RequestImpl(request); - + + @RequestMapping(value = "/StartAuthentication", method = {RequestMethod.POST, RequestMethod.GET}) + public void PVPMetadataRequest(HttpServletRequest req, HttpServletResponse resp) throws MOAIDException, IOException { if (!AuthConfigurationProviderFactory.getInstance().getAllowedProtocols().isSAML1Active()) { Logger.info("SAML1 is deaktivated!"); throw new ProtocolNotActiveException("auth.22", new Object[] { "SAML 1" }); } - - String oaURL = (String) request.getParameter(PARAM_OA); - //oaURL = StringEscapeUtils.escapeHtml(oaURL); - - String target = (String) request.getParameter(PARAM_TARGET); - target = StringEscapeUtils.escapeHtml(target); - - String sourceID = request.getParameter(PARAM_SOURCEID); - sourceID = StringEscapeUtils.escapeHtml(sourceID); - - //the target parameter is used to define the OA in SAML1 standard - if (target != null && target.startsWith("http")) { - oaURL = target; - target = null; - } - if (MiscUtil.isEmpty(oaURL)) { - Logger.info("Receive SAML1 request with no OA parameter. Authentication STOPPED!"); - throw new WrongParametersException("StartAuthentication", PARAM_OA, - "auth.12"); + SAML1RequestImpl pendingReq = applicationContext.getBean(SAML1RequestImpl.class); + pendingReq.initialize(req); + pendingReq.setModule(NAME); + + revisionsLogger.logEvent(MOAIDEventConstants.SESSION_CREATED, pendingReq.getUniqueSessionIdentifier()); + revisionsLogger.logEvent(MOAIDEventConstants.TRANSACTION_CREATED, pendingReq.getUniqueTransactionIdentifier()); + revisionsLogger.logEvent( + pendingReq.getUniqueSessionIdentifier(), + pendingReq.getUniqueTransactionIdentifier(), + MOAIDEventConstants.TRANSACTION_IP, + req.getRemoteAddr()); + + //preProcess SAML1 Request + preProcess(req, resp, pendingReq); - } - - if (!ParamValidatorUtils.isValidOA(oaURL)) - throw new WrongParametersException("StartAuthentication", PARAM_OA, - "auth.12"); - - config.setOAURL(oaURL); - - Logger.info("Dispatch SAML1 Request: OAURL=" + oaURL); - - if (!ParamValidatorUtils.isValidSourceID(sourceID)) - throw new WrongParametersException("StartAuthentication", PARAM_SOURCEID, "auth.12"); - - - //load Target only from OA config - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() - .getOnlineApplicationParameter(oaURL); - - if (oaParam == null) - throw new InvalidProtocolRequestException("auth.00", - new Object[] { null }); + performAuthentication(req, resp, pendingReq); + return; - SAML1ConfigurationParameters saml1 = oaParam.getSAML1Parameter(); - if (saml1 == null || !(saml1.isIsActive() != null && saml1.isIsActive()) ) { - Logger.info("Online-Application " + oaURL + " can not use SAML1 for authentication."); - throw new InvalidProtocolRequestException("auth.00", - new Object[] { null }); - } - config.setOnlineApplicationConfiguration(oaParam); - config.setSourceID(sourceID); - - MOAReversionLogger.getInstance().logEvent(sessionId, transactionId, MOAIDEventConstants.AUTHPROTOCOL_SAML1_AUTHNREQUEST); - - if (MiscUtil.isNotEmpty(target)) - config.setTarget(target); - - else - config.setTarget(oaParam.getTarget()); + } + + + public void preProcess(HttpServletRequest request, + HttpServletResponse response, SAML1RequestImpl pendingRequest) throws MOAIDException { + try { + String oaURL = (String) request.getParameter(PARAM_OA); + //oaURL = StringEscapeUtils.escapeHtml(oaURL); + + String target = (String) request.getParameter(PARAM_TARGET); + target = StringEscapeUtils.escapeHtml(target); + + String sourceID = request.getParameter(PARAM_SOURCEID); + sourceID = StringEscapeUtils.escapeHtml(sourceID); + + //the target parameter is used to define the OA in SAML1 standard + if (target != null && target.startsWith("http")) { + oaURL = target; + target = null; + } + + if (MiscUtil.isEmpty(oaURL)) { + Logger.info("Receive SAML1 request with no OA parameter. Authentication STOPPED!"); + throw new WrongParametersException("StartAuthentication", PARAM_OA, + "auth.12"); + + } + + if (!ParamValidatorUtils.isValidOA(oaURL)) + throw new WrongParametersException("StartAuthentication", PARAM_OA, + "auth.12"); + + pendingRequest.setOAURL(oaURL); + + Logger.info("Dispatch SAML1 Request: OAURL=" + oaURL); + + if (!ParamValidatorUtils.isValidSourceID(sourceID)) + throw new WrongParametersException("StartAuthentication", PARAM_SOURCEID, "auth.12"); + + + //load Target only from OA config + OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance() + .getOnlineApplicationParameter(oaURL); + if (oaParam == null) + throw new InvalidProtocolRequestException("auth.00", + new Object[] { null }); + + SAML1ConfigurationParameters saml1 = oaParam.getSAML1Parameter(); + if (saml1 == null || !(saml1.isIsActive() != null && saml1.isIsActive()) ) { + Logger.info("Online-Application " + oaURL + " can not use SAML1 for authentication."); + throw new InvalidProtocolRequestException("auth.00", + new Object[] { null }); + } + pendingRequest.setOnlineApplicationConfiguration(oaParam); + + + //check and set SourceID + if (oaParam.getSAML1Parameter() != null && + MiscUtil.isNotEmpty(oaParam.getSAML1Parameter().getSourceID())) { + pendingRequest.setSourceID(oaParam.getSAML1Parameter().getSourceID()); - return config; + } else + pendingRequest.setSourceID(sourceID); + + revisionsLogger.logEvent(pendingRequest, MOAIDEventConstants.AUTHPROTOCOL_SAML1_AUTHNREQUEST); + + if (MiscUtil.isNotEmpty(target)) + pendingRequest.setGenericDataToSession(REQ_DATA_TARGET, target); + + else + pendingRequest.setGenericDataToSession(REQ_DATA_TARGET, oaParam.getTarget()); + + //AuthnRequest needs authentication + pendingRequest.setNeedAuthentication(true); + + //set protocol action, which should be executed after authentication + pendingRequest.setAction(GetArtifactAction.class.getName()); + + } catch (WrongParametersException e) { + throw new InvalidProtocolRequestException(e.getMessageId(), e.getParameters()); + + } catch (InvalidProtocolRequestException e) { + throw e; + + } + } public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) throws Throwable{ - - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(protocolRequest.getOAURL()); - if (!oa.getSAML1Parameter().isProvideAllErrors()) + if (!protocolRequest.getOnlineApplicationConfiguration().getSAML1Parameter().isProvideAllErrors()) return false; - else { - SAML1AuthenticationServer saml1authentication = SAML1AuthenticationServer.getInstace(); - String samlArtifactBase64 = saml1authentication.BuildErrorAssertion(e, protocolRequest); + else { + String samlArtifactBase64 = saml1AuthServer.BuildErrorAssertion(e, protocolRequest); String url = protocolRequest.getAuthURL() + "/RedirectServlet"; url = addURLParameter(url, RedirectServlet.REDIRCT_PARAM_URL, URLEncoder.encode(protocolRequest.getOAURL(), "UTF-8")); @@ -199,15 +235,6 @@ public class SAML1Protocol extends MOAIDAuthConstants implements IModulInfo { } } - public IAction getAction(String action) { - return actions.get(action); - } - - public IAction canHandleRequest(HttpServletRequest request, - HttpServletResponse response) { - return null; - } - public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) { diff --git a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java index 3da7cab80..e85f8ce6b 100644 --- a/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java +++ b/id/server/modules/moa-id-modules-saml1/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java @@ -23,36 +23,24 @@ package at.gv.egovernment.moa.id.protocols.saml1; import java.util.ArrayList; +import java.util.Collection; import java.util.List; -import javax.servlet.http.HttpServletRequest; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Scope; +import org.springframework.stereotype.Component; -import org.opensaml.saml2.core.Attribute; - -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.config.auth.data.SAML1ConfigurationParameters; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; -import at.gv.egovernment.moa.logging.Logger; /** * @author tlenz * */ +@Component("SAML1RequestImpl") +@Scope(value = BeanDefinition.SCOPE_PROTOTYPE) public class SAML1RequestImpl extends RequestImpl { - - /** - * @param req - * @throws ConfigurationException - */ - public SAML1RequestImpl(HttpServletRequest req) - throws ConfigurationException { - super(req); - - } private static final long serialVersionUID = -4961979968425683115L; @@ -76,32 +64,26 @@ public class SAML1RequestImpl extends RequestImpl { * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes() */ @Override - public List<Attribute> getRequestedAttributes() { + public Collection<String> getRequestedAttributes() { List<String> reqAttr = new ArrayList<String>(); reqAttr.addAll(SAML1Protocol.DEFAULTREQUESTEDATTRFORINTERFEDERATION); - try { - OAAuthParameter oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(getOAURL()); - SAML1ConfigurationParameters saml1 = oa.getSAML1Parameter(); - if (saml1 != null) { - if (saml1.isProvideAUTHBlock()) - reqAttr.add(PVPConstants.EID_AUTH_BLOCK_NAME); - - if (saml1.isProvideCertificate()) - reqAttr.add(PVPConstants.EID_SIGNER_CERTIFICATE_NAME); - - if (saml1.isProvideFullMandatorData()) - reqAttr.add(PVPConstants.MANDATE_FULL_MANDATE_NAME); - } - - return AttributQueryBuilder.buildSAML2AttributeList(oa, reqAttr.iterator()); + SAML1ConfigurationParameters saml1 = this.getOnlineApplicationConfiguration().getSAML1Parameter(); + if (saml1 != null) { + if (saml1.isProvideAUTHBlock()) + reqAttr.add(PVPConstants.EID_AUTH_BLOCK_NAME); + + if (saml1.isProvideCertificate()) + reqAttr.add(PVPConstants.EID_SIGNER_CERTIFICATE_NAME); - } catch (ConfigurationException e) { - Logger.error("Load configuration for OA " + getOAURL() + " FAILED", e); - return null; + if (saml1.isProvideFullMandatorData()) + reqAttr.add(PVPConstants.MANDATE_FULL_MANDATE_NAME); } - + + //return attributQueryBuilder.buildSAML2AttributeList(this.getOnlineApplicationConfiguration(), reqAttr.iterator()); + + return reqAttr; } diff --git a/id/server/modules/moa-id-modules-saml1/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo b/id/server/modules/moa-id-modules-saml1/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo deleted file mode 100644 index 5bff0dbc2..000000000 --- a/id/server/modules/moa-id-modules-saml1/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo +++ /dev/null @@ -1 +0,0 @@ -at.gv.egovernment.moa.id.protocols.saml1.SAML1Protocol
\ No newline at end of file diff --git a/id/server/modules/moa-id-modules-saml1/src/main/resources/plain_info.vm b/id/server/modules/moa-id-modules-saml1/src/main/resources/plain_info.vm new file mode 100644 index 000000000..dfc11820f --- /dev/null +++ b/id/server/modules/moa-id-modules-saml1/src/main/resources/plain_info.vm @@ -0,0 +1,14 @@ +<html> +<head> +<meta content="text/html; charset=utf-8" http-equiv="Content-Type"> +</head> +<body> +<h1>GetAuthenticationData</h1> +<p>Hi there, this is an Web service!</p> +#if($error) + <i>Your request has an error: $error</i> +#else + <i>Perhaps there will be a form for invoking the service here...</i> +#end +</body> +</html> diff --git a/id/server/modules/moa-id-modules-saml1/src/main/resources/soap_error.vm b/id/server/modules/moa-id-modules-saml1/src/main/resources/soap_error.vm new file mode 100644 index 000000000..65945e2de --- /dev/null +++ b/id/server/modules/moa-id-modules-saml1/src/main/resources/soap_error.vm @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="UTF-8"?> +<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <soapenv:Body><samlp:Response #if($requestID) InResponseTo="$requestID" #end IssueInstant="$issueInstant" MajorVersion="1" MinorVersion="0" ResponseID="$responseID" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol"> <samlp:Status> <samlp:StatusCode Value="$statusCode"/> <samlp:StatusMessage>$errorMsg</samlp:StatusMessage> </samlp:Status> </samlp:Response> </soapenv:Body> +</soapenv:Envelope>
\ No newline at end of file diff --git a/id/server/modules/moa-id-modules-saml1/src/main/resources/soap_success.vm b/id/server/modules/moa-id-modules-saml1/src/main/resources/soap_success.vm new file mode 100644 index 000000000..7dad2c259 --- /dev/null +++ b/id/server/modules/moa-id-modules-saml1/src/main/resources/soap_success.vm @@ -0,0 +1,4 @@ +<?xml version="1.0" encoding="UTF-8"?> +<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <soapenv:Body>$assertion</soapenv:Body> +</soapenv:Envelope>
\ No newline at end of file diff --git a/id/server/modules/moa-id-modules-saml1/src/main/resources/wsdl/MOA-ID-1.x.vm b/id/server/modules/moa-id-modules-saml1/src/main/resources/wsdl/MOA-ID-1.x.vm new file mode 100644 index 000000000..74be59723 --- /dev/null +++ b/id/server/modules/moa-id-modules-saml1/src/main/resources/wsdl/MOA-ID-1.x.vm @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8"?> +<definitions name="MOA" targetNamespace="http://reference.e-government.gv.at/namespace/moa/20020822#" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://reference.e-government.gv.at/namespace/moa/20020822#" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:samlp="urn:oasis:names:tc:SAML:1.0:protocol" xmlns:moa="http://reference.e-government.gv.at/namespace/moa/20020822#" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.xmlsoap.org/wsdl/ http://schemas.xmlsoap.org/wsdl/"> + <import namespace="http://reference.e-government.gv.at/namespace/moa/20020822#" location="$endpoint?xsd"/> + <message name="GetAuthenticationDataInput"> + <part name="body" element="samlp:Request"/> + </message> + <message name="GetAuthenticationDataOutput"> + <part name="body" element="samlp:Response"/> + </message> + <message name="MOAFault"> + <part name="body" element="moa:ErrorResponse"/> + </message> + <portType name="IdentificationPortType"> + <operation name="getAuthenticationData"> + <input message="tns:GetAuthenticationDataInput"/> + <output message="tns:GetAuthenticationDataOutput"/> + <fault name="MOAFault" message="tns:MOAFault"/> + </operation> + </portType> + <binding name="IdentificationBinding" type="tns:IdentificationPortType" xsi:schemaLocation="http://schemas.xmlsoap.org/wsdl/soap/ http://schemas.xmlsoap.org/wsdl/soap/"> + <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/> + <operation name="getAuthenticationData"> + <soap:operation soapAction="urn:GetAuthenticationDataAction"/> + <input> + <soap:body use="literal" namespace="http://reference.e-government.gv.at/namespace/moa/20020822#"/> + </input> + <output> + <soap:body use="literal" namespace="http://reference.e-government.gv.at/namespace/moa/20020822#"/> + </output> + <fault name="MOAFault"> + <soap:fault name="MOAFault" use="literal" namespace="http://reference.e-government.gv.at/namespace/moa/20020822#"/> + </fault> + </operation> + </binding> + <service name="GetAuthenticationDataService"> + <port name="IdentificationPort" binding="tns:IdentificationBinding"> + <soap:address location="$endpoint"/> + </port> + </service> +</definitions> diff --git a/id/server/modules/moa-id-modules-saml1/src/main/resources/wsdl/MOA-SPSS-1.2.vm b/id/server/modules/moa-id-modules-saml1/src/main/resources/wsdl/MOA-SPSS-1.2.vm new file mode 100644 index 000000000..4c86626a0 --- /dev/null +++ b/id/server/modules/moa-id-modules-saml1/src/main/resources/wsdl/MOA-SPSS-1.2.vm @@ -0,0 +1,528 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- MOA SP/SS 1.2 Schema --> +<xsd:schema + targetNamespace="http://reference.e-government.gv.at/namespace/moa/20020822#" + xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:xsd="http://www.w3.org/2001/XMLSchema" + xmlns="http://reference.e-government.gv.at/namespace/moa/20020822#" + elementFormDefault="qualified" attributeFormDefault="unqualified" + version="1.2"> + <xsd:import namespace="http://www.w3.org/2000/09/xmldsig#" + schemaLocation="http://www.w3.org/TR/xmldsig-core/xmldsig-core-schema.xsd" /> + <xsd:import namespace="http://www.w3.org/XML/1998/namespace" + schemaLocation="http://www.w3.org/2001/xml.xsd" /> + <!--########## Create XML Signature ### --> + <!--### Create XML Signature Request ### --> + <xsd:element name="CreateXMLSignatureRequest"> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="CreateXMLSignatureRequestType" /> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + <xsd:complexType name="CreateXMLSignatureRequestType"> + <xsd:sequence> + <xsd:element name="KeyIdentifier" type="KeyIdentifierType" /> + <xsd:element name="SingleSignatureInfo" maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation>Ermöglichung der Stapelsignatur durch + wiederholte Angabe dieses Elements</xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="DataObjectInfo" maxOccurs="unbounded"> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="DataObjectInfoType"> + <xsd:attribute name="ChildOfManifest" type="xsd:boolean" + use="optional" default="false" /> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + <xsd:element name="CreateSignatureInfo" minOccurs="0"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="CreateSignatureEnvironment" + type="ContentOptionalRefType" /> + <xsd:choice> + <xsd:annotation> + <xsd:documentation>Auswahl: Entweder explizite Angabe des + Signaturorts sowie ggf. sinnvoller Supplements im Zshg. mit + der Signaturumgebung, oder Verweis auf ein benanntes Profil + </xsd:documentation> + </xsd:annotation> + <xsd:element ref="CreateSignatureEnvironmentProfile" /> + <xsd:element name="CreateSignatureEnvironmentProfileID" + type="ProfileIdentifierType" /> + </xsd:choice> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + </xsd:sequence> + <xsd:attribute name="SecurityLayerConformity" type="xsd:boolean" + use="optional" default="true" /> + </xsd:complexType> + </xsd:element> + </xsd:sequence> + </xsd:complexType> + <!--### Create XML Signature Response ### --> + <xsd:complexType name="CreateXMLSignatureResponseType"> + <xsd:choice maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation>Kardinalität 1..oo erlaubt die Antwort auf eine + Stapelsignatur-Anfrage</xsd:documentation> + </xsd:annotation> + <xsd:element name="SignatureEnvironment"> + <xsd:annotation> + <xsd:documentation>Resultat, falls die Signaturerstellung + erfolgreich war</xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:sequence> + <xsd:any namespace="##any" processContents="lax" /> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:element ref="ErrorResponse" /> + </xsd:choice> + </xsd:complexType> + <xsd:element name="CreateXMLSignatureResponse" type="CreateXMLSignatureResponseType" /> + <!--########## Verify CMS Signature ### --> + <!--### Verifiy CMS Signature Request ### --> + <xsd:element name="VerifyCMSSignatureRequest"> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="VerifyCMSSignatureRequestType"> + <xsd:attribute name="Signatories" type="SignatoriesType" + use="optional" default="1" /> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + <xsd:complexType name="VerifyCMSSignatureRequestType"> + <xsd:sequence> + <xsd:element name="DateTime" type="xsd:dateTime" + minOccurs="0" /> + <xsd:element name="CMSSignature" type="xsd:base64Binary" /> + <xsd:element name="DataObject" type="CMSDataObjectOptionalMetaType" + minOccurs="0" /> + <xsd:element name="TrustProfileID"> + <xsd:annotation> + <xsd:documentation>mit diesem Profil wird eine Menge von + vertrauenswürdigen Wurzelzertifikaten spezifiziert + </xsd:documentation> + </xsd:annotation> + </xsd:element> + </xsd:sequence> + </xsd:complexType> + <!--### Verify CMS Signature Response ### --> + <xsd:element name="VerifyCMSSignatureResponse" type="VerifyCMSSignatureResponseType" /> + <xsd:complexType name="VerifyCMSSignatureResponseType"> + <xsd:sequence maxOccurs="unbounded"> + <xsd:element name="SignerInfo" type="dsig:KeyInfoType"> + <xsd:annotation> + <xsd:documentation>only ds:X509Data and RetrievalMethod is + supported; QualifiedCertificate is included as + X509Data/any;publicAuthority is included as X509Data/any + </xsd:documentation> + </xsd:annotation> + </xsd:element> + <xsd:element name="SignatureCheck" type="CheckResultType" /> + <xsd:element name="CertificateCheck" type="CheckResultType" /> + </xsd:sequence> + </xsd:complexType> + <!--########## Verify XML Signature ### --> + <!--### Verify XML Signature Request ### --> + <xsd:element name="VerifyXMLSignatureRequest" type="VerifyXMLSignatureRequestType" /> + <xsd:complexType name="VerifyXMLSignatureRequestType"> + <xsd:sequence> + <xsd:element name="DateTime" type="xsd:dateTime" + minOccurs="0" /> + <xsd:element name="VerifySignatureInfo"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="VerifySignatureEnvironment" type="ContentOptionalRefType" /> + <xsd:element name="VerifySignatureLocation" type="xsd:token" /> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:choice minOccurs="0" maxOccurs="unbounded"> + <xsd:element ref="SupplementProfile" /> + <xsd:element name="SupplementProfileID" type="xsd:string" /> + </xsd:choice> + <xsd:element name="SignatureManifestCheckParams" + minOccurs="0"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="ReferenceInfo" type="VerifyTransformsDataType" + maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation>Pro dsig:Reference-Element in der zu + überprüfenden XML-Signatur muss hier ein ReferenceInfo-Element + erscheinen. Die Reihenfolge der einzelnen ReferenceInfo + Elemente entspricht jener der dsig:Reference Elemente in der + XML-Signatur.</xsd:documentation> + </xsd:annotation> + </xsd:element> + </xsd:sequence> + <xsd:attribute name="ReturnReferenceInputData" type="xsd:boolean" + use="optional" default="true" /> + </xsd:complexType> + </xsd:element> + <xsd:element name="ReturnHashInputData" minOccurs="0" /> + <xsd:element name="TrustProfileID"> + <xsd:annotation> + <xsd:documentation>mit diesem Profil wird eine Menge von + vertrauenswürdigen Wurzelzertifikaten spezifiziert + </xsd:documentation> + </xsd:annotation> + </xsd:element> + </xsd:sequence> + </xsd:complexType> + <!--### Verify XML Signature Response ### --> + <xsd:element name="VerifyXMLSignatureResponse" type="VerifyXMLSignatureResponseType" /> + <xsd:complexType name="VerifyXMLSignatureResponseType"> + <xsd:sequence> + <xsd:element name="SignerInfo" type="dsig:KeyInfoType"> + <xsd:annotation> + <xsd:documentation>only ds:X509Data and ds:RetrievalMethod is + supported; QualifiedCertificate is included as X509Data/any; + PublicAuthority is included as X509Data/any</xsd:documentation> + </xsd:annotation> + </xsd:element> + <xsd:element name="HashInputData" type="ContentExLocRefBaseType" + minOccurs="0" maxOccurs="unbounded" /> + <xsd:element name="ReferenceInputData" type="ContentExLocRefBaseType" + minOccurs="0" maxOccurs="unbounded" /> + <xsd:element name="SignatureCheck" type="ReferencesCheckResultType" /> + <xsd:element name="SignatureManifestCheck" type="ReferencesCheckResultType" + minOccurs="0" /> + <xsd:element name="XMLDSIGManifestCheck" type="ManifestRefsCheckResultType" + minOccurs="0" maxOccurs="unbounded" /> + <xsd:element name="CertificateCheck" type="CheckResultType" /> + </xsd:sequence> + </xsd:complexType> + <xsd:simpleType name="ProfileIdentifierType"> + <xsd:restriction base="xsd:token" /> + </xsd:simpleType> + <xsd:complexType name="MetaInfoType"> + <xsd:sequence> + <xsd:element name="MimeType" type="MimeTypeType" /> + <xsd:element name="Description" type="xsd:anyURI" + minOccurs="0" /> + <xsd:any namespace="##other" minOccurs="0" maxOccurs="unbounded" /> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="FinalDataMetaInfoType"> + <xsd:complexContent> + <xsd:extension base="MetaInfoType"> + <xsd:sequence> + <xsd:element name="Type" type="xsd:anyURI" minOccurs="0" /> + </xsd:sequence> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + <xsd:complexType name="DataObjectInfoType"> + <xsd:sequence> + <xsd:element name="DataObject"> + <xsd:complexType> + <xsd:complexContent> + <xsd:extension base="ContentOptionalRefType" /> + </xsd:complexContent> + </xsd:complexType> + </xsd:element> + <xsd:choice> + <xsd:annotation> + <xsd:documentation>Auswahl: Entweder explizite Angabe EINER + Transformationskette inklusive ggf. sinnvoller Supplements oder + Verweis auf ein benanntes Profil</xsd:documentation> + </xsd:annotation> + <xsd:element ref="CreateTransformsInfoProfile" /> + <xsd:element name="CreateTransformsInfoProfileID" type="ProfileIdentifierType" /> + </xsd:choice> + </xsd:sequence> + <xsd:attribute name="Structure" use="required"> + <xsd:simpleType> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="detached" /> + <xsd:enumeration value="enveloping" /> + </xsd:restriction> + </xsd:simpleType> + </xsd:attribute> + </xsd:complexType> + <xsd:complexType name="TransformsInfoType"> + <xsd:sequence> + <xsd:element ref="dsig:Transforms" minOccurs="0" /> + <xsd:element name="FinalDataMetaInfo" type="FinalDataMetaInfoType" /> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="XMLDataObjectAssociationType"> + <xsd:sequence> + <xsd:element name="MetaInfo" type="MetaInfoType" + minOccurs="0" /> + <xsd:element name="Content" type="ContentRequiredRefType" /> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="CMSDataObjectOptionalMetaType"> + <xsd:sequence> + <xsd:element name="MetaInfo" type="MetaInfoType" + minOccurs="0" /> + <xsd:element name="Content" type="CMSContentBaseType" /> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="CMSContentBaseType"> + <xsd:complexContent> + <xsd:restriction base="ContentOptionalRefType"> + <xsd:choice minOccurs="0"> + <xsd:element name="Base64Content" type="xsd:base64Binary" /> + </xsd:choice> + </xsd:restriction> + </xsd:complexContent> + </xsd:complexType> + <xsd:complexType name="CheckResultType"> + <xsd:sequence> + <xsd:element name="Code" type="xsd:nonNegativeInteger" /> + <xsd:element name="Info" type="AnyChildrenType" + minOccurs="0" /> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="ReferencesCheckResultType"> + <xsd:complexContent> + <xsd:restriction base="CheckResultType"> + <xsd:sequence> + <xsd:element name="Code" type="xsd:nonNegativeInteger" /> + <xsd:element name="Info" type="ReferencesCheckResultInfoType" + minOccurs="0" /> + </xsd:sequence> + </xsd:restriction> + </xsd:complexContent> + </xsd:complexType> + <xsd:complexType name="ReferencesCheckResultInfoType" + mixed="true"> + <xsd:complexContent mixed="true"> + <xsd:restriction base="AnyChildrenType"> + <xsd:sequence> + <xsd:any namespace="##other" processContents="lax" + minOccurs="0" maxOccurs="unbounded" /> + <xsd:element name="FailedReference" type="xsd:positiveInteger" + minOccurs="0" maxOccurs="unbounded" /> + </xsd:sequence> + </xsd:restriction> + </xsd:complexContent> + </xsd:complexType> + <xsd:complexType name="ManifestRefsCheckResultType"> + <xsd:complexContent> + <xsd:restriction base="CheckResultType"> + <xsd:sequence> + <xsd:element name="Code" type="xsd:nonNegativeInteger" /> + <xsd:element name="Info" type="ManifestRefsCheckResultInfoType" /> + </xsd:sequence> + </xsd:restriction> + </xsd:complexContent> + </xsd:complexType> + <xsd:complexType name="ManifestRefsCheckResultInfoType" + mixed="true"> + <xsd:complexContent mixed="true"> + <xsd:restriction base="AnyChildrenType"> + <xsd:sequence> + <xsd:any namespace="##other" processContents="lax" + minOccurs="0" maxOccurs="unbounded" /> + <xsd:element name="FailedReference" type="xsd:positiveInteger" + minOccurs="0" maxOccurs="unbounded" /> + <xsd:element name="ReferringSigReference" type="xsd:positiveInteger" /> + </xsd:sequence> + </xsd:restriction> + </xsd:complexContent> + </xsd:complexType> + <!--########## Error Response ### --> + <xsd:element name="ErrorResponse" type="ErrorResponseType"> + <xsd:annotation> + <xsd:documentation>Resultat, falls die Signaturerstellung gescheitert + ist</xsd:documentation> + </xsd:annotation> + </xsd:element> + <xsd:complexType name="ErrorResponseType"> + <xsd:sequence> + <xsd:element name="ErrorCode" type="xsd:integer" /> + <xsd:element name="Info" type="xsd:string" /> + </xsd:sequence> + </xsd:complexType> + <!--########## Auxiliary Types ### --> + <xsd:simpleType name="KeyIdentifierType"> + <xsd:restriction base="xsd:string" /> + </xsd:simpleType> + <xsd:simpleType name="KeyStorageType"> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="Software" /> + <xsd:enumeration value="Hardware" /> + </xsd:restriction> + </xsd:simpleType> + <xsd:simpleType name="MimeTypeType"> + <xsd:restriction base="xsd:token" /> + </xsd:simpleType> + <xsd:complexType name="AnyChildrenType" mixed="true"> + <xsd:sequence> + <xsd:any namespace="##any" processContents="lax" minOccurs="0" + maxOccurs="unbounded" /> + </xsd:sequence> + </xsd:complexType> + <xsd:complexType name="XMLContentType" mixed="true"> + <xsd:complexContent mixed="true"> + <xsd:extension base="AnyChildrenType"> + <xsd:attribute ref="xml:space" use="optional" /> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + <xsd:complexType name="ContentBaseType"> + <xsd:choice minOccurs="0"> + <xsd:element name="Base64Content" type="xsd:base64Binary" /> + <xsd:element name="XMLContent" type="XMLContentType" /> + <xsd:element name="LocRefContent" type="xsd:anyURI" /> + </xsd:choice> + </xsd:complexType> + <xsd:complexType name="ContentExLocRefBaseType"> + <xsd:complexContent> + <xsd:restriction base="ContentBaseType"> + <xsd:choice minOccurs="0"> + <xsd:element name="Base64Content" type="xsd:base64Binary" /> + <xsd:element name="XMLContent" type="XMLContentType" /> + </xsd:choice> + </xsd:restriction> + </xsd:complexContent> + </xsd:complexType> + <xsd:complexType name="ContentOptionalRefType"> + <xsd:complexContent> + <xsd:extension base="ContentBaseType"> + <xsd:attribute name="Reference" type="xsd:anyURI" use="optional" /> + </xsd:extension> + </xsd:complexContent> + </xsd:complexType> + <xsd:complexType name="ContentRequiredRefType"> + <xsd:complexContent> + <xsd:restriction base="ContentOptionalRefType"> + <xsd:choice minOccurs="0"> + <xsd:element name="Base64Content" type="xsd:base64Binary" /> + <xsd:element name="XMLContent" type="XMLContentType" /> + <xsd:element name="LocRefContent" type="xsd:anyURI" /> + </xsd:choice> + <xsd:attribute name="Reference" type="xsd:anyURI" use="required" /> + </xsd:restriction> + </xsd:complexContent> + </xsd:complexType> + <xsd:complexType name="VerifyTransformsDataType"> + <xsd:choice maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation>Ein oder mehrere Transformationswege können von + der Applikation an MOA mitgeteilt werden. Die zu prüfende Signatur + hat zumindest einem dieser Transformationswege zu entsprechen. Die + Angabe kann explizit oder als Profilbezeichner erfolgen. + </xsd:documentation> + </xsd:annotation> + <xsd:element ref="VerifyTransformsInfoProfile" /> + <xsd:element name="VerifyTransformsInfoProfileID" type="xsd:string"> + <xsd:annotation> + <xsd:documentation>Profilbezeichner für einen Transformationsweg + </xsd:documentation> + </xsd:annotation> + </xsd:element> + </xsd:choice> + </xsd:complexType> + <xsd:element name="QualifiedCertificate" /> + <xsd:element name="PublicAuthority" type="PublicAuthorityType" /> + <xsd:complexType name="PublicAuthorityType"> + <xsd:sequence> + <xsd:element name="Code" type="xsd:string" minOccurs="0" /> + </xsd:sequence> + </xsd:complexType> + <xsd:simpleType name="SignatoriesType"> + <xsd:union memberTypes="AllSignatoriesType"> + <xsd:simpleType> + <xsd:list itemType="xsd:positiveInteger" /> + </xsd:simpleType> + </xsd:union> + </xsd:simpleType> + <xsd:simpleType name="AllSignatoriesType"> + <xsd:restriction base="xsd:string"> + <xsd:enumeration value="all" /> + </xsd:restriction> + </xsd:simpleType> + <xsd:complexType name="CreateSignatureLocationType"> + <xsd:simpleContent> + <xsd:extension base="xsd:token"> + <xsd:attribute name="Index" type="xsd:nonNegativeInteger" + use="required" /> + </xsd:extension> + </xsd:simpleContent> + </xsd:complexType> + <xsd:complexType name="TransformParameterType"> + <xsd:choice minOccurs="0"> + <xsd:annotation> + <xsd:documentation>Die Angabe des Transformationsparameters + (explizit oder als Hashwert) kann unterlassen werden, wenn die + Applikation von der Unveränderlichkeit des Inhalts der in + "Transformationsparamter", Attribut "URI" angegebenen URI ausgehen + kann.</xsd:documentation> + </xsd:annotation> + <xsd:element name="Base64Content" type="xsd:base64Binary"> + <xsd:annotation> + <xsd:documentation>Der Transformationsparameter explizit angegeben. + </xsd:documentation> + </xsd:annotation> + </xsd:element> + <xsd:element name="Hash"> + <xsd:annotation> + <xsd:documentation>Der Hashwert des Transformationsparameters. + </xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:sequence> + <xsd:element ref="dsig:DigestMethod" /> + <xsd:element ref="dsig:DigestValue" /> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + </xsd:choice> + <xsd:attribute name="URI" type="xsd:anyURI" use="required" /> + </xsd:complexType> + <xsd:element name="CreateSignatureEnvironmentProfile"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="CreateSignatureLocation" type="CreateSignatureLocationType" /> + <xsd:element name="Supplement" type="XMLDataObjectAssociationType" + minOccurs="0" maxOccurs="unbounded" /> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:element name="VerifyTransformsInfoProfile"> + <xsd:annotation> + <xsd:documentation>Explizite Angabe des Transformationswegs + </xsd:documentation> + </xsd:annotation> + <xsd:complexType> + <xsd:sequence> + <xsd:element ref="dsig:Transforms" minOccurs="0" /> + <xsd:element name="TransformParameter" type="TransformParameterType" + minOccurs="0" maxOccurs="unbounded"> + <xsd:annotation> + <xsd:documentation>Alle impliziten Transformationsparameter, die + zum Durchlaufen der oben angeführten Transformationskette bekannt + sein müssen, müssen hier angeführt werden. Das Attribut "URI" + bezeichnet den Transformationsparameter in exakt jener Weise, wie + er in der zu überprüfenden Signatur gebraucht wird. + </xsd:documentation> + </xsd:annotation> + </xsd:element> + </xsd:sequence> + </xsd:complexType> + </xsd:element> + <xsd:element name="Supplement" type="XMLDataObjectAssociationType" /> + <xsd:element name="SupplementProfile" type="XMLDataObjectAssociationType" /> + <xsd:element name="CreateTransformsInfoProfile"> + <xsd:complexType> + <xsd:sequence> + <xsd:element name="CreateTransformsInfo" type="TransformsInfoType" /> + <xsd:element ref="Supplement" minOccurs="0" maxOccurs="unbounded" /> + </xsd:sequence> + </xsd:complexType> + </xsd:element> +</xsd:schema> diff --git a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java index a7d7b9759..4e5bed97c 100644 --- a/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java +++ b/id/server/modules/module-monitoring/src/main/java/at/gv/egovernment/moa/id/auth/servlet/MonitoringServlet.java @@ -28,35 +28,38 @@ import java.util.Arrays; import java.util.List; import javax.servlet.ServletException; -import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; import at.gv.egovernment.moa.id.monitoring.TestManager; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; -@WebServlet(name = "MonitoringServlet", value = "/MonitoringServlet") -public class MonitoringServlet extends AuthServlet { +@Controller +public class MonitoringServlet { - private static final long serialVersionUID = 1L; private static final String REQUEST_ATTR_MODULE = "module"; + @Autowired private AuthConfiguration authConfig; + public MonitoringServlet() { super(); Logger.debug("Registering servlet " + getClass().getName() + " with mapping '/MonitoringServlet'."); } - protected void doGet(HttpServletRequest req, HttpServletResponse resp) + @RequestMapping(value = "/MonitoringServlet", method = RequestMethod.GET) + public void getStatusInformation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - try { - AuthConfiguration config = AuthConfigurationProviderFactory.getInstance(); - - if (config.isMonitoringActive()) { + try { + if (authConfig.isMonitoringActive()) { Logger.debug("Monitoring Servlet received request"); TestManager tests = TestManager.getInstance(); @@ -71,7 +74,7 @@ public class MonitoringServlet extends AuthServlet { } else { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/html;charset=UTF-8"); - resp.getWriter().write(getHtml(config.getMonitoringMessageSuccess())); + resp.getWriter().write(getHtml(authConfig.getMonitoringMessageSuccess())); Logger.info("Monitoring Servlet finished without errors"); } @@ -84,7 +87,7 @@ public class MonitoringServlet extends AuthServlet { } else { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/html;charset=UTF-8"); - resp.getWriter().write(getHtml(config.getMonitoringMessageSuccess())); + resp.getWriter().write(getHtml(authConfig.getMonitoringMessageSuccess())); Logger.info("Monitoring Servlet finished without errors"); } diff --git a/id/server/modules/module-stork/pom.xml b/id/server/modules/module-stork/pom.xml deleted file mode 100644 index b52c10391..000000000 --- a/id/server/modules/module-stork/pom.xml +++ /dev/null @@ -1,66 +0,0 @@ -<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.server.modules</groupId> - <artifactId>moa-id-modules</artifactId> - <version>${moa-id-version}</version> - </parent> - - <groupId>MOA.id.server.modules</groupId> - <artifactId>moa-id-module-stork</artifactId> - <version>${moa-id-version}</version> - <packaging>jar</packaging> - - <name>MOA ID-Module STORK</name> - - <properties> - <repositoryPath>${basedir}/../../../../repository</repositoryPath> - </properties> - - <dependencies> - - <dependency> - <groupId>eu.stork</groupId> - <artifactId>DocumentService</artifactId> - <version>0.0.1-SNAPSHOT</version> - <classifier>classes</classifier> - <exclusions> - <exclusion> - <artifactId>axis</artifactId> - <groupId>org.apache.axis</groupId> - </exclusion> - <exclusion> - <artifactId>bcprov-jdk16</artifactId> - <groupId>org.bouncycastle</groupId> - </exclusion> - <exclusion> - <artifactId>jaxws-tools</artifactId> - <groupId>com.sun.xml.ws</groupId> - </exclusion> - </exclusions> - </dependency> - - <dependency> - <groupId>eu.stork</groupId> - <artifactId>SamlEngine</artifactId> - <version>1.5.1</version> - </dependency> - - <dependency> - <groupId>org.springframework</groupId> - <artifactId>spring-test</artifactId> - <scope>test</scope> - </dependency> - - <dependency> - <groupId>junit</groupId> - <artifactId>junit</artifactId> - <version>${junit.version}</version> - <scope>test</scope> - </dependency> - - </dependencies> - -</project> diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java deleted file mode 100644 index 41384690e..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthModuleImpl.java +++ /dev/null @@ -1,39 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork;
-
-import org.apache.commons.lang3.StringUtils;
-
-import at.gv.egovernment.moa.id.auth.modules.AuthModule;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-
-/**
- * Module descriptor for an auth module providing stork authentication related processes.
- * @author tknall
- */
-public class STORKAuthModuleImpl implements AuthModule {
-
- private int priority = 0;
-
- @Override
- public int getPriority() {
- return priority;
- }
-
- /**
- * Sets the priority of this module. Default value is {@code 0}.
- * @param priority The priority.
- */
- public void setPriority(int priority) {
- this.priority = priority;
- }
-
- @Override
- public String selectProcess(ExecutionContext context) {
- return StringUtils.isNotBlank((String) context.get("ccc")) ? "STORKAuthentication" : null;
- }
-
- @Override
- public String[] getProcessDefinitions() {
- return new String[] { "classpath:at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthentication.process.xml" };
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java deleted file mode 100644 index efc1cd498..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServlet.java +++ /dev/null @@ -1,113 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-import javax.servlet.annotation.WebServlet;
-import javax.servlet.http.HttpServletRequest;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.xpath.XPath;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathFactory;
-
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.springframework.util.xml.SimpleNamespaceContext;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants;
-import at.gv.egovernment.moa.id.auth.servlet.ProcessEngineSignalServlet;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.Base64Utils;
-
-/**
- * STORK module specific servlet, overloading {@link ProcessEngineSignalServlet}'s method
- * {@linkplain ProcessEngineSignalServlet#getMoaSessionId(HttpServletRequest) getMoaSessionId(HttpServletRequest)}
- * extending its capabilities for retrieving the current moa session id.
- * <p/>
- * This {@code STORKProcessEngineSignalServlet} tries to resolve the moa session id using the following strategy:
- * <ul>
- * <li>Use the super class' approach, looking at the HttpServletRequest parameter
- * {@link MOAIDAuthConstants#PARAM_SESSIONID}.</li>
- * <li>Evaluate the request parameter "{@code RelayState}".
- * <li>Finally evaluate the SAML response, which should come base64 encoded as request parameter "{@code SAMLResponse}".</li>
- * </ul>
- *
- * @author tknall
- *
- */
-@WebServlet(urlPatterns = { "/PEPSConnectorWithLocalSigning", "/PEPSConnector" }, loadOnStartup = 1)
-public class STORKProcessEngineSignalServlet extends ProcessEngineSignalServlet {
-
- private static final long serialVersionUID = 1L;
-
- public STORKProcessEngineSignalServlet() {
- super();
- Logger.debug("Registering servlet " + getClass().getName() + " with mappings '/PEPSConnectorWithLocalSigning', '/PEPSConnector'.");
- }
-
- @Override
- public String getMoaSessionId(HttpServletRequest request) {
- String sessionId = super.getMoaSessionId(request);
-
- try {
-
- // use SAML2 relayState
- if (sessionId == null) {
- sessionId = StringEscapeUtils.escapeHtml(request.getParameter("RelayState"));
- }
-
- // take from InResponseTo attribute of SAMLResponse
- if (sessionId == null) {
- String base64SamlToken = request.getParameter("SAMLResponse");
- if (base64SamlToken != null) {
- byte[] samlToken = Base64Utils.decode(base64SamlToken, false);
- Document samlResponse = parseDocument(new ByteArrayInputStream(samlToken));
-
- XPath xPath = XPathFactory.newInstance().newXPath();
- SimpleNamespaceContext nsContext = new SimpleNamespaceContext();
- nsContext.bindNamespaceUri("saml2p", "urn:oasis:names:tc:SAML:2.0:protocol");
- xPath.setNamespaceContext(nsContext);
- XPathExpression expression = xPath.compile("string(/saml2p:Response/@InResponseTo)");
- sessionId = (String) expression.evaluate(samlResponse, XPathConstants.STRING);
- sessionId = StringEscapeUtils.escapeHtml(StringUtils.trimToNull(sessionId));
- } else {
- Logger.warn("No parameter 'SAMLResponse'. Unable to retrieve MOA session id.");
- }
- }
-
- } catch (Exception e) {
- Logger.warn("Unable to retrieve moa session id.", e);
- }
-
- return sessionId;
- }
-
- /**
- * Parses a xml document (namespace aware).
- *
- * @param in
- * The input stream.
- * @return The DOM document.
- * @throws ParserConfigurationException
- * Thrown in case of configuration error.
- * @throws IOException
- * Thrown in case of error reading from the input stream.
- * @throws SAXException
- * Thrown in case of error parsing the document.
- */
- public static Document parseDocument(InputStream in) throws ParserConfigurationException, SAXException, IOException {
- DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
- documentBuilderFactory.setNamespaceAware(true);
- documentBuilderFactory.setIgnoringElementContentWhitespace(false);
- documentBuilderFactory.setValidating(false);
- DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
- return documentBuilder.parse(in);
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java deleted file mode 100644 index 939390847..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/AbstractPepsConnectorWithLocalSigningTask.java +++ /dev/null @@ -1,225 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import iaik.x509.X509Certificate;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.security.cert.CertificateException;
-import java.util.HashMap;
-
-import javax.activation.DataSource;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.bind.JAXBException;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactoryConfigurationError;
-
-import org.apache.commons.io.IOUtils;
-import org.xml.sax.SAXException;
-
-import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
-import at.gv.egovernment.moa.id.auth.data.IdentityLink;
-import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.BKUException;
-import at.gv.egovernment.moa.id.auth.exception.BuildException;
-import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.exception.ParseException;
-import at.gv.egovernment.moa.id.auth.exception.ServiceException;
-import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask;
-import at.gv.egovernment.moa.id.auth.stork.STORKException;
-import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor;
-import at.gv.egovernment.moa.id.config.ConfigurationException;
-import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
-import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
-import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.spss.MOAException;
-import at.gv.egovernment.moa.spss.api.SPSSFactory;
-import at.gv.egovernment.moa.spss.api.SignatureVerificationService;
-import at.gv.egovernment.moa.spss.api.common.Content;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureInfo;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifySignatureLocation;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureRequest;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse;
-import at.gv.util.xsd.xmldsig.SignatureType;
-import at.gv.util.xsd.xmldsig.X509DataType;
-import eu.stork.oasisdss.api.LightweightSourceResolver;
-import eu.stork.oasisdss.api.exceptions.ApiUtilsException;
-import eu.stork.oasisdss.api.exceptions.UtilsException;
-import eu.stork.oasisdss.profile.SignResponse;
-import eu.stork.peps.auth.commons.IPersonalAttributeList;
-
-public abstract class AbstractPepsConnectorWithLocalSigningTask extends AbstractAuthServletTask {
-
- public static final String PEPSCONNECTOR_SERVLET_URL_PATTERN = "/PEPSConnectorWithLocalSigning";
-
- String getCitizienSignatureFromSignResponse(SignResponse dssSignResponse) throws IllegalArgumentException,
- TransformerConfigurationException, UtilsException, TransformerException,
- TransformerFactoryConfigurationError, IOException, ApiUtilsException {
- // fetch signed doc
- DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse);
- if (ds == null) {
- throw new ApiUtilsException("No datasource found in response");
- }
-
- InputStream incoming = ds.getInputStream();
- String citizenSignature = IOUtils.toString(incoming);
- incoming.close();
-
- return citizenSignature;
- }
-
- void SZRGInsertion(AuthenticationSession moaSession, IPersonalAttributeList personalAttributeList,
- String authnContextClassRef, String citizenSignature) throws STORKException, MOAIDException {
- Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)");
- Logger.debug("Citizen signature will be verified by SZR Gateway!");
-
- Logger.debug("fetching OAParameters from database");
-
- OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(
- moaSession.getPublicOAURLPrefix());
- if (oaParam == null)
- throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });
-
- // retrieve target
- // TODO: check in case of SSO!!!
- String targetType = null;
- if (oaParam.getBusinessService()) {
- String id = oaParam.getIdentityLinkDomainIdentifier();
- if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
- targetType = id;
- else
- targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier();
- } else {
- targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
- }
-
- Logger.debug("Starting connecting SZR Gateway");
- // contact SZR Gateway
- IdentityLink identityLink = null;
-
- identityLink = STORKResponseProcessor.connectToSZRGateway(personalAttributeList, oaParam.getFriendlyName(),
- targetType, null, oaParam.getMandateProfiles(), citizenSignature);
- Logger.debug("SZR communication was successfull");
-
- if (identityLink == null) {
- Logger.error("SZR Gateway did not return an identity link.");
- throw new MOAIDException("stork.10", null);
- }
- Logger.info("Received Identity Link from SZR Gateway");
- moaSession.setIdentityLink(identityLink);
-
- Logger.debug("Adding addtional STORK attributes to MOA session");
- moaSession.setStorkAttributes(personalAttributeList);
-
- // We don't have BKUURL, setting from null to "Not applicable"
- moaSession.setBkuURL("Not applicable (STORK Authentication)");
-
- // free for single use
- moaSession.setAuthenticatedUsed(false);
-
- // stork did the authentication step
- moaSession.setAuthenticated(true);
-
- // TODO: found better solution, but QAA Level in response could be not supported yet
- try {
- if (authnContextClassRef == null)
- authnContextClassRef = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel();
- moaSession.setQAALevel(authnContextClassRef);
-
- } catch (Throwable e) {
- Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
- moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
-
- }
-
- }
-
- X509Certificate getSignerCertificate(String citizenSignature) throws CertificateException, JAXBException,
- UnsupportedEncodingException {
- JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName());
- SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller().unmarshal(
- IOUtils.toInputStream(citizenSignature))).getValue();
-
- // extract certificate
- for (Object current : root.getKeyInfo().getContent())
- if (((JAXBElement<?>) current).getValue() instanceof X509DataType) {
- for (Object currentX509Data : ((JAXBElement<X509DataType>) current).getValue()
- .getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
- JAXBElement<?> casted = ((JAXBElement<?>) currentX509Data);
- if (casted.getName().getLocalPart().equals("X509Certificate")) {
- return new X509Certificate(((String) casted.getValue()).getBytes("UTF-8"));
- }
- }
- }
- return null;
- }
-
- VerifyXMLSignatureResponse verifyXMLSignature(String signature) throws AuthenticationException, ParseException,
- BKUException, BuildException, ConfigurationException, ServiceException, UnsupportedEncodingException,
- SAXException, IOException, ParserConfigurationException, MOAException {
- // Based on MOA demo client
- // Factory und Service instanzieren
- SPSSFactory spssFac = SPSSFactory.getInstance();
- SignatureVerificationService sigVerifyService = SignatureVerificationService.getInstance();
-
- Content sigDocContent1 = spssFac.createContent(IOUtils.toInputStream(signature, "UTF-8"), null);
-
- // Position der zu prüfenden Signatur im Dokument angeben
- // (Nachdem im XPath-Ausdruck ein NS-Präfix verwendet wird, muss in einer Lookup-Tabelle
- // der damit bezeichnete Namenraum mitgegeben werden)
- HashMap nSMap = new HashMap();
- nSMap.put("dsig", "http://www.w3.org/2000/09/xmldsig#");
- VerifySignatureLocation sigLocation = spssFac.createVerifySignatureLocation("//dsig:Signature", nSMap);
-
- // Zu prüfendes Dokument und Signaturposition zusammenfassen
-
- VerifySignatureInfo sigInfo = spssFac.createVerifySignatureInfo(sigDocContent1, sigLocation);
-
- // Prüfrequest zusammenstellen
- VerifyXMLSignatureRequest verifyRequest = spssFac.createVerifyXMLSignatureRequest(null, // Wird Prüfzeit nicht
- // angegeben, wird
- // aktuelle Zeit
- // verwendet
- sigInfo, null, // Keine Ergänzungsobjekte notwendig
- null, // Signaturmanifest-Prüfung soll nicht durchgeführt werden
- false, // Hash-Inputdaten, d.h. tatsächlich signierte Daten werden nicht zurückgeliefert
- "MOAIDBuergerkartePersonenbindungMitTestkarten");// TODO load from config
- // "Test-Signaturdienste"); // ID des verwendeten Vertrauensprofils
-
- VerifyXMLSignatureResponse verifyResponse = null;
- try {
- // Aufruf der Signaturprüfung
- verifyResponse = sigVerifyService.verifyXMLSignature(verifyRequest);
- } catch (MOAException e) {
- // Service liefert Fehler
- System.err.println("Die Signaturprüfung hat folgenden Fehler geliefert:");
- System.err.println("Fehlercode: " + e.getMessageId());
- System.err.println("Fehlernachricht: " + e.getMessage());
- throw e;
- }
-
- return verifyResponse;
- }
-
- at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse convert(
- VerifyXMLSignatureResponse xMLVerifySignatureResponse) {
- at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse response = new at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse();
- response.setCertificateCheckCode(xMLVerifySignatureResponse.getCertificateCheck().getCode());
- response.setPublicAuthority(xMLVerifySignatureResponse.getSignerInfo().isPublicAuthority());
- // response.setPublicAuthorityCode(publicAuthorityCode)
- response.setQualifiedCertificate(xMLVerifySignatureResponse.getSignerInfo().isQualifiedCertificate());
- response.setSignatureCheckCode(xMLVerifySignatureResponse.getSignatureCheck().getCode());
- response.setSignatureManifestCheckCode(xMLVerifySignatureResponse.getSignatureManifestCheck().getCode());
- // response.setSigningDateTime()
- // response.setX509certificate(x509certificate)
- response.setXmlDSIGManifestCheckCode(xMLVerifySignatureResponse.getSignatureManifestCheck().getCode());
- // response.setXmlDSIGManigest(xMLVerifySignatureResponse.getSignatureManifestCheck())
- // response.setXmlDsigSubjectName(xmlDsigSubjectName)
- return response;
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java deleted file mode 100644 index 138776976..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/CreateStorkAuthRequestFormTask.java +++ /dev/null @@ -1,447 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import static at.gv.egovernment.moa.id.auth.MOAIDAuthConstants.PARAM_SESSIONID;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.math.BigInteger;
-import java.net.URL;
-import java.security.NoSuchAlgorithmException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang3.BooleanUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-import org.opensaml.common.IdentifierGenerator;
-import org.opensaml.common.impl.SecureRandomIdentifierGenerator;
-import org.w3c.dom.DOMException;
-
-import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
-import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
-import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
-import at.gv.egovernment.moa.id.auth.builder.CreateXMLSignatureRequestBuilder;
-import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
-import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
-import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask;
-import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
-import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
-import at.gv.egovernment.moa.id.config.ConfigurationException;
-import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
-import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
-import at.gv.egovernment.moa.id.config.stork.CPEPS;
-import at.gv.egovernment.moa.id.config.stork.STORKConfig;
-import at.gv.egovernment.moa.id.config.stork.StorkAttribute;
-import at.gv.egovernment.moa.id.moduls.IRequest;
-import at.gv.egovernment.moa.id.moduls.RequestStorage;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
-import at.gv.egovernment.moa.id.util.VelocityProvider;
-import at.gv.egovernment.moa.logging.Logger;
-import eu.stork.oasisdss.api.AdditionalProfiles;
-import eu.stork.oasisdss.api.ApiUtils;
-import eu.stork.oasisdss.api.Profiles;
-import eu.stork.oasisdss.api.QualityLevels;
-import eu.stork.oasisdss.api.SignatureTypes;
-import eu.stork.oasisdss.api.exceptions.ApiUtilsException;
-import eu.stork.oasisdss.profile.AnyType;
-import eu.stork.oasisdss.profile.DocumentType;
-import eu.stork.oasisdss.profile.SignRequest;
-import eu.stork.peps.auth.commons.PEPSUtil;
-import eu.stork.peps.auth.commons.PersonalAttribute;
-import eu.stork.peps.auth.commons.PersonalAttributeList;
-import eu.stork.peps.auth.commons.STORKAuthnRequest;
-import eu.stork.peps.auth.engine.STORKSAMLEngine;
-import eu.stork.peps.exceptions.STORKSAMLEngineException;
-
-/**
- * Creates a SAML2 STORK authentication request, embeds it in a form (in order to satisfy saml post binging) and returns the form withing the HttpServletResponse.<p/>
- * In detail:
- * <ul>
- * <li>Validates the stork configuration in order to make sure the selected country is supported.</li>
- * <li>Puts a flag ({@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}) into the ExecutionContext reflecting the capability of the C-PEPS to create xml signatures.</li>
- * <li>Invokes {@link AuthenticationServer#startSTORKAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationSession)} which</li>
- * <ul>
- * <li>Creates and signs a SAML2 stork authentication request.</li>
- * <li>Creates a signature request for auth block signature (either to be performed by the C-PEPS or locally).</li>
- * <li>Using the velocity template engine in order to create a form with the embedded stork request.</li>
- * <li>Writes the form to the response output stream.</li>
- * </ul>
- * </ul>
- * Expects:
- * <ul>
- * <li>HttpServletRequest parameter {@linkplain at.gv.egovernment.moa.id.auth.MOAIDAuthConstants#PARAM_SESSIONID PARAM_SESSIONID}</li>
- * <li>Property {@code ccc} set within the moa session.</li>
- * </ul>
- * Result:
- * <ul>
- * <li>Form containing a SAML2 Stork authentication request and an action url pointing to the selected C-PEPS.</li>
- * <li>Assertion consumer URL for C-PEPS set either to {@code /PEPSConnector} in case of a C-PEPS supporting xml signatures or {@code /PEPSConnectorWithLocalSigning} if the selected C-PEPS does not support xml signatures.</li>
- * <li>In case of a C-PEPS not supporting xml signature: moasession with set signedDoc property (containing the signature request for local signing).</li>
- * <li>ExecutionContext contains the boolean flag {@link #PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED}.
- * </ul>
- * Code taken from {@link StartAuthenticationBuilder#build(AuthenticationSession, HttpServletRequest, HttpServletResponse)}.<br/>
- * Using {@link AuthenticationServer#startSTORKAuthentication(HttpServletRequest, HttpServletResponse, AuthenticationSession)}
- * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse)
- */
-public class CreateStorkAuthRequestFormTask extends AbstractAuthServletTask {
-
- /**
- * Boolean value reflecting the capability of the selected c-peps of creating xml signatures.
- */
- public static final String PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED = "C-PEPS:XMLSignatureSupported";
-
- @Override
- public void execute(ExecutionContext executionContext, HttpServletRequest req, HttpServletResponse resp)
- throws TaskExecutionException {
-
- String pendingRequestID = null;
- String sessionID = null;
- try {
- setNoCachingHeaders(resp);
-
- sessionID = (String) executionContext.get(PARAM_SESSIONID);
- pendingRequestID = (String) executionContext.get("pendingRequestID");
- String ccc = (String) executionContext.get("CCC");
-
-
- // check parameter
- if (!ParamValidatorUtils.isValidSessionID(sessionID)) {
- throw new WrongParametersException("CreateStorkAuthRequestFormTask", PARAM_SESSIONID, "auth.12");
- }
- AuthenticationSession moasession = BaseAuthenticationServer.getSession(sessionID);
- IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
-
- if (StringUtils.isEmpty(ccc)) {
- // illegal state; task should not have been executed without a selected country
- throw new AuthenticationException("stork.22", new Object[] { sessionID });
-
- }
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_STORK_REQUESTED);
-
- STORKConfig storkConfig = AuthConfigurationProviderFactory.getInstance().getStorkConfig();
- if (!storkConfig.isSTORKAuthentication(moasession.getCcc())) {
- throw new AuthenticationException("stork.23", new Object[] { moasession.getCcc(), sessionID });
- }
-
- // STORK authentication
- // cpeps cannot be null
- CPEPS cpeps = storkConfig.getCPEPS(ccc);
- Logger.debug("Found C-PEPS configuration for citizen of country: " + moasession.getCcc());
- executionContext.put(PROCESS_CTX_KEY_CPEPS_ISXMLSIGSUPPORTED, cpeps.isXMLSignatureSupported());
-
- //add selected Country-Code to MOASession DAO
- moasession.setCcc(ccc);
-
- Logger.info("Starting STORK authentication for a citizen of country: " + moasession.getCcc());
- startSTORKAuthentication(req, resp, moasession, pendingReq);
-
- } catch (MOAIDException ex) {
- throw new TaskExecutionException(ex.getMessage(), ex);
-
- } catch (Exception e) {
- Logger.error("CreateStorkAuthRequestFormTask has an interal Error.", e);
- throw new TaskExecutionException("CreateStorkAuthRequestFormTask has an interal Error.", e);
-
- }
-
- finally {
-
- }
- }
-
- /**
- * Starts a MOA-ID authentication process using STORK
- *
- * @param req HttpServletRequest
- * @param resp HttpServletResponse
- * @param pendingReq
- * @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 void startSTORKAuthentication(
- HttpServletRequest req,
- HttpServletResponse resp,
- AuthenticationSession moasession, IRequest pendingReq) throws MOAIDException, AuthenticationException, WrongParametersException, ConfigurationException {
-
- if (moasession == null) {
- throw new AuthenticationException("auth.18", new Object[]{});
- }
-
- //read configuration paramters of OA
- OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix());
- if (oaParam == null)
- throw new AuthenticationException("auth.00", new Object[]{moasession.getPublicOAURLPrefix()});
-
- //Start of STORK Processing
- STORKConfig storkConfig = AuthConfigurationProviderFactory.getInstance().getStorkConfig();
-
- CPEPS cpeps = storkConfig.getCPEPS(moasession.getCcc());
-
- Logger.debug("Preparing to assemble STORK AuthnRequest with the following values:");
- String destination = cpeps.getPepsURL().toExternalForm();
- Logger.debug("C-PEPS URL: " + destination);
-
-
- String issuerValue = pendingReq.getAuthURL();
- // String acsURL = new DataURLBuilder().buildDataURL(issuerValue,
- // PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN, moasession.getSessionID());
-
-
- String providerName = oaParam.getFriendlyName();
- Logger.debug("Issuer value: " + issuerValue);
-
- // prepare collection of required attributes
- // - attributes for online application
- Collection<StorkAttribute> attributesFromConfig = oaParam.getRequestedSTORKAttributes();
-
- // - prepare attribute list
- PersonalAttributeList attributeList = new PersonalAttributeList();
-
- // - fill container
- for (StorkAttribute current : attributesFromConfig) {
- PersonalAttribute newAttribute = new PersonalAttribute();
- newAttribute.setName(current.getName());
-
- boolean globallyMandatory = false;
- for (StorkAttribute currentGlobalAttribute : storkConfig.getStorkAttributes())
- if (current.getName().equals(currentGlobalAttribute.getName())) {
- globallyMandatory = BooleanUtils.isTrue(currentGlobalAttribute.getMandatory());
- break;
- }
-
- newAttribute.setIsRequired(current.getMandatory() || globallyMandatory);
- attributeList.add(newAttribute);
- }
-
- // add sign request
- PersonalAttribute newAttribute = new PersonalAttribute();
- newAttribute.setName("signedDoc");
- newAttribute.setIsRequired(true);
- List<String> value = new ArrayList<String>();
-
- Logger.debug("PEPS supports XMLSignatures:"+cpeps.isXMLSignatureSupported());
- String acsURL;
- if(cpeps.isXMLSignatureSupported())//Send SignRequest to PEPS
- {
- //solve Problem with sessionIDs
- acsURL = issuerValue + PepsConnectorTask.PEPSCONNECTOR_SERVLET_URL_PATTERN;
-
- value.add(generateDssSignRequest(CreateXMLSignatureRequestBuilder.buildForeignIDTextToBeSigned("wie im Signaturzertifikat (as in my signature certificate)", oaParam, moasession),
- "application/xhtml+xml", moasession.getCcc()));
- newAttribute.setValue(value);
- attributeList.add(newAttribute);
-
- // TODO[branch]: STORK AuthReq CPEPS acsURL "/PEPSConnector"
- }
- else//Process SignRequest locally with MOCCA
- {
- String target = moasession.getTarget();
- moasession.setTarget("AT");
- String signedDoc = (generateDssSignRequest(CreateXMLSignatureRequestBuilder.buildForeignIDTextToBeSigned("wie im Signaturzertifikat (as in my signature certificate)", oaParam, moasession),
- "application/xhtml+xml", "AT"));//moasession.getCcc()
- moasession.setTarget(target);
- Logger.warn("signedDoc to store:"+signedDoc);
- //attributeList.add(newAttribute);
-
- //store SignRequest for later...
- moasession.setSignedDoc(signedDoc);
-
- acsURL = issuerValue + AbstractPepsConnectorWithLocalSigningTask.PEPSCONNECTOR_SERVLET_URL_PATTERN;
- // TODO[branch]: STORK AuthReq acsURL "/PEPSConnectorWithLocalSigning"
- try {
- AuthenticationSessionStoreage.storeSession(moasession);
- } catch (MOADatabaseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
- Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL);
-
- if (Logger.isDebugEnabled()) {
- Logger.debug("The following attributes are requested for this OA:");
- for (StorkAttribute logReqAttr : attributesFromConfig)
- Logger.debug("OA specific requested attribute: " + logReqAttr.getName() + ", isRequired: " + logReqAttr.getMandatory());
- }
-
- //TODO: check Target in case of SSO!!
- String spSector = StringUtils.isEmpty(moasession.getTarget()) ? "Business" : moasession.getTarget();
- String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName();
- String spApplication = spInstitution;
- String spCountry = "AT"; // intentionally set AT - the flow is limited on that use case only
-
- //generate AuthnRquest
- STORKAuthnRequest authnRequest = new STORKAuthnRequest();
- authnRequest.setDestination(destination);
- authnRequest.setAssertionConsumerServiceURL(acsURL);//PEPSConnectorWithLocalSigning
- authnRequest.setProviderName(providerName);
- authnRequest.setIssuer(issuerValue);
- authnRequest.setQaa(oaParam.getQaaLevel());
- authnRequest.setSpInstitution(spInstitution);
- authnRequest.setSpCountry(spCountry);
- authnRequest.setSpApplication(spApplication);
- authnRequest.setSpSector(spSector);
- authnRequest.setPersonalAttributeList(attributeList);
-
- //TODO change
- authnRequest.setEIDCrossBorderShare(true);
- authnRequest.setEIDCrossSectorShare(true);
- authnRequest.setEIDSectorShare(true);
-
- authnRequest.setCitizenCountryCode(moasession.getCcc());
-
- Logger.debug("STORK AuthnRequest succesfully assembled.");
-
- STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("outgoing");
-
- if (samlEngine == null) {
- Logger.error("Could not initalize STORK SAML engine.");
- throw new MOAIDException("stork.00", null);
- }
-
- try {
- authnRequest = samlEngine.generateSTORKAuthnRequest(authnRequest);
- } catch (STORKSAMLEngineException e) {
- Logger.error("Could not sign STORK SAML AuthnRequest.", e);
- throw new MOAIDException("stork.00", null);
- }
-
- Logger.info("STORK AuthnRequest successfully signed!");
-
- //validate AuthnRequest
- try {
- samlEngine.validateSTORKAuthnRequest(authnRequest.getTokenSaml());
- } catch (STORKSAMLEngineException e) {
- Logger.error("STORK SAML AuthnRequest not valid.", e);
- throw new MOAIDException("stork.01", null);
- }
-
- Logger.debug("STORK AuthnRequest successfully internally validated.");
-
- //send
- moasession.setStorkAuthnRequest(authnRequest);
-
- // do PEPS-conform logging for easier evaluation
- try {
- // 2015-03-12 16:44:27.144#S-PEPS receives request from SP#spurl#spepsurl#spapp#spdomain#citizen country#qaa#msghash#msg_id id1#
- Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS receives request from SP#" +
- moasession.getPublicOAURLPrefix() + "#" + issuerValue + "#" + spApplication + "#" +
- new URL(moasession.getPublicOAURLPrefix()).getHost() + "#" + moasession.getCcc() + "#" + oaParam.getQaaLevel() +
- "#_hash_#" + moasession.getProcessInstanceId() + "#");
- } catch (Exception e1) {
- Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage());
- }
-
- AuthenticationSessionStoreage.changeSessionID(moasession, authnRequest.getSamlId());
-
-
- Logger.info("Preparing to send STORK AuthnRequest.");
- Logger.info("prepared STORKAuthnRequest: ");
- Logger.info(new String(authnRequest.getTokenSaml()));
-
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/saml2-post-binding-moa.vm");
- VelocityContext context = new VelocityContext();
- context.put("SAMLRequest", PEPSUtil.encodeSAMLToken(authnRequest.getTokenSaml()));
- context.put("RelayState", moasession.getSessionID());
- context.put("action", destination);
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
-
- // TODO[branch]: SAML2 Form Submit to CPEPS, response to acsURL Servlet
-
- resp.setContentType("text/html;charset=UTF-8");
- resp.getOutputStream().write(writer.toString().getBytes("UTF-8"));
-
- } catch (Exception e) {
- Logger.error("Error sending STORK SAML AuthnRequest.", e);
- throw new MOAIDException("stork.02", new Object[]{destination});
-
- }
-
- Logger.info("STORK AuthnRequest successfully successfully prepared for client with target location: " + authnRequest.getDestination());
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_PEPS_REQUESTED, authnRequest.getDestination());
-
- // do PEPS-conform logging for easier evaluation
- try {
- // 2015-03-12 16:44:27.144#S-PEPS generates request to C-PEPS#spepsurl#cpepsurl#spapp#spdomain#citizen country#qaa#msghash#msg_id id1#id2#
- Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS generates request to C-PEPS#" +
- issuerValue + "#" + destination + "#" + spApplication + "#" +
- new URL(moasession.getPublicOAURLPrefix()).getHost() + "#" + moasession.getCcc() + "#" + oaParam.getQaaLevel() +
- "#_hash_#" + moasession.getProcessInstanceId() + "#" + authnRequest.getSamlId() + "#");
- } catch (Exception e1) {
- Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage());
- }
- }
-
- private String generateDssSignRequest(String text, String mimeType, String citizenCountry) {
- IdentifierGenerator idGenerator;
- try {
- idGenerator = new SecureRandomIdentifierGenerator();
-
- DocumentType doc = new DocumentType();
- doc.setBase64XML(text.getBytes("UTF-8"));
- doc.setID(idGenerator.generateIdentifier());
-
- SignRequest request = new SignRequest();
- request.setInputDocuments(ApiUtils.createInputDocuments(doc));
-
- String id = idGenerator.generateIdentifier();
- request.setRequestID(id);
- request.setDocUI(id);
-
- request.setProfile(Profiles.XADES_BES.toString());
- request.setNumberOfSigners(BigInteger.ONE);
- request.setTargetCountry(citizenCountry);
-
- // no, no todo. PEPS will alter this value anyhow.
- request.setReturnURL("http://invalid_return");
-
- AnyType required = new AnyType();
- required.getAny().add(ApiUtils.createSignatureType(SignatureTypes.XMLSIG_RFC3275.toString()));
- required.getAny().add(ApiUtils.createAdditionalProfile(AdditionalProfiles.XADES.toString()));
- required.getAny().add(ApiUtils.createQualityRequirements(QualityLevels.QUALITYLEVEL_QUALIFIEDSIG));
- required.getAny().add(ApiUtils.createIncludeObject(doc));
- request.setOptionalInputs(required);
-
- return IOUtils.toString(ApiUtils.marshalToInputStream(request));
- } catch (NoSuchAlgorithmException e) {
- Logger.error("Cannot generate id", e);
- throw new RuntimeException(e);
- } catch (ApiUtilsException e) {
- Logger.error("Could not create SignRequest", e);
- throw new RuntimeException(e);
- } catch (DOMException e) {
- Logger.error("Could not create SignRequest", e);
- throw new RuntimeException(e);
- } catch (IOException e) {
- Logger.error("Could not create SignRequest", e);
- throw new RuntimeException(e);
- }
- }
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java deleted file mode 100644 index 7b9fa3f12..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleLocalSignResponseTask.java +++ /dev/null @@ -1,228 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import iaik.x509.X509Certificate;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.xml.transform.Source;
-import javax.xml.transform.stream.StreamSource;
-
-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.advancedlogging.MOAIDEventConstants;
-import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
-import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
-import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
-import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
-import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
-import at.gv.egovernment.moa.id.auth.stork.STORKException;
-
-import at.gv.egovernment.moa.id.moduls.IRequest;
-import at.gv.egovernment.moa.id.moduls.ModulUtils;
-import at.gv.egovernment.moa.id.moduls.RequestStorage;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.id.util.VelocityProvider;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.spss.api.xmlverify.VerifyXMLSignatureResponse;
-import at.gv.egovernment.moa.util.Base64Utils;
-import eu.stork.oasisdss.api.ApiUtils;
-import eu.stork.oasisdss.profile.SignResponse;
-import eu.stork.peps.auth.commons.IPersonalAttributeList;
-import eu.stork.peps.auth.commons.PersonalAttribute;
-
-/**
- * Processes the citizen's signature, creates identity link using szr gateway and finalizes authentication.
- * <p/>
- * In detail:
- * <ul>
- * <li>Changes moa session id.</li>
- * <li>Decodes and validates the sign response, extracting the citizen's signature.</li>
- * <li>Verifies the citizen's signature.</li>
- * <li>Create {@code signedDoc} attribute.</li>
- * <li>Retrieve identity link from SZR gateway using the citizen's signature.</li>
- * <li>If the S-PEPS did not provide any gender information, the szr gateway will not be able to issue an identity link.
- * Therefore a form is presented asking for the subject's gender. The form finally submits the user back to the
- * {@code /PepsConnectorWithLocalSigning} servlet (this task).</li>
- * <li>The moa session is updated with authentication information.</li>
- * <li>Change moa session id.</li>
- * <li>Redirects back to {@code /dispatcher} in order to finalize the authentication.</li>
- * </ul>
- * Expects:
- * <ul>
- * <li>HttpServletRequest parameter {@code moaSessionID}</li>
- * <li>HttpServletRequest parameter {@code signresponse}</li>
- * </ul>
- * Result:
- * <ul>
- * <li>Updated moa id session (signed auth block, signer certificate etc.)</li>
- * <li>Redirect to {@code /dispatcher}.</li>
- * <li>{@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.</li>
- * </ul>
- * Possible branches:
- * <ul>
- * <li>In case the szr gateway throws exception due to missing gender information:
- * <ul>
- * <li>Returns a form for gender selection with action url back to this servlet/task.</li>
- * </ul>
- * </li>
- * </ul>
- * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.<br/>
- *
- * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse)
- */
-public class PepsConnectorHandleLocalSignResponseTask extends AbstractPepsConnectorWithLocalSigningTask {
-
- @Override
- public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response)
- throws TaskExecutionException {
- String moaSessionID = request.getParameter("moaSessionID");
- String signResponse = request.getParameter("signresponse");
- Logger.info("moaSessionID:" + moaSessionID);
- Logger.info("signResponse:" + signResponse);
-
- if (moaSessionID != null && signResponse != null) {
- // redirect from oasis with signresponse
- handleSignResponse(executionContext, request, response);
- } else {
- // should not occur
- throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", null);
- }
- return;
- }
-
- private void handleSignResponse(ExecutionContext executionContext, HttpServletRequest request,
- HttpServletResponse response) throws TaskExecutionException {
- Logger.info("handleSignResponse started");
- String moaSessionID = request.getParameter("moaSessionID");
- String signResponse = request.getParameter("signresponse");
- Logger.info("moaSessionID:" + moaSessionID);
- Logger.info("signResponse:" + signResponse);
- String pendingRequestID = null;
- try {
-
- // load MOASession from database
- AuthenticationSession moaSession = BaseAuthenticationServer.getSession(moaSessionID);
- // change MOASessionID
- moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);
- IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
-
- Logger.info("pendingRequestID:" + pendingRequestID);
- String signResponseString = new String(Base64Utils.decode(signResponse, false), "UTF8");
- Logger.info("RECEIVED signresponse:" + signResponseString);
- // create SignResponse object
- Source response1 = new StreamSource(new java.io.StringReader(signResponseString));
- SignResponse dssSignResponse = ApiUtils.unmarshal(response1, SignResponse.class);
-
- // SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(new
- // java.io.StringReader(Base64.signResponse)));
-
- String citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse);
-
- // memorize signature into authblock
- moaSession.setAuthBlock(citizenSignature);
-
- X509Certificate cert = getSignerCertificate(citizenSignature);
- moaSession.setSignerCertificate(cert);
- VerifyXMLSignatureResponse xMLVerifySignatureResponse = verifyXMLSignature(citizenSignature);
- at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse tmp = convert(xMLVerifySignatureResponse);
-
- moaSession.setXMLVerifySignatureResponse(tmp);
- executionContext.put("identityLinkAvailable", false);
- try {
- IPersonalAttributeList personalAttributeList = moaSession.getAuthnResponseGetPersonalAttributeList();
- // Add SignResponse TODO Add signature (extracted from signResponse)?
- List<String> values = new ArrayList<String>();
- values.add(signResponseString);
- // values.add(citizenSignature);
- Logger.debug("Assembling signedDoc attribute");
- PersonalAttribute signedDocAttribute = new PersonalAttribute("signedDoc", false, values, "Available");
- personalAttributeList.add(signedDocAttribute);
-
- String authnContextClassRef = moaSession.getAuthnContextClassRef();
- SZRGInsertion(moaSession, personalAttributeList, authnContextClassRef, citizenSignature);
- executionContext.put("identityLinkAvailable", true);
- } catch (STORKException e) {
- // this is really nasty but we work against the system here. We are supposed to get the gender attribute
- // from
- // stork. If we do not, we cannot register the person in the ERnP - we have to have the
- // gender for the represented person. So here comes the dirty hack.
- if (e.getCause() instanceof STORKException
- && e.getCause().getMessage().equals("gender not found in response")) {
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
- VelocityContext context = new VelocityContext();
- context.put("SAMLResponse", request.getParameter("SAMLResponse"));
- context.put("action", request.getRequestURL());
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
- response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
- } catch (Exception e1) {
- Logger.error("Error sending gender retrival form.", e1);
- // httpSession.invalidate();
- throw new MOAIDException("stork.10", null);
- }
-
- return;
- }
-
- Logger.error("Error connecting SZR Gateway", e);
- throw new MOAIDException("stork.10", null);
- }
-
- Logger.debug("Add full STORK AuthnResponse to MOA session");
- moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));// TODO ask Florian/Thomas
- // authnResponse?
-
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_PEPS_RECEIVED);
-
- moaSession.setForeigner(true);
-
- // session is implicit stored in changeSessionID!!!!
- String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);
-
- // redirect
- String redirectURL = null;
- redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
- ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
- newMOASessionID);
- redirectURL = response.encodeRedirectURL(redirectURL);
-
- response.sendRedirect(redirectURL);
- Logger.info("REDIRECT TO: " + redirectURL);
-
- } catch (AuthenticationException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (MOAIDException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (Exception e) {
- Logger.error("PEPSConnector has an interal Error.", e);
- throw new TaskExecutionException(e.getMessage(), e);
- }
-
- finally {
-
- }
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java deleted file mode 100644 index e84c33d5d..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorHandleResponseWithoutSignatureTask.java +++ /dev/null @@ -1,451 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import iaik.x509.X509Certificate;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.xml.transform.Source;
-import javax.xml.transform.stream.StreamSource;
-
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-import org.opensaml.saml2.core.StatusCode;
-
-import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
-import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
-import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
-import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
-import at.gv.egovernment.moa.id.auth.stork.STORKException;
-import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor;
-
-import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
-import at.gv.egovernment.moa.id.config.stork.StorkAttributeProviderPlugin;
-import at.gv.egovernment.moa.id.moduls.IRequest;
-import at.gv.egovernment.moa.id.moduls.ModulUtils;
-import at.gv.egovernment.moa.id.moduls.RequestStorage;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.id.util.HTTPUtils;
-import at.gv.egovernment.moa.id.util.VelocityProvider;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.Base64Utils;
-import at.gv.egovernment.moa.util.StringUtils;
-import eu.stork.oasisdss.api.ApiUtils;
-import eu.stork.oasisdss.profile.SignRequest;
-import eu.stork.oasisdss.profile.SignResponse;
-import eu.stork.peps.auth.commons.IPersonalAttributeList;
-import eu.stork.peps.auth.commons.PEPSUtil;
-import eu.stork.peps.auth.commons.PersonalAttribute;
-import eu.stork.peps.auth.commons.STORKAuthnRequest;
-import eu.stork.peps.auth.commons.STORKAuthnResponse;
-import eu.stork.peps.auth.engine.STORKSAMLEngine;
-import eu.stork.peps.exceptions.STORKSAMLEngineException;
-
-/**
- * Validates the SAML response from C-PEPS.
- * <p/>
- * In detail:
- * <ul>
- * <li>Decodes and validates SAML response from C-PEPS.</li>
- * <li>Retrieves the moa session using the session id provided by HttpServletRequest parameter {@code RelayState} or by {@code inResponseTo} attribute of the saml response.</li>
- * <li>Store saml response in moa session.</li>
- * <li>Change moa session id.</li>
- * <li>Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.</li>
- * </ul>
- * Expects:
- * <ul>
- * <li>HttpServletRequest parameter {@code moaSessionID} <strong>to be {@code null}</strong></li>
- * <li>HttpServletRequest parameter {@code signresponse} <strong>to be {@code null}</strong></li>
- * <li>HttpServletRequest parameter {@code SAMLResponse}</li>
- * <li>Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute within the saml response, both reflecting the moa session id.</li>
- * </ul>
- * Result:
- * <ul>
- * <li>Updated moa session (with saml response).</li>
- * <li>Redirect to {@code /PEPSConnectorWithLocalSigning}, with providing the moa session id as request parameter.</li>
- * </ul>
- * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorWithLocalSigningServlet}.<br/>
- *
- * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse)
- */
-public class PepsConnectorHandleResponseWithoutSignatureTask extends AbstractPepsConnectorWithLocalSigningTask {
-
- private String oasisDssWebFormURL = "https://testvidp.buergerkarte.at/oasis-dss/DSSWebFormServlet";
- // load from config below
-
- @Override
- public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response)
- throws TaskExecutionException {
- String moaSessionID = request.getParameter("moaSessionID");
- String signResponse = request.getParameter("signresponse");
- Logger.info("moaSessionID:" + moaSessionID);
- Logger.info("signResponse:" + signResponse);
-
- if (moaSessionID == null && signResponse == null) {
- // normal saml response
- handleSAMLResponse(executionContext, request, response);
-
- } else {
- // should not occur
- throw new TaskExecutionException("Parsing mulitpart/form-data request parameters failed", null);
- }
- return;
- }
-
- private void handleSAMLResponse(ExecutionContext executionContext, HttpServletRequest request,
- HttpServletResponse response) throws TaskExecutionException {
- Logger.info("handleSAMLResponse started");
- String pendingRequestID = null;
-
- setNoCachingHeaders(response);
- try {
- Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message.");
- Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request));
-
- Logger.trace("No Caching headers set for HTTP response");
-
- // check if https or only http
- super.checkIfHTTPisAllowed(request.getRequestURL().toString());
-
- Logger.debug("Beginning to extract SAMLResponse out of HTTP Request");
-
- // extract STORK Response from HTTP Request
- // Decodes SAML Response
- byte[] decSamlToken;
- try {
- decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse"));
- Logger.debug("SAMLResponse: " + new String(decSamlToken));
-
- } catch (NullPointerException e) {
- Logger.error("Unable to retrieve STORK Response", e);
- throw new MOAIDException("stork.04", null);
- }
-
- // Get SAMLEngine instance
- STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing");
-
- STORKAuthnResponse authnResponse = null;
- try {
- // validate SAML Token
- Logger.debug("Starting validation of SAML response");
- authnResponse = engine.validateSTORKAuthnResponseWithQuery(decSamlToken, (String) request.getRemoteHost());
- Logger.info("SAML response succesfully verified!");
- } catch (STORKSAMLEngineException e) {
- Logger.error("Failed to verify STORK SAML Response", e);
- throw new MOAIDException("stork.05", null);
- }
-
- Logger.info("STORK SAML Response message succesfully extracted");
- Logger.debug("STORK response: ");
- Logger.debug(authnResponse.toString());
-
- Logger.debug("Trying to find MOA Session-ID ...");
- // String moaSessionID = request.getParameter(PARAM_SESSIONID);
- // first use SAML2 relayState
- String moaSessionID = request.getParameter("RelayState");
-
- // escape parameter strings
- moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);
-
- // check if SAML2 relaystate includes a MOA sessionID
- if (StringUtils.isEmpty(moaSessionID)) {
- // if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier
-
- moaSessionID = authnResponse.getInResponseTo();
- moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);
-
- if (StringUtils.isEmpty(moaSessionID)) {
- // No authentication session has been started before
- Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started");
- Logger.debug("PEPSConnectorURL was: " + request.getRequestURL());
- throw new AuthenticationException("auth.02", new Object[] { moaSessionID });
-
- } else
- Logger.trace("Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute.");
-
- } else
- // Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter.");
- Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState.");
-
- /*
- * INFO!!!! SAML message IDs has an different format then MOASessionIDs This is only a workaround because
- * many PEPS does not support SAML2 relayState or MOASessionID as AttributConsumerServiceURL GET parameter
- */
- // if (!ParamValidatorUtils.isValidSessionID(moaSessionID))
- // throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");
-
- pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);
- IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
-
- // load MOASession from database
- AuthenticationSession moaSession = BaseAuthenticationServer.getSession(moaSessionID);
- // change MOASessionID
- moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Found MOA sessionID: " + moaSessionID);
-
- String statusCodeValue = authnResponse.getStatusCode();
-
- if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) {
- Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue);
- throw new MOAIDException("stork.06", new Object[] { statusCodeValue });
- }
-
- Logger.info("Got SAML response with authentication success message.");
-
- Logger.debug("MOA session is still valid");
-
- STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest();
-
- if (storkAuthnRequest == null) {
- Logger.error("Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
- throw new MOAIDException("stork.07", null);
- }
-
- Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
-
-
- // first, try to fetch the attributes from the list of total attributes. Note that this very list is only filled
- // with ALL attributes when there is more than one assertion in the SAML2 STORK message.
- IPersonalAttributeList attributeList = authnResponse.getTotalPersonalAttributeList();
-
- // if the list is empty, there was just one assertion... probably
- if(attributeList.isEmpty())
- attributeList = authnResponse.getPersonalAttributeList();
-
- // //////////// incorporate gender from parameters if not in stork response
- // but first, check if we have a representation case
- if (STORKResponseProcessor.hasAttribute("mandateContent", attributeList)
- || STORKResponseProcessor.hasAttribute("representative", attributeList)
- || STORKResponseProcessor.hasAttribute("represented", attributeList)) {
- // in a representation case...
- moaSession.setUseMandate("true");
-
- // and check if we have the gender value
- PersonalAttribute gender = attributeList.get("gender");
- if (null == gender) {
- String gendervalue = (String) request.getParameter("gender");
- if (null != gendervalue) {
- gender = new PersonalAttribute();
- gender.setName("gender");
- ArrayList<String> tmp = new ArrayList<String>();
- tmp.add(gendervalue);
- gender.setValue(tmp);
-
- attributeList.add(gender);
- }
- }
- }
-
-
-
- // ////////////////////////////////////////////////////////////////////////
-
- Logger.debug("Starting extraction of signedDoc attribute");
- // extract signed doc element and citizen signature
- String citizenSignature = null;
- try {
- PersonalAttribute signedDoc = attributeList.get("signedDoc");
- String signatureInfo = null;
- // FIXME: Remove nonsense code (signedDoc attribute... (throw Exception for "should not occur" situations)), adjust error messages in order to reflect the true problem...
- if (signedDoc != null) {
- signatureInfo = signedDoc.getValue().get(0);
- // should not occur
- } else {
-
- // store SAMLResponse
- moaSession.setSAMLResponse(request.getParameter("SAMLResponse"));
- // store authnResponse
-
- // moaSession.setAuthnResponse(authnResponse);//not serializable
- moaSession.setAuthnResponseGetPersonalAttributeList(attributeList);
-
- String authnContextClassRef = null;
- try {
- authnContextClassRef = authnResponse.getAssertions().get(0).getAuthnStatements().get(0)
- .getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef();
- } catch (Throwable e) {
- Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
- }
-
- moaSession.setAuthnContextClassRef(authnContextClassRef);
- moaSession.setReturnURL(request.getRequestURL());
-
- // load signedDoc
- String signRequest = moaSession.getSignedDoc();
-
- // session is implicit stored in changeSessionID!!!!
- String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- // set return url to PEPSConnectorWithLocalSigningServlet and add newMOASessionID
- // signRequest
-
- String issuerValue = pendingReq.getAuthURL();
- String acsURL = issuerValue
- + AbstractPepsConnectorWithLocalSigningTask.PEPSCONNECTOR_SERVLET_URL_PATTERN;
-
- String url = acsURL + "?moaSessionID=" + newMOASessionID;
- // redirect to OASIS module and sign there
-
- boolean found = false;
- try {
- Collection<StorkAttributeProviderPlugin> aps = AuthConfigurationProviderFactory.getInstance()
- .getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix()).getStorkAPs();
- Logger.info("Found AttributeProviderPlugins:" + aps.size());
- for (StorkAttributeProviderPlugin ap : aps) {
- Logger.info("Found AttributeProviderPlugin attribute:" + ap.getAttributes());
- if (ap.getAttributes().equalsIgnoreCase("signedDoc")) {
- // FIXME: A servlet's class field is not thread safe!!!
- oasisDssWebFormURL = ap.getUrl();
- found = true;
- Logger.info("Loaded signedDoc attribute provider url from config:" + oasisDssWebFormURL);
- break;
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- Logger.error("Loading the signedDoc attribute provider url from config failed");
- }
- if (!found) {
- Logger.error("Failed to load the signedDoc attribute provider url from config");
- }
- performRedirect(url, request, response, signRequest);
-
- return;
- }
-
- // FIXME: This servlet/task is intended to handle peps responses without signature, so why do we try to process that signature here?
- SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(
- new java.io.StringReader(signatureInfo)));
-
- citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse);
-
- // memorize signature into authblock
- moaSession.setAuthBlock(citizenSignature);
-
- X509Certificate cert = getSignerCertificate(citizenSignature);
- moaSession.setSignerCertificate(cert);
- moaSession.setForeigner(true);
-
- } catch (Throwable e) {
- Logger.error("Could not extract citizen signature from C-PEPS", e);
- throw new MOAIDException("stork.09", null);
- }
-
- // FIXME: Same here; we do not have the citizen's signature, so this code might be regarded as dead code.
- try {
- SZRGInsertion(moaSession, attributeList, authnResponse.getAssertions()
- .get(0).getAuthnStatements().get(0).getAuthnContext().getAuthnContextClassRef()
- .getAuthnContextClassRef(), citizenSignature);
- } catch (STORKException e) {
- // this is really nasty but we work against the system here. We are supposed to get the gender attribute
- // from
- // stork. If we do not, we cannot register the person in the ERnP - we have to have the
- // gender for the represented person. So here comes the dirty hack.
- if (e.getCause() instanceof STORKException
- && e.getCause().getMessage().equals("gender not found in response")) {
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
- VelocityContext context = new VelocityContext();
- context.put("SAMLResponse", request.getParameter("SAMLResponse"));
- context.put("action", request.getRequestURL());
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
-
- response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
- } catch (Exception e1) {
- Logger.error("Error sending gender retrival form.", e1);
- // httpSession.invalidate();
- throw new MOAIDException("stork.10", null);
- }
-
- return;
- }
-
- Logger.error("Error connecting SZR Gateway", e);
- throw new MOAIDException("stork.10", null);
- }
-
- Logger.debug("Add full STORK AuthnResponse to MOA session");
- moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));// TODO ask Florian/Thomas
- // authnResponse?
-
- // session is implicit stored in changeSessionID!!!!
- String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);
-
- // redirect
- String redirectURL = null;
- redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
- ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
- newMOASessionID);
- redirectURL = response.encodeRedirectURL(redirectURL);
-
- response.setContentType("text/html");
- response.setStatus(302);
- response.addHeader("Location", redirectURL);
- Logger.info("REDIRECT TO: " + redirectURL);
-
- } catch (AuthenticationException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (MOAIDException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (Exception e) {
- Logger.error("PEPSConnector has an interal Error.", e);
- throw new TaskExecutionException(e.getMessage(), e);
- }
-
- finally {
-
- }
-
- }
-
- private void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, String signRequestString)
- throws MOAIDException {
-
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/oasis_dss_webform_binding.vm");
- VelocityContext context = new VelocityContext();
-
- Logger.debug("performRedirect, signrequest:" + signRequestString);
- Source signDoc = new StreamSource(new java.io.StringReader(signRequestString));
- SignRequest signRequest = ApiUtils.unmarshal(signDoc, SignRequest.class);
- signRequest.setReturnURL("TODO");
- signRequestString = IOUtils.toString(ApiUtils.marshalToInputStream(signRequest));
- context.put("signrequest", Base64Utils.encode(signRequestString.getBytes("UTF8")));
- context.put("clienturl", url);
- context.put("action", oasisDssWebFormURL);
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
-
- resp.getOutputStream().write(writer.toString().getBytes("UTF-8"));
- } catch (Exception e) {
- Logger.error("Error sending DSS signrequest.", e);
- throw new MOAIDException("stork.11", null);
- }
- }
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java deleted file mode 100644 index b505605ab..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/modules/stork/tasks/PepsConnectorTask.java +++ /dev/null @@ -1,791 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork.tasks;
-
-import iaik.x509.X509Certificate;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringWriter;
-import java.net.URL;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.Properties;
-
-import javax.activation.DataSource;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import javax.xml.bind.JAXBContext;
-import javax.xml.bind.JAXBElement;
-import javax.xml.namespace.QName;
-import javax.xml.transform.stream.StreamSource;
-import javax.xml.ws.BindingProvider;
-import javax.xml.ws.Service;
-import javax.xml.ws.soap.SOAPBinding;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.lang.StringEscapeUtils;
-import org.apache.velocity.Template;
-import org.apache.velocity.VelocityContext;
-import org.apache.velocity.app.VelocityEngine;
-import org.opensaml.saml2.core.StatusCode;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import at.gv.egovernment.moa.id.advancedlogging.MOAIDEventConstants;
-import at.gv.egovernment.moa.id.advancedlogging.MOAReversionLogger;
-
-import at.gv.egovernment.moa.id.auth.BaseAuthenticationServer;
-import at.gv.egovernment.moa.id.auth.builder.DataURLBuilder;
-import at.gv.egovernment.moa.id.auth.data.AuthenticationSession;
-import at.gv.egovernment.moa.id.auth.data.IdentityLink;
-import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
-import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
-import at.gv.egovernment.moa.id.auth.modules.AbstractAuthServletTask;
-import at.gv.egovernment.moa.id.auth.modules.TaskExecutionException;
-import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser;
-import at.gv.egovernment.moa.id.auth.stork.STORKException;
-import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor;
-
-import at.gv.egovernment.moa.id.config.auth.AuthConfiguration;
-import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory;
-import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
-import at.gv.egovernment.moa.id.moduls.IRequest;
-import at.gv.egovernment.moa.id.moduls.ModulUtils;
-import at.gv.egovernment.moa.id.moduls.RequestStorage;
-import at.gv.egovernment.moa.id.process.api.ExecutionContext;
-import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
-import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
-import at.gv.egovernment.moa.id.util.HTTPUtils;
-import at.gv.egovernment.moa.id.util.IdentityLinkReSigner;
-import at.gv.egovernment.moa.id.util.VelocityProvider;
-import at.gv.egovernment.moa.logging.Logger;
-import at.gv.egovernment.moa.util.DOMUtils;
-import at.gv.egovernment.moa.util.StringUtils;
-import at.gv.egovernment.moa.util.XPathUtils;
-import at.gv.util.xsd.xmldsig.SignatureType;
-import at.gv.util.xsd.xmldsig.X509DataType;
-import eu.stork.documentservice.DocumentService;
-import eu.stork.oasisdss.api.ApiUtils;
-import eu.stork.oasisdss.api.LightweightSourceResolver;
-import eu.stork.oasisdss.profile.DocumentType;
-import eu.stork.oasisdss.profile.DocumentWithSignature;
-import eu.stork.oasisdss.profile.SignResponse;
-import eu.stork.peps.auth.commons.IPersonalAttributeList;
-import eu.stork.peps.auth.commons.PEPSUtil;
-import eu.stork.peps.auth.commons.PersonalAttribute;
-import eu.stork.peps.auth.commons.PersonalAttributeList;
-import eu.stork.peps.auth.commons.STORKAttrQueryRequest;
-import eu.stork.peps.auth.commons.STORKAuthnRequest;
-import eu.stork.peps.auth.commons.STORKAuthnResponse;
-import eu.stork.peps.auth.engine.STORKSAMLEngine;
-import eu.stork.peps.exceptions.STORKSAMLEngineException;
-
-/**
- * Evaluates the SAML response from the C-PEPS and authenticates the user.
- * <p/>
- * In detail:
- * <ul>
- * <li>Decodes and validates the SAML response from the C-PEPS.</li>
- * <li>Change moa session id.</li>
- * <li>Extracts the subject's gender from request parameter {@code gender} if not available from the saml response.</li>
- * <li>Extracts the {@code signedDoc} attribute from the response, get signed doc payload using stork attribute query request.</li>
- * <li>Request SZR gateway for verification of the citizen's signature and for creating of an identity link.</li>
- * <li>In case of mandate mode: If the S-PEPS did not provide any gender information, the szr gateway will not be able to issue an identity link. Therefore a form is presented asking for the subject's gender. The form submits the user back to the {@code /PepsConnector} servlet (this task).</li>
- * <li>The moa session is updated with authentication information.</li>
- * <li>Change moa session id.</li>
- * <li>Redirects back to {@code /dispatcher} in order to finalize the authentication.</li>
- * </ul>
- * Expects:
- * <ul>
- * <li>HttpServletRequest parameter {@code SAMLResponse}</li>
- * <li>Either HttpServletRequest parameter {@code RelayState} or {@code inResponseTo} attribute from the SAML response (both depicting the moa session id)</li>
- * <li>HttpServletRequest parameter {@code gender} in case the request comes from the gender selection form</li>
- * <li>{@code signedDoc} attribute within the SAML response.</li>
- * </ul>
- * Result:
- * <ul>
- * <li>Updated moa id session (identity link, stork attributes...)</li>
- * <li>{@link ExecutionContext} contains boolean flag {@code identityLinkAvailable} indicating if an identitylink has been successfully creates or not.</li>
- * <li>Redirect to {@code /dispatcher}.</li>
- * </ul>
- * Possible branches:
- * <ul>
- * <li>In case the szr gateway throws exception due to missing gender information:
- * <ul>
- * <li>Returns a form for gender selection with action url back to this servlet/task.</li>
- * </ul>
- * </li>
- * </ul>
- * Code taken from {@link at.gv.egovernment.moa.id.auth.servlet.PEPSConnectorServlet}.<br/>
- *
- * @see #execute(ExecutionContext, HttpServletRequest, HttpServletResponse)
- */
-public class PepsConnectorTask extends AbstractAuthServletTask {
-
- public static final String PEPSCONNECTOR_SERVLET_URL_PATTERN = "/PEPSConnector";
-
- public PepsConnectorTask() {
- super();
-
- }
-
- @Override
- public void execute(ExecutionContext executionContext, HttpServletRequest request, HttpServletResponse response)
- throws TaskExecutionException {
- String pendingRequestID = null;
-
- setNoCachingHeaders(response);
-
- try {
-
- Logger.info("PEPSConnector Servlet invoked, expecting C-PEPS message.");
- Logger.debug("This ACS endpoint is: " + HTTPUtils.getBaseURL(request));
-
- // check if https or only http
- super.checkIfHTTPisAllowed(request.getRequestURL().toString());
-
- Logger.debug("Beginning to extract SAMLResponse out of HTTP Request");
-
- // extract STORK Response from HTTP Request
- // Decodes SAML Response
- byte[] decSamlToken;
- try {
- decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse"));
- Logger.debug("SAMLResponse: " + new String(decSamlToken));
-
- } catch (NullPointerException e) {
- Logger.error("Unable to retrieve STORK Response", e);
- throw new MOAIDException("stork.04", null);
- }
-
- // Get SAMLEngine instance
- STORKSAMLEngine engine = STORKSAMLEngine.getInstance("outgoing");
-
- STORKAuthnResponse authnResponse = null;
- try {
- // validate SAML Token
- Logger.debug("Starting validation of SAML response");
- authnResponse = engine.validateSTORKAuthnResponseWithQuery(decSamlToken, (String) request.getRemoteHost());
- Logger.info("SAML response succesfully verified!");
- } catch (STORKSAMLEngineException e) {
- Logger.error("Failed to verify STORK SAML Response", e);
- throw new MOAIDException("stork.05", null);
- }
-
- Logger.info("STORK SAML Response message succesfully extracted");
- Logger.debug("STORK response: ");
- Logger.debug(authnResponse.toString());
-
- // do PEPS-conform logging for easier evaluation
- try {
- // 2015-03-12 16:44:27.144#S-PEPS receives response from C-PEPS#orig_msg_id id2 (in response to)#orig_msg_id id1 (in response to)#status#msghash#msg_id id3#
- Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS receives response from C-PEPS#" +
- authnResponse.getInResponseTo() + "#NA#" + authnResponse.getMessage() + "#_hash_#" + authnResponse.getSamlId() + "#");
- } catch (Exception e1) {
- Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage());
- }
-
- Logger.debug("Trying to find MOA Session-ID ...");
- // String moaSessionID = request.getParameter(PARAM_SESSIONID);
- // first use SAML2 relayState
- String moaSessionID = request.getParameter("RelayState");
-
- // escape parameter strings
- moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);
-
- // check if SAML2 relaystate includes a MOA sessionID
- if (StringUtils.isEmpty(moaSessionID)) {
- // if relaystate is emtpty, use SAML response -> inResponseTo element as session identifier
-
- moaSessionID = authnResponse.getInResponseTo();
- moaSessionID = StringEscapeUtils.escapeHtml(moaSessionID);
-
- if (StringUtils.isEmpty(moaSessionID)) {
- // No authentication session has been started before
- Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started");
- Logger.debug("PEPSConnectorURL was: " + request.getRequestURL());
- throw new AuthenticationException("auth.02", new Object[] { moaSessionID });
-
- } else
- Logger.trace("Use MOA SessionID " + moaSessionID + " from AuthnResponse->inResponseTo attribute.");
-
- } else
- // Logger.trace("MOA SessionID " + moaSessionID + " is found in http GET parameter.");
- Logger.trace("MOA SessionID " + moaSessionID + " is found in SAML2 relayState.");
-
- /*
- * INFO!!!! SAML message IDs has an different format then MOASessionIDs This is only a workaround because
- * many PEPS does not support SAML2 relayState or MOASessionID as AttributConsumerServiceURL GET parameter
- */
- // if (!ParamValidatorUtils.isValidSessionID(moaSessionID))
- // throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");
-
- pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);
- IRequest pendingReq = RequestStorage.getPendingRequest(pendingRequestID);
-
- // load MOASession from database
- AuthenticationSession moaSession = BaseAuthenticationServer.getSession(moaSessionID);
- // change MOASessionID
- moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Found MOA sessionID: " + moaSessionID);
-
- String statusCodeValue = authnResponse.getStatusCode();
-
- if (!statusCodeValue.equals(StatusCode.SUCCESS_URI)) {
- Logger.error("Received ErrorResponse from PEPS: " + statusCodeValue);
- throw new MOAIDException("stork.06", new Object[] { statusCodeValue });
- }
-
- Logger.info("Got SAML response with authentication success message.");
-
- Logger.debug("MOA session is still valid");
-
- STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest();
-
- if (storkAuthnRequest == null) {
- Logger.error("Could not find any preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
- throw new MOAIDException("stork.07", null);
- }
-
- OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(moaSession.getPublicOAURLPrefix());
- if (oaParam == null)
- throw new AuthenticationException("auth.00", new Object[] { moaSession.getPublicOAURLPrefix() });
-
- //================== Check QAA level start ====================
- int reqQaa = -1;
- int authQaa = -1;
- String authQaaStr = null;
- try {
- reqQaa = storkAuthnRequest.getQaa();
-
- //TODO: found better solution, but QAA Level in response could be not supported yet
- try {
-
- authQaaStr = authnResponse.getAssertions().get(0).
- getAuthnStatements().get(0).getAuthnContext().
- getAuthnContextClassRef().getAuthnContextClassRef();
- moaSession.setQAALevel(authQaaStr);
-
- } catch (Throwable e) {
- Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
- moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
- authQaaStr = PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel();
- }
- if(authQaaStr != null)//Check value only if set
- {
- authQaa = Integer.valueOf(authQaaStr.substring(PVPConstants.STORK_QAA_PREFIX.length()));
-// authQaa = Integer.valueOf(authQaaStr);
- if (reqQaa > authQaa) {
- Logger.warn("Requested QAA level does not match to authenticated QAA level");
- throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa});
-
- }
- }
- } catch (MOAIDException e) {
- throw e;
-
- } catch (Exception e) {
- if (Logger.isDebugEnabled())
- Logger.warn("STORK QAA Level evaluation error", e);
-
- else
- Logger.warn("STORK QAA Level evaluation error (ErrorMessage="
- + e.getMessage() + ")");
-
- throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa});
-
- }
- //================== Check QAA level end ====================
-
-
- Logger.debug("Found a preceeding STORK AuthnRequest to this MOA session: " + moaSessionID);
-
- // fetch attribute list from response
- IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList();
- if(authnResponse.getAssertions().size() > 1) {
- for(IPersonalAttributeList currentList : authnResponse.getPersonalAttributeLists()) {
- for(PersonalAttribute currentAttribute : currentList.values()) {
- if(!attributeList.containsKey(currentAttribute.getName()))
- attributeList.add((PersonalAttribute) currentAttribute.clone());
- else {
- if(!attributeList.get(currentAttribute.getName()).getValue().equals(currentAttribute.getValue()))
- throw new TaskExecutionException("data integrity failure", new Exception("data integrity failure: found non-matching values in multiple attributes of type " + currentAttribute.getName()));
- }
- }
- }
- }
-
- // //////////// incorporate gender from parameters if not in stork response
-
- // but first, check if we have a representation case
- if (STORKResponseProcessor.hasAttribute("mandateContent", attributeList)
- || STORKResponseProcessor.hasAttribute("representative", attributeList)
- || STORKResponseProcessor.hasAttribute("represented", attributeList)) {
- // in a representation case...
- moaSession.setUseMandate("true");
-
- // and check if we have the gender value
- PersonalAttribute gender = attributeList.get("gender"); // TODO Do we need to check gender value if
- // there is no representation case?
- if (null == gender) {
- String gendervalue = (String) request.getParameter("gender");
- if (null != gendervalue) {
- gender = new PersonalAttribute();
- gender.setName("gender");
- ArrayList<String> tmp = new ArrayList<String>();
- tmp.add(gendervalue);
- gender.setValue(tmp);
-
- attributeList.add(gender);
- }
- }
- }
-
- // ////////////////////////////////////////////////////////////////////////
-
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_PEPS_RECEIVED);
-
- AuthConfiguration config = AuthConfigurationProviderFactory.getInstance();
- String citizenSignature = null;
- if(config.isStorkFakeIdLActive() && config.getStorkNoSignatureCountries().contains(storkAuthnRequest.getCitizenCountryCode()) && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) {
- Logger.debug("signedDoc extraction skipped due to configuration");
- } else {
- Logger.debug("Starting extraction of signedDoc attribute");
- // extract signed doc element and citizen signature
- try {
-
- if (attributeList.get("signedDoc") == null
- || attributeList.get("signedDoc").getValue() == null
- || attributeList.get("signedDoc").getValue().get(0) == null) {
- Logger.info("STORK Response include NO signedDoc attribute!");
- throw new STORKException("STORK Response include NO signedDoc attribute.");
-
- }
-
- String signatureInfo = attributeList.get("signedDoc").getValue().get(0);
-
-
- Logger.debug("signatureInfo:" + signatureInfo);
-
- SignResponse dssSignResponse = (SignResponse) ApiUtils.unmarshal(new StreamSource(
- new java.io.StringReader(signatureInfo)));
-
- // fetch signed doc
- DataSource ds = null;
- try{
- ds = LightweightSourceResolver.getDataSource(dssSignResponse);
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- if(ds == null){
- //Normal DocumentServices return a http-page, but the SI DocumentService returns HTTP error 500
- //which results in an exception and ds==null
-
- //try to load document from documentservice
- citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
- //throw new ApiUtilsException("No datasource found in response");
- }
- else
- {
- InputStream incoming = ds.getInputStream();
- citizenSignature = IOUtils.toString(incoming);
- incoming.close();
-
- Logger.debug("citizenSignature:"+citizenSignature);
- if(isDocumentServiceUsed(citizenSignature)==true)
- {
- citizenSignature = loadDocumentFromDocumentService(dssSignResponse);
- // Logger.debug("Loading document from DocumentService.");
- // String url = getDtlUrlFromResponse(dssSignResponse);
- // //get Transferrequest
- // String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url);
- // //Load document from DocumentService
- // byte[] data = getDocumentFromDtl(transferRequest, url);
- // citizenSignature = new String(data, "UTF-8");
- // Logger.debug("Overridung citizenSignature with:"+citizenSignature);
- }
- }
-
- JAXBContext ctx = JAXBContext.newInstance(SignatureType.class.getPackage().getName());
- SignatureType root = ((JAXBElement<SignatureType>) ctx.createUnmarshaller().unmarshal(
- IOUtils.toInputStream(citizenSignature))).getValue();
-
- // memorize signature into authblock
- moaSession.setAuthBlock(citizenSignature);
-
- // extract certificate
- for (Object current : root.getKeyInfo().getContent())
- if (((JAXBElement<?>) current).getValue() instanceof X509DataType) {
- for (Object currentX509Data : ((JAXBElement<X509DataType>) current).getValue()
- .getX509IssuerSerialOrX509SKIOrX509SubjectName()) {
- JAXBElement<?> casted = ((JAXBElement<?>) currentX509Data);
- if (casted.getName().getLocalPart().equals("X509Certificate")) {
- moaSession.setSignerCertificate(new X509Certificate(((String) casted.getValue())
- .getBytes("UTF-8")));
- break;
- }
- }
- }
-
- } catch (Throwable e) {
- Logger.error("Could not extract citizen signature from C-PEPS", e);
- throw new MOAIDException("stork.09", null);
- }
- }
- Logger.debug("Foregin Citizen signature successfully extracted from STORK Assertion (signedDoc)");
- Logger.debug("Citizen signature will be verified by SZR Gateway!");
-
- Logger.debug("fetching OAParameters from database");
-
- // //read configuration paramters of OA
- // AuthenticationSession moasession;
- // try {
- // moasession = AuthenticationSessionStoreage.getSession(moaSessionID);
- // } catch (MOADatabaseException e2) {
- // Logger.error("could not retrieve moa session");
- // throw new AuthenticationException("auth.01", null);
- // }
-
- // retrieve target
- // TODO: check in case of SSO!!!
- String targetType = null;
- if (oaParam.getBusinessService()) {
- String id = oaParam.getIdentityLinkDomainIdentifier();
- if (id.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_))
- targetType = id;
- else
- targetType = AuthenticationSession.REGISTERANDORDNR_PREFIX_ + moaSession.getDomainIdentifier();
- } else {
- targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget();
- }
-
- Logger.debug("Starting connecting SZR Gateway");
- // contact SZR Gateway
- IdentityLink identityLink = null;
- executionContext.put("identityLinkAvailable", false);
- try {
- if(config.isStorkFakeIdLActive() && config.getStorkFakeIdLCountries().contains(storkAuthnRequest.getCitizenCountryCode())) {
- // create fake IdL
- // - fetch IdL template from resources
- InputStream s = PepsConnectorTask.class.getResourceAsStream("/resources/xmldata/fakeIdL_IdL_template.xml");
- Element idlTemplate = DOMUtils.parseXmlValidating(s);
-
- identityLink = new IdentityLinkAssertionParser(idlTemplate).parseIdentityLink();
-
- // replace data
- Element idlassertion = identityLink.getSamlAssertion();
- // - set bpk/wpbk;
- Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH);
- if(!STORKResponseProcessor.hasAttribute("eIdentifier", attributeList))
- throw new STORKException("eIdentifier is missing");
- String eIdentifier = STORKResponseProcessor.getAttributeValue("eIdentifier", attributeList, false);
- prIdentification.getFirstChild().setNodeValue(eIdentifier);
-
- // - set last name
- Node prFamilyName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_FAMILY_NAME_XPATH);
- if(!STORKResponseProcessor.hasAttribute("surname", attributeList))
- throw new STORKException("surname is missing");
- String familyName = STORKResponseProcessor.getAttributeValue("surname", attributeList, false);
- prFamilyName.getFirstChild().setNodeValue(familyName);
-
- // - set first name
- Node prGivenName = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_GIVEN_NAME_XPATH);
- if(!STORKResponseProcessor.hasAttribute("givenName", attributeList))
- throw new STORKException("givenName is missing");
- String givenName = STORKResponseProcessor.getAttributeValue("givenName", attributeList, false);
- prGivenName.getFirstChild().setNodeValue(givenName);
-
- // - set date of birth
- Node prDateOfBirth = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_DATE_OF_BIRTH_XPATH);
- if(!STORKResponseProcessor.hasAttribute("dateOfBirth", attributeList))
- throw new STORKException("dateOfBirth is missing");
- String dateOfBirth = STORKResponseProcessor.getAttributeValue("dateOfBirth", attributeList, false);
- dateOfBirth = new SimpleDateFormat("yyyy-MM-dd").format(new SimpleDateFormat("yyyyMMdd").parse(dateOfBirth));
- prDateOfBirth.getFirstChild().setNodeValue(dateOfBirth);
-
- identityLink = new IdentityLinkAssertionParser(idlassertion).parseIdentityLink();
-
- //resign IDL
- IdentityLinkReSigner identitylinkresigner = IdentityLinkReSigner.getInstance();
- Element resignedilAssertion = identitylinkresigner.resignIdentityLink(identityLink.getSamlAssertion(), config.getStorkFakeIdLResigningKey());
- identityLink = new IdentityLinkAssertionParser(resignedilAssertion).parseIdentityLink();
-
- } else {
- //contact SZR Gateway
- Logger.debug("Starting connecting SZR Gateway");
-
- identityLink = STORKResponseProcessor.connectToSZRGateway(
- attributeList,
- oaParam.getFriendlyName(),
- targetType,
- null,
- oaParam.getMandateProfiles(),
- citizenSignature);
-
- }
-
- } catch (STORKException e) {
- // this is really nasty but we work against the system here. We are supposed to get the gender attribute
- // from
- // stork. If we do not, we cannot register the person in the ERnP - we have to have the
- // gender for the represented person. So here comes the dirty hack.
- if (e.getCause() instanceof STORKException
- && e.getCause().getMessage().equals("gender not found in response")) {
- try {
- Logger.trace("Initialize VelocityEngine...");
-
- VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine();
- Template template = velocityEngine.getTemplate("/resources/templates/fetchGender.html");
- VelocityContext context = new VelocityContext();
- context.put("SAMLResponse", request.getParameter("SAMLResponse"));
- context.put("action", request.getRequestURL());
-
- StringWriter writer = new StringWriter();
- template.merge(context, writer);
-
- response.getOutputStream().write(writer.toString().getBytes("UTF-8"));
- } catch (Exception e1) {
- Logger.error("Error sending gender retrival form.", e1);
- // httpSession.invalidate();
- throw new MOAIDException("stork.10", null);
- }
-
- return;
- }
-
- Logger.error("Error connecting SZR Gateway", e);
- throw new MOAIDException("stork.10", null);
- }
- Logger.debug("SZR communication was successfull");
-
- if (identityLink == null) {
- Logger.error("SZR Gateway did not return an identity link.");
- throw new MOAIDException("stork.10", null);
- }
-
- MOAReversionLogger.getInstance().logEvent(pendingReq, MOAIDEventConstants.AUTHPROCESS_PEPS_IDL_RECEIVED);
- moaSession.setForeigner(true);
-
- Logger.info("Received Identity Link from SZR Gateway");
- executionContext.put("identityLinkAvailable", true);
- moaSession.setIdentityLink(identityLink);
-
- Logger.debug("Adding addtional STORK attributes to MOA session");
- moaSession.setStorkAttributes(attributeList);
-
- Logger.debug("Add full STORK AuthnResponse to MOA session");
- moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));
-
- // We don't have BKUURL, setting from null to "Not applicable"
- moaSession.setBkuURL("Not applicable (STORK Authentication)");
-
- // free for single use
- moaSession.setAuthenticatedUsed(false);
-
- // stork did the authentication step
- moaSession.setAuthenticated(true);
-
- // do PEPS-conform logging for easier evaluation
- try {
- // 2015-03-12 16:44:27.144#S-PEPS generates response to SP#orig_msg_id id1 (in response to)#status#msghash#msg_id id4#
- Logger.info(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date()) + "#S-PEPS generates response to SP#" +
- "#" + moaSession.getProcessInstanceId() + "#" + authnResponse.getMessage() + "#_hash_#" + moaSession.getProcessInstanceId() + "#");
- } catch (Exception e1) {
- Logger.info("STORK PEPS conform logging failed because of: " + e1.getMessage());
- }
-
- // TODO: found better solution, but QAA Level in STORK response is not be supported yet
-// try {
-//
-// moaSession.setQAALevel(authnResponse.getAssertions().get(0).getAuthnStatements().get(0)
-// .getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef());
-//
-// } catch (Throwable e) {
-// Logger.warn("STORK QAA-Level is not found in AuthnResponse. Set QAA Level to requested level");
-// moaSession.setQAALevel(PVPConstants.STORK_QAA_PREFIX + oaParam.getQaaLevel());
-//
-// }
-
- // session is implicit stored in changeSessionID!!!!
- String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
-
- Logger.info("Changed MOASession " + moaSessionID + " to Session " + newMOASessionID);
-
- // redirect
- String redirectURL = null;
- redirectURL = new DataURLBuilder().buildDataURL(moaSession.getAuthURL(),
- ModulUtils.buildAuthURL(moaSession.getModul(), moaSession.getAction(), pendingRequestID),
- newMOASessionID);
- redirectURL = response.encodeRedirectURL(redirectURL);
-
- // response.setContentType("text/html");
- // response.setStatus(302);
- // response.addHeader("Location", redirectURL);
- response.sendRedirect(redirectURL);
- Logger.info("REDIRECT TO: " + redirectURL);
-
- } catch (AuthenticationException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (MOAIDException e) {
- throw new TaskExecutionException(e.getMessage(), e);
-
- } catch (Exception e) {
- Logger.error("PEPSConnector has an interal Error.", e);
- throw new TaskExecutionException(e.getMessage(), e);
- }
-
- finally {
-
- }
-
- }
-
- private boolean isDocumentServiceUsed(String citizenSignature) // TODo add better check
- {
- if (citizenSignature
- .contains("<table border=\"0\"><tr><td>Service Name:</td><td>{http://stork.eu}DocumentService</td></tr><tr><td>Port Name:</td><td>{http://stork.eu}DocumentServicePort</td></tr></table>")) {
- Logger.trace("isDocumentServiceUsed => true");
- return true;
- }
-
- Logger.trace("isDocumentServiceUsed => false");
- return false;
- }
-
- /**
- * Get DTL uril from the oasis sign response
- *
- * @param signRequest
- * The signature response
- * @return The URL of DTL service
- * @throws SimpleException
- */
- private String getDtlUrlFromResponse(SignResponse dssSignResponse) {
- List<DocumentWithSignature> documents = ApiUtils.findNamedElement(dssSignResponse.getOptionalOutputs(),
- ApiUtils.OPTIONAL_OUTPUT_DOCUMENTWITHSIGNATURE, DocumentWithSignature.class);
- DocumentType sourceDocument = documents.get(0).getDocument();
-
- if (sourceDocument.getDocumentURL() != null)
- return sourceDocument.getDocumentURL();
- else
- return null;// throw new Exception("No document url found");
- }
-
- // From DTLPEPSUTIL
-
- /**
- * Get document from DTL
- *
- * @param transferRequest
- * The transfer request (attribute query)
- * @param eDtlUrl
- * The DTL url of external DTL
- * @return the document data
- * @throws SimpleException
- */
- private byte[] getDocumentFromDtl(String transferRequest, String eDtlUrl) throws Exception {
- URL url = null;
- try {
-
- Logger.trace("getDocumentFromDtl, dtlUrl:'"+getdtlUrl()+"' eDtlUrl:'"+eDtlUrl+"'");
- url = new URL(getdtlUrl());
- QName qname = new QName("http://stork.eu", "DocumentService");
-
- Service service = Service.create(url, qname);
- DocumentService docservice = service.getPort(DocumentService.class);
-
- BindingProvider bp = (BindingProvider) docservice;
- SOAPBinding binding = (SOAPBinding) bp.getBinding();
- binding.setMTOMEnabled(true);
-
- if (eDtlUrl.equalsIgnoreCase(getdtlUrl()))
- return docservice.getDocument(transferRequest, "");
- else
- return docservice.getDocument(transferRequest, eDtlUrl);
- } catch (Exception e) {
- e.printStackTrace();
- throw new Exception("Error in getDocumentFromDtl", e);
- }
- }
-
- /**
- * Get a document transfer request (attribute query)
- *
- * @param docId
- * @return
- * @throws SimpleException
- */
- private String getDocTransferRequest(String docId, String destinationUrl) throws Exception {
- String spCountry = docId.substring(0, docId.indexOf("/"));
- final STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP");
- STORKAttrQueryRequest req = new STORKAttrQueryRequest();
- req.setAssertionConsumerServiceURL(getdtlUrl());
- req.setDestination(destinationUrl);
- req.setSpCountry(spCountry);
- req.setQaa(3);// TODO
- PersonalAttributeList pal = new PersonalAttributeList();
- PersonalAttribute attr = new PersonalAttribute();
- attr.setName("docRequest");
- attr.setIsRequired(true);
- attr.setValue(Arrays.asList(docId));
- pal.add(attr);
- req.setPersonalAttributeList(pal);
-
- STORKAttrQueryRequest req1;
- try {
- req1 = engine.generateSTORKAttrQueryRequest(req);
- return PEPSUtil.encodeSAMLTokenUrlSafe(req1.getTokenSaml());
- } catch (STORKSAMLEngineException e) {
- e.printStackTrace();
- throw new Exception("Error in doc request attribute query generation", e);
- }
- }
-
- private String getdtlUrl() {
- String dtlUrl;
- try {
- AuthConfiguration authConfigurationProvider = AuthConfigurationProviderFactory.getInstance();
- dtlUrl = authConfigurationProvider.getDocumentServiceUrl();
- Logger.info ("PEPSConnectorServlet, using dtlUrl:"+dtlUrl);
-
- } catch (Exception e) {
- dtlUrl = "http://testvidp.buergerkarte.at/DocumentService/DocumentService";
- Logger.error("Loading documentservice url failed, using default value:"+dtlUrl, e);
-
- }
-
-
-// Properties props = new Properties();
-// try {
-// props.load(DatabaseConnectorMySQLImpl.class.getResourceAsStream("docservice.properties"));
-// dtlUrl = props.getProperty("docservice.url");
-// } catch (IOException e) {
-// dtlUrl = "http://testvidp.buergerkarte.at/DocumentService/DocumentService";
-// Logger.error("Loading DTL config failed, using default value:" + dtlUrl);
-// e.printStackTrace();
-// }
-
- return dtlUrl;
-
- }
-
- private String loadDocumentFromDocumentService(SignResponse dssSignResponse) throws Exception
- {
- Logger.debug("Loading document from DocumentService.");
- String url = getDtlUrlFromResponse(dssSignResponse);
- Logger.debug("Loading document from DocumentService, url:"+url);
- //get Transferrequest
- String transferRequest = getDocTransferRequest(dssSignResponse.getDocUI(), url);
- //Load document from DocumentService
- byte[] data = getDocumentFromDtl(transferRequest, url);
- String citizenSignature = new String(data, "UTF-8");
- Logger.debug("Overridung citizenSignature with:"+citizenSignature);
- return citizenSignature;
- }
-
-}
diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java deleted file mode 100644 index 65a3637a9..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java +++ /dev/null @@ -1,286 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - ******************************************************************************/ -/** - * - */ -package at.gv.egovernment.moa.id.auth.stork; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; -import java.util.Vector; - -import javax.activation.DataSource; -import javax.xml.transform.Source; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.stream.StreamSource; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringEscapeUtils; - -import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttribute; -import at.gv.egovernment.moa.id.auth.data.ExtendedSAMLAttributeImpl; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.exception.ParseException; -import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser; -import at.gv.egovernment.moa.id.client.SZRGWClientException; -import at.gv.egovernment.moa.id.client.utils.SZRGWClientUtils; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Constants; -import at.gv.egovernment.moa.util.DateTimeUtils; -import at.gv.egovernment.moa.util.StringUtils; -import at.gv.util.xsd.srzgw.CreateIdentityLinkResponse; -import eu.stork.oasisdss.api.ApiUtils; -import eu.stork.oasisdss.api.LightweightSourceResolver; -import eu.stork.oasisdss.api.exceptions.ApiUtilsException; -import eu.stork.oasisdss.api.exceptions.UtilsException; -import eu.stork.oasisdss.profile.SignResponse; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PersonalAttribute; - -/** - * - * Handles all functionality for the processing of a STORK response - * @author bzwattendorfer - * - */ -public class STORKResponseProcessor { - - /** OASIS DSS Namespace */ - public static final String OASIS_DSS_NS = "urn:oasis:names:tc:dss:1.0:core:schema"; - - /** OASIS DSS Success Message */ - public static final String OASIS_DSS_SUCCESS_MSG = "urn:oasis:names:tc:dss:1.0:resultmajor:Success"; - - /** - * Checks for attribute. - * - * @param attributeName the attribute name - * @param attributeList the attribute list - * @return true, if successful - */ - public static boolean hasAttribute(String attributeName, IPersonalAttributeList attributeList) { - try { - getAttributeValue(attributeName, attributeList); - return true; - } catch(STORKException e) { - return false; - } - } - - /** - * helper for reading attributes. Handles logging and error handling. - * - * @param attributeName the attribute name - * @param attributeList the attribute list - * @return the attribute value - * @throws STORKException the sTORK exception - */ - private static String getAttributeValue(String attributeName, IPersonalAttributeList attributeList) throws STORKException { - return getAttributeValue(attributeName, attributeList, true); - } - public static String getAttributeValue(String attributeName, IPersonalAttributeList attributeList, boolean throwException) throws STORKException { - try { - String result = attributeList.get(attributeName).getValue().get(0); - Logger.trace(attributeName + " : " + result); - return result; - } catch(Exception e) { - Logger.error(attributeName + " not found in response"); - if(throwException) - throw new STORKException(attributeName + " not found in response"); - else - return null; - } - } - - /** - * Handels connection to SZR-GW and returns Identity Link on success. - * - * @param attributeList the attribute list - * @param oaFriendlyName the oa friendly name - * @param targetType the target type - * @param targetValue the target value - * @param filters the filters - * @param citizenSignature2 - * @return Identity Link - * @throws STORKException the sTORK exception - * @throws MOAIDException - */ - public static IdentityLink connectToSZRGateway(IPersonalAttributeList attributeList, String oaFriendlyName, String targetType, String targetValue, List<String> filters, String citizenSignature) throws STORKException, MOAIDException { - Logger.trace("Calling SZR Gateway with the following attributes:"); - - CreateIdentityLinkResponse identityLinkResponse = null; - IdentityLink identityLink = null; - try { - Logger.trace("Starting call..."); - - // if there is no signedDoc attribute, we cannot go on - if(citizenSignature==null || citizenSignature.length()==0) - { - String signResponseString = getAttributeValue("signedDoc", attributeList); - - //Extract signature from SIgnResponse - Source response1 = new StreamSource(new java.io.StringReader(signResponseString)); - SignResponse dssSignResponse = ApiUtils.unmarshal(response1, SignResponse.class); - citizenSignature = getCitizienSignatureFromSignResponse(dssSignResponse); - } - - String fiscalNumber = getAttributeValue("fiscalNumber", attributeList, false); - - // if we have a signedDoc we test for a representation case - // - according to stork samlengine and commons - if(hasAttribute("mandate", attributeList)) { - // we have a representation case - String mandate = getAttributeValue("mandate", attributeList, false); - - if(!hasAttribute("dateOfBirth", attributeList)) { - // if we get here, we have a natural person representing a legal person - String organizationAddress = getAttributeValue("canonicalRegisteredAddress", attributeList, false); - String organizationType = getAttributeValue("translateableType", attributeList, false); - - identityLinkResponse = SZRGWClientUtils.getIdentityLink(citizenSignature, null, null, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters, fiscalNumber); - } else { - // if we get here, we have a natural person representing another natural person - String eIdentifier = getAttributeValue("eIdentifier", attributeList, false); - String givenName = getAttributeValue("givenName", attributeList, false); - String lastName = getAttributeValue("surname", attributeList, false); - String dateOfBirth = getAttributeValue("dateOfBirth", attributeList, false); - - // gender attribute is mandatory here because of some legal stuff - String gender = getAttributeValue("gender", attributeList, false); - - if (!StringUtils.isEmpty(dateOfBirth)) - dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth); - - identityLinkResponse = SZRGWClientUtils.getIdentityLink(eIdentifier, - givenName, lastName, dateOfBirth, gender, citizenSignature, null, - null, mandate, targetType, targetValue, oaFriendlyName, filters, fiscalNumber); - } - } - // - according to stork spec - else if(hasAttribute("mandateContent", attributeList) || hasAttribute("representative", attributeList) || hasAttribute("represented", attributeList)) { - // we have a representation case - String representative = getAttributeValue("representative", attributeList, false); - String represented = getAttributeValue("represented", attributeList, false); - String mandate = getAttributeValue("mandateContent", attributeList, false); - - if(!hasAttribute("dateOfBirth", attributeList)) { - // if we get here, we have a natural person representing a legal person - String organizationAddress = getAttributeValue("canonicalRegisteredAddress", attributeList, false); - String organizationType = getAttributeValue("translateableType", attributeList, false); - - identityLinkResponse = SZRGWClientUtils.getIdentityLink(citizenSignature, representative, represented, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters, fiscalNumber); - } else { - // if we get here, we have a natural person representing another natural person - String eIdentifier = getAttributeValue("eIdentifier", attributeList, false); - String givenName = getAttributeValue("givenName", attributeList, false); - String lastName = getAttributeValue("surname", attributeList, false); - String dateOfBirth = getAttributeValue("dateOfBirth", attributeList, false); - - // gender attribute is mandatory here because of some legal stuff - String gender = getAttributeValue("gender", attributeList, false); - - if (!StringUtils.isEmpty(dateOfBirth)) - dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth); - - identityLinkResponse = SZRGWClientUtils.getIdentityLink(eIdentifier, - givenName, lastName, dateOfBirth, gender, citizenSignature, representative, - represented, mandate, targetType, targetValue, oaFriendlyName, filters, fiscalNumber); - } - } else { - // we do not have a representation case - String eIdentifier = getAttributeValue("eIdentifier", attributeList, false); - String givenName = getAttributeValue("givenName", attributeList, false); - String lastName = getAttributeValue("surname", attributeList, false); - String dateOfBirth = getAttributeValue("dateOfBirth", attributeList, false); - if (!StringUtils.isEmpty(dateOfBirth)) - dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth); - identityLinkResponse = SZRGWClientUtils.getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, citizenSignature, fiscalNumber); - } - - if (null != identityLinkResponse.getErrorResponse()){ - throw new SZRGWClientException("service.08", (String)identityLinkResponse.getErrorResponse().getErrorCode(), - (String)identityLinkResponse.getErrorResponse().getInfo()); - } - else { - IdentityLinkAssertionParser ilParser = new IdentityLinkAssertionParser(new ByteArrayInputStream(identityLinkResponse.getIdentityLink())); - identityLink = ilParser.parseIdentityLink(); - - Logger.debug("Received Identity Link from SZR Gateway"); - //TODO: is this ok? -// if (StringUtils.isEmpty(identityLink.getDateOfBirth())) { -// identityLink.setDateOfBirth("9999-12-31"); -// } - - } - - } catch (ParseException e) { - Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); - throw new MOAIDException("auth.25", null, e); - } catch (ApiUtilsException e) { - Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); - throw new MOAIDException("auth.25", null, e); - } catch (IllegalArgumentException e) { - Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); - throw new MOAIDException("auth.25", null, e); - } catch (TransformerConfigurationException e) { - Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); - throw new MOAIDException("auth.25", null, e); - } catch (UtilsException e) { - Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); - throw new MOAIDException("auth.25", null, e); - } catch (TransformerException e) { - Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); - throw new MOAIDException("auth.25", null, e); - } catch (TransformerFactoryConfigurationError e) { - Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); - throw new MOAIDException("auth.25", null, e); - } catch (IOException e) { - Logger.error("Error parsing IdentityLink received from SZR-Gateway: ", e); - throw new MOAIDException("auth.25", null, e); - } - - return identityLink; - - } - - private static String getCitizienSignatureFromSignResponse(SignResponse dssSignResponse) throws IllegalArgumentException, TransformerConfigurationException, UtilsException, TransformerException, TransformerFactoryConfigurationError, IOException, ApiUtilsException - { - // fetch signed doc - DataSource ds = LightweightSourceResolver.getDataSource(dssSignResponse); - if(ds == null){ - throw new ApiUtilsException("No datasource found in response"); - } - - InputStream incoming = ds.getInputStream(); - String citizenSignature = IOUtils.toString(incoming); - incoming.close(); - - return citizenSignature; - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java deleted file mode 100644 index 124e490f2..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAdoptedFamilyNameAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKAdoptedFamilyNameAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.ADOPTEDFAMILYNAME_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.ADOPTEDFAMILYNAME_FRIENDLYNAME, STORKConstants.ADOPTEDFAMILYNAME_NAME, - STORKAttributHelper.getAttribut(STORKConstants.ADOPTEDFAMILYNAME_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.ADOPTEDFAMILYNAME_FRIENDLYNAME, STORKConstants.ADOPTEDFAMILYNAME_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAttributHelper.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAttributHelper.java deleted file mode 100644 index 9a0598cf6..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKAttributHelper.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PersonalAttribute; -import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -import at.gv.egovernment.moa.logging.Logger; - -/** - * @author tlenz - * - */ -public class STORKAttributHelper { - - public static String getAttribut(String attributName, - IAuthData authSession) throws UnavailableAttributeException { - - if (!authSession.isForeigner()) { - throw new UnavailableAttributeException(attributName); - - } else { - IPersonalAttributeList storkAttributes = authSession.getStorkAttributes(); - - if ( storkAttributes == null ) { - throw new UnavailableAttributeException(attributName); - - } - - try { - PersonalAttribute attribut = storkAttributes.get(attributName); - if (attribut != null) { - - return attribut.getValue().get(0); - - } else - throw new UnavailableAttributeException(attributName); - - } catch (Exception e) { - Logger.warn("Attribut " + attributName + " generation error", e); - throw new UnavailableAttributeException(attributName); - } - } - - } -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java deleted file mode 100644 index 66d8a6bc1..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCanonicalResidenceAddressAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKCanonicalResidenceAddressAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.CANONICALRESIDENCEADDRESS_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.CANONICALRESIDENCEADDRESS_FRIENDLYNAME, STORKConstants.CANONICALRESIDENCEADDRESS_NAME, - STORKAttributHelper.getAttribut(STORKConstants.CANONICALRESIDENCEADDRESS_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.CANONICALRESIDENCEADDRESS_FRIENDLYNAME, STORKConstants.CANONICALRESIDENCEADDRESS_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java deleted file mode 100644 index 706f5dd3a..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKCountryCodeOfBirthAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKCountryCodeOfBirthAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.CONTRYCODEOFBIRTH_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.CONTRYCODEOFBIRTH_FRIENDLYNAME, STORKConstants.CONTRYCODEOFBIRTH_NAME, - STORKAttributHelper.getAttribut(STORKConstants.CONTRYCODEOFBIRTH_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.CONTRYCODEOFBIRTH_FRIENDLYNAME, STORKConstants.CONTRYCODEOFBIRTH_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKFiscalNumberAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKFiscalNumberAttributBuilder.java deleted file mode 100644 index adc1d28da..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKFiscalNumberAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKFiscalNumberAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.FISCALNUMBER_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.FISCALNUMBER_FRIENDLYNAME, STORKConstants.FISCALNUMBER_NAME, - STORKAttributHelper.getAttribut(STORKConstants.FISCALNUMBER_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.FISCALNUMBER_FRIENDLYNAME, STORKConstants.FISCALNUMBER_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKGenderAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKGenderAttributBuilder.java deleted file mode 100644 index 2faeaf2d7..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKGenderAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKGenderAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.GENDER_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.GENDER_FRIENDLYNAME, STORKConstants.GENDER_NAME, - STORKAttributHelper.getAttribut(STORKConstants.GENDER_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.GENDER_FRIENDLYNAME, STORKConstants.GENDER_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java deleted file mode 100644 index b6d29d42f..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKInhertedFamilyNameAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKInhertedFamilyNameAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.INHERITEDFAMILYNAME_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.INHERITEDFAMILYNAME_FRIENDLYNAME, STORKConstants.INHERITEDFAMILYNAME_NAME, - STORKAttributHelper.getAttribut(STORKConstants.INHERITEDFAMILYNAME_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.INHERITEDFAMILYNAME_FRIENDLYNAME, STORKConstants.INHERITEDFAMILYNAME_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKIsAgeOverAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKIsAgeOverAttributBuilder.java deleted file mode 100644 index 2ac3e2aaa..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKIsAgeOverAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKIsAgeOverAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.ISAGEOVER_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.ISAGEOVER_FRIENDLYNAME, STORKConstants.ISAGEOVER_NAME, - STORKAttributHelper.getAttribut(STORKConstants.ISAGEOVER_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.ISAGEOVER_FRIENDLYNAME, STORKConstants.ISAGEOVER_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKMaritalStatusAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKMaritalStatusAttributBuilder.java deleted file mode 100644 index c4e42029e..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKMaritalStatusAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKMaritalStatusAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.MARITALSTATUS_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.MARITALSTATUS_FRIENDLYNAME, STORKConstants.MARITALSTATUS_NAME, - STORKAttributHelper.getAttribut(STORKConstants.MARITALSTATUS_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.MARITALSTATUS_FRIENDLYNAME, STORKConstants.MARITALSTATUS_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKNationalityCodeAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKNationalityCodeAttributBuilder.java deleted file mode 100644 index 47fbdd145..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKNationalityCodeAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKNationalityCodeAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.NATIONALITYCODE_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.NATIONALITYCODE_FRIENDLYNAME, STORKConstants.NATIONALITYCODE_NAME, - STORKAttributHelper.getAttribut(STORKConstants.NATIONALITYCODE_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.NATIONALITYCODE_FRIENDLYNAME, STORKConstants.NATIONALITYCODE_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKPseudonymAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKPseudonymAttributBuilder.java deleted file mode 100644 index 6b079b8d4..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKPseudonymAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKPseudonymAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.PSEUDONYM_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.PSEUDONYM_FRIENDLYNAME, STORKConstants.PSEUDONYM_NAME, - STORKAttributHelper.getAttribut(STORKConstants.PSEUDONYM_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.PSEUDONYM_FRIENDLYNAME, STORKConstants.PSEUDONYM_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKResidencePermitAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKResidencePermitAttributBuilder.java deleted file mode 100644 index 5728a3979..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKResidencePermitAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKResidencePermitAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.RESIDENCEPERMIT_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.RESIDENCEPERMIT_FRIENDLYNAME, STORKConstants.RESIDENCEPERMIT_NAME, - STORKAttributHelper.getAttribut(STORKConstants.RESIDENCEPERMIT_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.RESIDENCEPERMIT_FRIENDLYNAME, STORKConstants.RESIDENCEPERMIT_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTextResidenceAddressAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTextResidenceAddressAttributBuilder.java deleted file mode 100644 index 1879eb42a..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTextResidenceAddressAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKTextResidenceAddressAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.TEXTRESIDENCEADDRESS_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.TEXTRESIDENCEADDRESS_FRIENDLYNAME, STORKConstants.TEXTRESIDENCEADDRESS_NAME, - STORKAttributHelper.getAttribut(STORKConstants.TEXTRESIDENCEADDRESS_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.TEXTRESIDENCEADDRESS_FRIENDLYNAME, STORKConstants.TEXTRESIDENCEADDRESS_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTitleAttributBuilder.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTitleAttributBuilder.java deleted file mode 100644 index 107386b5a..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/builder/attributes/STORKTitleAttributBuilder.java +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.builder.attributes; - -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; - -public class STORKTitleAttributBuilder implements IPVPAttributeBuilder { - - public String getName() { - return STORKConstants.TITLE_NAME; - } - - public <ATT> ATT build(IOAAuthParameters oaParam, IAuthData authData, - IAttributeGenerator<ATT> g) throws AttributeException { - - return g.buildStringAttribute(STORKConstants.TITLE_FRIENDLYNAME, STORKConstants.TITLE_NAME, - STORKAttributHelper.getAttribut(STORKConstants.TITLE_NAME, authData)); - - } - - public <ATT> ATT buildEmpty(IAttributeGenerator<ATT> g) { - return g.buildEmptyAttribute(STORKConstants.TITLE_FRIENDLYNAME, STORKConstants.TITLE_NAME); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java deleted file mode 100644 index 2e72f216a..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java +++ /dev/null @@ -1,367 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationImpl; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.logging.Logger; -import eu.stork.peps.auth.commons.*; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.AttributeStatusType; -import eu.stork.peps.exceptions.STORKSAMLEngineException; - -import org.opensaml.common.impl.SecureRandomIdentifierGenerator; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * The AttributeCollector Action tries to get all requested attributes from a set of {@link AttributeProvider} Plugins. - * 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. - * - * TODO how do we treat mandatory and optional attributes? - */ -public class AttributeCollector implements IAction { - - /** - * The Constant ARTIFACT_ID. - */ - private static final String ARTIFACT_ID = "artifactId"; - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.auth.data.AuthenticationSession) - */ - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { - - // - fetch the container - String artifactId = (String) httpReq.getParameter(ARTIFACT_ID); - DataContainer container; - try { - container = AssertionStorage.getInstance().get(artifactId, DataContainer.class); - } catch (MOADatabaseException e) { - Logger.error("Error fetching incomplete Stork response from temporary storage. Most likely a timeout occured.", e); - throw new MOAIDException("stork.11", null); - } - - - if (httpReq.getParameter("SAMLResponse") != null) { - Logger.info("Got SAML response from external attribute provider."); - - MOASTORKResponse STORK2Response = new MOASTORKResponse(httpReq); - - //extract STORK Response from HTTP Request - byte[] decSamlToken; - try { - decSamlToken = PEPSUtil.decodeSAMLToken(httpReq.getParameter("SAMLResponse")); - } catch (NullPointerException e) { - if (httpReq.getRemoteHost().contains("129.27.142")) { - Logger.warn("Availability check by " + httpReq.getRemoteHost() + " on URI: " + httpReq.getRequestURI()); - } else { - Logger.error("Unable to retrieve STORK Request for host: " + httpReq.getRemoteHost() + " and URI: " + httpReq.getRequestURI(), e); - } - throw new MOAIDException("stork.04", null); - } - - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - - STORKAuthnResponse authnResponse = null; - - - // check if valid authn response is contained - try { - authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, httpReq.getRemoteAddr()); - } catch (STORKSAMLEngineException ex) { - Logger.error("Unable to validate Stork AuthenticationResponse: " + ex.getMessage()); - } - - STORK2Response.setSTORKAuthnResponseToken(decSamlToken); - - // check if the attributes are provided for the same person from request - // requires presence of eIdentifier for unambigious correlation - Logger.debug("Checking if the attribute relates to the correct person.."); - try { - String remoteEIdentifier= authnResponse.getPersonalAttributeList().get("eIdentifier").getValue().get(0); - String localEidentifier= container.getResponse().getStorkAuthnResponse().getPersonalAttributeList().get("eIdentifier").getValue().get(0); - if (!remoteEIdentifier.equals(localEidentifier)) { - Logger.error("The attribute is not provided for the same person!"); - throw new MOAIDException("stork.25", null); - } - } catch (NullPointerException ex) { - Logger.warn("Could not check the correlation of attributes from external provider. Ignoring the check."); - //Logger.debug(ex); - //throw new MOAIDException("stork.04", null); // TODO revise message, raise exception when ehvd checked - } - - if (authnResponse.getPersonalAttributeList().size() > 0) { - Logger.info("Response from external attribute provider contains " + authnResponse.getPersonalAttributeList().size() + " attributes."); - container.getResponse().setPersonalAttributeList(addOrUpdateAll(container.getResponse().getPersonalAttributeList(), authnResponse.getPersonalAttributeList())); - } - - } - - // end addition - - - // read configuration parameters of OA - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(container.getRequest().getAssertionConsumerServiceURL()); - if (oaParam == null) - throw new AuthenticationException("stork.12", new Object[]{container.getRequest().getAssertionConsumerServiceURL()}); - - // find the attribute provider plugin that can handle the response - IPersonalAttributeList newAttributes = null; - - Iterator<AttributeProvider> attibuteProvidersInterator = AttributeProviderFactory.getConfiguredPlugins(oaParam.getStorkAPs()); - while(attibuteProvidersInterator.hasNext()) - try { - newAttributes = attibuteProvidersInterator.next().parse(httpReq); - - // stop as soon as we hit a capable plugin - break; - } catch (UnsupportedAttributeException e1) { - // the current provider cannot find anything familiar within the - // provided httpreq. Try the next one. - } - - if (null == newAttributes) { - // we do not have a provider which is capable of fetching something - // from the received httpreq. - Logger.error("No attribute could be retrieved from the response the attribute provider gave us."); - } - - // - insert the embedded attribute(s) into the container - if (null != newAttributes) - container.getResponse().setPersonalAttributeList(addOrUpdateAll(container.getResponse().getPersonalAttributeList(), newAttributes)); - - // see if we need some more attributes - SLOInformationImpl sloInfo = (SLOInformationImpl) processRequest(container, httpReq, httpResp, authData, oaParam); - - if (sloInfo == null) { - sloInfo = new SLOInformationImpl(req.getAuthURL(), null, null, null, req.requestedModule()); - } - - return sloInfo; - - } - - /** - * Checks if there are missing attributes and tries to fetch them. If there are no more attribute to fetch, - * this very method creates and sends the protocol result to the asking S-PEPS. - * - * @param container the {@link DataContainer} representing the status of the overall query. - * @return the string - * @throws MOAIDException - */ - public SLOInformationInterface processRequest(DataContainer container, HttpServletRequest request, HttpServletResponse response, IAuthData authData, OAAuthParameter oaParam) throws MOAIDException { - // check if there are attributes we need to fetch - - IPersonalAttributeList requestAttributeList = container.getRequest().getPersonalAttributeList(); - IPersonalAttributeList responseAttributeList = container.getResponse().getPersonalAttributeList(); - List<PersonalAttribute> missingAttributes = new ArrayList<PersonalAttribute>(); - Logger.debug("aquire list of missing attributes"); - for (PersonalAttribute current : requestAttributeList) - if (!responseAttributeList.containsKey(current.getName())) { - if(null == current.getStatus() || (null != current.getStatus() && !current.getStatus().equals(AttributeStatusType.WITHHELD.value()))) { - // add the ones we need - missingAttributes.add(current); - Logger.debug("add " + current.getName() + " to the list of missing attributes"); - } - } else { - // remove the ones we do not want to share from the response list - if(null != current.getStatus() && current.getStatus().equals(AttributeStatusType.WITHHELD.value())) { - responseAttributeList.remove(current.getName()); - Logger.debug("remove " + current.getName() + " from the list of resulting attributes because the user does not want to disclose the data"); - } - } - - Logger.info("collecting attributes..."); - Logger.debug("found " + missingAttributes.size() + " missing attributes"); - - // Try to get all missing attributes - try { - // for each attribute still missing - for (PersonalAttribute currentAttribute : missingAttributes) { - - /* - * prefill attributes with "notAvailable". If we get them later, we override the value and status. - * This way, there is no error case in which an attribute is left unanswered. - */ - IPersonalAttributeList aquiredAttributes = new PersonalAttributeList(); - currentAttribute.setStatus(AttributeStatusType.NOT_AVAILABLE.value()); - aquiredAttributes.add((PersonalAttribute) currentAttribute.clone()); - container.getResponse().setPersonalAttributeList( - addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes)); - // - check if we can find a suitable AttributeProvider Plugin - - Iterator<AttributeProvider> attibuteProvidersInterator = AttributeProviderFactory.getConfiguredPlugins(oaParam.getStorkAPs()); - while(attibuteProvidersInterator.hasNext()) { - AttributeProvider currentProvider = attibuteProvidersInterator.next(); - - // build a section of attribute provider's predefined attributes and missing attributes - // only missing attributes that can be handled by attribute provider will be sent to it - List<PersonalAttribute> currentProviderConfiguredAttributes = new ArrayList<PersonalAttribute>(); - for (String attributeName : currentProvider.getSupportedAttributeNames()) { - for (PersonalAttribute missingAttribute : missingAttributes) { - if (missingAttribute.getName().equals(attributeName)) { - currentProviderConfiguredAttributes.add(missingAttribute); - break; - } - } - } - - try { - // - hand over control to the suitable plugin - Logger.info(currentProvider.getClass().getSimpleName() + " called to handle attribute '" + currentAttribute.getName() + "'"); - - //aquiredAttributes = currentProvider.acquire(currentAttribute, container.getRequest().getSpCountry(), moasession); - //aquiredAttributes = currentProvider.acquire(missingAttributes, container.getRequest().getSpCountry(), moasession); - aquiredAttributes = currentProvider.acquire(currentProviderConfiguredAttributes, container.getRequest(), authData); - - Logger.info(currentProvider.getClass().getSimpleName() + " can handle attribute '" + currentAttribute.getName() + "'"); - break; - } catch (UnsupportedAttributeException e) { - // ok, try the next attributeprovider - Logger.info(currentProvider.getClass().getSimpleName() + " could not handle attribute '" + currentAttribute.getName() + "'"); - } catch (MOAIDException e) { - // the current plugin had an error. Try the next one. - Logger.info(currentProvider.getClass().getSimpleName() + " could not handle attribute '" + currentAttribute.getName() + "' due to an error"); - } - } - - // check if we could fetch the attribute - if (null == aquiredAttributes) { - // if not - Logger.error("We have no suitable plugin for obtaining the attribute '" + currentAttribute.getName() + "'"); - } else - // else, update any existing attributes - container.getResponse().setPersonalAttributeList(addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes)); - } - Logger.info("collecting attributes done"); - - // ask for consent if necessary - new ConsentEvaluator().generateSTORKResponse(response, container); - - return null; // AssertionId - // TODO - - } catch (ExternalAttributeRequestRequiredException e) { - // the attribute request is ongoing and requires an external service. - try { - // memorize the container again - Logger.debug("prepare putting the container into temporary storage..."); - - // - generate new key - String newArtifactId = new SecureRandomIdentifierGenerator() - .generateIdentifier(); - // - put container in temporary store. - AssertionStorage.getInstance().put(newArtifactId, container); - - Logger.debug("...successful"); - - Logger.info(e.getAp().getClass().getSimpleName() + " is going to ask an external service provider for the requested attributes"); - - // add container-key to redirect embedded within the return URL - e.getAp().performRedirect(AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix().get(0) + "/stork2/ResumeAuthentication?" + ARTIFACT_ID + "=" + newArtifactId, request, response, oaParam); - - } catch (Exception e1) { - // TODO should we return the response as is to the PEPS? - Logger.error("Error putting incomplete Stork response into temporary storage", e1); - e1.printStackTrace(); - throw new MOAIDException("stork.11", null); - } - - //TODO: in case of Single LogOut -> SLO information has to be stored - return null; // TODO what to do here? - } - } - - /** - * Adds or updates all {@link PersonalAttribute} objects given in {@code source} to/in {@code target}. - * - * @param target the target - * @param source the source - * @return - * @throws MOAIDException - */ - private PersonalAttributeList addOrUpdateAll(IPersonalAttributeList target, IPersonalAttributeList source) throws MOAIDException { - - PersonalAttributeList updatedList = new PersonalAttributeList(); - for (PersonalAttribute el : target) - updatedList.add(el); - - Logger.debug("Updating " + source.size() + " attributes..."); - for (PersonalAttribute current : source) { - Logger.debug("treating " + current.getName()); - - // check if we need to update the current pa - if (updatedList.containsKey(current.getName())) { - PersonalAttribute existing = target.get(current.getName()); - if(!(existing.isEmptyValue() && existing.isEmptyComplexValue())) - if(!(existing.getValue().equals(current.getValue()) || existing.getComplexValue().equals(current.getComplexValue()))) { - Logger.error("Attribute Value does not match the value from first authentication!"); - throw new MOAIDException("stork.16", new Object[] {existing.getName()}); - } - - updatedList.get(current.getName()).setStatus(current.getStatus()); - updatedList.get(current.getName()).setValue(current.getValue()); - updatedList.get(current.getName()).setComplexValue(current.getComplexValue()); - } else - updatedList.add(current); - - Logger.debug("...successfully treated " + current.getName()); - } - - return updatedList; - } - - /* (non-Javadoc) - * @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. - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() - */ - public String getDefaultActionName() { - return STORKProtocol.ATTRIBUTE_COLLECTOR; - } -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java deleted file mode 100644 index aadbbd959..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java +++ /dev/null @@ -1,101 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import at.gv.egovernment.moa.id.commons.MOAIDConstants; -import at.gv.egovernment.moa.id.config.stork.StorkAttributeProviderPlugin; -import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider; -import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.EHvdAttributeProviderPlugin; -import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.MandateAttributeRequestProvider; -import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.PVPAuthenticationProvider; -import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.SignedDocAttributeRequestProvider; -import at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.StorkAttributeRequestProvider; -import at.gv.egovernment.moa.logging.Logger; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.PriorityQueue; - -/** - * A factory for creating AttributeProvider objects. - */ -public class AttributeProviderFactory { - - /** - * Gets the available plugins. - * - * @return the available plugins - */ - public static List<String> getAvailablePlugins() { - return MOAIDConstants.ALLOWED_STORKATTRIBUTEPROVIDERS; - } - - /** - * Creates an AttributeProvider object for the given shortname. Returns - * {@code null} if there is no such provider available. - * - * @param shortname the simpleName for the providers class - * @return the attribute provider - */ - public static AttributeProvider create(String shortname, String url, String attributes) { - if (shortname.equals("StorkAttributeRequestProvider")) { - return new StorkAttributeRequestProvider(url, attributes); - } else if (shortname.equals("EHvdAttributeProvider")) { - return new EHvdAttributeProviderPlugin(url, attributes); - } else if (shortname.equals("SignedDocAttributeRequestProvider")) { - return new SignedDocAttributeRequestProvider(url, attributes); - } else if (shortname.equals("MandateAttributeRequestProvider")) { - try { - return new MandateAttributeRequestProvider(url, attributes); - } catch (Exception ex) { - ex.printStackTrace(); - return null; - } - } else if (shortname.equals("PVPAuthenticationProvider")) { - return new PVPAuthenticationProvider(url, attributes); - } else { - return null; - } - } - - /** - * Gets fresh instances of the configured plugins. - * - * @param collection the configured a ps - * @return the configured plugins - */ - public static Iterator<AttributeProvider> getConfiguredPlugins( - Collection<StorkAttributeProviderPlugin> collection) { - - PriorityQueue<AttributeProvider> result = new PriorityQueue<AttributeProvider>(); - for (StorkAttributeProviderPlugin current : collection) { - - result.add(create(current.getName(), current.getUrl(), current.getAttributes())); - Logger.debug("Adding configured attribute provider: " + current.getClass().getName() + current.getName() + " at " + current.getUrl()); - } - - return result.iterator(); - } -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java deleted file mode 100644 index f16f7c9a8..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java +++ /dev/null @@ -1,531 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.MISMandate; -import at.gv.egovernment.moa.id.data.SLOInformationImpl; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.id.util.VelocityProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; -import eu.stork.peps.auth.commons.*; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.exceptions.STORKSAMLEngineException; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.apache.velocity.runtime.RuntimeConstants; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.StringWriter; -import java.net.MalformedURLException; -import java.net.URL; - - -/** - * Second request step - after authentication of the user is done and moasession obtained, - * process request and forward the user further to PEPS and/or other entities - * - * @author bsuzic - */ - -public class AuthenticationRequest implements IAction { - - - private VelocityEngine velocityEngine; - private MOASTORKRequest moaStorkRequest = null; - - - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { - - if ((req instanceof MOASTORKRequest)) { // && ( ((MOASTORKRequest) req).getCitizenCountryCode() == null || ((MOASTORKRequest) req).getCitizenCountryCode().equals("AT") )) { - - this.moaStorkRequest = (MOASTORKRequest) req; - - Logger.debug("Entering MOASTORKRequest"); - httpResp.reset(); - - //TODO: CHECK: req.getOAURL() should return the unique OA identifier - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(req.getOAURL()); - if (oaParam == null) - throw new AuthenticationException("stork.12", new Object[]{req.getOAURL()}); - - MOASTORKResponse moaStorkResponse = new MOASTORKResponse(httpReq); - - // check if it is attribute query - if (moaStorkRequest.isAttrRequest()) { - Logger.debug("Starting AttrQueryRequest"); - - moaStorkResponse.setSTORKAttrResponse(new STORKAttrQueryResponse()); - } - // check if we have authentication request - else if (moaStorkRequest.isAuthnRequest()) { - Logger.debug("Starting AuthenticationRequest"); - moaStorkResponse.setSTORKAuthnResponse(new STORKAuthnResponse()); - - //STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - - // Logger.debug("Starting generation of SAML response"); - // try { - // moaStorkResponse.setSTORKAuthnResponse(engine.generateSTORKAuthnResponse(moaStorkRequest.getStorkAuthnRequest(), moaStorkResponse.getStorkAuthnResponse(), httpReq.getRemoteAddr(), false)); - // } catch (STORKSAMLEngineException ex) { - // Logger.error("Failed to generate STORK SAML Response", ex); - // throw new MOAIDException("stork.05", null); // TODO - // } - - // Get personal attributtes from MOA/IdentityLink - - //build STORK attributes from local authentication information - if (authData != null) { - int reqQaa = -1; - int authQaa = -1; - try { - reqQaa = moaStorkRequest.getStorkAuthnRequest().getQaa(); - authQaa = Integer.valueOf( - authData.getQAALevel().substring(PVPConstants.STORK_QAA_PREFIX.length())); - - if (reqQaa > authQaa) { - Logger.warn("Requested QAA level does not match to authenticated QAA level"); - throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa}); - - } - - } catch (MOAIDException e) { - throw e; - - } catch (Exception e) { - if (Logger.isDebugEnabled()) - Logger.warn("STORK QAA Level evaluation error", e); - - else - Logger.warn("STORK QAA Level evaluation error (ErrorMessage=" - + e.getMessage() + ")"); - - throw new MOAIDException("stork.21", new Object[]{reqQaa, authQaa}); - - } - - moaStorkResponse.setPersonalAttributeList(populateAttributes(authData, oaParam)); - - } - } - - //moaStorkResponse.setCountry(moaStorkRequest.getSpCountry()); - - // Prepare extended attributes - Logger.debug("Preparing data container"); - - // create fresh container - DataContainer container = new DataContainer(); - - // - fill in the request we extracted above - container.setRequest(moaStorkRequest); - - // - fill in the partial response created above - container.setResponse(moaStorkResponse); - - container.setRemoteAddress(httpReq.getRemoteAddr()); - - Logger.debug("Data container prepared"); - - if(oaParam.isRequireConsentForStorkAttributes()) - new ConsentEvaluator().requestConsent(container, httpReq, httpResp, authData, oaParam); - else - new AttributeCollector().processRequest(container, httpReq, httpResp, authData, oaParam); - - return null; - } -// // check if we are getting request for citizen of some other country -// else if (req instanceof MOASTORKRequest) { -// return handleMOAStorkRequest("VIDP", (MOASTORKRequest) req, httpReq.getRemoteAddr(), httpResp); -// } - - // Check if we got the response from PEPS - // If so then process it and forward to SP - else if ((req instanceof MOASTORKResponse)) { - return handleMOAStorkResponse("VIDP", (MOASTORKResponse) req, httpReq.getRemoteAddr(), httpResp); - } else { - Logger.error("Could not recognize request."); - throw new MOAIDException("stork.15", null); - } - } - - /* - Handles STORKAuthnRequeste received for citizens of other countries - */ - private SLOInformationInterface handleMOAStorkRequest(String instanceName, MOASTORKRequest moastorkRequest, String remoteAddr, HttpServletResponse httpResp) throws MOAIDException { - - STORKAuthnRequest spAuthnRequest = moastorkRequest.getStorkAuthnRequest(); - STORKAuthnRequest storkAuthnRequest = null; - - String citizenCountryCode = spAuthnRequest.getCitizenCountryCode(); - Logger.info("Got authentication request for citizen of " + citizenCountryCode); - - try { - storkAuthnRequest = (STORKAuthnRequest) spAuthnRequest.clone(); - } catch (CloneNotSupportedException e) { - Logger.error("Could not clone AuthnRequest ", e); - throw new MOAIDException("stork.05", null); // TODO - } - - //TODO: in case of Single LogOut -> SLO information has to be stored - // check if citizen country is configured in the system - if (!(AuthConfigurationProviderFactory.getInstance().getStorkConfig().getCpepsMap().containsKey(citizenCountryCode))) { - Logger.error("Citizen country PEPS not configured in MOA instance: " + citizenCountryCode); - throw new MOAIDException("stork.05", null); // TODO - } - - // extracting basic settings and adjusting assertion consumer - String issuer = null; - String assertionConsumerURL = null; - String publicURLPrefix = null; - String destinationURL = null; - - try { - issuer = new URL(moaStorkRequest.getAuthURL()).toString(); - destinationURL = AuthConfigurationProviderFactory.getInstance().getStorkConfig().getCPEPS(citizenCountryCode).getPepsURL().toString(); - publicURLPrefix = moaStorkRequest.getAuthURL(); - assertionConsumerURL = publicURLPrefix + "/stork2/SendPEPSAuthnRequest"; - } catch (MalformedURLException ex) { - Logger.error("Wrong PublicURLPrefix setting of MOA instance: " + AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix(), ex); - throw new MOAIDException("stork.05", null); // TODO - } catch (Exception ex) { - Logger.error("Problem with PEPS configuration of MOA instance.", ex); - throw new MOAIDException("stork.05", null); // TODO - } - - - // drop if we do not have publicprefix url configured on the instance - if (publicURLPrefix == null) - throw new AuthenticationException("stork.12", new String[]{"PublicURLPrefix"}); - - // adjusting request - storkAuthnRequest.setEIDCrossBorderShare(spAuthnRequest.isEIDCrossBorderShare()); - storkAuthnRequest.setEIDSectorShare(spAuthnRequest.isEIDSectorShare()); - storkAuthnRequest.setEIDCrossSectorShare(spAuthnRequest.isEIDCrossSectorShare()); - storkAuthnRequest.setCitizenCountryCode(spAuthnRequest.getCitizenCountryCode()); - storkAuthnRequest.setIssuer(issuer); - storkAuthnRequest.setAssertionConsumerServiceURL(assertionConsumerURL); - storkAuthnRequest.setDestination(destinationURL); - - // regenerate request - try { - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - Logger.debug("Starting generation of SAML request"); - storkAuthnRequest = engine.generateSTORKAuthnRequest(storkAuthnRequest); - - //generateSAML Token - Logger.info("SAML response succesfully generated!"); - } catch (STORKSAMLEngineException e) { - Logger.error("Failed to generate STORK SAML Response", e); - throw new MOAIDException("stork.05", null); - } - - // store original request from SP in order to be able to extract it in later iteration/response - DataContainer spRequestContainer = new DataContainer(); - spRequestContainer.setRequest(moastorkRequest); - - try { - AssertionStorage.getInstance().put(storkAuthnRequest.getSamlId(), spRequestContainer); - Logger.info("Storing artifactId " + storkAuthnRequest.getSamlId() + " of SP authentication request with id " + spAuthnRequest.getSamlId()); - } catch (MOADatabaseException e) { - e.printStackTrace(); - } - - // preparing redirection for the client - performRedirection("SAMLRequest", destinationURL, storkAuthnRequest.getTokenSaml(), httpResp); - - SLOInformationImpl sloInfo = new SLOInformationImpl(); - sloInfo.setProtocolType(moastorkRequest.requestedModule()); - return sloInfo; - } - - /* - Handles STORKAuthnResponse received from PEPS (return to SP) - */ - private SLOInformationInterface handleMOAStorkResponse(String instanceName, MOASTORKResponse moastorkResponse, String remoteAddr, HttpServletResponse httpResp) throws MOAIDException { - - STORKAuthnResponse authnResponse = null; - - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance(instanceName); - - try { - authnResponse = engine.validateSTORKAuthnResponse(moastorkResponse.getSTORKAuthnResponseToken(), remoteAddr); - } catch (STORKSAMLEngineException ex) { - Logger.error("Unable to validate Stork AuthenticationResponse: " + ex.getMessage()); - throw new MOAIDException("stork.15", null); // TODO - } - - Logger.debug("Requesting artifactId " + authnResponse.getInResponseTo() + " from store."); - - DataContainer dataContainer = null; - try { - dataContainer = AssertionStorage.getInstance().get(authnResponse.getInResponseTo(), DataContainer.class); - } catch (MOADatabaseException e) { - Logger.error("Unable to retrieve datacontainer with reference authentication request. Database exception."); - throw new MOAIDException("stork.15", null); // TODO - } - - // setting new reference request and return url - authnResponse.setInResponseTo(dataContainer.getRequest().getStorkAuthnRequest().getSamlId()); - authnResponse.setAudienceRestriction(dataContainer.getRequest().getAssertionConsumerServiceURL()); - //AudienceRestrictionBuilder audienceRestrictionBuilder = new AudienceRestrictionBuilder(); - //AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject(dataContainer.getRequest().getAssertionConsumerServiceURL(), "localname", "nameprefix"); - - //authnResponse.getAssertions().get(0).getConditions().getAudienceRestrictions().add(audienceRestriction); - - Logger.debug("Starting generation of SAML response"); - try { - authnResponse = engine.generateSTORKAuthnResponse(dataContainer.getRequest().getStorkAuthnRequest(), authnResponse, remoteAddr, false); - } catch (STORKSAMLEngineException e) { - Logger.error("Failed to generate STORK SAML Response", e); - throw new MOAIDException("stork.05", null); // TODO check - } - - Logger.info("SAML response succesfully generated."); - - // preparing redirection for the client - performRedirection("SAMLResponse", dataContainer.getRequest().getAssertionConsumerServiceURL(), authnResponse.getTokenSaml(), httpResp); - - return null; - } - - /* - Perform redirection of the client based on post binding - */ - private void performRedirection(String actionType, String assertionConsumerURL, byte[] tokenSaml, HttpServletResponse httpResp) throws MOAIDException { - Logger.info("Performing redirection, using action type: " + actionType); - - try { - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/stork2_postbinding_template.html"); - VelocityContext context = new VelocityContext(); - - context.put(actionType, PEPSUtil.encodeSAMLToken(tokenSaml)); - Logger.debug("Encoded " + actionType + " original: " + new String(tokenSaml)); - - Logger.debug("Using assertion consumer url as action: " + assertionConsumerURL); - context.put("action", assertionConsumerURL); - - Logger.debug("Starting template merge"); - StringWriter writer = new StringWriter(); - - Logger.debug("Doing template merge"); - template.merge(context, writer); - Logger.debug("Template merge done"); - - Logger.debug("Sending html content: " + writer.getBuffer().toString()); - Logger.debug("Sending html content2 : " + new String(writer.getBuffer())); - - httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8")); - - } catch (IOException e) { - Logger.error("Velocity IO error: " + e.getMessage()); - throw new MOAIDException("stork.15", null); // TODO - } catch (Exception e) { - Logger.error("Velocity general error: " + e.getMessage()); - throw new MOAIDException("stork.15", null); // TODO - } - - } - - public void generatePEPSRedirect(HttpServletResponse httpResp, DataContainer container) throws MOAIDException { - MOASTORKRequest request = container.getRequest(); - MOASTORKResponse response = container.getResponse(); - - Logger.info("generating stork response..."); - - try { - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - Logger.debug("Starting generation of SAML response"); - if (response.isAuthnResponse()) - response.setSTORKAuthnResponse(engine.generateSTORKAuthnResponse(request.getStorkAuthnRequest(), response.getStorkAuthnResponse(), container.getRemoteAddress(), false)); - else - response.setSTORKAttrResponse(engine.generateSTORKAttrQueryResponse(request.getStorkAttrQueryRequest(), response.getStorkAttrQueryResponse(), container.getRemoteAddress(), "", false)); - - - //generateSAML Token - Logger.info("SAML response succesfully generated!"); - } catch (STORKSAMLEngineException e) { - Logger.error("Failed to generate STORK SAML Response", e); - throw new MOAIDException("stork.05", null); - } - - // preparing redirection for the client - try { - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/stork2_postbinding_template.html"); - VelocityContext context = new VelocityContext(); - - byte[] blob; - if (request.isAttrRequest()) - blob = response.getStorkAttrQueryResponse().getTokenSaml(); - else - blob = response.getStorkAuthnResponse().getTokenSaml(); - - context.put("SAMLResponse", PEPSUtil.encodeSAMLToken(blob)); - Logger.debug("SAMLResponse original: " + new String(blob)); - - Logger.debug("Putting assertion consumer url as action: " + request.getAssertionConsumerServiceURL()); - context.put("action", request.getAssertionConsumerServiceURL()); - Logger.trace("Starting template merge"); - StringWriter writer = new StringWriter(); - - Logger.trace("Doing template merge"); - template.merge(context, writer); - Logger.trace("Template merge done"); - - Logger.trace("Sending html content: " + writer.getBuffer().toString()); - Logger.trace("Sending html content2 : " + new String(writer.getBuffer())); - - httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8")); - - } catch (Exception e) { - Logger.error("Velocity error: " + e.getMessage()); - } - } - - - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { - - //redirect to national PVP IDP infrastructure if special attributes are requested - if (MiscUtil.isEmpty(req.getRequestedIDP()) && req instanceof MOASTORKRequest) - return !STORKPVPUtilits.performAuthenticationOnNationalIDP((MOASTORKRequest) req); - -// // authentication is not needed if we have authentication request from SP for citizen of configured PEPS country -// if (req instanceof MOASTORKRequest) { -// MOASTORKRequest moastorkRequest = (MOASTORKRequest) req; -// if (moastorkRequest.getStorkAuthnRequest() != null) { -// String citizenCountryCode = moastorkRequest.getStorkAuthnRequest().getCitizenCountryCode(); -// // check if citizen country is configured in the system -// try { -// if (AuthConfigurationProvider.getInstance().getStorkConfig().getCpepsMap().containsKey(citizenCountryCode)) { -// return false; -// } -// } catch (MOAIDException e) { -// Logger.error("Could not initialize AuthConfigurationProvider"); -// } -// } -// // authentication is not required if received authentication response -// } else if (req instanceof MOASTORKResponse) { -// return false; -// } - - return true; - } - - - private void iterate(NamedNodeMap attributesList) { - for (int j = 0; j < attributesList.getLength(); j++) { - Logger.debug("--Attribute: " - + attributesList.item(j).getNodeName() + " = " - + attributesList.item(j).getNodeValue()); - } - } - - - // does nothing - public void mandate(IAuthData authData) { - - if (authData.isUseMandate()) { - try { - MISMandate mandate = authData.getMISMandate(); - String owbpk = mandate.getOWbPK(); - byte[] mand = mandate.getMandate(); - String profprep = mandate.getProfRep(); - //String textdesc = mandate.getTextualDescriptionOfOID(); - Element mndt = authData.getMandate(); - - iterate(mndt.getAttributes()); - Logger.debug("mandate encoded: " + new String(org.bouncycastle.util.encoders.Base64.encode(mand))); - } catch (Exception x) { - Logger.debug("There is no mandate used in transaction"); - } - } - - - } - - public PersonalAttributeList populateAttributes(IAuthData authData, IOAAuthParameters oaParam) { - - IPersonalAttributeList attrLst = moaStorkRequest.getStorkAuthnRequest().getPersonalAttributeList(); - Logger.info("Found " + attrLst.size() + " personal attributes in the request."); - - // Define attribute list to be populated - PersonalAttributeList attributeList = new PersonalAttributeList(); - MOAAttributeProvider moaAttributeProvider = new MOAAttributeProvider(authData, moaStorkRequest); - - try { - for (PersonalAttribute personalAttribute : attrLst) { - try { - Logger.debug("Personal attribute found in request: " + personalAttribute.getName() + " isRequired: " + personalAttribute.isRequired()); - moaAttributeProvider.populateAttribute(attributeList, personalAttribute); - } catch (Exception e) { - Logger.error("Exception, attributes: " + e.getMessage(), e); - } - } - } catch (Exception e) { - Logger.error("Exception, attributes: " + e.getMessage(), e); - } - - Logger.trace("AUTHBLOCK " + authData.getAuthBlock()); - Logger.debug("SESSION IDENTIFIER " + authData.getCcc() + " " + oaParam.getIdentityLinkDomainIdentifier()); - - return attributeList; - } - - public String getDefaultActionName() { - return STORKProtocol.AUTHENTICATIONREQUEST; - } - - - private void initVelocityEngine() throws Exception { - velocityEngine = new VelocityEngine(); - velocityEngine.setProperty(RuntimeConstants.ENCODING_DEFAULT, "UTF-8"); - velocityEngine.setProperty(RuntimeConstants.OUTPUT_ENCODING, "UTF-8"); - velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath"); - velocityEngine.setProperty("classpath.resource.loader.class", - "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); - - velocityEngine.init(); - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java deleted file mode 100644 index 2b7d4e045..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ConsentEvaluator.java +++ /dev/null @@ -1,249 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import java.io.StringWriter; - -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map.Entry; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.storage.AssertionStorage; -import at.gv.egovernment.moa.id.util.VelocityProvider; -import at.gv.egovernment.moa.logging.Logger; -import eu.stork.peps.auth.commons.PEPSUtil; -import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.AttributeStatusType; -import eu.stork.peps.exceptions.STORKSAMLEngineException; - -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; -import org.opensaml.common.impl.SecureRandomIdentifierGenerator; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * The ConsentEvaluator assists with fetching user consent on the list of attributes to be sent to the asking S-PEPS. - */ -public class ConsentEvaluator implements IAction { - - /** - * The Constant ARTIFACT_ID. - */ - private static final String ARTIFACT_ID = "artifactId"; - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IAction#processRequest(at.gv.egovernment.moa.id.moduls.IRequest, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.auth.data.AuthenticationSession) - */ - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { - - // - fetch the container - String artifactId = (String) httpReq.getParameter(ARTIFACT_ID); - DataContainer container; - try { - container = AssertionStorage.getInstance().get(artifactId, DataContainer.class); - req = container.getRequest(); - } catch (MOADatabaseException e) { - Logger.error("Error fetching incomplete Stork response from temporary storage. Most likely a timeout occured.", e); - throw new MOAIDException("stork.17", null); - } - - // evaluate response - for(PersonalAttribute current : container.getRequest().getPersonalAttributeList()) { - if(null == httpReq.getParameter(current.getName())) { - current.setStatus(AttributeStatusType.WITHHELD.value()); - current.setValue(new ArrayList<String>()); - current.setComplexValue(new HashMap<String, String>()); - } - } - - //TODO: CHECK: req.getOAURL() should return the unique OA identifier - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(req.getOAURL()); - if (oaParam == null) - throw new AuthenticationException("stork.12", new Object[]{req.getOAURL()}); - - new AttributeCollector().processRequest(container, httpReq, httpResp, authData, oaParam); - - return null; // AssertionId - } - - /** - * Fills the given HttpResponse with the required web page. - * - * @param container the container - * @param authData - * @param response the response - * @param oaParam the oa param - * @return the string - * @throws MOAIDException the mOAID exception - */ - public String requestConsent(DataContainer container, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData, OAAuthParameter oaParam) throws MOAIDException { - //check if we need to collect consent - if(!oaParam.isRequireConsentForStorkAttributes()) { - (new AttributeCollector()).processRequest(container, httpReq, httpResp, authData, oaParam); - return ""; - } - - // prepare redirect - String newArtifactId; - try { - - // memorize the container again - Logger.debug("prepare putting the container into temporary storage..."); - - // - generate new key - newArtifactId = new SecureRandomIdentifierGenerator().generateIdentifier(); - - // - put container in temporary store. - AssertionStorage.getInstance().put(newArtifactId, container); - - Logger.debug("...successful"); - - } catch (Exception e1) { - // TODO should we return the response as is to the PEPS? - e1.printStackTrace(); - Logger.error("Error putting incomplete Stork response into temporary storage", e1); - throw new MOAIDException("stork.17", null); - } - - // ask for consent - try { - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/stork2_consent.html"); - VelocityContext context = new VelocityContext(); - - context.put("action", AuthConfigurationProviderFactory.getInstance().getPublicURLPrefix().get(0) + "/stork2/GetConsent?" + ARTIFACT_ID + "=" + newArtifactId); - - // assemble table - String table = ""; - for (PersonalAttribute current : container.getRequest().getPersonalAttributeList()) - table += "<tr><td><input type=\"checkbox\" checked=\"yes\" name=\"" + current.getName() + "\"></td><td>" + current.getName() + (current.isRequired() ? "" : " (optional)") + "</td></tr>\n"; - - context.put("tablecontent", table); - for(Entry<String, String> current : oaParam.getFormCustomizaten().entrySet()) - context.put(current.getKey().replace("#", ""), current.getValue()); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8")); - - } catch (Exception e) { - Logger.error("Velocity error: " + e.getMessage()); - throw new MOAIDException("stork.17", null); - } - - return "12345"; // AssertionId - } - - /** - * generates binary response from given response class and fill the given HttpResponse with a SAML Post Binding template. - * - * @param httpResp the http resp - * @param container the container - * @throws MOAIDException the mOAID exception - */ - public void generateSTORKResponse(HttpServletResponse httpResp, DataContainer container) throws MOAIDException { - MOASTORKRequest request = container.getRequest(); - MOASTORKResponse response = container.getResponse(); - - Logger.info("generating stork response..."); - - try { - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - Logger.debug("Starting generation of SAML response"); - if(response.isAuthnResponse()) - response.setSTORKAuthnResponse(engine.generateSTORKAuthnResponse(request.getStorkAuthnRequest(), response.getStorkAuthnResponse(), container.getRemoteAddress(), false)); - else - response.setSTORKAttrResponse(engine.generateSTORKAttrQueryResponse(request.getStorkAttrQueryRequest(), response.getStorkAttrQueryResponse(), container.getRemoteAddress(), "", false)); - - - //generateSAML Token - Logger.info("SAML response succesfully generated!"); - } catch (STORKSAMLEngineException e) { - Logger.error("Failed to generate STORK SAML Response", e); - throw new MOAIDException("stork.05", null); - } - - // preparing redirection for the client - try { - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/stork2_postbinding_template.html"); - VelocityContext context = new VelocityContext(); - - byte[] blob; - if(request.isAttrRequest()) - blob = response.getStorkAttrQueryResponse().getTokenSaml(); - else - blob = response.getStorkAuthnResponse().getTokenSaml(); - - context.put("SAMLResponse", PEPSUtil.encodeSAMLToken(blob)); - Logger.debug("SAMLResponse original: " + new String(blob)); - - Logger.debug("Putting assertion consumer url as action: " + request.getAssertionConsumerServiceURL()); - context.put("action", request.getAssertionConsumerServiceURL()); - Logger.trace("Starting template merge"); - StringWriter writer = new StringWriter(); - - Logger.trace("Doing template merge"); - template.merge(context, writer); - Logger.trace("Template merge done"); - - Logger.trace("Sending html content: " + writer.getBuffer().toString()); - Logger.trace("Sending html content2 : " + new String(writer.getBuffer())); - - httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes("UTF-8")); - - } catch (Exception e) { - Logger.error("Velocity error: " + e.getMessage()); - } - } - - /* (non-Javadoc) - * @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. - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IAction#getDefaultActionName() - */ - public String getDefaultActionName() { - return STORKProtocol.CONSENT_EVALUATOR; - } -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java deleted file mode 100644 index acbf1678a..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/CorporateBodyMandateContainer.java +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.logging.Logger; -import org.xml.sax.InputSource; - -import javax.xml.xpath.XPathExpressionException; -import java.io.StringReader; -/** - * Physical person representing corporate body - * - * @author bsuzic - * Date: 4/29/14, Time: 3:40 PM - */ -public class CorporateBodyMandateContainer extends MandateContainer { - - protected String corpMandatorIdentificationValue = null; - protected String corpMandatorIdentificationType = null; - protected String corpMandatorFullName = null; - - - String localMethods[] = new String[]{"getCorpMandatorIdentificationValue", "getCorpMandatorIdentificationType", "getCorpMandatorFullName", - "getMandateIssuePlace", "getMandateIssueDate", "getMandateIssueTime", "getSimpleMandateContent", "getMandateValidFrom", - "getMandateValidTo", "getPhysicalRepresentativeIdentificationValue", "getPhysicalRepresentativeIdentificationType", "getAnnotation", - "getPhysicalRepresentativeGivenName", "getPhysicalRepresentativeFamilyName", "getPhysicalRepresentativeBirthDate" - }; - - public CorporateBodyMandateContainer(String mandate) throws XPathExpressionException, MOAIDException { - super(mandate); - Logger.debug("Initializing corporate body mandate container."); - - setAnnotation(xPath.evaluate(S2Constants.MANDATE_ANNOTATION_QUERY, new InputSource(new StringReader(mandate)))); - setCorpMandatorFullName(xPath.evaluate(S2Constants.MANDATE_MANDATOR_CORPBODY_FULLNAME_QUERY, new InputSource(new StringReader(mandate)))); - setCorpMandatorIdentificationType(xPath.evaluate(S2Constants.MANDATE_MANDATOR_CORPBODY_IDTYPE_QUERY, new InputSource(new StringReader(mandate)))); - setCorpMandatorIdentificationValue(xPath.evaluate(S2Constants.MANDATE_MANDATOR_CORPBODY_IDVALUE_QUERY, new InputSource(new StringReader(mandate)))); - setMandateIssueDate(xPath.evaluate(S2Constants.MANDATE_ISSUEDDATE_QUERY, new InputSource(new StringReader(mandate)))); - setMandateIssuePlace(xPath.evaluate(S2Constants.MANDATE_ISSUEDPLACE_QUERY, new InputSource(new StringReader(mandate)))); - setMandateIssueTime(xPath.evaluate(S2Constants.MANDATE_ISSUEDTIME_QUERY, new InputSource(new StringReader(mandate)))); - setMandateValidFrom(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_VALIDFROM_QUERY, new InputSource(new StringReader(mandate)))); - setMandateValidTo(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_VALIDTO_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeBirthDate(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_DATEOFBIRTH_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeFamilyName(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_FAMILYNAME_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeGivenName(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_GIVENNAME_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeIdentificationType(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_IDTYPE_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeIdentificationValue(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_IDVALUE_QUERY, new InputSource(new StringReader(mandate)))); - setSimpleMandateContent(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_TXTDESC_QUERY, new InputSource(new StringReader(mandate)))); - - // check if all necessary fields are present - Logger.debug("Starting mandate structure validation"); - try { - validateMandateStructure(localMethods); // TODO - } catch (Exception e) { - - if (e instanceof MOAIDException) { - Logger.error("Could not validate mandate structure."); - throw new MOAIDException("stork.16", new Object[] {e.getMessage()}); // TODO - } else { - Logger.error("Error during mandate structure validation."); - throw new MOAIDException("stork.16", new Object[] {e.getMessage()}); // TODO - } - - } - - } - - public String getCorpMandatorIdentificationValue() { - return corpMandatorIdentificationValue; - } - - public void setCorpMandatorIdentificationValue(String corpMandatorIdentificationValue) { - Logger.debug("Setting corpMandatorIdentificationValue to AT/" + corpMandatorIdentificationValue); - this.corpMandatorIdentificationValue = "AT/" + corpMandatorIdentificationValue; - } - - public String getCorpMandatorIdentificationType() { - return corpMandatorIdentificationType; - } - - public void setCorpMandatorIdentificationType(String corpMandatorIdentificationType) { - this.corpMandatorIdentificationType = corpMandatorIdentificationType; - } - - public String getCorpMandatorFullName() { - return corpMandatorFullName; - } - - public void setCorpMandatorFullName(String corpMandatorFullName) { - this.corpMandatorFullName = corpMandatorFullName; - } - - - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java deleted file mode 100644 index e01a7526a..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java +++ /dev/null @@ -1,100 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import java.io.Serializable; - -/** - * Holds info about an ongoing but yet incomplete stork authnrequest process. - */ -public class DataContainer implements Serializable { - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = -8765997480582363012L; - - /** The incoming request. */ - private MOASTORKRequest request; - - /** The yet incomplete response. */ - private MOASTORKResponse response; - - /** The target. */ - private String target; - - /** The remote address. */ - private String remoteAddress; - - /** - * Gets the request. - * - * @return the request - */ - public MOASTORKRequest getRequest() { - return request; - } - - /** - * Sets the request. - * - * @param moaStorkRequest the new request - */ - public void setRequest(MOASTORKRequest moaStorkRequest) { - this.request = moaStorkRequest; - } - - /** - * Gets the response. - * - * @return the response - */ - public MOASTORKResponse getResponse() { - return response; - } - - /** - * Sets the response. - * - * @param moaStorkResponse the new response - */ - public void setResponse(MOASTORKResponse moaStorkResponse) { - this.response = moaStorkResponse; - } - - /** - * Gets the remote address. - * - * @return the remote address - */ - public String getRemoteAddress() { - return remoteAddress; - } - - /** - * Sets the remote address. - * - * @param remoteAddress the new remote address - */ - public void setRemoteAddress(String remoteAddress) { - this.remoteAddress = remoteAddress; - } -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java deleted file mode 100644 index 2c7e5b539..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java +++ /dev/null @@ -1,248 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; -import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.id.data.AuthenticationRole; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.util.PVPtoSTORKMapper; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; -import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.commons.PersonalAttributeList; -import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.AttributeStatusType; -import org.joda.time.Period; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; - -/** - * @author bsuzic - * Date: 2/19/14, Time: 4:42 PM - * - * @author tlenz - * Date: 23.10.14 - */ -public class MOAAttributeProvider { - private final IAuthData authData; - private static final Map<String, String> storkAttributeSimpleMapping; - private static final Map<String, String> storkAttributeFunctionMapping; - private final MOASTORKRequest moastorkRequest; - - // mappings for attribute population methods - // based on mapping of moa authndata and executing functions to extract attributes - static { - Map<String, String> tempSimpleMap = new HashMap<String, String>(); - tempSimpleMap.put("givenName", "getGivenName"); - tempSimpleMap.put("surname", "getFamilyName"); - tempSimpleMap.put("MSOrganization", "getPvpAttribute_OU"); - storkAttributeSimpleMapping = Collections.unmodifiableMap(tempSimpleMap); - - Map<String, String> tempFunctionMap = new HashMap<String, String>(); - tempFunctionMap.put("eIdentifier", "geteIdentifier"); - tempFunctionMap.put("ECApplicationRole","getECApplicationRole"); - tempFunctionMap.put("dateOfBirth", "getFormatedDateOfBirth"); - tempFunctionMap.put("MSOrganization", "getMSOrganization"); - tempFunctionMap.put("age", "getAge"); - tempFunctionMap.put("isAgeOver", "getIsAgeOver"); - tempFunctionMap.put("citizenQAALevel", "getQAALevel"); - storkAttributeFunctionMapping = Collections.unmodifiableMap(tempFunctionMap); - - } - - public MOAAttributeProvider(IAuthData authData, MOASTORKRequest moastorkRequest) { - this.authData = authData; - this.moastorkRequest = moastorkRequest; - - } - - public void populateAttribute(PersonalAttributeList attributeList, PersonalAttribute requestedAttribute ) { - String storkAttribute = requestedAttribute.getName(); - - // TODO: check if authData gets populated with stork attributtes during previous steps; it seems it is not - if (null != authData && null != authData.getStorkAttributes() && authData.getStorkAttributes().containsKey(requestedAttribute.getName())) { - Logger.debug("Trying to get value for attribute directly from STORK2 response [" + storkAttribute + "]"); - try { - PersonalAttribute tmp = authData.getStorkAttributes().get(requestedAttribute.getName()); - attributeList.add((PersonalAttribute) tmp.clone()); - } catch(Exception e) { - Logger.error("Could not retrieve attribute from STORK2 response: " + storkAttribute); - Logger.debug(e); - } - } else if (storkAttributeSimpleMapping.containsKey(storkAttribute)) { - Logger.debug("Trying to get value for attribute using simple mapping [" + storkAttribute + "]"); - try { - Method method = authData.getClass().getDeclaredMethod(storkAttributeSimpleMapping.get(storkAttribute)); - populateAttributeWithMethod(method, authData, attributeList, storkAttribute, requestedAttribute); - } catch (NoSuchMethodException e) { - Logger.error("Could not found MOA extraction method while getting attribute: " + storkAttribute); - Logger.debug(e); - } catch (NullPointerException e) { - Logger.error("Error getting MOA extraction method while getting attribute: " + storkAttribute); - Logger.debug(e); - } - - } else if (storkAttributeFunctionMapping.containsKey(storkAttribute)) { - - Logger.debug("Trying to get value for attribute using function mapping [" + storkAttribute + "]"); - try { - Method method = this.getClass().getDeclaredMethod(storkAttributeFunctionMapping.get(storkAttribute), PersonalAttribute.class); - populateAttributeWithMethod(method, this, attributeList, storkAttribute, requestedAttribute); - } catch (NoSuchMethodException e) { - Logger.error("Could not found MOA extraction method while getting attribute: " + storkAttribute); - } - } else { - Logger.debug("MOA method for extraction of attribute " + storkAttribute + " not defined."); - } - } - - private String getAge(PersonalAttribute personalAttribute) { - if (authData.getDateOfBirth() != null) { - Integer age = new Period(authData.getDateOfBirth().getTime(), Calendar.getInstance().getTime().getTime()).getYears(); - return age >= 0 ? age.toString() : null; - } - return null; // WP4 D4.2, Table 12:age, description - considerations - } - - private String getIsAgeOver(PersonalAttribute personalAttribute) - { - try { - if ((authData.getDateOfBirth() != null) && (personalAttribute.getValue() != null) && (personalAttribute.getValue().size() > 0)) { - Integer ageOver = Integer.parseInt(personalAttribute.getValue().get(0)); - Integer age = new Period(authData.getDateOfBirth().getTime(), Calendar.getInstance().getTime().getTime()).getYears(); - return age >= ageOver ? ageOver.toString() : ""; - } - } catch (Exception ex) { - Logger.error("Error encountered when determining isAgeOver"); - Logger.debug(ex); - } - return null; - } - - public String getQAALevel(PersonalAttribute personalAttribute) { - if (authData.getQAALevel().startsWith(PVPConstants.STORK_QAA_PREFIX)) - return authData.getQAALevel().substring(PVPConstants.STORK_QAA_PREFIX.length()); - else - return null; - } - - - private String geteIdentifier(PersonalAttribute personalAttribute) { - Logger.debug("Using base urn for identification value: " + authData.getIdentificationType() + " and target country: " + moastorkRequest.getStorkAuthnRequest().getSpCountry()); - try { - return new BPKBuilder().buildStorkeIdentifier(authData.getIdentificationType(), authData.getIdentificationValue(), - moastorkRequest.getStorkAuthnRequest().getSpCountry()); - } catch (BuildException be) { - Logger.error("Stork eid could not be constructed; " + be.getMessage()); - return null; // TODO error - } - } - - private List<String> getECApplicationRole(PersonalAttribute personalAttribute) { - List<String> storkRoles = null; - - if (authData.getAuthenticationRoles() != null - && authData.getAuthenticationRoles().size() > 0) { - - storkRoles = new ArrayList<String>(); - PVPtoSTORKMapper mapper = PVPtoSTORKMapper.getInstance(); - for (AuthenticationRole el : authData.getAuthenticationRoles()) { - String storkRole = mapper.map(el); - if (MiscUtil.isNotEmpty(storkRole)) - storkRoles.add(storkRole); - } - } - return storkRoles; - } - - private String getFormatedDateOfBirth(PersonalAttribute personalAttribute) { - if (authData.getDateOfBirth() != null) { - DateFormat fmt = new SimpleDateFormat("yyyyMMdd"); - return fmt.format(authData.getDateOfBirth()); - } - else - return null; - } - - private void populateAttributeWithMethod(Method method, Object object, PersonalAttributeList attributeList, String storkAttribute, PersonalAttribute requestedAttribute) { - try { - Object attributeValue; - if (storkAttributeSimpleMapping.containsValue(method.getName())) { - attributeValue = method.invoke(object, new Class[]{}); - } else { - attributeValue = method.invoke(object, requestedAttribute); - } - - PersonalAttribute newAttribute = new PersonalAttribute(); - newAttribute.setName(storkAttribute); - newAttribute.setIsRequired(requestedAttribute.isRequired()); - - if (attributeValue != null) { - newAttribute.setStatus(AttributeStatusType.AVAILABLE.value()); - Logger.info("Got attribute value: " + attributeValue); - - if (attributeValue instanceof String) - newAttribute.setValue(new ArrayList<String>(Collections.singletonList((String)attributeValue))); - - else if (attributeValue instanceof List<?>) { - List<?> attributeValueList = (List<?>) attributeValue; - if (attributeValueList.size() > 0 && attributeValueList.get(0) instanceof String) { - newAttribute.setValue((List<String>) attributeValueList); - - } else { - Logger.info("Attribute " + storkAttribute + " is not available."); - newAttribute.setStatus(AttributeStatusType.NOT_AVAILABLE.value()); - - } - - } else { - Logger.error("Receive an unsupported type for attribute " + storkAttribute); - - } - attributeList.add(newAttribute); - - } else { - Logger.info("Attribute " + storkAttribute + " is not available."); - newAttribute.setStatus(AttributeStatusType.NOT_AVAILABLE.value()); - } - - } catch (InvocationTargetException e) { - Logger.error("Invocation target exception while getting attribute: " + storkAttribute); - Logger.debug(e); - } catch (IllegalAccessException e) { - Logger.error("Illegal access exception while getting attribute: " + storkAttribute); - Logger.debug(e); - } catch (NullPointerException e) { - Logger.error("Could not find method: " + storkAttribute); - Logger.debug(e); - } - } - - -} - diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java deleted file mode 100644 index 4e666c21c..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java +++ /dev/null @@ -1,265 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.opensaml.saml2.core.Attribute; - -import at.gv.egovernment.moa.id.auth.builder.DynamicOAAuthParameterBuilder; -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.IOAAuthParameters; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.config.auth.data.DynamicOAAuthParameters; -import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.id.protocols.pvp2x.builder.AttributQueryBuilder; -import at.gv.egovernment.moa.id.protocols.pvp2x.messages.MOAResponse; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Constants; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAttrQueryRequest; -import eu.stork.peps.auth.commons.STORKAuthnRequest; -import eu.stork.peps.auth.commons.STORKAuthnResponse; - -/** - * Implements MOA request and stores StorkAuthn/Attr-Request related data. - * - * @author bsuzic - */ -public class MOASTORKRequest extends RequestImpl { - - /** - * @param req - * @throws ConfigurationException - */ - public MOASTORKRequest(HttpServletRequest req) - throws ConfigurationException { - super(req); - } - - public static final List<String> DEFAULTREQUESTEDATTRFORINTERFEDERATION = Arrays.asList( - new String[] { - PVPConstants.BPK_NAME, - PVPConstants.EID_SECTOR_FOR_IDENTIFIER_NAME, - PVPConstants.GIVEN_NAME_NAME, - PVPConstants.PRINCIPAL_NAME_NAME, - PVPConstants.BIRTHDATE_NAME, - PVPConstants.EID_CITIZEN_QAA_LEVEL_NAME, - }); - - /** The Constant serialVersionUID. */ - private static final long serialVersionUID = 4581953368724501376L; - - /** The request id. */ - private String requestID; - - /** The stork authn request. */ - private STORKAuthnRequest storkAuthnRequest; - - /** The stork attr query request. */ - private STORKAttrQueryRequest storkAttrQueryRequest; - - - /** - * Sets the sTORK authn request. - * - * @param request the new sTORK authn request - */ - public void setSTORKAuthnRequest(STORKAuthnRequest request) { - this.storkAuthnRequest = request; - } - - /** - * Sets the sTORK attr request. - * - * @param request the new sTORK attr request - */ - public void setSTORKAttrRequest(STORKAttrQueryRequest request) { - this.storkAttrQueryRequest = request; - } - - /** - * Checks if the container holds an AttrQueryRequest - * - * @return true, if is attr request - */ - public boolean isAttrRequest() { - return null != storkAttrQueryRequest; - } - - /** - * Checks if the container holds an AuthnRequest - * - * @return true, if is authn request - */ - public boolean isAuthnRequest() { - return null != storkAuthnRequest; - } - - /** - * Gets the stork authn request. - * - * @return the stork authn request - */ - public STORKAuthnRequest getStorkAuthnRequest() { - return this.storkAuthnRequest; - } - - /** - * Gets the stork attr query request. - * - * @return the stork attr query request - */ - public STORKAttrQueryRequest getStorkAttrQueryRequest() { - return this.storkAttrQueryRequest; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getOAURL() - */ - public String getOAURL() { - if (isAuthnRequest()) - return storkAuthnRequest.getAssertionConsumerServiceURL(); - else if (isAttrRequest()) - return storkAttrQueryRequest.getAssertionConsumerServiceURL(); - else { - Logger.error("There is no authentication or attribute request contained in MOASTORKRequest."); - return null; - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#isPassiv() - */ - public boolean isPassiv() { - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#forceAuth() - */ - public boolean forceAuth() { - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#isSSOSupported() - */ - public boolean isSSOSupported() { - return false; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#setRequestID(java.lang.String) - */ - public void setRequestID(String id) { - this.requestID = id; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getRequestID() - */ - public String getRequestID() { - return this.requestID; - } - - /** - * Gets the personal attribute list. - * - * @return the personal attribute list - */ - public IPersonalAttributeList getPersonalAttributeList() { - if(isAttrRequest()) - return this.storkAttrQueryRequest.getPersonalAttributeList(); - else - return this.storkAuthnRequest.getPersonalAttributeList(); - } - - /** - * Gets the sp country. - * - * @return the sp country - */ - public String getSpCountry() { - if(isAttrRequest()) - return this.storkAttrQueryRequest.getSpCountry(); - else - return this.storkAuthnRequest.getSpCountry(); - } - - /** - * Gets the assertion consumer service url. - * - * @return the assertion consumer service url - */ - public String getAssertionConsumerServiceURL() { - if(isAttrRequest()) - return this.storkAttrQueryRequest.getAssertionConsumerServiceURL(); - else - return this.storkAuthnRequest.getAssertionConsumerServiceURL(); - } - - /** - * Gets the citizen country code. - * - * @return the citizen country code - */ - public String getCitizenCountryCode() { - if(isAttrRequest()) - return this.storkAttrQueryRequest.getCitizenCountryCode(); - else - return this.storkAuthnRequest.getCitizenCountryCode(); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes() - */ - @Override - public List<Attribute> getRequestedAttributes() { - //TODO: only for testing with MOA-ID as PVP Stammportal - IOAAuthParameters oa; - try { - oa = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(getOAURL()); - oa = DynamicOAAuthParameterBuilder.buildFromAuthnRequest(oa, this); - - DynamicOAAuthParameters tmp = (DynamicOAAuthParameters) oa; - tmp.setBusinessTarget(Constants.URN_PREFIX_CDID + "+BF"); - - return AttributQueryBuilder.buildSAML2AttributeList(tmp, DEFAULTREQUESTEDATTRFORINTERFEDERATION.iterator()); - - } catch (ConfigurationException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - return null; - } - - //return new ArrayList<Attribute>(); - - } -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java deleted file mode 100644 index a233835bf..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java +++ /dev/null @@ -1,308 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import at.gv.egovernment.moa.id.config.ConfigurationException; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.moduls.RequestImpl; -import at.gv.egovernment.moa.logging.Logger; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAttrQueryResponse; -import eu.stork.peps.auth.commons.STORKAuthnResponse; - -import java.io.Serializable; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; - -import org.opensaml.saml2.core.Attribute; - -/** - * Implements MOA request and stores StorkAuthn/Attr-Request related data. - * - * @author bsuzic - */ -public class MOASTORKResponse extends RequestImpl { - - /** - * @param req - * @throws ConfigurationException - */ - public MOASTORKResponse(HttpServletRequest req) - throws ConfigurationException { - super(req); - } - - /** - * The Constant serialVersionUID. - */ - private static final long serialVersionUID = -5798803155055518747L; - - /** - * The stork authn request. - */ - private STORKAuthnResponse storkAuthnResponse; - - /** - * The stork attr query request. - */ - private STORKAttrQueryResponse storkAttrQueryResponse; - - /** - * The action. - */ - String action = null; - - /** - * The token - */ - private byte[] storkAuthnResponseToken = null; - - /** - * The request id. - */ - private String requestID; - - - /** - * The module. - */ - String module = null; - - /** - * The target. - */ - private String target = null; - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#requestedModule() - */ - public String requestedModule() { - return this.module; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#requestedAction() - */ - public String requestedAction() { - return action; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getRequestID() - */ - public String getRequestID() { - return this.requestID; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getTarget() - */ - public String getTarget() { - return this.target; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#isSSOSupported() - */ - public boolean isSSOSupported() { - return false; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#forceAuth() - */ - public boolean forceAuth() { - return false; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#setModule(java.lang.String) - */ - public void setModule(String module) { - this.module = module; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#setRequestID(java.lang.String) - */ - public void setRequestID(String id) { - this.requestID = id; - } - - /** - * Sets the sTORK authn response. - * - * @param request the new sTORK authn response - */ - public void setSTORKAuthnResponse(STORKAuthnResponse request) { - this.storkAuthnResponse = request; - } - - /** - * Sets the sTORK authn response token - * - * @param request the new sTORK authn response token - */ - public void setSTORKAuthnResponseToken(byte[] token) { - this.storkAuthnResponseToken = token; - } - - /** - * Gets the sTORK authn response token . - * - * @param request the new sTORK authn response - */ - public byte[] getSTORKAuthnResponseToken() { - return this.storkAuthnResponseToken; - } - /** - * Sets the sTORK attr response. - * - * @param request the new sTORK attr response - */ - public void setSTORKAttrResponse(STORKAttrQueryResponse request) { - this.storkAttrQueryResponse = request; - } - - /** - * Checks if the container holds an AttrQuery - * - * @return true, if is attr response - */ - public boolean isAttrResponse() { - return null != storkAttrQueryResponse; - } - - /** - * Checks if the container holds an AuthnRequest - * - * @return true, if is authn response - */ - public boolean isAuthnResponse() { - return null != storkAuthnResponse; - } - - - /** - * Gets the AuthnResponse. - * - * @return the stork authn response - */ - public STORKAuthnResponse getStorkAuthnResponse() { - return this.storkAuthnResponse; - } - - /** - * Gets the AttrQueryResponse. - * - * @return the stork attr query response - */ - public STORKAttrQueryResponse getStorkAttrQueryResponse() { - return this.storkAttrQueryResponse; - } - - /** - * Gets the personal attribute list. - * - * @return the personal attribute list - */ - public IPersonalAttributeList getPersonalAttributeList() { - if (isAttrResponse()) - return this.storkAttrQueryResponse.getPersonalAttributeList(); - else - return this.storkAuthnResponse.getPersonalAttributeList(); - } - - /** - * Sets the personal attribute list. - * - * @param populateAttributes the new personal attribute list - */ - public void setPersonalAttributeList(PersonalAttributeList populateAttributes) { - if (isAttrResponse()) - this.storkAttrQueryResponse.setPersonalAttributeList(populateAttributes); - else - this.storkAuthnResponse.setPersonalAttributeList(populateAttributes); - } - - /** - * Sets the country. - * - * @param spCountry the new country - */ - public void setCountry(String spCountry) { - if (isAttrResponse()) - this.storkAttrQueryResponse.setCountry(spCountry); - else - this.storkAuthnResponse.setCountry(spCountry); - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#getOAURL() - */ - public String getOAURL() { - if (isAuthnResponse()) - return storkAuthnResponse.getAudienceRestriction(); - else if (isAttrResponse()) - return storkAttrQueryResponse.getAudienceRestriction(); - else { - Logger.error("There is no authentication or attribute request contained in MOASTORKRequest."); - return null; - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#isPassiv() - */ - public boolean isPassiv() { - return false; - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.IRequest#setAction(java.lang.String) - */ - public void setAction(String action) { - this.action = action; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.moduls.RequestImpl#getRequestedAttributes() - */ - @Override - public List<Attribute> getRequestedAttributes() { - // TODO Auto-generated method stub - return null; - } - - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java deleted file mode 100644 index a3fac0f6e..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateContainer.java +++ /dev/null @@ -1,182 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.logging.Logger; - -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.HashMap; - -/** - * @author bsuzic - * Date: 5/5/14, Time: 2:35 PM - */ -public abstract class MandateContainer { - protected String mandateIssuePlace = null; - protected String mandateIssueDate = null; - protected String mandateIssueTime = null; - protected String simpleMandateContent = null; - protected String mandateValidFrom = null; - protected String mandateValidTo = null; - protected String annotation = null; - protected String physicalRepresentativeIdentificationValue = null; - protected String physicalRepresentativeIdentificationType = null; - protected String physicalRepresentativeGivenName = null; - protected String physicalRepresentativeFamilyName = null; - protected String physicalRepresentativeBirthDate = null; - protected XPath xPath = null; - - - public MandateContainer(String mandate) throws XPathExpressionException, MOAIDException { - Logger.debug("Received mandate content for processing: " + mandate); - - xPath = XPathFactory.newInstance().newXPath(); - HashMap<String, String> prefMap = new HashMap<String, String>() {{ - put(S2Constants.MANDATE_PREFIX, S2Constants.MANDATE_NS); - put(S2Constants.PERSONDATA_PREFIX, S2Constants.PERSONDATA_NS); - put(S2Constants.XMLDSIG_PREFIX, S2Constants.XMLDSIG_NS); - }}; - - SimpleNamespaceContext namespace = new SimpleNamespaceContext(prefMap); - xPath.setNamespaceContext(namespace); - } - - - public void validateMandateStructure(String localMethods[]) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, MOAIDException { - for (String localMethod : localMethods) { - Method method = this.getClass().getMethod(localMethod); - Object x = method.invoke(this); - if ((x == null) || x.toString().length() == 0) { - throw new MOAIDException("stork.16", new Object[] {localMethod}); // TODO - } - } - Logger.debug("Mandate structure validated"); - } - - - public String getMandateIssuePlace() { - return mandateIssuePlace; - } - - public void setMandateIssuePlace(String mandateIssuePlace) { - this.mandateIssuePlace = mandateIssuePlace; - } - - public String getMandateIssueDate() { - return mandateIssueDate; - } - - public void setMandateIssueDate(String mandateIssueDate) { - this.mandateIssueDate = mandateIssueDate; - } - - public String getMandateIssueTime() { - return mandateIssueTime; - } - - public void setMandateIssueTime(String mandateIssueTime) { - this.mandateIssueTime = mandateIssueTime; - } - - public String getSimpleMandateContent() { - return simpleMandateContent; - } - - public void setSimpleMandateContent(String simpleMandateContent) { - this.simpleMandateContent = simpleMandateContent; - } - - public String getMandateValidFrom() { - return mandateValidFrom; - } - - public void setMandateValidFrom(String mandateValidFrom) { - this.mandateValidFrom = mandateValidFrom; - } - - public String getMandateValidTo() { - return mandateValidTo; - } - - public void setMandateValidTo(String mandateValidTo) { - this.mandateValidTo = mandateValidTo; - } - - public String getPhysicalRepresentativeIdentificationValue() { - return physicalRepresentativeIdentificationValue; - } - - public void setPhysicalRepresentativeIdentificationValue(String physicalRepresentativeIdentificationValue) { - this.physicalRepresentativeIdentificationValue = physicalRepresentativeIdentificationValue; - } - - public String getPhysicalRepresentativeIdentificationType() { - return physicalRepresentativeIdentificationType; - } - - public void setPhysicalRepresentativeIdentificationType(String physicalRepresentativeIdentificationType) { - this.physicalRepresentativeIdentificationType = physicalRepresentativeIdentificationType; - } - - public String getPhysicalRepresentativeGivenName() { - return physicalRepresentativeGivenName; - } - - public void setPhysicalRepresentativeGivenName(String physicalRepresentativeGivenName) { - this.physicalRepresentativeGivenName = physicalRepresentativeGivenName; - } - - public String getPhysicalRepresentativeFamilyName() { - return physicalRepresentativeFamilyName; - } - - public void setPhysicalRepresentativeFamilyName(String physicalRepresentativeFamilyName) { - this.physicalRepresentativeFamilyName = physicalRepresentativeFamilyName; - } - - public String getPhysicalRepresentativeBirthDate() { - return physicalRepresentativeBirthDate; - } - - public void setPhysicalRepresentativeBirthDate(String physicalRepresentativeBirthDate) { - // making it conform to STORK dateOfBirth specifications, removing dash - this.physicalRepresentativeBirthDate = physicalRepresentativeBirthDate.replaceAll("-",""); - } - - public String getAnnotation() { - return annotation; - } - - public void setAnnotation(String annotation) { - this.annotation = annotation; - } - - - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java deleted file mode 100644 index 2351450e4..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java +++ /dev/null @@ -1,602 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; -import at.gv.egovernment.moa.id.auth.data.IdentityLink; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.BuildException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.data.SLOInformationInterface; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Constants; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.commons.PersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAttrQueryResponse; -import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.*; -import org.apache.commons.codec.binary.StringUtils; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.Marshaller; -import javax.xml.datatype.DatatypeConfigurationException; -import javax.xml.datatype.DatatypeFactory; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.regex.Pattern; - -/** - * Entry point for mandate retrieval. Processes MIS data and transforms into STORK mandate attribute. - * Additionally provides eIdentifier attribute (if requested) in order to enable identity correlation - */ -public class MandateRetrievalRequest implements IAction { - - private IAuthData authData; - private MOASTORKRequest moaStorkRequest; - private IdentityLink representingIdentityLink; - private Integer QAALevel; - private byte[] originalContent; - - public SLOInformationInterface processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, IAuthData authData) throws MOAIDException { - Logger.debug("Entering AttributeRequest for MandateProvider"); - httpResp.reset(); - this.representingIdentityLink = authData.getIdentityLink(); - this.QAALevel = translateQAALevel(authData.getQAALevel()); - - // preparing original content and removing sensitive data from it - try { - this.originalContent = authData.getMISMandate().getMandate(); - } catch (Exception e) { - Logger.error("Could not extract mandate"); - Logger.debug(e); - throw new MOAIDException("stork.26", new Object[]{}); - } - String originalMandate = StringUtils.newStringUtf8(authData.getMISMandate().getMandate()).replaceAll("<pd:Value>.*?==</pd:Value><pd:Type>urn:publicid:gv.at:baseid</pd:Type>","<pd:Value></pd:Value><pd:Type></pd:Type>");; - Logger.debug("Removing personal identification value and type from original mandate "); - originalContent = StringUtils.getBytesUtf8(originalMandate); - - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(req.getOAURL()); - if (oaParam == null) - throw new AuthenticationException("stork.12", new Object[]{req.getOAURL()}); - - MOASTORKResponse moaStorkResponse = new MOASTORKResponse(httpReq); - STORKAttrQueryResponse attrResponse = new STORKAttrQueryResponse(); - - this.authData = authData; - - if ((req instanceof MOASTORKRequest)) { - this.moaStorkRequest = (MOASTORKRequest) req; - } else { - Logger.error("Internal error - did not receive MOASTORKRequest as expected"); - throw new MOAIDException("stork.27", new Object[]{}); - } - - - if (!(moaStorkRequest.isAttrRequest() || moaStorkRequest.getStorkAttrQueryRequest() == null)) { - Logger.error("Did not receive attribute request as expected"); - throw new MOAIDException("stork.27", new Object[]{}); - } - - MandateContainer mandateContainer = null; - - try { - mandateContainer = new CorporateBodyMandateContainer(new String(authData.getMISMandate().getMandate(), "UTF-8")); - } catch (Exception ex) { - try { - mandateContainer = new PhyPersonMandateContainer(new String(authData.getMISMandate().getMandate(), "UTF-8")); - } catch (Exception ex2) { - Logger.error("Could not extract data and create mandate container."); - throw new MOAIDException("stork.27", new Object[]{}); - } - } - - IPersonalAttributeList sourceAttributeList = moaStorkRequest.getStorkAttrQueryRequest().getPersonalAttributeList(); - - IPersonalAttributeList attributeList = new PersonalAttributeList(); - - // according to new mapping, only mandate attribute is directly relevant - for (PersonalAttribute currentAttribute : sourceAttributeList) { - Logger.debug("Evaluating attributes, current attribute: " + currentAttribute.getName()); - if (currentAttribute.getName().equals("mandateContent")) { // deprecated - MandateContentType mandateContent = getMandateContent(mandateContainer, currentAttribute); - attributeList.add(marshallComplexAttribute(currentAttribute, mandateContent)); - } else if (currentAttribute.getName().equals("representative")) { // deprecated - RepresentationPersonType representative = getRepresentative(mandateContainer, currentAttribute); - attributeList.add(marshallComplexAttribute(currentAttribute, representative)); - } else if (currentAttribute.getName().equals("represented")) { - RepresentationPersonType represented = getRepresented(mandateContainer, currentAttribute); - attributeList.add(marshallComplexAttribute(currentAttribute, represented)); - } else if (currentAttribute.getName().equals("mandate")) { - MandateType mandateType = getMandateType(mandateContainer, currentAttribute); - attributeList.add(marshallComplexAttribute(currentAttribute, mandateType)); - } else if (currentAttribute.getName().equals("legalName")) { - String legalName = getLegalName(mandateContainer, currentAttribute); - if (legalName.length() > 0) { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(legalName), AttributeStatusType.AVAILABLE.value())); - } else { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(legalName), AttributeStatusType.NOT_AVAILABLE.value())); - } - } else if (currentAttribute.getName().equals("eLPIdentifier")) { - String eLPIdentifier = geteLPIdentifier(mandateContainer, currentAttribute); - if (eLPIdentifier.length() > 0) { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(eLPIdentifier), AttributeStatusType.AVAILABLE.value())); - } else { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(eLPIdentifier), AttributeStatusType.NOT_AVAILABLE.value())); - } - } else if (currentAttribute.getName().equals("type")) { - String type = getCompanyType(mandateContainer, currentAttribute); - if (type.length() > 0) { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(type), AttributeStatusType.AVAILABLE.value())); - } else { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(type), AttributeStatusType.NOT_AVAILABLE.value())); - } - } else if (currentAttribute.getName().equals("status")) { - String status = getCompanyStatus(mandateContainer, currentAttribute); - if (status.length() > 0) { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(status), AttributeStatusType.AVAILABLE.value())); - } else { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(status), AttributeStatusType.NOT_AVAILABLE.value())); - } - } else if (currentAttribute.getName().equals("translatableType")) { - String translatableType = getCompanyTranslatableType(mandateContainer, currentAttribute); - if (translatableType.length() > 0) { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(translatableType), AttributeStatusType.AVAILABLE.value())); - } else { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(translatableType), AttributeStatusType.NOT_AVAILABLE.value())); - } - } - - if (currentAttribute.getName().equals("eIdentifier")) { - attributeList.add(new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), Arrays.asList(geteIdentifier(authData.getIdentificationType(), authData.getIdentificationValue(), moaStorkRequest.getStorkAttrQueryRequest().getSpCountry())), AttributeStatusType.AVAILABLE.value())); - Logger.info("Adding eIdentifier for mandate holder using SP country: " + moaStorkRequest.getStorkAttrQueryRequest().getSpCountry()); - } - - } - - -// if (attrResponse.getPersonalAttributeList().size() == 0) { -// Logger.error("AttributeList empty - could not retrieve attributes"); -// throw new MOAIDException("stork.16", new Object[]{}); // TODO MESSAGE -// } - - attrResponse.setPersonalAttributeList(attributeList); - moaStorkResponse.setSTORKAttrResponse(attrResponse); - - Logger.debug("Attributes retrieved: " + moaStorkResponse.getStorkAttrQueryResponse().getPersonalAttributeList().size() + " for SP country " + attrResponse.getCountry()); - - // Prepare extended attributes - Logger.debug("Preparing data container"); - - // create fresh container - DataContainer container = new DataContainer(); - - // - fill in the request we extracted above - container.setRequest(moaStorkRequest); - - // - fill in the partial response created above - container.setResponse(moaStorkResponse); - - container.setRemoteAddress(httpReq.getRemoteAddr()); - - Logger.debug("Data container prepared"); - - // ask for consent if necessary - if (oaParam.isRequireConsentForStorkAttributes()) - new ConsentEvaluator().requestConsent(container, httpReq, httpResp, authData, oaParam); - else - new ConsentEvaluator().generateSTORKResponse(httpResp, container); - - return null; - } - - private Integer translateQAALevel(String qaaLevel) throws MOAIDException { - if (qaaLevel.equals(PVPConstants.STORK_QAA_1_1)) - return 1; - if (qaaLevel.equals(PVPConstants.STORK_QAA_1_2)) - return 2; - if (qaaLevel.equals(PVPConstants.STORK_QAA_1_3)) - return 3; - if (qaaLevel.equals(PVPConstants.STORK_QAA_1_4)) - return 4; - Logger.error("Wrong QAA Number format"); - throw new MOAIDException("stork.28", new Object[]{}); - } - - private String geteLPIdentifier(MandateContainer mandateContainer, PersonalAttribute currentAttribute) throws MOAIDException { - RepresentationPersonType represented = getRepresented(mandateContainer, currentAttribute); - if (mandateContainer instanceof CorporateBodyMandateContainer) { - return represented.getELPIdentifier(); - } else if (currentAttribute.isRequired()) { - Logger.error("Cannot provide eLPIdentifier for natural person."); - throw new MOAIDException("stork.29", new Object[]{currentAttribute.getName()}); - } - return ""; - } - - private String geteIdentifier(String identificationType, String identificationValue, String destinationCountry) throws MOAIDException { - BPKBuilder bpkBuilder = new BPKBuilder(); - try { - return bpkBuilder.buildStorkeIdentifier(identificationType, identificationValue, destinationCountry); - } catch (BuildException be) { - Logger.error("Could not build STORK eIdentifier while generating mandate assertion."); - throw new MOAIDException("stork.29", new Object[]{}); - } - } - - private PersonalAttribute marshallComplexAttribute(PersonalAttribute currentAttribute, Object obj) { // TODO refactor - StringWriter stringWriter = new StringWriter(); - try { - if (obj instanceof MandateContentType) { - final Marshaller marshaller = JAXBContext.newInstance(MandateContentType.class).createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.marshal(new JAXBElement<MandateContentType>(new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()), MandateContentType.class, null, (MandateContentType) obj), stringWriter); - } else if (obj instanceof MandateType) { - final Marshaller marshaller = JAXBContext.newInstance(MandateType.class).createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.marshal(new JAXBElement<MandateType>(new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()), MandateType.class, null, (MandateType) obj), stringWriter); - } else if (obj instanceof RepresentationPersonType) { - final Marshaller marshaller = JAXBContext.newInstance(RepresentationPersonType.class).createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.marshal(new JAXBElement<RepresentationPersonType>(new QName("urn:eu:stork:names:tc:STORK:1.0:assertion", currentAttribute.getName()), RepresentationPersonType.class, null, (RepresentationPersonType) obj), stringWriter); - } - - } catch (Exception ex) { - Logger.error("Could not marshall atrribute: " + currentAttribute.getName() + ", " + ex.getMessage()); - return new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), new ArrayList<String>(), AttributeStatusType.NOT_AVAILABLE.value()); - } - ArrayList<String> value = new ArrayList<String>(); - value.add(stringWriter.toString()); - - PersonalAttribute personalAttribute = new PersonalAttribute(currentAttribute.getName(), currentAttribute.isRequired(), value, AttributeStatusType.AVAILABLE.value()); - return personalAttribute; - } - - - private String mapPowersType(MandateContainer mandateContainer) { - Logger.debug("Analyzing mandate of type: " + mandateContainer.getAnnotation() + "."); - // using if for java 6 compatibility if necessary - if (mandateContainer.getAnnotation().equals("ELGABilateral")) { - return "6"; // Health Powers - } else if (mandateContainer.getAnnotation().equals("ERsB")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("Gesetzliche Vollmacht auf Basis Ergäzungsregister für sonstige Betroffene")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("Gesetzliche Vollmacht auf Basis Ergänzungsregister für sonstige Betroffene")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().contains("Gesetzliche Vollmacht auf Basis Erg")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("GeneralvollmachtBilateral")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().contains("Gesetzliche Vollmacht auf Basis Firmenbuch")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("ERsBMitPostvollmacht")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("ZVR")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("ZVRMitPostvollmacht")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("EVB")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("Einzelvertretungsbefugnis")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("Prokura")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("Notar")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("Organwalter")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("Rechtsanwalt")) { - return "0"; // General Powers - } else if (mandateContainer.getAnnotation().equals("Ziviltechniker")) { - return "0"; // General Powers - } - Logger.debug("Returning other type of mandate"); - return "9"; - } - - private MandateType getMandateType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { - MandateType mandateType = new MandateType(); - RepresentationPersonType representative = getRepresentative(mandateContainer, sourceAttribute); - RepresentationPersonType represented = getRepresented(mandateContainer, sourceAttribute); - MandateContentType mandateContent = getMandateContent(mandateContainer, sourceAttribute); - mandateType.setRepresentative(representative); - mandateType.setRepresented(represented); - mandateType.getMandateContent().add(mandateContent); - Logger.debug("Complex attribute extracted: " + sourceAttribute.getName()); - return mandateType; - } - - private String getLegalName(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { - RepresentationPersonType represented = getRepresented(mandateContainer, sourceAttribute); - if (mandateContainer instanceof CorporateBodyMandateContainer) { - represented.getLegalName(); - //return represented.getName(); - } else if (sourceAttribute.isRequired()) { - Logger.error("Cannot provide legalName for natural person."); - throw new MOAIDException("stork.19", new Object[]{sourceAttribute.getName()}); - } - return ""; - } - - - private String getLegalIdentificationType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { - if (mandateContainer instanceof CorporateBodyMandateContainer) { - return ((CorporateBodyMandateContainer) mandateContainer).getCorpMandatorIdentificationType(); - } else if (sourceAttribute.isRequired()) { - Logger.error("Cannot provide type for natural person."); - throw new MOAIDException("stork.19", new Object[]{sourceAttribute.getName()}); // TODO - } - return ""; - } - - private String getCompanyStatus(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { - String legalName = getLegalName(mandateContainer, sourceAttribute); - if (legalName.contains("in Liquidation") || legalName.contains("in Liqu.")) { - return "L"; // liqudation - } - return "R"; - } - - private String getCompanyType(String legalName, String legalIdentificationType, PersonalAttribute sourceAttrivbute) throws MOAIDException { - // compile patterns for different organisation types - // sources: USP, WKO, LexAndTax - - // gmbh patterns - ArrayList<Pattern> gmbhPatterns = new ArrayList<Pattern>(); - gmbhPatterns.add(Pattern.compile(".+ GmbH(( in Liquidation)|( in Liqu.)){0,1}$")); - gmbhPatterns.add(Pattern.compile(".+ GesmbH$")); - gmbhPatterns.add(Pattern.compile(".+ Gesellschaft mit beschränkter Haftung$")); - gmbhPatterns.add(Pattern.compile(".+ Ges\\.m\\.b\\.H\\.$")); - gmbhPatterns.add(Pattern.compile(".+ G\\.m\\.b\\.H\\.$")); - gmbhPatterns.add(Pattern.compile(".+ Handelsges\\.m\\.b\\.H\\.$")); - gmbhPatterns.add(Pattern.compile(".+ Gesellschaft m\\.b\\.H\\.$")); - - // ag patterns - ArrayList<Pattern> agPatterns = new ArrayList<Pattern>(); - agPatterns.add(Pattern.compile(".+ AG$")); - agPatterns.add(Pattern.compile(".+ Aktiengesellschaft$")); - - // og patterns - ArrayList<Pattern> ogPatterns = new ArrayList<Pattern>(); - ogPatterns.add(Pattern.compile(".+ OG$")); - ogPatterns.add(Pattern.compile(".+ OHG$")); - ogPatterns.add(Pattern.compile(".+ offene Gesellschaft$")); - - // kg patterns - ArrayList<Pattern> kgPatterns = new ArrayList<Pattern>(); - kgPatterns.add(Pattern.compile(".+ KG$")); - kgPatterns.add(Pattern.compile(".+ Kommanditgesellschaft$")); - - // eu patterns - ArrayList<Pattern> euPatterns = new ArrayList<Pattern>(); - euPatterns.add(Pattern.compile(".+ eingetragene Unternehmerin$")); - euPatterns.add(Pattern.compile(".+ eingetragener Unternehmer$")); - euPatterns.add(Pattern.compile(".+ e\\.U\\.$")); - - - // company patterns - HashMap<String, ArrayList<Pattern>> companyPatterns = new HashMap<String, ArrayList<Pattern>>(); - companyPatterns.put("GmbH", gmbhPatterns); - companyPatterns.put("AG", agPatterns); - companyPatterns.put("OG", ogPatterns); - companyPatterns.put("KG", kgPatterns); - companyPatterns.put("e.U.", euPatterns); - - // iterate over different types of companies and check if the name ending matches - if (S2Constants.IDENTIFICATION_TYPE_COMPANY.equals(legalIdentificationType)) { - for (String companyType : companyPatterns.keySet()) { - for (Pattern pattern : companyPatterns.get(companyType)) { - if (pattern.matcher(legalName).matches()) { - return companyType; - } - } - } - } - - // check if the subject is association - if (S2Constants.IDENTIFICATION_TYPE_ASSOCIATION.equals(legalIdentificationType)) { - return "Verein"; - } - - // check if the subject falls under category of others - if (S2Constants.IDENTIFICATION_TYPE_OTHERS.equals(legalIdentificationType)) { - return "ERsB"; - } - - return ""; - } - - private String getCompanyType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { - // retrieve the registered subject name and identification type - String legalName = getLegalName(mandateContainer, sourceAttribute); - String legalIdentificationType = getLegalIdentificationType(mandateContainer, sourceAttribute); - return getCompanyType(legalName, legalIdentificationType, sourceAttribute); - } - - private String getCompanyTranslatableType(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { - // retrieve first the company type - String companyType = getCompanyType(mandateContainer, sourceAttribute); - - // translate company type based on the section 5.6 in STORK 2 D4.11 - if (companyType.length() == 0) { - return ""; - } else if (companyType.equals("GmbH")) { - return "G"; - } else if (companyType.equals("AG")) { - return "A"; - } else if (companyType.equals("OG")) { - return "O"; - } else if (companyType.equals("KG")) { - return "K"; - } else { - return ""; - } - } - - - private String getRepresentedStorkeIdentifier(MandateContainer mandateContainer) throws MOAIDException { - - if (!(mandateContainer instanceof PhyPersonMandateContainer)) { - Logger.error("Physical person mandate container missing"); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - PhyPersonMandateContainer phyPersonMandateContainer = (PhyPersonMandateContainer) mandateContainer; - - if (!phyPersonMandateContainer.getPhyPersMandatorIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - Logger.error("Identification type of represented person from MIS is not correct"); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - if (phyPersonMandateContainer.getPhyPersMandatorIdentificationValue().length() != 24) { - Logger.error("Identification value of represented person from MIS is not correct"); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - if ((this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry() == null) || (this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry().length() == 0)) { - Logger.error("Error accessing SP country code"); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - return geteIdentifier(phyPersonMandateContainer.getPhyPersMandatorIdentificationType(), phyPersonMandateContainer.getPhyPersMandatorIdentificationValue(), this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry()); - } - - private String getRepresentingStorkeIdentifier(MandateContainer mandateContainer) throws MOAIDException { - if ((this.representingIdentityLink == null)) { - Logger.error("Error accessing identityLink while fetching mandate attribute"); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - if ((this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry() == null) || (this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry().length() == 0)) { - Logger.error("Error accessing SP country code"); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - if (!this.representingIdentityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - Logger.error("Incorrect identity link (local): identification type is not correct! Got: " + this.representingIdentityLink.getIdentificationType()); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - if (!mandateContainer.getPhysicalRepresentativeIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - Logger.error("Incorrect identity link (MIS): identification type is not correct! Got: " + this.representingIdentityLink.getIdentificationType() + " (representingIdentityLink) and " + mandateContainer.getPhysicalRepresentativeIdentificationType() + " (mandateContainer.phyRepresentative)"); - Logger.debug("mandatecontainervalue: " + mandateContainer.getPhysicalRepresentativeIdentificationValue() + ", representingidentitylinkvalue: " + this.representingIdentityLink.getIdentificationValue()); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - if (!mandateContainer.getPhysicalRepresentativeIdentificationValue().equals(this.representingIdentityLink.getIdentificationValue())) { - Logger.error("Identification values from MIS and local service are not equal!"); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - BPKBuilder bpkBuilder = new BPKBuilder(); - try { - return bpkBuilder.buildStorkeIdentifier(this.representingIdentityLink, this.moaStorkRequest.getStorkAttrQueryRequest().getSpCountry()); - } catch (BuildException be) { - Logger.error("Could not build STORK eIdentifier while generating mandate assertion."); - throw new MOAIDException("stork.20", new Object[]{}); // TODO - } - - } - - private RepresentationPersonType getRepresentative(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { - RepresentationPersonType representative = new RepresentationPersonType(); - - representative.setEIdentifier(getRepresentingStorkeIdentifier(mandateContainer)); - representative.setGivenName(mandateContainer.getPhysicalRepresentativeGivenName()); - representative.setSurname(mandateContainer.getPhysicalRepresentativeFamilyName()); - representative.setDateOfBirth(mandateContainer.getPhysicalRepresentativeBirthDate()); - - Logger.debug("Complex attribute extracted: " + sourceAttribute.getName()); - return representative; - } - - private RepresentationPersonType getRepresented(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { - RepresentationPersonType represented = new RepresentationPersonType(); - - if (mandateContainer instanceof CorporateBodyMandateContainer) { - CorporateBodyMandateContainer corporateBodyMandateContainer = (CorporateBodyMandateContainer) mandateContainer; - represented.setELPIdentifier(corporateBodyMandateContainer.getCorpMandatorIdentificationValue()); - represented.setLegalName(corporateBodyMandateContainer.getCorpMandatorFullName()); - represented.setTextRegisteredAddress(null); - represented.setCanonicalRegisteredAddress(new CanonicalAddressType()); - represented.setLegalForm(getCompanyType(corporateBodyMandateContainer.corpMandatorFullName, corporateBodyMandateContainer.corpMandatorIdentificationType, sourceAttribute)); - } else if (mandateContainer instanceof PhyPersonMandateContainer) { - PhyPersonMandateContainer phyPersonMandateContainer = (PhyPersonMandateContainer) mandateContainer; - represented.setEIdentifier(getRepresentedStorkeIdentifier(mandateContainer)); - represented.setGivenName(phyPersonMandateContainer.getPhyPersMandatorGivenName()); - represented.setSurname(phyPersonMandateContainer.getPhyPersMandatorFamilyName()); - represented.setDateOfBirth(phyPersonMandateContainer.getPhyPersMandatorBirthDate()); - } - - Logger.debug("Complex attribute extracted: " + sourceAttribute.getName()); - - return represented; - } - - - private MandateContentType getMandateContent(MandateContainer mandateContainer, PersonalAttribute sourceAttribute) throws MOAIDException { - MandateContentType mandateContent = new MandateContentType(); - try { - XMLGregorianCalendar validFrom = DatatypeFactory.newInstance().newXMLGregorianCalendar(mandateContainer.getMandateValidFrom()); - XMLGregorianCalendar validTo = DatatypeFactory.newInstance().newXMLGregorianCalendar(mandateContainer.getMandateValidTo()); - TimeRestrictionType timeRestriction = new TimeRestrictionType(); - timeRestriction.setValidFrom(validFrom); - timeRestriction.setValidTo(validTo); - mandateContent.setTimeRestriction(timeRestriction); - } catch (DatatypeConfigurationException dte) { - Logger.error("Error converting date from mandate: " + mandateContainer.getMandateValidFrom() + ", " + mandateContainer.getMandateValidTo()); - throw new MOAIDException("stork.20", new Object[]{}); - } - mandateContent.setAQAA(this.QAALevel); - mandateContent.setOriginalMandate(originalContent); - mandateContent.setOriginalMandateType("application/xml"); - TransactionLimitRestrictionType transactionLimit = new TransactionLimitRestrictionType(); - mandateContent.setTransactionLimit(transactionLimit); - mandateContent.setIsJoint(""); - mandateContent.setIsChained(false); - mandateContent.setTypeOfPower(mapPowersType(mandateContainer)); // TODO check - Logger.debug("Complex attribute extracted: " + sourceAttribute.getName()); - return mandateContent; - } - - public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { - return true; - } - - public String getDefaultActionName() { - return STORKProtocol.MANDATERETRIEVALREQUEST; - } -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java deleted file mode 100644 index c715b65eb..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/PhyPersonMandateContainer.java +++ /dev/null @@ -1,132 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.logging.Logger; -import org.xml.sax.InputSource; - -import javax.xml.xpath.XPathExpressionException; -import java.io.StringReader; - -/** - * Physical person representing physical person - * @author bsuzic - * Date: 4/30/14, Time: 11:29 AM - */ -public class PhyPersonMandateContainer extends MandateContainer { - - private String phyPersMandatorIdentificationValue = null; - private String phyPersMandatorIdentificationType = null; - private String phyPersMandatorGivenName = null; - private String phyPersMandatorFamilyName = null; - private String phyPersMandatorBirthDate = null; - - String localMethods[] = new String[]{"getPhyPersMandatorGivenName", "getPhyPersMandatorFamilyName", "getPhyPersMandatorBirthDate", "getPhyPersMandatorIdentificationValue", - "getPhyPersMandatorIdentificationType", "getMandateIssuePlace", "getMandateIssueDate", "getMandateIssueTime", "getSimpleMandateContent", "getMandateValidFrom", - "getMandateValidTo", "getPhysicalRepresentativeIdentificationValue", "getPhysicalRepresentativeIdentificationType", "getAnnotation", - "getPhysicalRepresentativeGivenName", "getPhysicalRepresentativeFamilyName", "getPhysicalRepresentativeBirthDate" - }; - - - public PhyPersonMandateContainer(String mandate) throws XPathExpressionException, MOAIDException { - super(mandate); - - setAnnotation(xPath.evaluate(S2Constants.MANDATE_ANNOTATION_QUERY, new InputSource(new StringReader(mandate)))); - setPhyPersMandatorIdentificationType(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_IDTYPE_QUERY, new InputSource(new StringReader(mandate)))); - setPhyPersMandatorIdentificationValue(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_IDVALUE_QUERY, new InputSource(new StringReader(mandate)))); - setPhyPersMandatorGivenName(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_GIVENNAME_QUERY, new InputSource(new StringReader(mandate)))); - setPhyPersMandatorFamilyName(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_FAMILYNAME_QUERY, new InputSource(new StringReader(mandate)))); - setPhyPersMandatorBirthDate(xPath.evaluate(S2Constants.MANDATE_MANDATOR_PHYPERS_DATEOFBIRTH_QUERY, new InputSource(new StringReader(mandate)))); - setMandateIssueDate(xPath.evaluate(S2Constants.MANDATE_ISSUEDDATE_QUERY, new InputSource(new StringReader(mandate)))); - setMandateIssuePlace(xPath.evaluate(S2Constants.MANDATE_ISSUEDPLACE_QUERY, new InputSource(new StringReader(mandate)))); - setMandateIssueTime(xPath.evaluate(S2Constants.MANDATE_ISSUEDTIME_QUERY, new InputSource(new StringReader(mandate)))); - setMandateValidFrom(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_VALIDFROM_QUERY, new InputSource(new StringReader(mandate)))); - setMandateValidTo(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_VALIDTO_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeBirthDate(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_DATEOFBIRTH_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeFamilyName(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_FAMILYNAME_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeGivenName(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_GIVENNAME_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeIdentificationType(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_IDTYPE_QUERY, new InputSource(new StringReader(mandate)))); - setPhysicalRepresentativeIdentificationValue(xPath.evaluate(S2Constants.MANDATE_REPRESENTATIVE_PHYPERS_IDVALUE_QUERY, new InputSource(new StringReader(mandate)))); - setSimpleMandateContent(xPath.evaluate(S2Constants.MANDATE_SIMPLEMANDATECONTENT_TXTDESC_QUERY, new InputSource(new StringReader(mandate)))); - - // check if all necessary fields are present - Logger.debug("Starting mandate structure validation"); - try { - validateMandateStructure(localMethods); // TODO - } catch (Exception e) { - if (e instanceof MOAIDException) { - Logger.error("Could not validate mandate structure."); - throw new MOAIDException("stork.16", new Object[] {e.getMessage()}); // TODO - } else { - Logger.error("Error during mandate structure validation."); - throw new MOAIDException("stork.16", new Object[] {e.getMessage()}); // TODO - } - - } - } - - - - public String getPhyPersMandatorGivenName() { - return phyPersMandatorGivenName; - } - - public void setPhyPersMandatorGivenName(String phyPersMandatorGivenName) { - this.phyPersMandatorGivenName = phyPersMandatorGivenName; - } - - public String getPhyPersMandatorFamilyName() { - return phyPersMandatorFamilyName; - } - - public void setPhyPersMandatorFamilyName(String phyPersMandatorFamilyName) { - this.phyPersMandatorFamilyName = phyPersMandatorFamilyName; - } - - public String getPhyPersMandatorBirthDate() { - return phyPersMandatorBirthDate; - } - - public void setPhyPersMandatorBirthDate(String phyPersMandatorBirthDate) { - // making it conform to STORK dateOfBirth specifications, removing dash - this.phyPersMandatorBirthDate = phyPersMandatorBirthDate.replaceAll("-",""); - } - - public String getPhyPersMandatorIdentificationValue() { - return phyPersMandatorIdentificationValue; - } - - public void setPhyPersMandatorIdentificationValue(String phyPersMandatorIdentificationValue) { - this.phyPersMandatorIdentificationValue = phyPersMandatorIdentificationValue; - } - - public String getPhyPersMandatorIdentificationType() { - return phyPersMandatorIdentificationType; - } - - public void setPhyPersMandatorIdentificationType(String phyPersMandatorIdentificationType) { - this.phyPersMandatorIdentificationType = phyPersMandatorIdentificationType; - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java deleted file mode 100644 index a560bdaff..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/S2Constants.java +++ /dev/null @@ -1,66 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -/** - * @author bsuzic - * Date: 4/29/14, Time: 5:34 PM - */ -public interface S2Constants { - public static final String MANDATE_PREFIX = "mandate"; - public static final String PERSONDATA_PREFIX = "persondata"; - public static final String XMLDSIG_PREFIX = "xmldsig"; - - public static final String MANDATE_NS = "http://reference.e-government.gv.at/namespace/mandates/20040701#"; - public static final String PERSONDATA_NS = "http://reference.e-government.gv.at/namespace/persondata/20020228#"; - public static final String XMLDSIG_NS = "http://www.w3.org/2000/09/xmldsig#"; - - public static final String MANDATE_ANNOTATION_QUERY = "/mandate:Mandate/mandate:Annotation/text()"; - public static final String MANDATE_REPRESENTATIVE_PHYPERS_IDVALUE_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:Identification/persondata:Value/text()"; - public static final String MANDATE_REPRESENTATIVE_PHYPERS_IDTYPE_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:Identification/persondata:Type/text()"; - public static final String MANDATE_REPRESENTATIVE_PHYPERS_GIVENNAME_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:Name/persondata:GivenName/text()"; - public static final String MANDATE_REPRESENTATIVE_PHYPERS_FAMILYNAME_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:Name/persondata:FamilyName/text()"; - public static final String MANDATE_REPRESENTATIVE_PHYPERS_DATEOFBIRTH_QUERY = "/mandate:Mandate/mandate:Representative/persondata:PhysicalPerson/persondata:DateOfBirth/text()"; - public static final String MANDATE_MANDATOR_CORPBODY_IDVALUE_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:CorporateBody/persondata:Identification/persondata:Value/text()"; - public static final String MANDATE_MANDATOR_CORPBODY_IDTYPE_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:CorporateBody/persondata:Identification/persondata:Type/text()"; - public static final String MANDATE_MANDATOR_CORPBODY_FULLNAME_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:CorporateBody/persondata:FullName/text()"; - public static final String MANDATE_ISSUEDPLACE_QUERY = "/mandate:Mandate/mandate:Issued/mandate:Place/text()"; - public static final String MANDATE_ISSUEDDATE_QUERY = "/mandate:Mandate/mandate:Issued/mandate:Date/text()"; - public static final String MANDATE_ISSUEDTIME_QUERY = "/mandate:Mandate/mandate:Issued/mandate:Time/text()"; - public static final String MANDATE_SIMPLEMANDATECONTENT_TXTDESC_QUERY = "/mandate:Mandate/mandate:SimpleMandateContent/mandate:TextualDescription/text()"; - public static final String MANDATE_SIMPLEMANDATECONTENT_VALIDFROM_QUERY = "/mandate:Mandate/mandate:SimpleMandateContent/mandate:TimeConstraint/mandate:ValidFrom/text()"; - public static final String MANDATE_SIMPLEMANDATECONTENT_VALIDTO_QUERY = "/mandate:Mandate/mandate:SimpleMandateContent/mandate:TimeConstraint/mandate:ValidTo/text()"; - - public static final String MANDATE_MANDATOR_PHYPERS_IDVALUE_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:Identification/persondata:Value/text()"; - public static final String MANDATE_MANDATOR_PHYPERS_IDTYPE_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:Identification/persondata:Type/text()"; - public static final String MANDATE_MANDATOR_PHYPERS_GIVENNAME_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:Name/persondata:GivenName/text()"; - public static final String MANDATE_MANDATOR_PHYPERS_FAMILYNAME_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:Name/persondata:FamilyName/text()"; - public static final String MANDATE_MANDATOR_PHYPERS_DATEOFBIRTH_QUERY = "/mandate:Mandate/mandate:Mandator/persondata:PhysicalPerson/persondata:DateOfBirth/text()"; - - public static final String IDENTIFICATION_TYPE_COMPANY = "urn:publicid:gv.at:baseid+XFN"; - public static final String IDENTIFICATION_TYPE_ASSOCIATION = "urn:publicid:gv.at:baseid+XZVR"; - public static final String IDENTIFICATION_TYPE_OTHERS = "urn:publicid:gv.at:baseid+XERSB"; - - - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java deleted file mode 100644 index c4f9658e4..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java +++ /dev/null @@ -1,233 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2; - -import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; -import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.moduls.IAction; -import at.gv.egovernment.moa.id.moduls.IModulInfo; -import at.gv.egovernment.moa.id.moduls.IRequest; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.MiscUtil; -import eu.stork.peps.auth.commons.*; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.exceptions.STORKSAMLEngineException; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.util.HashMap; - -/** - * Stork 2 Protocol Support - * - * @author bsuzic - */ -public class STORKProtocol extends MOAIDAuthConstants implements IModulInfo { - - public static final String NAME = STORKProtocol.class.getName(); - public static final String PATH = "id_stork2"; - - public static final String AUTHENTICATIONREQUEST = "AuthenticationRequest"; - public static final String ATTRIBUTE_COLLECTOR = "AttributeCollector"; - public static final String MANDATERETRIEVALREQUEST = "MandateRetrievalRequest"; - public static final String CONSENT_EVALUATOR = "ConsentEvaluator"; - - private static HashMap<String, IAction> actions = new HashMap<String, IAction>(); - - static { - actions.put(AUTHENTICATIONREQUEST, new AuthenticationRequest()); - actions.put(ATTRIBUTE_COLLECTOR, new AttributeCollector()); - actions.put(CONSENT_EVALUATOR, new ConsentEvaluator()); - actions.put(MANDATERETRIEVALREQUEST, new MandateRetrievalRequest()); - } - - public String getName() { - return NAME; - } - - public String getPath() { - return PATH; - } - - public IAction getAction(String action) { - return actions.get(action); - } - - public STORKProtocol() { - super(); - } - - /* - First request step - send it to BKU selection for user authentication. After the user credentials - and other info are obtained, in the second step the request will be processed and the user redirected - */ - public IRequest preProcess(HttpServletRequest request, HttpServletResponse response, String action, - String sessionId, String transactionId) throws MOAIDException { - Logger.info("Starting preprocessing for Stork2 protocol"); - Logger.debug("Request method: " + request.getMethod()); - Logger.debug("Request content length: " + request.getContentLength()); - Logger.debug("Initiating action: " + action); - - MOASTORKRequest STORK2Request = new MOASTORKRequest(request); - MOASTORKResponse STORK2Response = new MOASTORKResponse(request); - - - if (AttributeCollector.class.getSimpleName().equals(action) || ConsentEvaluator.class.getSimpleName().equals(action)) - return STORK2Request; - - - if (request.getParameter("SAMLResponse") != null) { // TODO check attribute collector - //extract STORK Response from HTTP Request - byte[] decSamlToken; - try { - decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLResponse")); - } catch (NullPointerException e) { - if (request.getRemoteHost().contains("129.27.142")) { - Logger.warn("Availability check by " + request.getRemoteHost() + " on URI: " + request.getRequestURI()); - } else { - Logger.error("Unable to retrieve STORK Request for host: " + request.getRemoteHost() + " and URI: " + request.getRequestURI(), e); - } - throw new MOAIDException("stork.04", null); - } - - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - - STORKAuthnResponse authnResponse = null; - - - // check if valid authn request is contained - try { - authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, request.getRemoteAddr()); - } catch (STORKSAMLEngineException ex) { - Logger.error("Unable to validate Stork AuthenticationResponse: " + ex.getMessage()); - } - - STORK2Response.setSTORKAuthnResponseToken(decSamlToken); - - return STORK2Response; - - } else if (request.getParameter("SAMLRequest") != null) { - - //extract STORK Response from HTTP Request - byte[] decSamlToken; - try { - decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLRequest")); - } catch (NullPointerException e) { - if (request.getRemoteHost().contains("129.27.142")) { - Logger.warn("Availability check by " + request.getRemoteHost() + " on URI: " + request.getRequestURI()); - } else { - Logger.error("Unable to retrieve STORK Request for host: " + request.getRemoteHost() + " and URI: " + request.getRequestURI(), e); - } - throw new MOAIDException("stork.04", null); - } - - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - - STORKAuthnRequest authnRequest = null; - STORKAttrQueryRequest attrRequest = null; - - // check if valid authn request is contained - try { - authnRequest = engine.validateSTORKAuthnRequest(decSamlToken); - - } catch (STORKSAMLEngineException ex) { - Logger.error("Unable to validate Stork AuthenticationRequest: " + ex.getMessage()); - - } catch (ClassCastException e) { - // we do not have a authnRequest - // check if a valid attr request is container - try { - attrRequest = engine.validateSTORKAttrQueryRequest(decSamlToken); - - } catch (STORKSAMLEngineException ex) { - Logger.error("Unable to validate Stork AuthenticationRequest: " + ex.getMessage()); - - } - } - - // if there is no authn or attr request, raise error - if ((authnRequest == null) && (attrRequest == null)) { - Logger.error("There is no authentication or attribute request contained."); - throw new MOAIDException("stork.14", null); - } - // list attributes in the request - try { - for (PersonalAttribute personalAttribute : authnRequest.getPersonalAttributeList()) { - Logger.debug("Personal attribute found in request: " + personalAttribute.getName() + " isRequired: " + personalAttribute.isRequired()); - } - } catch (Exception e) { - Logger.error("Exception, attributes: " + e.getMessage()); - } - - STORK2Request.setSTORKAuthnRequest(authnRequest); - STORK2Request.setSTORKAttrRequest(attrRequest); - - //check if OA is instance of VIDP or STORKPVPGateway - OAAuthParameter oaParam = AuthConfigurationProviderFactory.getInstance().getOnlineApplicationParameter(STORK2Request.getOAURL()); - if (oaParam == null) - throw new AuthenticationException("stork.12", new Object[]{STORK2Request.getOAURL()}); - - else { - STORK2Request.setOnlineApplicationConfiguration(oaParam); - if (oaParam.isSTORKPVPGateway()) { - if (MiscUtil.isNotEmpty(oaParam.getSTORKPVPForwardEntity())) { - Logger.info("Received request for STORK->PVP gateway. " + - "Forward to PVP portal with entiyID " + oaParam.getSTORKPVPForwardEntity() + - " ..." ); - STORK2Request.setRequestedIDP(oaParam.getSTORKPVPForwardEntity()); - - } else { - Logger.error("InterfederatedGateway configuration with ID " + STORK2Request.getOAURL() + - " not configure a forward entityID."); - throw new MOAIDException("", null); - - } - } - - } - - return STORK2Request; - } else { - throw new MOAIDException("stork.14", null); // TODO Specify message - } - } - - public IAction canHandleRequest(HttpServletRequest request, HttpServletResponse response) { - return null; - } - - public boolean generateErrorMessage(Throwable e, HttpServletRequest request, HttpServletResponse response, IRequest protocolRequest) throws Throwable { - return false; - } - - public boolean validate(HttpServletRequest request, HttpServletResponse response, IRequest pending) { - return false; - } -} - - diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java deleted file mode 100644 index aaf13a779..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/AttributeProvider.java +++ /dev/null @@ -1,139 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2.attributeproviders; - -import java.util.ArrayList; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException; -import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest; -import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PersonalAttribute; - -/** - * An {@link AttributeProvider} can fetch a set of stork attributes. It might complete the query within one method call, - * but might also need to redirect to another webservice to accomplish its task. - */ -public abstract class AttributeProvider implements Comparable<AttributeProvider>{ - - protected String attributes; - - public AttributeProvider(String attributes){ - this.attributes = attributes; - } - - /** - * Acquire the specified attribute. Returns {@code null} when attribute retrieval is in progress, but requires for - * for redirecting the user to an external service. Use {@link AttributeProvider#parse(HttpServletRequest)} to parse - * the response. - * - * @param currentProviderConfiguredAttributes the list of attributes to be acquired - * @param moastorkRequest the sp county code - * @param authData the moasession - * @return the personal attribute - * @throws UnsupportedAttributeException the unsupported attribute exception - * @throws ExternalAttributeRequestRequiredException an attribute request to an external service has to be done - * @throws MOAIDException the mOAID exception - */ - protected abstract IPersonalAttributeList acquire(PersonalAttribute currentProviderConfiguredAttributes, MOASTORKRequest moastorkRequest, IAuthData authData) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException; - - public IPersonalAttributeList acquire(List<PersonalAttribute> attributes, MOASTORKRequest moastorkRequest, IAuthData authData) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException { - if (attributes.size() == 1) { - return acquire(attributes.get(0), moastorkRequest, authData); - } else { - throw new MOAIDException("stork.13", new Object[] { }); // TODO message only one attribute supported by this provider - - } - } - - /** - * Perform redirect. - * - * @param url the return URL ending with ?artifactId=... - * @param req the request we got from the S-PEPS and for which we have to ask our APs - * @param resp the response to the preceding request - * @param oaParam the oa param - * @throws MOAIDException the mOAID exception - */ - public abstract void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException; - - /** - * Parses the response we got from the external attribute provider. - * - * @param httpReq the http req - * @return a list of attributes - * @throws UnsupportedAttributeException if the provider cannot find anything familiar in the provided httpReq - * @throws MOAIDException if something went wrong - */ - public abstract IPersonalAttributeList parse(HttpServletRequest httpReq) throws UnsupportedAttributeException, MOAIDException; - - /** - * Returns the list of supported attributes - * - * @return a list of attributes - * @throws MOAIDException if something went wrong - */ - public List<String> getSupportedAttributeNames() throws MOAIDException { - ArrayList<String> supportedAttributeNames = new ArrayList<String>(); - for (String attributeName : this.attributes.split(",")) { - supportedAttributeNames.add(attributeName); - } - return supportedAttributeNames; - } - - - /** - * Returns the sequence priority of this attribute provider. - * Providers with small numbers are requested first. - * - * @return a sequence priority of this provider - */ - public abstract int getPriority(); - - /** - * Compare the sequence priority of two attribute providers - * @param o attribute provider - * @return 0 if priority is equal - * @return -1 if priority if this is higher then from o - * @return +1 if priority if o is higher then from this - */ - @Override - public int compareTo(AttributeProvider o) { - if (this.getPriority() == o.getPriority()) - return 0; - - if (this.getPriority() < o.getPriority()) - return -1; - - else - return +1; - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java deleted file mode 100644 index bd1576020..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/EHvdAttributeProviderPlugin.java +++ /dev/null @@ -1,254 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2.attributeproviders; - -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; -import javax.xml.soap.MessageFactory; -import javax.xml.soap.SOAPBody; -import javax.xml.soap.SOAPConnection; -import javax.xml.soap.SOAPConnectionFactory; -import javax.xml.soap.SOAPElement; -import javax.xml.soap.SOAPEnvelope; -import javax.xml.soap.SOAPMessage; -import javax.xml.soap.SOAPPart; - -import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException; -import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest; -import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException; -import at.gv.egovernment.moa.logging.Logger; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.commons.PersonalAttributeList; -import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.AttributeStatusType; -import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.IsHealthCareProfessionalType; -import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.ObjectFactory; - -/** - * Fetches the attribute IsHealthcareProfessional from the BAGDAD SOAP service - */ -public class EHvdAttributeProviderPlugin extends AttributeProvider { - - /** The destination. */ - private Object destination; - - /** - * Instantiates a new e hvd attribute provider plugin. - * - * @param url the service url - * @param supportedAttributes - */ - public EHvdAttributeProviderPlugin(String url, String supportedAttributes) { - super(supportedAttributes); - destination = url; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#acquire(eu.stork.peps.auth.commons.PersonalAttribute) - */ - @Override - protected IPersonalAttributeList acquire(PersonalAttribute attribute, MOASTORKRequest moastorkRequest, IAuthData authData) - throws UnsupportedAttributeException, - ExternalAttributeRequestRequiredException, MOAIDException { - - // break when we cannot handle the requested attribute - if(!attributes.contains(attribute.getName())) - throw new UnsupportedAttributeException(); - - try { - Logger.debug("initializing SOAP connections..."); - // create SOAP connection - SOAPConnection soapConnection = SOAPConnectionFactory.newInstance().createConnection(); - - // assemble SOAP request - MessageFactory messageFactory = MessageFactory.newInstance(); - SOAPMessage requestMessage = messageFactory.createMessage(); - SOAPPart requestPart = requestMessage.getSOAPPart(); - - // (soap 1.1 relevant part. could not find a solution to use soap 1.2 in time. - requestMessage.getMimeHeaders().setHeader("SOAPAction", "http://gesundheit.gv.at/BAGDAD/DataAccessService/IsHealthcareProfessional"); - - /* - Construct SOAP Request Message: - <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> - <soap:Body> - <IsHealthcareProfessional xmlns="http://gesundheit.gv.at/BAGDAD/DataAccessService"> - <bPK>string</bPK> - </IsHealthcareProfessional> - </soap:Body> - </soap:Envelope> - - see https://stork.ehealth.gv.at/GDAService.asmx?op=IsHealthcareProfessional - */ - - // SOAP Envelope - SOAPEnvelope envelope = requestPart.getEnvelope(); - - // SOAP Body - SOAPBody requestBody = envelope.getBody(); - SOAPElement requestBodyElem = requestBody.addChildElement("IsHealthcareProfessional"); - requestBodyElem.addAttribute(envelope.createName("xmlns"), "http://gesundheit.gv.at/BAGDAD/DataAccessService"); - - SOAPElement requestBodyElem1 = requestBodyElem.addChildElement("bPK"); - - //TODO: CHECK: IdentificationValue containts wbPK if MOA-ID is used as VIDP - requestBodyElem1.addTextNode(new BPKBuilder().buildBPK(authData.getIdentificationValue(), "GH")); - - requestMessage.saveChanges(); - - // perform SOAP call - Logger.debug("call..."); - SOAPMessage responseMessage = soapConnection.call(requestMessage, destination); - - // parse SOAP response - - /* - <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> - <soap:Body> - <IsHealthcareProfessionalResponse xmlns="http://gesundheit.gv.at/BAGDAD/DataAccessService"> - <IsHealthcareProfessionalResult> - <RequestOK>boolean</RequestOK> - <Message>string</Message> - <IsHealthcareProfessional>boolean</IsHealthcareProfessional> - <NameOfOrganisation>string</NameOfOrganisation> - <Type>string</Type> - <Specialization>string</Specialization> - </IsHealthcareProfessionalResult> - </IsHealthcareProfessionalResponse> - </soap:Body> - </soap:Envelope> - - see https://stork.ehealth.gv.at/GDAService.asmx?op=IsHealthcareProfessional - */ - Logger.debug("call successful. Parse..."); - SOAPBody responseBody = responseMessage.getSOAPBody(); - - // iterate through tree - SOAPElement responseElement = (SOAPElement) responseBody.getChildElements().next(); - SOAPElement resultElement = (SOAPElement) responseElement.getChildElements().next(); - - // collect all info in a map - Iterator<?> it = resultElement.getChildElements(); - Map<String, String> collection = new HashMap<String, String>(); - while (it.hasNext()) { - SOAPElement current = (SOAPElement) it.next(); - - collection.put(current.getNodeName(), current.getTextContent()); - } - - // check if there is anything valid in the map - if (collection.isEmpty() || collection.size() != 6) { - Logger.warn("eHVD returned an unexpected count of values. Expected 6 got " + collection.size()); - throw new IndexOutOfBoundsException("response attributes not like specified"); - } - - // - fetch request validity - if (collection.get("RequestOK").equals("false")) { - Logger.warn("eHVD reported an invalid request. The error message is: " + collection.get("Message")); - throw new Exception("eHVD reported an invalid request"); - } - - PersonalAttribute acquiredAttribute = null; - - if (collection.get("IsHealthcareProfessional").equals("false") || !collection.get("Type").equals("Medical doctor")) { - // the citizen is no HCP - acquiredAttribute = new PersonalAttribute("isHealthCareProfessional", false, new ArrayList<String>(), AttributeStatusType.NOT_AVAILABLE.value()); - } else { - // go on and parse the data - IsHealthCareProfessionalType result = new IsHealthCareProfessionalType(); - - // TODO: we do not have any list of possible values yet. Fix as soon as we get some. -// if (collection.get("Type").equals("Medical doctor")) - result.setTypeOfHCP("physician"); - - result.setNameOfOrganisation(collection.get("NameOfOrganisation")); - //result.setTypeOfOrganisation("Unknown"); // TODO used in previous version, check what to do with this - - result.setAQAA(4); - - final Marshaller m = JAXBContext.newInstance(IsHealthCareProfessionalType.class).createMarshaller(); - m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - - StringWriter stringWriter = new StringWriter(); - m.marshal(new ObjectFactory().createIsHealthCareProfessional(result), stringWriter); - - ArrayList<String> value = new ArrayList<String>(); - value.add(stringWriter.toString()); - - acquiredAttribute = new PersonalAttribute("isHealthCareProfessional", false, value, AttributeStatusType.AVAILABLE.value()); - } - - // pack and return the result - PersonalAttributeList result = new PersonalAttributeList(); - result.add(acquiredAttribute); - - // add stork id for verification - ArrayList<String> value = new ArrayList<String>(); - value.add(new BPKBuilder().buildStorkeIdentifier(authData.getIdentityLink(), moastorkRequest.getSpCountry())); - result.add(new PersonalAttribute("eIdentifier", false, value, AttributeStatusType.AVAILABLE.value())); - - return result; - } catch (Exception e) { - throw new MOAIDException("stork.13", new Object[] { e }); - } - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#performRedirect(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.config.auth.OAAuthParameter) - */ - public void performRedirect(String url, - HttpServletRequest req, HttpServletResponse resp, - OAAuthParameter oaParam) throws MOAIDException { - // there is no redirect required - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#parse(javax.servlet.http.HttpServletRequest) - */ - public IPersonalAttributeList parse(HttpServletRequest httpReq) - throws UnsupportedAttributeException, MOAIDException { - // there is no redirect required, so we throw an exception when someone asks us to parse a response - throw new UnsupportedAttributeException(); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority() - */ - @Override - public int getPriority() { - return 99; - } - -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java deleted file mode 100644 index f671f0807..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/MandateAttributeRequestProvider.java +++ /dev/null @@ -1,231 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2.attributeproviders; - -import java.io.StringWriter; -import java.util.List; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException; -import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest; -import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.VelocityProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.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.engine.STORKSAMLEngine; -import eu.stork.peps.exceptions.STORKSAMLEngineException; - -/** - * Provides mandate attribute from MIS - */ -public class MandateAttributeRequestProvider extends AttributeProvider { - /** - * The destination. - */ - private String destination; - - private String spCountryCode; - - private PersonalAttributeList requestedAttributes; - - public MandateAttributeRequestProvider(String aPurl, String supportedAttributes) throws MOAIDException { - super(supportedAttributes); - destination = aPurl; - - } - - public String getAttrProviderName() { - return "MandateAttributeRequestProvider"; - } - - // TODO check if used - @Override - protected IPersonalAttributeList acquire(PersonalAttribute attribute, MOASTORKRequest moastorkRequest, IAuthData authData) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException { - Logger.info("Acquiring attribute: " + attribute.getName() + ", by: " + getAttrProviderName()); - this.spCountryCode = moastorkRequest.getSpCountry(); - requestedAttributes = new PersonalAttributeList(1); - requestedAttributes.add(attribute); - - // break if we cannot handle the requested attribute - if (!attributes.contains(attribute.getName())) { - Logger.info("Attribute " + attribute.getName() + " not supported by the provider: " + getAttrProviderName()); - throw new UnsupportedAttributeException(); - } - - // check if there is eIdentifier included and add if necessary -// if (!requestedAttributes.containsKey("eIdentifier")) { -// PersonalAttribute eIdentifier = new PersonalAttribute(); - // eIdentifier.setName("eIdentifier"); -// eIdentifier.setIsRequired(true); -// requestedAttributes.add(eIdentifier); -// } - - Logger.info("Thrown external request by: " + getAttrProviderName()); - throw new ExternalAttributeRequestRequiredException(this); - } - - @Override - public IPersonalAttributeList acquire(List<PersonalAttribute> attributes, MOASTORKRequest moastorkRequest, IAuthData moasession) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException { - Logger.info("Acquiring " + attributes.size() + " attributes, by: " + getAttrProviderName()); - this.spCountryCode = moastorkRequest.getSpCountry(); - requestedAttributes = new PersonalAttributeList(attributes.size()); - - for (PersonalAttribute personalAttribute : attributes) { - // break if we cannot handle the requested attribute - if (!this.attributes.contains(personalAttribute.getName())) { - Logger.info("Attribute " + personalAttribute.getName() + " not supported by the provider: " + getAttrProviderName()); - throw new UnsupportedAttributeException(); - } - requestedAttributes.add(personalAttribute); - } - - // continue with other attribute providers if there are no attributes current provider is able to handle - if (requestedAttributes.size() == 0) { - Logger.info("Attribute(s) " + attributes.toString() + " not supported by the provider: " + getAttrProviderName()); - throw new UnsupportedAttributeException(); - } - - - - Logger.info("Thrown external request by: " + getAttrProviderName()); - throw new ExternalAttributeRequestRequiredException(this); - } - - - - - public void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException { - - String spSector = "Business"; - String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName(); - String spApplication = spInstitution; - - if ((spCountryCode == null) || (spCountryCode.length()<2)) { - spCountryCode = oaParam.getTarget(); - Logger.info("Setting spcountry target: " + oaParam.getTarget()); - Logger.info("idlink ident " + oaParam.getIdentityLinkDomainIdentifier()); - Logger.info("idlink type " + oaParam.getIdentityLinkDomainIdentifierType()); - Logger.info("Setting spcountry target friendly : " + oaParam.getTargetFriendlyName()); - Logger.info("Oatype : " + oaParam.getOaType()); - Logger.info("puburl : " + oaParam.getPublicURLPrefix()); - if ("STORK".equals(oaParam.getIdentityLinkDomainIdentifierType())) { - - spCountryCode = oaParam.getIdentityLinkDomainIdentifier().substring(oaParam.getIdentityLinkDomainIdentifier().length()-2); - Logger.info("Set to " +spCountryCode); - } - - } - - // TODO ensure that other providers request eidentifier - // check if there is eIdentifier included and add if necessary - if (!requestedAttributes.containsKey("eIdentifier")) { - PersonalAttribute eIdentifier = new PersonalAttribute(); - eIdentifier.setName("eIdentifier"); - eIdentifier.setIsRequired(true); - requestedAttributes.add(eIdentifier); - } - - //generate AttrQueryRequest - STORKAttrQueryRequest attributeRequest = new STORKAttrQueryRequest(); - attributeRequest.setDestination(destination); - attributeRequest.setAssertionConsumerServiceURL(url); - attributeRequest.setIssuer(HTTPUtils.getBaseURL(req)); - attributeRequest.setQaa(oaParam.getQaaLevel()); - attributeRequest.setSpInstitution(spInstitution); - attributeRequest.setCountry(spCountryCode); - attributeRequest.setSpCountry(spCountryCode); - attributeRequest.setSpApplication(spApplication); - attributeRequest.setSpSector(spSector); - attributeRequest.setPersonalAttributeList(requestedAttributes); - - attributeRequest.setCitizenCountryCode("AT"); - attributeRequest.setQaa(oaParam.getQaaLevel()); - - if (attributeRequest.getQaa() == 0 ) { - attributeRequest.setQaa(4); // workaround - } - - - - Logger.info("STORK AttrRequest successfully assembled."); - - STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("VIDP"); - try { - - attributeRequest = samlEngine.generateSTORKAttrQueryRequest(attributeRequest); - } catch (STORKSAMLEngineException e) { - Logger.error("Could not sign STORK SAML AttrRequest.", e); - throw new MOAIDException("stork.00", null); - } - - Logger.info("STORK AttrRequest successfully signed!"); - - 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(attributeRequest.getTokenSaml())); - context.put("action", destination); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - resp.getOutputStream().write(writer.toString().getBytes("UTF-8")); - } catch (Exception e) { - Logger.error("Error sending STORK SAML AttrRequest.", e); - throw new MOAIDException("stork.11", null); - } - Logger.info("STORK AttrRequest successfully rendered!"); - - } - - public IPersonalAttributeList parse(HttpServletRequest httpReq) throws UnsupportedAttributeException, MOAIDException { - return null; // - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority() - */ - @Override - public int getPriority() { - return 99; - } -} - diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java deleted file mode 100644 index 7f06c604b..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/PVPAuthenticationProvider.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - */ -package at.gv.egovernment.moa.id.protocols.stork2.attributeproviders; - -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException; -import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest; -import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.VelocityProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.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.STORKAttrQueryRequest; -import eu.stork.peps.auth.commons.STORKAttrQueryResponse; -import eu.stork.peps.auth.commons.STORKAuthnRequest; -import eu.stork.peps.auth.commons.STORKAuthnResponse; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.exceptions.STORKSAMLEngineException; - -/** - * @author tlenz - * - */ -public class PVPAuthenticationProvider extends AttributeProvider { - - private String destination = null; - private MOASTORKRequest moastorkRequest = null; - - /** - * @param attributes - * @param attributes2 - */ - public PVPAuthenticationProvider(String url, String attributes) { - super(attributes); - this.destination = url; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#acquire(eu.stork.peps.auth.commons.PersonalAttribute, java.lang.String, at.gv.egovernment.moa.id.data.IAuthData) - */ - @Override - protected IPersonalAttributeList acquire(PersonalAttribute attribute, - MOASTORKRequest moastorkRequest, IAuthData authData) - throws UnsupportedAttributeException, - ExternalAttributeRequestRequiredException, MOAIDException { - - this.moastorkRequest = moastorkRequest; - // break if we cannot handle the requested attribute - if (!getSupportedAttributeNames().contains(attribute.getName())) { - Logger.info("Attribute " + attribute.getName() + " not supported by the provider: " + getAttrProviderName()); - throw new UnsupportedAttributeException(); - - } - - Logger.info("Thrown external request by: " + getAttrProviderName()); - throw new ExternalAttributeRequestRequiredException(this); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#performRedirect(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, at.gv.egovernment.moa.id.config.auth.OAAuthParameter) - */ - @Override - public void performRedirect(String url, HttpServletRequest req, - HttpServletResponse resp, OAAuthParameter oaParam) - throws MOAIDException { - - String spSector = "Business"; - String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName(); - String spApplication = spInstitution; - String spCountryCode = moastorkRequest.getSpCountry(); - - if ((spCountryCode == null) || (spCountryCode.length()<2)) { - spCountryCode = oaParam.getTarget(); - Logger.info("Setting spcountry target: " + oaParam.getTarget()); - Logger.info("idlink ident " + oaParam.getIdentityLinkDomainIdentifier()); - Logger.info("idlink type " + oaParam.getIdentityLinkDomainIdentifierType()); - Logger.info("Setting spcountry target friendly : " + oaParam.getTargetFriendlyName()); - Logger.info("Oatype : " + oaParam.getOaType()); - Logger.info("puburl : " + oaParam.getPublicURLPrefix()); - if ("STORK".equals(oaParam.getIdentityLinkDomainIdentifierType())) { - - spCountryCode = oaParam.getIdentityLinkDomainIdentifier().substring(oaParam.getIdentityLinkDomainIdentifier().length()-2); - Logger.info("Set to " +spCountryCode); - } - - } - - //generate AttrQueryRequest - STORKAuthnRequest authRequest = new STORKAuthnRequest(); - authRequest.setDestination(destination); - authRequest.setAssertionConsumerServiceURL(url); - authRequest.setIssuer(HTTPUtils.getBaseURL(req)); - authRequest.setQaa(oaParam.getQaaLevel()); - authRequest.setSpInstitution(spInstitution); - authRequest.setCountry(spCountryCode); - authRequest.setSpCountry(spCountryCode); - authRequest.setSpApplication(spApplication); - authRequest.setProviderName(spApplication); - authRequest.setSpSector(spSector); - authRequest.setPersonalAttributeList(moastorkRequest.getPersonalAttributeList()); - - authRequest.setCitizenCountryCode("AT"); - //authRequest.setQaa(oaParam.getQaaLevel()); - authRequest.setQaa(moastorkRequest.getStorkAuthnRequest().getQaa()); - - - - - Logger.info("STORK AttrRequest successfully assembled."); - - STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("VIDP"); - try { - - authRequest = samlEngine.generateSTORKAuthnRequest(authRequest); - } catch (STORKSAMLEngineException e) { - Logger.error("Could not sign STORK SAML AttrRequest.", e); - throw new MOAIDException("stork.00", null); - } - - Logger.info("STORK AttrRequest successfully signed!"); - - //validate AuthnRequest - try { - samlEngine.validateSTORKAuthnRequest(authRequest.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."); - - 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(authRequest.getTokenSaml())); - context.put("action", destination); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - resp.getOutputStream().write(writer.toString().getBytes("UTF-8")); - - } catch (Exception e) { - Logger.error("Error sending STORK SAML AttrRequest.", e); - throw new MOAIDException("stork.11", null); - - } - Logger.info("STORK AttrRequest successfully rendered!"); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#parse(javax.servlet.http.HttpServletRequest) - */ - @Override - public IPersonalAttributeList parse(HttpServletRequest httpReq) - throws UnsupportedAttributeException, MOAIDException { - - throw new UnsupportedAttributeException(); - -// Logger.info(this.getClass().getSimpleName() + " tries to extract SAMLResponse out of HTTP Request"); -// //extract STORK Response from HTTP Request -// //Decodes SAML Response -// byte[] decSamlToken; -// try { -// decSamlToken = PEPSUtil.decodeSAMLToken(httpReq.getParameter("SAMLResponse")); -// } catch(NullPointerException e) { -// throw new UnsupportedAttributeException(); -// } -// -// //Get SAMLEngine instance -// STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); -// -// STORKAuthnResponse authnResponse = null; -// try { -// //validate SAML Token -// Logger.debug("Starting validation of SAML response"); -// authnResponse = engine.validateSTORKAuthnResponse(decSamlToken, (String) httpReq.getRemoteHost()); -// Logger.info("SAML response successfully verified!"); -// -// }catch(STORKSAMLEngineException e){ -// Logger.error("Failed to verify STORK SAML Response", e); -// throw new MOAIDException("stork.05", null); -// } -// -// return authnResponse.getPersonalAttributeList(); - - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority() - */ - @Override - public int getPriority() { - return 1; - } - - public String getAttrProviderName() { - return this.getClass().getName(); - } -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java deleted file mode 100644 index def89d0d9..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/SignedDocAttributeRequestProvider.java +++ /dev/null @@ -1,688 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2.attributeproviders; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringWriter; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import javax.activation.DataSource; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.xml.namespace.QName; -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; -import javax.xml.ws.Service; -import javax.xml.ws.soap.SOAPBinding; -import javax.xml.ws.BindingProvider; - -import eu.stork.peps.complex.attributes.eu.stork.names.tc.stork._1_0.assertion.AttributeStatusType; - -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.NotImplementedException; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.AuthConfiguration; -import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProviderFactory; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException; -import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest; -import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException; -import at.gv.egovernment.moa.id.util.VelocityProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.Base64Utils; -import eu.stork.oasisdss.api.ApiUtils; -import eu.stork.oasisdss.api.LightweightSourceResolver; -import eu.stork.oasisdss.api.ResultMajor; -import eu.stork.oasisdss.api.exceptions.ApiUtilsException; -import eu.stork.oasisdss.profile.AnyType; -import eu.stork.oasisdss.profile.Base64Data; -import eu.stork.oasisdss.profile.DocumentType; -import eu.stork.oasisdss.profile.DocumentWithSignature; -import eu.stork.oasisdss.profile.IncludeObject; -import eu.stork.oasisdss.profile.SignRequest; -import eu.stork.oasisdss.profile.SignResponse; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PEPSUtil; -import eu.stork.peps.auth.commons.PersonalAttribute; -import eu.stork.peps.auth.commons.PersonalAttributeList; -import eu.stork.peps.auth.commons.STORKAttrQueryRequest; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.exceptions.STORKSAMLEngineException; -import eu.stork.documentservice.DocumentService; -/** - * Forwards a signedDoc attribute request to the oasis-dss service instance - */ -public class SignedDocAttributeRequestProvider extends AttributeProvider { - - private String dtlUrl = null; - 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 - * @param attributes - */ - public SignedDocAttributeRequestProvider(String oasisDssWebFormURL, String attributes) { - super(attributes); - this.oasisDssWebFormURL = oasisDssWebFormURL; - - try { - AuthConfiguration authConfigurationProvider = AuthConfigurationProviderFactory.getInstance(); - dtlUrl = authConfigurationProvider.getDocumentServiceUrl(); - Logger.info ("SignedDocAttributeRequestProvider, using dtlUrl:"+dtlUrl); - } catch (Exception e) { - dtlUrl = "http://testvidp.buergerkarte.at/DocumentService/DocumentService"; - e.printStackTrace(); - Logger.error("Loading documentservice url failed, using default value:"+dtlUrl); - } - -// Properties props = new Properties(); -// try { -// props.load(DatabaseConnectorMySQLImpl.class.getResourceAsStream("docservice.properties")); -// dtlUrl = props.getProperty("docservice.url"); -// } catch (IOException e) { -// dtlUrl = "http://testvidp.buergerkarte.at/DocumentService/DocumentService"; -// Logger.error("Loading DTL config failed, using default value:"+dtlUrl); -// e.printStackTrace(); -// } - } - - /* - * (non-Javadoc) - * - * @see - * at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#acquire(java - * .lang.String) - */ - @Override - protected IPersonalAttributeList acquire(PersonalAttribute attribute, MOASTORKRequest moastorkRequest, IAuthData authData) throws UnsupportedAttributeException, - ExternalAttributeRequestRequiredException { - if(!attributes.contains(attribute.getName())) { - throw new UnsupportedAttributeException(); - } - - requestedAttribute = attribute; - try - { - String tmp = requestedAttribute.getValue().get(0); - }catch(Exception e) - { - Logger.info("SignedDocAttributeProvide failed:"+e.toString()); - throw new UnsupportedAttributeException(); - } - - 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"); - - try { - String base64 = httpReq.getParameter("signresponse"); - Logger.debug("signresponse url: " + httpReq.getRequestURI().toString()); - Logger.debug("signresponse querystring: " + httpReq.getQueryString()); - Logger.debug("signresponse method: " + httpReq.getMethod()); - Logger.debug("signresponse content type: " + httpReq.getContentType()); - Logger.debug("signresponse parameter:"+base64); - String signResponseString = new String(Base64Utils.decode(base64, false), "UTF8"); - Logger.debug("RECEIVED signresponse:"+signResponseString); - //create SignResponse object - Source response = new StreamSource(new java.io.StringReader(signResponseString)); - SignResponse signResponse = ApiUtils.unmarshal(response, SignResponse.class); - //Check if Signing was successfully or not - - if(!signResponse.getResult().getResultMajor().equals(ResultMajor.RESULT_MAJOR_SUCCESS)) - { - //Pass unmodifed or unmarshal & marshal?? - InputStream istr = ApiUtils.marshalToInputStream(signResponse); - StringWriter writer = new StringWriter(); - IOUtils.copy(istr, writer, "UTF-8"); - signResponseString = writer.toString(); - Logger.info("SignResponse with error (unmodified):"+signResponseString); - istr.close(); - } - else - { - //extract doc from signresponse - DataSource dataSource = LightweightSourceResolver.getDataSource(signResponse); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - IOUtils.copy(dataSource.getInputStream(), baos); - byte[] data = baos.toByteArray(); - baos.close(); - - //update doc in DTL - String docId, dssId = ""; - docId = signResponse.getDocUI(); - //For reference dssId equals docId - dssId = docId; - if (dssId != null && data!=null) - { - boolean success = false; - try{ - success = updateDocumentInDtl(data, docId, signResponseString); - }catch(Exception e){//No document service used? - Logger.info("No document service used?"); - e.printStackTrace(); - success = false; - } - if(success) - { - // set the url in the SignResponse - DocumentWithSignature documentWithSignature = new DocumentWithSignature(); - DocumentType value = new DocumentType(); - if(dtlUrl.endsWith("?wsdl")) - { - String tmp = dtlUrl.replace("?wsdl", ""); - Logger.debug("DocumentUrl ends with ? wsdl, using "+tmp+" instead."); - value.setDocumentURL(tmp); - } - else - { - value.setDocumentURL(dtlUrl); - } - documentWithSignature.setDocument(value); - if(signResponse.getOptionalOutputs()!=null) - { - //signResponse.getOptionalOutputs().getAny().add(documentWithSignature); - for(Object o :signResponse.getOptionalOutputs().getAny()) - { - if(o instanceof DocumentWithSignature) - { - signResponse.getOptionalOutputs().getAny().remove(o); - signResponse.getOptionalOutputs().getAny().add(documentWithSignature); - break; - } - } - } - else - { - AnyType anytype = new AnyType(); - anytype.getAny().add(documentWithSignature); - signResponse.setOptionalOutputs(anytype ); - } - - // System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl); - InputStream istr = ApiUtils.marshalToInputStream(signResponse); - StringWriter writer = new StringWriter(); - IOUtils.copy(istr, writer, "UTF-8"); - signResponseString = writer.toString(); - Logger.info("SignResponse overwritten:"+signResponseString); - istr.close(); - } - else - { - //No document service used? - // do nothing.... - //TODO temporary fix because document is deleted after fetching => SP can't download Doc - //Add doc to Signresponse - - DocumentWithSignature documentWithSignature = new DocumentWithSignature(); - DocumentType value = new DocumentType(); - if(signResponse.getProfile().toLowerCase().contains("xades")) - { - value.setBase64XML(data); - } - else - { - Base64Data base64data = new Base64Data(); - base64data.setValue(data); - base64data.setMimeType(dataSource.getContentType()); - value.setBase64Data(base64data); - } - documentWithSignature.setDocument(value); - if(signResponse.getOptionalOutputs()!=null) - { - //signResponse.getOptionalOutputs().getAny().add(documentWithSignature); - for(Object o :signResponse.getOptionalOutputs().getAny()) - { - if(o instanceof DocumentWithSignature) - { - signResponse.getOptionalOutputs().getAny().remove(o); - signResponse.getOptionalOutputs().getAny().add(documentWithSignature); - break; - } - } - } - else - { - AnyType anytype = new AnyType(); - anytype.getAny().add(documentWithSignature); - signResponse.setOptionalOutputs(anytype ); - } - - // System.out.println("overwriting:"+signResponse.getResult().getResultMessage()+" with DTL url:"+dtlUrl); - InputStream istr = ApiUtils.marshalToInputStream(signResponse); - StringWriter writer = new StringWriter(); - IOUtils.copy(istr, writer, "UTF-8"); - signResponseString = writer.toString(); - Logger.info("SignResponse overwritten:"+signResponseString); - istr.close(); - } - } - else - throw new Exception("No DSS id found."); - } - - //alter signresponse - //done - List<String> values = new ArrayList<String>(); - values.add(signResponseString); - - Logger.debug("Assembling signedDoc attribute"); - PersonalAttribute signedDocAttribute = new PersonalAttribute("signedDoc", false, values, - AttributeStatusType.AVAILABLE.value()); - - // 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); - } catch (ApiUtilsException e) { - e.printStackTrace(); - Logger.error("Failed to assemble signedDoc attribute"); - throw new MOAIDException("stork.05", null); - } catch (IOException e) { - e.printStackTrace(); - Logger.error("Failed to assemble signedDoc attribute"); - throw new MOAIDException("stork.05", null); - } catch (Exception e) { - e.printStackTrace(); - Logger.error("Failed to assemble signedDoc attribute"); - //throw new MOAIDException("stork.05", null); - throw new UnsupportedAttributeException(); - } - } - - /* - * (non-Javadoc) - * - * @see - * at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#performRedirect - * (java.lang.String) - */ - public void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) - throws MOAIDException { - - try { - Logger.trace("Initialize VelocityEngine..."); - Logger.info("performRedirect url:"+url); - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/oasis_dss_webform_binding.vm"); - VelocityContext context = new VelocityContext(); - - //Parse SignRequest - String signRequestString = requestedAttribute.getValue().get(0); - Logger.debug("performRedirect, signrequest:"+signRequestString); - Source signDoc = new StreamSource(new java.io.StringReader(signRequestString)); - SignRequest signRequest = ApiUtils.unmarshal(signDoc, SignRequest.class); - try{ - //search for DTL link - String dtlURL = getDtlUrlFromRequest(signRequest); - String docId = signRequest.getDocUI(); - - if(dtlURL!=null) - { - String docRequest = getDocTransferRequest(docId, dtlURL);//dtlUrl - - byte[] data = getDocumentFromDtl(docRequest, dtlURL);//dtlUrl - - //load doc from DTL - Logger.debug("data:"+data+" "+data.length); - try{ - Logger.trace("data:"+new String(data,"UTF-8")); - }catch(Exception e) - { - Logger.trace("data: creating String failed:"+e); - } - String mime = getDocumentMimeFromDtl(docId, dtlURL);//dtlUrl - Logger.debug("mime:"+mime); - - //add doc as base64* to signrequest => post doc to oasis - try{ - List<IncludeObject> includeObjects = ApiUtils.findNamedElement( - signRequest.getOptionalInputs(), "IncludeObject", - IncludeObject.class); - signRequest.getOptionalInputs().getAny().removeAll(includeObjects); - - String documentId = null; - Object objDoc = signRequest.getInputDocuments().getDocumentOrTransformedDataOrDocumentHash().get(0); - if (objDoc != null && objDoc instanceof DocumentType) - { - DocumentType document = (DocumentType)objDoc; - documentId = document.getID(); - } - DocumentType document = new DocumentType(); - if(documentId != null) - document.setID(documentId); - if(signRequest.getProfile().toLowerCase().contains("xades")) - { - document.setBase64XML(data); - } - else - { - Base64Data b64data = new Base64Data(); - b64data.setValue(data); - b64data.setMimeType(mime); - document.setBase64Data(b64data); - } - - signRequest.setInputDocuments(ApiUtils.createInputDocuments(document)); - //override old signRequestString - - InputStream istr = ApiUtils.marshalToInputStream(signRequest); - StringWriter writer = new StringWriter(); - IOUtils.copy(istr, writer, "UTF-8"); - signRequestString = writer.toString(); - Logger.info("Signrequest overwritten"); - Logger.debug("Signrequest overwritten:"+signRequestString); - istr.close(); - } catch (Exception e) { - e.printStackTrace(); - throw new Exception("Could not marshall sign request", e); - } - } - else//Do not modify signRequest, document is already included - { - - } - }catch(Exception e) - { - Logger.info("No documentservice used?"); - e.printStackTrace(); - } - - context.put("signrequest", Base64Utils.encode(signRequestString.getBytes("UTF8"))); - context.put("clienturl", url); - context.put("action", oasisDssWebFormURL); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - resp.getOutputStream().write(writer.toString().getBytes("UTF-8")); - } catch (Exception e) { - Logger.error("Error sending DSS signrequest.", e); - throw new MOAIDException("stork.11", null); - } - } - - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#getSupportedAttributeNames() - */ - @Override - public List<String> getSupportedAttributeNames() throws MOAIDException { - ArrayList<String> supportedAttributeNames = new ArrayList<String>(); - for (String attributeName : this.attributes.split(",")) { - supportedAttributeNames.add(attributeName); - } - return supportedAttributeNames; - } - - - //From DTLPEPSUTIL - - /** - * Get DTL uril from the oasis sign request - * @param signRequest The signature request - * @return The URL of DTL service - * @throws SimpleException - */ - private String getDtlUrlFromRequest(SignRequest signRequest) throws Exception - { - if (signRequest == null) - throw new Exception("Signature request is empty"); - else - { - try - { - Object objDoc = signRequest.getInputDocuments().getDocumentOrTransformedDataOrDocumentHash().get(0); - if (objDoc instanceof DocumentType) - { - DocumentType document = (DocumentType)objDoc; - if (document.getDocumentURL() != null) - return document.getDocumentURL(); - else - return null;//throw new Exception("No document url found"); - } - else - throw new Exception("No input document found"); - } - catch (Exception ex) - { - throw new Exception("Unable to parse xml.", ex); - } - } - } - - /** - * Get document from DTL - * @param transferRequest The transfer request (attribute query) - * @param eDtlUrl The DTL url of external DTL - * @return the document data - * @throws SimpleException - */ - private byte[] getDocumentFromDtl(String transferRequest, String eDtlUrl) throws Exception - { - URL url = null; - try - { - Logger.debug("getDocumentFromDtl:"+dtlUrl); - url = new URL(dtlUrl); - QName qname = new QName("http://stork.eu", - "DocumentService"); - - Service service = Service.create(url, qname); - DocumentService docservice = service.getPort(DocumentService.class); - - BindingProvider bp = (BindingProvider) docservice; - SOAPBinding binding = (SOAPBinding) bp.getBinding(); - binding.setMTOMEnabled(true); - - if (eDtlUrl.equalsIgnoreCase(dtlUrl)) - return docservice.getDocument(transferRequest, ""); - else - return docservice.getDocument(transferRequest, eDtlUrl); - } - catch (Exception e) - { - e.printStackTrace(); - throw new Exception("Error in getDocumentFromDtl", e); - } - } - - /** - * Get a document transfer request (attribute query) - * @param docId - * @return - * @throws SimpleException - */ - private String getDocTransferRequest(String docId, String destinationUrl) throws Exception - { - String spCountry = docId.substring(0, docId.indexOf("/")); - final STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - STORKAttrQueryRequest req = new STORKAttrQueryRequest(); - req.setAssertionConsumerServiceURL(dtlUrl); - req.setDestination(destinationUrl); - req.setSpCountry(spCountry); - req.setQaa(3);//TODO - PersonalAttributeList pal = new PersonalAttributeList(); - PersonalAttribute attr = new PersonalAttribute(); - attr.setName("docRequest"); - attr.setIsRequired(true); - attr.setValue(Arrays.asList(docId)); - pal.add(attr); - req.setPersonalAttributeList(pal); - - STORKAttrQueryRequest req1; - try { - req1 = engine.generateSTORKAttrQueryRequest(req); - return PEPSUtil.encodeSAMLTokenUrlSafe(req1.getTokenSaml()); - } catch (STORKSAMLEngineException e) { - e.printStackTrace(); - throw new Exception("Error in doc request attribute query generation", e); - } - } - - /** - * Get mime type of document from DTL - * @param docId The document id - * @param dtlUrl The url of dtl - * @return The mime type - */ - private String getDocumentMimeFromDtl(String docId, String eDtlUrl) throws Exception - { - URL url = null; - try - { - url = new URL(dtlUrl); - QName qname = new QName("http://stork.eu", - "DocumentService"); - - Service service = Service.create(url, qname); - DocumentService docservice = service.getPort(DocumentService.class); - - BindingProvider bp = (BindingProvider) docservice; - SOAPBinding binding = (SOAPBinding) bp.getBinding(); - binding.setMTOMEnabled(true); - - if (eDtlUrl.equalsIgnoreCase(dtlUrl)) - return docservice.getDocumentMime(docId, ""); - else - return docservice.getDocumentMime(docId, eDtlUrl); - } - catch (Exception e) - { - e.printStackTrace(); - throw new Exception("Error in getDocumentFromDtl", e); - } - } - - /** - * Add document to DTL service - * @param docData the document data - * @param mime the mime type of data - * @param signRequest the sign request - * @return the document id - * @throws SimpleException - */ - private String addDocumentToDtl(byte[] docData, String mime, String signRequest, String destCountry, String spId) throws Exception - { - throw new NotImplementedException(); -// URL url = null; -// String docID = null; -// try -// { -// url = new URL(dtlUrl); -// QName qname = new QName("http://stork.eu", -// "DocumentService"); -// -// Service service = Service.create(url, qname); -// DocumentService docservice = service.getPort(DocumentService.class); -// -// BindingProvider bp = (BindingProvider) docservice; -// SOAPBinding binding = (SOAPBinding) bp.getBinding(); -// binding.setMTOMEnabled(true); -// -// docID = docservice.addDocument(docData, signRequest, destCountry, spId, mime, ""); -// } -// catch (Exception e) -// { -// e.printStackTrace(); -// throw new Exception("Error in addDocumentToDtl", e); -// } -// -// return docID; - } - - /** - * Update document in DTL - * @param docData The docment data - * @param docId The document ID - * @param signResponse The signature response - * @return True if successful - * @throws SimpleException - */ - private boolean updateDocumentInDtl(byte[] docData, String docId, String signResponse) throws Exception - { - boolean success = false; - URL url = null; - try - { - url = new URL(dtlUrl); - QName qname = new QName("http://stork.eu", - "DocumentService"); - - Service service = Service.create(url, qname); - DocumentService docservice = service.getPort(DocumentService.class); - - BindingProvider bp = (BindingProvider) docservice; - SOAPBinding binding = (SOAPBinding) bp.getBinding(); - binding.setMTOMEnabled(true); - - success = docservice.updateDocument(docId, signResponse, docData); - } - catch (Exception e) - { - e.printStackTrace(); - throw new Exception("Error in updateDocumentInDtl", e); - } - - return success; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority() - */ - @Override - public int getPriority() { - return 99; - } -} diff --git a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java b/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java deleted file mode 100644 index 5ee0e380e..000000000 --- a/id/server/modules/module-stork/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/attributeproviders/StorkAttributeRequestProvider.java +++ /dev/null @@ -1,193 +0,0 @@ -/******************************************************************************* - * Copyright 2014 Federal Chancellery Austria - * MOA-ID has been developed in a cooperation between BRZ, the Federal - * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * - * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by - * the European Commission - subsequent versions of the EUPL (the "Licence"); - * You may not use this work except in compliance with the Licence. - * You may obtain a copy of the Licence at: - * http://www.osor.eu/eupl/ - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the Licence is distributed on an "AS IS" basis, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the Licence for the specific language governing permissions and - * limitations under the Licence. - * - * This product combines work with different licenses. See the "NOTICE" text - * file for details on the various modules and licenses. - * The "NOTICE" text file is part of the distribution. Any derivative works - * that you distribute must include a readable copy of the "NOTICE" text file. - *******************************************************************************/ -package at.gv.egovernment.moa.id.protocols.stork2.attributeproviders; - -import java.io.StringWriter; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.VelocityEngine; - -import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; -import at.gv.egovernment.moa.id.data.IAuthData; -import at.gv.egovernment.moa.id.protocols.stork2.ExternalAttributeRequestRequiredException; -import at.gv.egovernment.moa.id.protocols.stork2.MOASTORKRequest; -import at.gv.egovernment.moa.id.protocols.stork2.UnsupportedAttributeException; -import at.gv.egovernment.moa.id.util.HTTPUtils; -import at.gv.egovernment.moa.id.util.VelocityProvider; -import at.gv.egovernment.moa.logging.Logger; -import at.gv.egovernment.moa.util.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; - -/** - * creates a STORK attribute request for a configurable set of attributes - */ -public class StorkAttributeRequestProvider extends AttributeProvider { - - private PersonalAttributeList requestedAttributes; - - /** The destination. */ - private String destination; - - /** The sp country code. */ - private String spCountryCode; - - /** - * Instantiates a new stork attribute request provider. - * - * @param apUrl the AP location - * @param supportedAttributes the supported attributes as csv - */ - public StorkAttributeRequestProvider(String apUrl, String supportedAttributes) { - super(supportedAttributes); - destination = apUrl; - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#acquire(java.lang.String) - */ - @Override - protected IPersonalAttributeList acquire(PersonalAttribute attribute, MOASTORKRequest moastorkRequest, IAuthData authData) - throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException { - - if (!attributes.contains(attribute.getName())) - throw new UnsupportedAttributeException(); - - this.spCountryCode = moastorkRequest.getSpCountry(); - - requestedAttributes = new PersonalAttributeList(1); - requestedAttributes.add(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.info(this.getClass().getSimpleName() + " tries to extract SAMLResponse out of HTTP Request"); - - //extract STORK Response from HTTP Request - //Decodes SAML Response - byte[] decSamlToken; - try { - decSamlToken = PEPSUtil.decodeSAMLToken(httpReq.getParameter("SAMLResponse")); - } catch(NullPointerException e) { - throw new UnsupportedAttributeException(); - } - - //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); - - STORKAttrQueryResponse attrResponse = null; - try { - //validate SAML Token - Logger.debug("Starting validation of SAML response"); - attrResponse = engine.validateSTORKAttrQueryResponse(decSamlToken, (String) httpReq.getRemoteHost()); - Logger.info("SAML response successfully verified!"); - }catch(STORKSAMLEngineException e){ - Logger.error("Failed to verify STORK SAML Response", e); - throw new MOAIDException("stork.05", null); - } - - return attrResponse.getPersonalAttributeList(); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#performRedirect(java.lang.String) - */ - public void performRedirect(String url, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException { - - String spSector = "Business"; - String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName(); - String spApplication = spInstitution; - - //generate AuthnRquest - STORKAttrQueryRequest attributeRequest = new STORKAttrQueryRequest(); - attributeRequest.setDestination(destination); - attributeRequest.setAssertionConsumerServiceURL(url); - attributeRequest.setIssuer(HTTPUtils.getBaseURL(req)); - attributeRequest.setQaa(oaParam.getQaaLevel()); - attributeRequest.setSpInstitution(spInstitution); - attributeRequest.setCountry(spCountryCode); - attributeRequest.setSpCountry(spCountryCode); - attributeRequest.setSpApplication(spApplication); - attributeRequest.setSpSector(spSector); - attributeRequest.setPersonalAttributeList(requestedAttributes); - - attributeRequest.setCitizenCountryCode("AT"); - - - Logger.debug("STORK AttrRequest successfully assembled."); - - STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("VIDP"); - try { - attributeRequest = samlEngine.generateSTORKAttrQueryRequest(attributeRequest); - } catch (STORKSAMLEngineException e) { - Logger.error("Could not sign STORK SAML AttrRequest.", e); - throw new MOAIDException("stork.00", null); - } - Logger.info("Using citizen country code: " + attributeRequest.getCitizenCountryCode()); - Logger.info("STORK AttrRequest successfully signed!"); - - 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(attributeRequest.getTokenSaml())); - context.put("action", destination); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - resp.getOutputStream().write(writer.toString().getBytes("UTF-8")); - } catch (Exception e) { - Logger.error("Error sending STORK SAML AttrRequest.", e); - throw new MOAIDException("stork.11", null); - } - Logger.info("STORK AttrRequest successfully rendered!"); - } - - /* (non-Javadoc) - * @see at.gv.egovernment.moa.id.protocols.stork2.attributeproviders.AttributeProvider#getPriority() - */ - @Override - public int getPriority() { - return 99; - } - -} - diff --git a/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo b/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo deleted file mode 100644 index 5d7af87d5..000000000 --- a/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.moduls.IModulInfo +++ /dev/null @@ -1 +0,0 @@ -at.gv.egovernment.moa.id.protocols.stork2.STORKProtocol
\ No newline at end of file diff --git a/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder b/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder deleted file mode 100644 index 540802dce..000000000 --- a/id/server/modules/module-stork/src/main/resources/META-INF/services/at.gv.egovernment.moa.id.protocols.builder.attributes.IAttributeBuilder +++ /dev/null @@ -1,14 +0,0 @@ -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKAdoptedFamilyNameAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKAgeAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKCanonicalResidenceAddressAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKCountryCodeOfBirthAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKFiscalNumberAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKGenderAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKInhertedFamilyNameAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKIsAgeOverAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKMaritalStatusAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKNationalityCodeAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKPseudonymAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKResidencePermitAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKTextResidenceAddressAttributBuilder -at.gv.egovernment.moa.id.protocols.builder.attributes.STORKTitleAttributBuilder
\ No newline at end of file diff --git a/id/server/modules/module-stork/src/main/resources/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthentication.process.xml b/id/server/modules/module-stork/src/main/resources/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthentication.process.xml deleted file mode 100644 index 60989e638..000000000 --- a/id/server/modules/module-stork/src/main/resources/at/gv/egovernment/moa/id/auth/modules/stork/STORKAuthentication.process.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?>
-<pd:ProcessDefinition id="STORKAuthentication" xmlns:pd="http://reference.e-government.gv.at/namespace/moa/process/definition/v1">
-
-<!--
- STORK authentication both with C-PEPS supporting xml signatures and with C-PEPS not supporting xml signatures.
--->
- <pd:Task id="createStorkAuthRequestForm" class="at.gv.egovernment.moa.id.auth.modules.stork.tasks.CreateStorkAuthRequestFormTask" />
- <pd:Task id="pepsConnector" class="at.gv.egovernment.moa.id.auth.modules.stork.tasks.PepsConnectorTask" async="true" />
- <pd:Task id="pepsConnectorWithoutSignature" class="at.gv.egovernment.moa.id.auth.modules.stork.tasks.PepsConnectorHandleResponseWithoutSignatureTask" async="true" />
- <pd:Task id="pepsConnectorWithLocalSignature" class="at.gv.egovernment.moa.id.auth.modules.stork.tasks.PepsConnectorHandleLocalSignResponseTask" async="true" />
-
- <!-- Process is triggered either by GenerateIFrameTemplateServlet (upon bku selection) or by AuthenticationManager (upon legacy authentication start using legacy parameters. -->
- <pd:StartEvent id="start" />
-
- <pd:Transition from="start" to="createStorkAuthRequestForm" />
-
- <pd:Transition from="createStorkAuthRequestForm" to="pepsConnector" conditionExpression="ctx['C-PEPS:XMLSignatureSupported']" />
- <pd:Transition from="createStorkAuthRequestForm" to="pepsConnectorWithoutSignature" />
-
- <pd:Transition from="pepsConnector" to="pepsConnector" conditionExpression="!ctx['identityLinkAvailable']" /> <!-- honor strange intermediate step of asking for the subject's gender -->
- <pd:Transition from="pepsConnector" to="end" />
-
- <pd:Transition from="pepsConnectorWithoutSignature" to="pepsConnectorWithLocalSignature" />
- <pd:Transition from="pepsConnectorWithLocalSignature" to="pepsConnectorWithoutSignature" conditionExpression="!ctx['identityLinkAvailable']" /> <!-- honor strange intermediate step of asking for the subject's gender -->
- <pd:Transition from="pepsConnectorWithLocalSignature" to="end" />
-
- <pd:EndEvent id="end" />
-
-</pd:ProcessDefinition>
diff --git a/id/server/modules/module-stork/src/test/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServletTest.java b/id/server/modules/module-stork/src/test/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServletTest.java deleted file mode 100644 index ab2d3071f..000000000 --- a/id/server/modules/module-stork/src/test/java/at/gv/egovernment/moa/id/auth/modules/stork/STORKProcessEngineSignalServletTest.java +++ /dev/null @@ -1,27 +0,0 @@ -package at.gv.egovernment.moa.id.auth.modules.stork;
-
-import static org.junit.Assert.*;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.commons.io.IOUtils;
-import org.junit.Test;
-import org.springframework.mock.web.MockHttpServletRequest;
-
-public class STORKProcessEngineSignalServletTest {
-
- @Test
- public void testGetMoaSessionId() throws IOException {
- try (InputStream in = getClass().getResourceAsStream("SAMLResponse.base64")) {
- String samlResponse = IOUtils.toString(in);
-
- MockHttpServletRequest request = new MockHttpServletRequest("GET", "/service/createTransactionId");
- request.addParameter("SAMLResponse", samlResponse);
- assertEquals("_f2358f2f4db445bd1ac75ce415d76a95",
- new STORKProcessEngineSignalServlet().getMoaSessionId(request));
- }
-
- }
-
-}
diff --git a/id/server/modules/module-stork/src/test/resources/at/gv/egovernment/moa/id/auth/modules/stork/SAMLResponse.base64 b/id/server/modules/module-stork/src/test/resources/at/gv/egovernment/moa/id/auth/modules/stork/SAMLResponse.base64 deleted file mode 100644 index e4061a705..000000000 --- a/id/server/modules/module-stork/src/test/resources/at/gv/egovernment/moa/id/auth/modules/stork/SAMLResponse.base64 +++ /dev/null @@ -1 +0,0 @@ -PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c2FtbDJwOlJlc3BvbnNlIHhtbG5zOnNhbWwycD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOnByb3RvY29sIiB4bWxuczpkcz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC8wOS94bWxkc2lnIyIgeG1sbnM6c2FtbDI9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDphc3NlcnRpb24iIHhtbG5zOnN0b3JrPSJ1cm46ZXU6c3Rvcms6bmFtZXM6dGM6U1RPUks6MS4wOmFzc2VydGlvbiIgeG1sbnM6c3RvcmtwPSJ1cm46ZXU6c3Rvcms6bmFtZXM6dGM6U1RPUks6MS4wOnByb3RvY29sIiB4bWxuczp4cz0iaHR0cDovL3d3dy53My5vcmcvMjAwMS9YTUxTY2hlbWEiIENvbnNlbnQ9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpjb25zZW50Om9idGFpbmVkIiBEZXN0aW5hdGlvbj0iaHR0cHM6Ly9sb2NhbGhvc3Q6ODQ0My9tb2EtaWQtYXV0aC9QRVBTQ29ubmVjdG9yIiBJRD0iXzY0MjUzODBkMjdlNjViY2I3NDc0OGE1ZjFjOWU2Yzk5IiBJblJlc3BvbnNlVG89Il9mMjM1OGYyZjRkYjQ0NWJkMWFjNzVjZTQxNWQ3NmE5NSIgSXNzdWVJbnN0YW50PSIyMDE1LTAyLTIzVDE2OjEzOjA4LjYxMVoiIFZlcnNpb249IjIuMCI+PHNhbWwyOklzc3VlciBGb3JtYXQ9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpuYW1laWQtZm9ybWF0OmVudGl0eSI+aHR0cDovL0MtUEVQUy5nb3YueHg8L3NhbWwyOklzc3Vlcj48ZHM6U2lnbmF0dXJlIHhtbG5zOmRzPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzA5L3htbGRzaWcjIj48ZHM6U2lnbmVkSW5mbz48ZHM6Q2Fub25pY2FsaXphdGlvbk1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvMTAveG1sLWV4Yy1jMTRuIyIvPjxkczpTaWduYXR1cmVNZXRob2QgQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNyc2Etc2hhMjU2Ii8+PGRzOlJlZmVyZW5jZSBVUkk9IiNfNjQyNTM4MGQyN2U2NWJjYjc0NzQ4YTVmMWM5ZTZjOTkiPjxkczpUcmFuc2Zvcm1zPjxkczpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzA5L3htbGRzaWcjZW52ZWxvcGVkLXNpZ25hdHVyZSIvPjxkczpUcmFuc2Zvcm0gQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzEwL3htbC1leGMtYzE0biMiPjxlYzpJbmNsdXNpdmVOYW1lc3BhY2VzIHhtbG5zOmVjPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzEwL3htbC1leGMtYzE0biMiIFByZWZpeExpc3Q9InhzIi8+PC9kczpUcmFuc2Zvcm0+PC9kczpUcmFuc2Zvcm1zPjxkczpEaWdlc3RNZXRob2QgQWxnb3JpdGhtPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzA5L3htbGRzaWcjc2hhMSIvPjxkczpEaWdlc3RWYWx1ZT5Ha2czSHZoemNSMjlEdko2U1U5TmI2bUlNb009PC9kczpEaWdlc3RWYWx1ZT48L2RzOlJlZmVyZW5jZT48L2RzOlNpZ25lZEluZm8+PGRzOlNpZ25hdHVyZVZhbHVlPkJUOVY0SVNWa2kwdExRUk1OZU1WaTc2QTB5VHpGRXRkdGIwS1VvQVpQUTNNWkcwSmlrL09wRnhoRFdjQ2gxSFR6am5PVzhsa21sVnpJcENGQ2l2cm9GOTZoN2ZLWmloODdLNi9JL084bEhKOGR0R0NobXFERUgrQ2liNEM3K3hsaUNna0luMGZoZzhDYTVBWWtJSzBIZTVHWm9VSk5uOWNKbnFNalNuQ2ZRRzNsUHRLOURPSTVsMU9oTkdYWGIrY3JVVHo2eUVlZFB1OENNUUpiWG1PVFFsb21ud00rN2VxV0RMWnd4dzJ3VHUrV252clpvYUJ4cG8rMlNrMTRhV0gxcytzVDJYbE1URE5ubVpzb21WalYzdTUrWlhxWlZFcm9TYkNkZW9BbmFZM3o2OGkxdWYzQzYvNFRBbzhBbENkbVBYMlNUUSs1Y21OUHMvRHhCM3RrZz09PC9kczpTaWduYXR1cmVWYWx1ZT48ZHM6S2V5SW5mbz48ZHM6WDUwOURhdGE+PGRzOlg1MDlDZXJ0aWZpY2F0ZT5NSUlGYkRDQ0JGU2dBd0lCQWdJRVFMSzU5ekFOQmdrcWhraUc5dzBCQVFVRkFEQStNUXN3Q1FZRFZRUUdFd0p6YVRFYk1Ca0dBMVVFCkNoTVNjM1JoZEdVdGFXNXpkR2wwZFhScGIyNXpNUkl3RUFZRFZRUUxFd2x6YVhSbGMzUXRZMkV3SGhjTk1UQXdNek13TVRNd09USXoKV2hjTk1UVXdNek13TVRNek9USXpXakNCaGpFTE1Ba0dBMVVFQmhNQ2Mya3hHekFaQmdOVkJBb1RFbk4wWVhSbExXbHVjM1JwZEhWMAphVzl1Y3pFU01CQUdBMVVFQ3hNSlUwbFVSVk5VTFVOQk1Sa3dGd1lEVlFRTEV4QmpaWEowYVdacFkyRjBaWE10ZDJWaU1Tc3dFd1lEClZRUURFd3hVUlZOVUlGQkZVRk1nVTBrd0ZBWURWUVFGRXcwek1EQXpNakF4TURBd01EQXhNSUlCSWpBTkJna3Foa2lHOXcwQkFRRUYKQUFPQ0FROEFNSUlCQ2dLQ0FRRUE0aDZMOVB2MVRLN2Z6NUs2VXVyMFJsaTZFS3pad1R0djl4WGhTdDJ4bEk0d0ZXenpGaUN5NS9PLwpRNUdQUmExMFlvTWM4czdXbU1kTTV5SS9iVTBCRjJ0NVNZdEVIN013YkdhRlpGS0p0MTdPdGJwWkFhQ1NvaDZmbTF5TzBIdFZWa0c5ClVkSDRtc3dTM3dIcC9kMUM5MWxRTmJhMmVuVmMycDlOZDRnWW9wL3picm9FdG9GZUR5SHhUbDBtWU4vY1VIUUZUNEgyNGh6QWZXWGgKMkZPQmZOU252TmwySG5QSk9UNkhuclVCc2R5emtTekxOMEVpczJSMUc1K21Ra3pBd1c2VU9yb29qdk1jbEVKSzN6MW9la2oyT1dqMQpGaGFsVE5tQTVEOWRrRHltVFJuNG8zQlcyUzdvdm1XUG14WVVXOXMyNmJrUGh6L0NiQ1F3SUY5eVBRSURBUUFCbzRJQ0p6Q0NBaU13CkRnWURWUjBQQVFIL0JBUURBZ1dnTUNzR0ExVWRFQVFrTUNLQUR6SXdNVEF3TXpNd01UTXdPVEl6V29FUE1qQXhOVEF6TXpBeE16TTUKTWpOYU1Fc0dBMVVkSUFSRU1FSXdOZ1lMS3dZQkJBR3ZXUUlCQVFJd0p6QWxCZ2dyQmdFRkJRY0NBUllaYUhSMGNEb3ZMM2QzZHk1agpZUzVuYjNZdWMya3ZZM0J6THpBSUJnWUVBSXN3QVFJd0dBWUlLd1lCQlFVSEFRTUVEREFLTUFnR0JnUUFqa1lCQVRBZUJnTlZIUkVFCkZ6QVZnUk4wWlhOMExuTnBMWEJsY0hOQVoyOTJMbk5wTUlIMkJnTlZIUjhFZ2U0d2dlc3dWYUJUb0ZHa1R6Qk5NUXN3Q1FZRFZRUUcKRXdKemFURWJNQmtHQTFVRUNoTVNjM1JoZEdVdGFXNXpkR2wwZFhScGIyNXpNUkl3RUFZRFZRUUxFd2x6YVhSbGMzUXRZMkV4RFRBTApCZ05WQkFNVEJFTlNURE13Z1pHZ2dZNmdnWXVHV0d4a1lYQTZMeTk0TlRBd0xtZHZkaTV6YVM5dmRUMXphWFJsYzNRdFkyRXNiejF6CmRHRjBaUzFwYm5OMGFYUjFkR2x2Ym5Nc1l6MXphVDlqWlhKMGFXWnBZMkYwWlZKbGRtOWpZWFJwYjI1TWFYTjBQMkpoYzJXR0wyaDAKZEhBNkx5OTNkM2N1YzJsblpXNHRZMkV1YzJrdlkzSnNMM05wZEdWemRDOXphWFJsYzNRdFkyRXVZM0pzTUI4R0ExVWRJd1FZTUJhQQpGRlJKQjBhSHp4MkpuY3F1Y3Flb29LQnB0eUhuTUIwR0ExVWREZ1FXQkJReVNlbWVEaTEwRGJlVFlqMXRrR1o1Wm80bXdqQUpCZ05WCkhSTUVBakFBTUJrR0NTcUdTSWIyZlFkQkFBUU1NQW9iQkZZM0xqRURBZ09vTUEwR0NTcUdTSWIzRFFFQkJRVUFBNElCQVFBU1E0bDEKVmQrTVJETEZvMkE2cVlZV0xWcVR2dFBMSWs3djdCc3dtcTJTRkFMMlhtUG9MNXhiUUZlRFcrTGlXaFFCbXJsZ1d5STdnYmkvMS9ycwoxRTAwWjRTa244bDk3dHVJeXV4dkNLVEZoSkR4OXB6Z1VRR293b0NZbzlJemNNTlFweHg2bGtlcHJlQ0R1YytlMGZBYnZUTkdFcHZRCjdEa2dyd0pkY3NVQUVsUTRPSjBpZkVMb2FoMURIOHdwVTMxenI3RDNZc2l6WmdwdTVURUlHUDU0QU9oYkZlWkVtWmxUVTZnd053NGkKVGY2blZRa0dheHNKdDZnR0dzeUw4UlV1dndwVlJSM1dtcGxDdGpYcnlHQ2U0Qi9hZ0FlM0VLVWgxNUlhUHZXcWRpeFNqeVN4akJJMQpiTjhJRUZIWVBabXV3aDdZMUZRdU9ZUUdqdVNMc0p5OTwvZHM6WDUwOUNlcnRpZmljYXRlPjwvZHM6WDUwOURhdGE+PC9kczpLZXlJbmZvPjwvZHM6U2lnbmF0dXJlPjxzYW1sMnA6U3RhdHVzPjxzYW1sMnA6U3RhdHVzQ29kZSBWYWx1ZT0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOnN0YXR1czpTdWNjZXNzIi8+PHNhbWwycDpTdGF0dXNNZXNzYWdlPnVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpzdGF0dXM6U3VjY2Vzczwvc2FtbDJwOlN0YXR1c01lc3NhZ2U+PC9zYW1sMnA6U3RhdHVzPjxzYW1sMjpBc3NlcnRpb24gSUQ9Il8zNzhiMGNjNTk0YThkMzhmMzJjN2M3NjQ5NTQ0OWQ1ZCIgSXNzdWVJbnN0YW50PSIyMDE1LTAyLTIzVDE2OjEzOjA4LjYxMVoiIFZlcnNpb249IjIuMCIgeG1sbnM6eHM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hIj48c2FtbDI6SXNzdWVyIEZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOm5hbWVpZC1mb3JtYXQ6ZW50aXR5Ij5odHRwOi8vQy1QRVBTLmdvdi54eDwvc2FtbDI6SXNzdWVyPjxkczpTaWduYXR1cmUgeG1sbnM6ZHM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiPjxkczpTaWduZWRJbmZvPjxkczpDYW5vbmljYWxpemF0aW9uTWV0aG9kIEFsZ29yaXRobT0iaHR0cDovL3d3dy53My5vcmcvMjAwMS8xMC94bWwtZXhjLWMxNG4jIi8+PGRzOlNpZ25hdHVyZU1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvMDQveG1sZHNpZy1tb3JlI3JzYS1zaGEyNTYiLz48ZHM6UmVmZXJlbmNlIFVSST0iI18zNzhiMGNjNTk0YThkMzhmMzJjN2M3NjQ5NTQ0OWQ1ZCI+PGRzOlRyYW5zZm9ybXM+PGRzOlRyYW5zZm9ybSBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNlbnZlbG9wZWQtc2lnbmF0dXJlIi8+PGRzOlRyYW5zZm9ybSBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvMTAveG1sLWV4Yy1jMTRuIyI+PGVjOkluY2x1c2l2ZU5hbWVzcGFjZXMgeG1sbnM6ZWM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvMTAveG1sLWV4Yy1jMTRuIyIgUHJlZml4TGlzdD0ieHMiLz48L2RzOlRyYW5zZm9ybT48L2RzOlRyYW5zZm9ybXM+PGRzOkRpZ2VzdE1ldGhvZCBBbGdvcml0aG09Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyNzaGExIi8+PGRzOkRpZ2VzdFZhbHVlPnJCYTMrbTU0RXVVZzgzSzhpTnVPVDlTaktQcz08L2RzOkRpZ2VzdFZhbHVlPjwvZHM6UmVmZXJlbmNlPjwvZHM6U2lnbmVkSW5mbz48ZHM6U2lnbmF0dXJlVmFsdWU+RGlZc3UxRXRzMzFocEJySEtvT2IvVnloRisxL1dxYjI5akE4T1J6cnZZb2h1WUlUdjV2V3oxcjhKdkpkK2NubVRNSFlZSU9hQ2V6SXd6L08yUlZ1K3IwWHEwdWNKbmhhcnQ3aUcwTTdFSGR4MVdFaGVzMWtHcHd2c1VjbnlLbm9tdnlSVklNVC80YmU3YTJLRTJZNzJkMGg3bVBsZmV4bVNvUENiaGJYSDIzc0grNTlVYjM1d3pwaXRUUFFtREFmOU5ibVAzV1I2OHpFS0VMTnRuaEZ2VUIyMHZVaGxGNi9hN3pPMlhRTmdFbzFaZW53RlBtWjdYbFhIK29BT3Q1cnFwUXNyMjN4R0tpYXV5YUpjRXpzQ0E5Z0I4YVhMYlQxR0xta1IwTndVa0RMWWxzcWwyeVZ2M01ZaHI5VjU3enk2T3dDR0dzUEltNTdlYnZ1d3RSbE5RPT08L2RzOlNpZ25hdHVyZVZhbHVlPjxkczpLZXlJbmZvPjxkczpYNTA5RGF0YT48ZHM6WDUwOUNlcnRpZmljYXRlPk1JSUZiRENDQkZTZ0F3SUJBZ0lFUUxLNTl6QU5CZ2txaGtpRzl3MEJBUVVGQURBK01Rc3dDUVlEVlFRR0V3SnphVEViTUJrR0ExVUUKQ2hNU2MzUmhkR1V0YVc1emRHbDBkWFJwYjI1ek1SSXdFQVlEVlFRTEV3bHphWFJsYzNRdFkyRXdIaGNOTVRBd016TXdNVE13T1RJegpXaGNOTVRVd016TXdNVE16T1RJeldqQ0JoakVMTUFrR0ExVUVCaE1DYzJreEd6QVpCZ05WQkFvVEVuTjBZWFJsTFdsdWMzUnBkSFYwCmFXOXVjekVTTUJBR0ExVUVDeE1KVTBsVVJWTlVMVU5CTVJrd0Z3WURWUVFMRXhCalpYSjBhV1pwWTJGMFpYTXRkMlZpTVNzd0V3WUQKVlFRREV3eFVSVk5VSUZCRlVGTWdVMGt3RkFZRFZRUUZFdzB6TURBek1qQXhNREF3TURBeE1JSUJJakFOQmdrcWhraUc5dzBCQVFFRgpBQU9DQVE4QU1JSUJDZ0tDQVFFQTRoNkw5UHYxVEs3Zno1SzZVdXIwUmxpNkVLelp3VHR2OXhYaFN0MnhsSTR3Rld6ekZpQ3k1L08vClE1R1BSYTEwWW9NYzhzN1dtTWRNNXlJL2JVMEJGMnQ1U1l0RUg3TXdiR2FGWkZLSnQxN090YnBaQWFDU29oNmZtMXlPMEh0VlZrRzkKVWRING1zd1Mzd0hwL2QxQzkxbFFOYmEyZW5WYzJwOU5kNGdZb3AvemJyb0V0b0ZlRHlIeFRsMG1ZTi9jVUhRRlQ0SDI0aHpBZldYaAoyRk9CZk5TbnZObDJIblBKT1Q2SG5yVUJzZHl6a1N6TE4wRWlzMlIxRzUrbVFrekF3VzZVT3Jvb2p2TWNsRUpLM3oxb2VrajJPV2oxCkZoYWxUTm1BNUQ5ZGtEeW1UUm40bzNCVzJTN292bVdQbXhZVVc5czI2YmtQaHovQ2JDUXdJRjl5UFFJREFRQUJvNElDSnpDQ0FpTXcKRGdZRFZSMFBBUUgvQkFRREFnV2dNQ3NHQTFVZEVBUWtNQ0tBRHpJd01UQXdNek13TVRNd09USXpXb0VQTWpBeE5UQXpNekF4TXpNNQpNak5hTUVzR0ExVWRJQVJFTUVJd05nWUxLd1lCQkFHdldRSUJBUUl3SnpBbEJnZ3JCZ0VGQlFjQ0FSWVphSFIwY0RvdkwzZDNkeTVqCllTNW5iM1l1YzJrdlkzQnpMekFJQmdZRUFJc3dBUUl3R0FZSUt3WUJCUVVIQVFNRUREQUtNQWdHQmdRQWprWUJBVEFlQmdOVkhSRUUKRnpBVmdSTjBaWE4wTG5OcExYQmxjSE5BWjI5MkxuTnBNSUgyQmdOVkhSOEVnZTR3Z2Vzd1ZhQlRvRkdrVHpCTk1Rc3dDUVlEVlFRRwpFd0p6YVRFYk1Ca0dBMVVFQ2hNU2MzUmhkR1V0YVc1emRHbDBkWFJwYjI1ek1SSXdFQVlEVlFRTEV3bHphWFJsYzNRdFkyRXhEVEFMCkJnTlZCQU1UQkVOU1RETXdnWkdnZ1k2Z2dZdUdXR3hrWVhBNkx5OTROVEF3TG1kdmRpNXphUzl2ZFQxemFYUmxjM1F0WTJFc2J6MXoKZEdGMFpTMXBibk4wYVhSMWRHbHZibk1zWXoxemFUOWpaWEowYVdacFkyRjBaVkpsZG05allYUnBiMjVNYVhOMFAySmhjMldHTDJoMApkSEE2THk5M2QzY3VjMmxuWlc0dFkyRXVjMmt2WTNKc0wzTnBkR1Z6ZEM5emFYUmxjM1F0WTJFdVkzSnNNQjhHQTFVZEl3UVlNQmFBCkZGUkpCMGFIengySm5jcXVjcWVvb0tCcHR5SG5NQjBHQTFVZERnUVdCQlF5U2VtZURpMTBEYmVUWWoxdGtHWjVabzRtd2pBSkJnTlYKSFJNRUFqQUFNQmtHQ1NxR1NJYjJmUWRCQUFRTU1Bb2JCRlkzTGpFREFnT29NQTBHQ1NxR1NJYjNEUUVCQlFVQUE0SUJBUUFTUTRsMQpWZCtNUkRMRm8yQTZxWVlXTFZxVHZ0UExJazd2N0Jzd21xMlNGQUwyWG1Qb0w1eGJRRmVEVytMaVdoUUJtcmxnV3lJN2diaS8xL3JzCjFFMDBaNFNrbjhsOTd0dUl5dXh2Q0tURmhKRHg5cHpnVVFHb3dvQ1lvOUl6Y01OUXB4eDZsa2VwcmVDRHVjK2UwZkFidlROR0VwdlEKN0RrZ3J3SmRjc1VBRWxRNE9KMGlmRUxvYWgxREg4d3BVMzF6cjdEM1lzaXpaZ3B1NVRFSUdQNTRBT2hiRmVaRW1abFRVNmd3Tnc0aQpUZjZuVlFrR2F4c0p0NmdHR3N5TDhSVXV2d3BWUlIzV21wbEN0alhyeUdDZTRCL2FnQWUzRUtVaDE1SWFQdldxZGl4U2p5U3hqQkkxCmJOOElFRkhZUFptdXdoN1kxRlF1T1lRR2p1U0xzSnk5PC9kczpYNTA5Q2VydGlmaWNhdGU+PC9kczpYNTA5RGF0YT48L2RzOktleUluZm8+PC9kczpTaWduYXR1cmU+PHNhbWwyOlN1YmplY3Q+PHNhbWwyOk5hbWVJRCBGb3JtYXQ9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjEuMTpuYW1laWQtZm9ybWF0OnVuc3BlY2lmaWVkIiBOYW1lUXVhbGlmaWVyPSJodHRwOi8vQy1QRVBTLmdvdi54eCI+dXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6MS4xOm5hbWVpZC1mb3JtYXQ6dW5zcGVjaWZpZWQ8L3NhbWwyOk5hbWVJRD48c2FtbDI6U3ViamVjdENvbmZpcm1hdGlvbiBNZXRob2Q9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpjbTpiZWFyZXIiPjxzYW1sMjpTdWJqZWN0Q29uZmlybWF0aW9uRGF0YSBBZGRyZXNzPSI5MS4xNDMuMTA1LjM3IiBJblJlc3BvbnNlVG89Il9mMjM1OGYyZjRkYjQ0NWJkMWFjNzVjZTQxNWQ3NmE5NSIgTm90T25PckFmdGVyPSIyMDE1LTAyLTIzVDE2OjE4OjA4LjYxMVoiIFJlY2lwaWVudD0iaHR0cHM6Ly9sb2NhbGhvc3Q6ODQ0My9tb2EtaWQtYXV0aC9QRVBTQ29ubmVjdG9yIi8+PC9zYW1sMjpTdWJqZWN0Q29uZmlybWF0aW9uPjwvc2FtbDI6U3ViamVjdD48c2FtbDI6Q29uZGl0aW9ucyBOb3RCZWZvcmU9IjIwMTUtMDItMjNUMTY6MTM6MDguNjExWiIgTm90T25PckFmdGVyPSIyMDE1LTAyLTIzVDE2OjE4OjA4LjYxMVoiPjxzYW1sMjpBdWRpZW5jZVJlc3RyaWN0aW9uPjxzYW1sMjpBdWRpZW5jZT5odHRwczovL2xvY2FsaG9zdDo4NDQzL21vYS1pZC1hdXRoPC9zYW1sMjpBdWRpZW5jZT48L3NhbWwyOkF1ZGllbmNlUmVzdHJpY3Rpb24+PHNhbWwyOk9uZVRpbWVVc2UvPjwvc2FtbDI6Q29uZGl0aW9ucz48c2FtbDI6QXV0aG5TdGF0ZW1lbnQgQXV0aG5JbnN0YW50PSIyMDE1LTAyLTIzVDE2OjEzOjA4LjYxMloiPjxzYW1sMjpTdWJqZWN0TG9jYWxpdHkgQWRkcmVzcz0iOTEuMTQzLjEwNS4zNyIvPjxzYW1sMjpBdXRobkNvbnRleHQ+PHNhbWwyOkF1dGhuQ29udGV4dERlY2wvPjwvc2FtbDI6QXV0aG5Db250ZXh0Pjwvc2FtbDI6QXV0aG5TdGF0ZW1lbnQ+PHNhbWwyOkF0dHJpYnV0ZVN0YXRlbWVudD48c2FtbDI6QXR0cmlidXRlIE5hbWU9Imh0dHA6Ly93d3cuc3RvcmsuZ292LmV1LzEuMC9lSWRlbnRpZmllciIgTmFtZUZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmF0dHJuYW1lLWZvcm1hdDp1cmkiIHN0b3JrOkF0dHJpYnV0ZVN0YXR1cz0iQXZhaWxhYmxlIj48c2FtbDI6QXR0cmlidXRlVmFsdWUgeG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOmFueVR5cGUiPlNJL0FUL1E4Ny93WkcrYWYxOGZ3d1orUjJ6SlNVOG5rSGFOVWh0QW9KRTJ6RTF5SldQdjBvWjRGd2srRFJUYTZNPTwvc2FtbDI6QXR0cmlidXRlVmFsdWU+PC9zYW1sMjpBdHRyaWJ1dGU+PHNhbWwyOkF0dHJpYnV0ZSBOYW1lPSJodHRwOi8vd3d3LnN0b3JrLmdvdi5ldS8xLjAvZ2l2ZW5OYW1lIiBOYW1lRm9ybWF0PSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXR0cm5hbWUtZm9ybWF0OnVyaSIgc3Rvcms6QXR0cmlidXRlU3RhdHVzPSJBdmFpbGFibGUiPjxzYW1sMjpBdHRyaWJ1dGVWYWx1ZSB4bWxuczp4c2k9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hLWluc3RhbmNlIiB4c2k6dHlwZT0ieHM6YW55VHlwZSI+SmFuZXo8L3NhbWwyOkF0dHJpYnV0ZVZhbHVlPjwvc2FtbDI6QXR0cmlidXRlPjxzYW1sMjpBdHRyaWJ1dGUgTmFtZT0iaHR0cDovL3d3dy5zdG9yay5nb3YuZXUvMS4wL2RhdGVPZkJpcnRoIiBOYW1lRm9ybWF0PSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXR0cm5hbWUtZm9ybWF0OnVyaSIgc3Rvcms6QXR0cmlidXRlU3RhdHVzPSJBdmFpbGFibGUiPjxzYW1sMjpBdHRyaWJ1dGVWYWx1ZSB4bWxuczp4c2k9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hLWluc3RhbmNlIiB4c2k6dHlwZT0ieHM6YW55VHlwZSI+MTk5OTA2MDM8L3NhbWwyOkF0dHJpYnV0ZVZhbHVlPjwvc2FtbDI6QXR0cmlidXRlPjxzYW1sMjpBdHRyaWJ1dGUgTmFtZT0iaHR0cDovL3d3dy5zdG9yay5nb3YuZXUvMS4wL3NpZ25lZERvYyIgTmFtZUZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOmF0dHJuYW1lLWZvcm1hdDp1cmkiIHN0b3JrOkF0dHJpYnV0ZVN0YXR1cz0iQXZhaWxhYmxlIj48c2FtbDI6QXR0cmlidXRlVmFsdWUgeG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOmFueVR5cGUiPjxuczI6U2lnblJlc3BvbnNlIHhtbG5zOm5zMj0idXJuOm9hc2lzOm5hbWVzOnRjOmRzczoxLjA6Y29yZTpzY2hlbWEiIHhtbG5zPSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoxLjA6YXNzZXJ0aW9uIiB4bWxuczpuczM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvMDkveG1sZHNpZyMiIERvY1VJPSJMT0NBTC9TSS83NDljOWNiOS01YzAzLTQwY2UtYmZmOC00NTc4MDJiMzk2OTUiIFByb2ZpbGU9InVybjpvYXNpczpuYW1lczp0Yzpkc3M6MS4wOnByb2ZpbGVzOlhBZEVTOmZvcm1zOkJFUyIgUmVxdWVzdElEPSJfMWUxNjkyODliZjEwMmNlMmViYzYyMDY4Nzc4OTNjMjQiPjxuczI6UmVzdWx0PjxuczI6UmVzdWx0TWFqb3I+dXJuOm9hc2lzOm5hbWVzOnRjOmRzczoxLjA6cmVzdWx0bWFqb3I6U3VjY2VzczwvbnMyOlJlc3VsdE1ham9yPjwvbnMyOlJlc3VsdD48bnMyOk9wdGlvbmFsT3V0cHV0cz48bnMyOkRvY3VtZW50V2l0aFNpZ25hdHVyZT48bnMyOkRvY3VtZW50PjxuczI6RG9jdW1lbnRVUkw+aHR0cHM6Ly9wZXBzLXRlc3QubWp1Lmdvdi5zaS9Eb2N1bWVudFNlcnZpY2UvRG9jdW1lbnRTZXJ2aWNlPC9uczI6RG9jdW1lbnRVUkw+PC9uczI6RG9jdW1lbnQ+PC9uczI6RG9jdW1lbnRXaXRoU2lnbmF0dXJlPjwvbnMyOk9wdGlvbmFsT3V0cHV0cz48L25zMjpTaWduUmVzcG9uc2U+PC9zYW1sMjpBdHRyaWJ1dGVWYWx1ZT48L3NhbWwyOkF0dHJpYnV0ZT48c2FtbDI6QXR0cmlidXRlIE5hbWU9Imh0dHA6Ly93d3cuc3RvcmsuZ292LmV1LzEuMC9zdXJuYW1lIiBOYW1lRm9ybWF0PSJ1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXR0cm5hbWUtZm9ybWF0OnVyaSIgc3Rvcms6QXR0cmlidXRlU3RhdHVzPSJBdmFpbGFibGUiPjxzYW1sMjpBdHRyaWJ1dGVWYWx1ZSB4bWxuczp4c2k9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hLWluc3RhbmNlIiB4c2k6dHlwZT0ieHM6YW55VHlwZSI+VnpvcmVjPC9zYW1sMjpBdHRyaWJ1dGVWYWx1ZT48L3NhbWwyOkF0dHJpYnV0ZT48L3NhbWwyOkF0dHJpYnV0ZVN0YXRlbWVudD48L3NhbWwyOkFzc2VydGlvbj48L3NhbWwycDpSZXNwb25zZT4=
\ No newline at end of file diff --git a/id/server/modules/pom.xml b/id/server/modules/pom.xml index 1018abf9c..94e1f7a3b 100644 --- a/id/server/modules/pom.xml +++ b/id/server/modules/pom.xml @@ -20,11 +20,14 @@ </properties> <modules> - <module>module-stork</module> <module>module-monitoring</module> <module>moa-id-modules-saml1</module> <module>moa-id-module-openID</module> <module>moa-id-modul-citizencard_authentication</module> + <module>moa-id-module-eIDAS</module> + <!-- <module>moa-id-module-pvp2</module> --> + <module>moa-id-modules-federated_authentication</module> + <module>moa-id-module-ssoTransfer</module> </modules> |