diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at')
20 files changed, 2800 insertions, 2439 deletions
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java index 6f6d9611a..22c08b3e0 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/AuthenticationServer.java @@ -138,6 +138,42 @@ import eu.stork.peps.auth.commons.PersonalAttributeList; import eu.stork.peps.auth.commons.STORKAuthnRequest; import eu.stork.peps.auth.engine.STORKSAMLEngine; import eu.stork.peps.exceptions.STORKSAMLEngineException; +import iaik.asn1.ObjectID; +import iaik.util.logging.Log; +import iaik.x509.X509Certificate; +import iaik.x509.X509ExtensionInitException; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringEscapeUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.VelocityEngine; +import org.apache.xpath.XPathAPI; +import org.opensaml.common.IdentifierGenerator; +import org.opensaml.common.impl.SecureRandomIdentifierGenerator; +import org.opensaml.xml.util.Base64; +import org.opensaml.xml.util.XMLHelper; +import org.w3c.dom.*; +import org.xml.sax.SAXException; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringWriter; +import java.math.BigInteger; +import java.security.NoSuchAlgorithmException; +import java.security.Principal; +import java.security.cert.CertificateException; +import java.util.*; + +//import java.security.cert.CertificateFactory; +//import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.CreateIdentityLinkResponse; +//import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClient; +//import at.gv.egovernment.moa.id.auth.validator.parep.client.szrgw.SZRGWClientException; /** * API for MOA ID Authentication Service.<br> {@link AuthenticationSession} is @@ -149,148 +185,147 @@ import eu.stork.peps.exceptions.STORKSAMLEngineException; */ public class AuthenticationServer implements MOAIDAuthConstants { - /** single instance */ - private static AuthenticationServer instance; - - /** - * time out in milliseconds used by {@link cleanup} for session store - */ - private long sessionTimeOutCreated = 15 * 60 * 1000; // default 10 minutes - private long sessionTimeOutUpdated = 10 * 60 * 1000; // default 10 minutes - /** - * time out in milliseconds used by {@link cleanup} for authentication data - * store - */ - private long authDataTimeOut = 2 * 60 * 1000; // default 2 minutes - - /** - * Returns the single instance of <code>AuthenticationServer</code>. - * - * @return the single instance of <code>AuthenticationServer</code> - */ - public static AuthenticationServer getInstance() { - if (instance == null) - instance = new AuthenticationServer(); - return instance; - } - - /** - * Constructor for AuthenticationServer. - */ - public AuthenticationServer() { - super(); - } - - - /** - * Processes the beginning of an authentication session. - * <ul> - * <li>Starts an authentication session</li> - * <li>Creates an <code><InfoboxReadRequest></code></li> - * <li>Creates an HTML form for querying the identity link from the security - * layer implementation. <br> - * Form parameters include - * <ul> - * <li>the <code><InfoboxReadRequest></code></li> - * <li>the data URL where the security layer implementation sends it - * response to</li> - * </ul> - * </ul> - * - * @param authURL - * URL of the servlet to be used as data URL - * @param target - * "Geschäftsbereich" of the online application requested - * @param targetFriendlyName - * Friendly name of the target if the target is configured via - * configuration - * @param oaURL - * online application URL requested - * @param bkuURL - * URL of the "Bürgerkartenumgebung" to be used; may be - * <code>null</code>; in this case, the default location will be - * used - * @param useMandate - * Indicates if mandate is used or not - * @param templateURL - * URL providing an HTML template for the HTML form generated - * @param templateMandteURL - * URL providing an HTML template for the HTML form generated - * (for signing in mandates mode) - * @param req - * determines the protocol used - * @param sourceID - * @return HTML form - * @throws AuthenticationException - * @see GetIdentityLinkFormBuilder - * @see InfoboxReadRequestBuilder - */ - public String startAuthentication(AuthenticationSession session, HttpServletRequest req) throws WrongParametersException, - AuthenticationException, ConfigurationException, BuildException { - - if (session == null) { - throw new AuthenticationException("auth.18", new Object[] { }); - } - - //load OnlineApplication configuration - OAAuthParameter oaParam = - AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[] { session.getPublicOAURLPrefix() }); - - //load Template - String template = null; - if (session.getTemplateURL() != null) { - try { - - template = new String(FileUtils.readURL(session.getTemplateURL())); - } catch (IOException ex) { - throw new AuthenticationException("auth.03", new Object[] { - session.getTemplateURL(), ex.toString() }, ex); - } - } - - String infoboxReadRequest = ""; - - String domainIdentifier = AuthConfigurationProvider.getInstance().getSSOTagetIdentifier().trim(); - if (MiscUtil.isEmpty(domainIdentifier) && session.isSsoRequested()) { - //do not use SSO if no Target is set - Log.warn("NO SSO-Target found in configuration. Single Sign-On is deaktivated!"); - session.setSsoRequested(false); - - } - - if (session.isSsoRequested()) { - //load identityLink with SSO Target - boolean isbuisness = false; - - if (domainIdentifier.startsWith(PREFIX_WPBK)) { - - isbuisness = true; - - } else { - isbuisness = false; - - } - - //build ReadInfobox request - infoboxReadRequest = new InfoboxReadRequestBuilder().build( - isbuisness, domainIdentifier); - - } else { - //build ReadInfobox request - infoboxReadRequest = new InfoboxReadRequestBuilder().build( - oaParam.getBusinessService(), oaParam - .getIdentityLinkDomainIdentifier()); - } - - - String dataURL = new DataURLBuilder().buildDataURL( - session.getAuthURL(), REQ_VERIFY_IDENTITY_LINK, session - .getSessionID()); - - //removed in MOAID 2.0 - String pushInfobox = ""; + /** + * single instance + */ + private static AuthenticationServer instance; + + /** + * time out in milliseconds used by {@link cleanup} for session store + */ + private long sessionTimeOutCreated = 15 * 60 * 1000; // default 10 minutes + private long sessionTimeOutUpdated = 10 * 60 * 1000; // default 10 minutes + /** + * time out in milliseconds used by {@link cleanup} for authentication data + * store + */ + private long authDataTimeOut = 2 * 60 * 1000; // default 2 minutes + + /** + * Returns the single instance of <code>AuthenticationServer</code>. + * + * @return the single instance of <code>AuthenticationServer</code> + */ + public static AuthenticationServer getInstance() { + if (instance == null) + instance = new AuthenticationServer(); + return instance; + } + + /** + * Constructor for AuthenticationServer. + */ + public AuthenticationServer() { + super(); + } + + + /** + * Processes the beginning of an authentication session. + * <ul> + * <li>Starts an authentication session</li> + * <li>Creates an <code><InfoboxReadRequest></code></li> + * <li>Creates an HTML form for querying the identity link from the security + * layer implementation. <br> + * Form parameters include + * <ul> + * <li>the <code><InfoboxReadRequest></code></li> + * <li>the data URL where the security layer implementation sends it + * response to</li> + * </ul> + * </ul> + * + * @param authURL URL of the servlet to be used as data URL + * @param target "Geschäftsbereich" of the online application requested + * @param targetFriendlyName Friendly name of the target if the target is configured via + * configuration + * @param oaURL online application URL requested + * @param bkuURL URL of the "Bürgerkartenumgebung" to be used; may be + * <code>null</code>; in this case, the default location will be + * used + * @param useMandate Indicates if mandate is used or not + * @param templateURL URL providing an HTML template for the HTML form generated + * @param templateMandteURL URL providing an HTML template for the HTML form generated + * (for signing in mandates mode) + * @param req determines the protocol used + * @param sourceID + * @return HTML form + * @throws AuthenticationException + * @see GetIdentityLinkFormBuilder + * @see InfoboxReadRequestBuilder + */ + public String startAuthentication(AuthenticationSession session, HttpServletRequest req) throws WrongParametersException, + AuthenticationException, ConfigurationException, BuildException { + + if (session == null) { + throw new AuthenticationException("auth.18", new Object[]{}); + } + + //load OnlineApplication configuration + OAAuthParameter oaParam = + AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + if (oaParam == null) + throw new AuthenticationException("auth.00", new Object[]{session.getPublicOAURLPrefix()}); + + //load Template + String template = null; + if (session.getTemplateURL() != null) { + try { + + template = new String(FileUtils.readURL(session.getTemplateURL())); + } catch (IOException ex) { + throw new AuthenticationException("auth.03", new Object[]{ + session.getTemplateURL(), ex.toString()}, ex); + } + } + + String infoboxReadRequest = ""; + + String domainIdentifier = AuthConfigurationProvider.getInstance().getSSOTagetIdentifier().trim(); + if (MiscUtil.isEmpty(domainIdentifier) && session.isSsoRequested()) { + //do not use SSO if no Target is set + Log.warn("NO SSO-Target found in configuration. Single Sign-On is deaktivated!"); + session.setSsoRequested(false); + + } + + if (session.isSsoRequested()) { + //load identityLink with SSO Target + boolean isbuisness = false; + + if (domainIdentifier.startsWith(PREFIX_WPBK)) { + + isbuisness = true; + + } else { + isbuisness = false; + + } + + //build ReadInfobox request + infoboxReadRequest = new InfoboxReadRequestBuilder().build( + isbuisness, domainIdentifier); + + } else { + + if (oaParam.getStorkService()) + // build stork request + infoboxReadRequest = new InfoboxReadRequestBuilder().buildStorkReadRequest( + oaParam.getIdentityLinkDomainIdentifier()); + else + //build ReadInfobox request + infoboxReadRequest = new InfoboxReadRequestBuilder().build( + oaParam.getBusinessService(), oaParam + .getIdentityLinkDomainIdentifier()); + } + + + String dataURL = new DataURLBuilder().buildDataURL( + session.getAuthURL(), REQ_VERIFY_IDENTITY_LINK, session + .getSessionID()); + + //removed in MOAID 2.0 + String pushInfobox = ""; // VerifyInfoboxParameters verifyInfoboxParameters = oaParam // .getVerifyInfoboxParameters(); @@ -299,1787 +334,1743 @@ public class AuthenticationServer implements MOAIDAuthConstants { // session.setPushInfobox(pushInfobox); // } - //build CertInfo request - String certInfoRequest = new CertInfoVerifyXMLSignatureRequestBuilder() - .build(); - String certInfoDataURL = new DataURLBuilder() - .buildDataURL(session.getAuthURL(), REQ_START_AUTHENTICATION, - session.getSessionID()); - - //get Applet Parameters - String appletwidth = req.getParameter(PARAM_APPLET_WIDTH); - String appletheigth = req.getParameter(PARAM_APPLET_HEIGTH); - appletheigth = StringEscapeUtils.escapeHtml(appletheigth); - appletwidth = StringEscapeUtils.escapeHtml(appletwidth); - - String htmlForm = new GetIdentityLinkFormBuilder().build(template, - session.getBkuURL(), infoboxReadRequest, dataURL, certInfoRequest, - certInfoDataURL, pushInfobox, oaParam, appletheigth, appletwidth); - - return htmlForm; - } - - /** - * Processes an <code><InfoboxReadResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><InfoboxReadResponse></code></li> - * <li>Parses identity link enclosed in - * <code><InfoboxReadResponse></code></li> - * <li>Verifies identity link by calling the MOA SP component</li> - * <li>Checks certificate authority of identity link</li> - * <li>Stores identity link in the session</li> - * <li>Verifies all additional infoboxes returned from the BKU</li> - * <li>Creates an authentication block to be signed by the user</li> - * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> - * containg the authentication block, meant to be returned to the security - * layer implementation</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param infoboxReadResponseParameters - * The parameters from the response returned from the BKU - * including the <code><InfoboxReadResponse></code> - * @return String representation of the - * <code><CreateXMLSignatureRequest></code> - * @throws BKUException - */ - public String verifyIdentityLink(AuthenticationSession session, - Map<String, String> infoboxReadResponseParameters) throws AuthenticationException, - BuildException, ParseException, ConfigurationException, - ValidateException, ServiceException, BKUException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_IDENTITY_LINK, PARAM_SESSIONID }); - - String xmlInfoboxReadResponse = (String) infoboxReadResponseParameters - .get(PARAM_XMLRESPONSE); - - if (isEmpty(xmlInfoboxReadResponse)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_IDENTITY_LINK, PARAM_XMLRESPONSE }); - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - - // check if an identity link was found - // Errorcode 2911 von Trustdesk BKU (nicht spezifikationskonform - // (SL1.2)) - // CharSequence se = "ErrorCode>2911".substring(0); - // boolean b = xmlInfoboxReadResponse.contains(se); - String se = "ErrorCode>2911"; - int b = xmlInfoboxReadResponse.indexOf(se); - if (b != -1) { // no identity link found - Logger - .info("Es konnte keine Personenbindung auf der Karte gefunden werden. Versuche Anmeldung als auslaendische eID."); - return null; - } - // spezifikationsgemaess (SL1.2) Errorcode - se = "ErrorCode>4002"; - // b = xmlInfoboxReadResponse.contains(se); - b = xmlInfoboxReadResponse.indexOf(se); - if (b != -1) { // Unbekannter Infoboxbezeichner - Logger - .info("Unbekannter Infoboxbezeichner. Versuche Anmeldung als auslaendische eID."); - return null; - } - - // parses the <InfoboxReadResponse> - IdentityLink identityLink = new InfoboxReadResponseParser( - xmlInfoboxReadResponse).parseIdentityLink(); - // validates the identity link - IdentityLinkValidator.getInstance().validate(identityLink); - // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP - Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() - .build(identityLink, authConf - .getMoaSpIdentityLinkTrustProfileID()); - - // invokes the call - Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() - .verifyXMLSignature(domVerifyXMLSignatureRequest); - // parses the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( - domVerifyXMLSignatureResponse).parseData(); - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - // if OA is type is business service the manifest validation result has - // to be ignored - boolean ignoreManifestValidationResult = oaParam.getBusinessService() ? true - : false; - - // validates the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponseValidator.getInstance().validate( - verifyXMLSignatureResponse, - authConf.getIdentityLinkX509SubjectNames(), - VerifyXMLSignatureResponseValidator.CHECK_IDENTITY_LINK, - ignoreManifestValidationResult); - - session.setIdentityLink(identityLink); - // now validate the extended infoboxes - - //Removed in MOA-ID 2.0 - //verifyInfoboxes(session, infoboxReadResponseParameters, false); - - return "found!"; - } - - /** - * Processes an <code><InfoboxReadResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><InfoboxReadResponse></code></li> - * <li>Parses identity link enclosed in - * <code><InfoboxReadResponse></code></li> - * <li>Verifies identity link by calling the MOA SP component</li> - * <li>Checks certificate authority of identity link</li> - * <li>Stores identity link in the session</li> - * <li>Verifies all additional infoboxes returned from the BKU</li> - * <li>Creates an authentication block to be signed by the user</li> - * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> - * containg the authentication block, meant to be returned to the security - * layer implementation</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param infoboxReadResponseParameters - * The parameters from the response returned from the BKU - * including the <code><InfoboxReadResponse></code> - * @return String representation of the - * <code><CreateXMLSignatureRequest></code> - */ - public String verifyCertificate(AuthenticationSession session, - X509Certificate certificate) throws AuthenticationException, - BuildException, ParseException, ConfigurationException, - ValidateException, ServiceException, MOAIDException{ - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID }); - - // check if person is a Organwalter - // if true - don't show bPK in AUTH Block - try { - for (ObjectID OWid : MOAIDAuthConstants.OW_LIST) { - if (certificate.getExtension(OWid) != null) { - session.setOW(true); - } - - } - - } catch (X509ExtensionInitException e) { - Logger.warn("Certificate extension is not readable."); - session.setOW(false); - } - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - String returnvalue = getCreateXMLSignatureRequestAuthBlockOrRedirect(session, - authConf, oaParam); - - return returnvalue; - } - - /** - * Processes an <code>Mandate</code> sent by the MIS.<br> - * <ul> - * <li>Validates given <code>Mandate</code></li> - * <li>Verifies Mandate by calling the MOA SP component</li> - * <li>Creates an authentication block to be signed by the user</li> - * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> - * containg the authentication block, meant to be returned to the security - * layer implementation</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param infoboxReadResponseParameters - * The parameters from the response returned from the BKU - * including the <code><InfoboxReadResponse></code> - * @return String representation of the - * <code><CreateXMLSignatureRequest></code> - */ - public void verifyMandate(AuthenticationSession session, MISMandate mandate) - throws AuthenticationException, BuildException, ParseException, - ConfigurationException, ValidateException, ServiceException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - GET_MIS_SESSIONID, PARAM_SESSIONID }); - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - try { - // sets the extended SAML attributes for OID (Organwalter) - setExtendedSAMLAttributeForMandatesOID(session, mandate, oaParam - .getBusinessService()); - - validateExtendedSAMLAttributeForMandates(session, mandate, oaParam.getBusinessService()); - - - } catch (SAXException e) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }, e); - } catch (IOException e) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }, e); - } catch (ParserConfigurationException e) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }, e); - } catch (TransformerException e) { - throw new AuthenticationException("auth.16", - new Object[] { GET_MIS_SESSIONID }, e); - } - - } - - /** - * - * @param session - * @param authConf - * @param oaParam - * @return - * @throws ConfigurationException - * @throws BuildException - * @throws ValidateException - */ - public String getCreateXMLSignatureRequestAuthBlockOrRedirect( - AuthenticationSession session, AuthConfigurationProvider authConf, - OAAuthParameter oaParam) throws ConfigurationException, - BuildException, ValidateException { - - // check for intermediate processing of the infoboxes - if (session.isValidatorInputPending()) - return "Redirect to Input Processor"; - - if (authConf == null) - authConf = AuthConfigurationProvider.getInstance(); - if (oaParam == null) - oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - - // builds the AUTH-block - String authBlock = buildAuthenticationBlock(session, oaParam); - - // builds the <CreateXMLSignatureRequest> - List<String> transformsInfos = oaParam.getTransformsInfos(); - if ((transformsInfos == null) || (transformsInfos.size() == 0)) { - // no OA specific transforms specified, use default ones - transformsInfos = authConf.getTransformsInfos(); - } - String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() - .build(authBlock, oaParam.getKeyBoxIdentifier(), - transformsInfos); - return createXMLSignatureRequest; - } - - /** - * Returns an CreateXMLSignatureRequest for signing the ERnP statement.<br> - * <ul> - * <li>Creates an CreateXMLSignatureRequest to be signed by the user</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param cert - * The certificate from the user - * @return String representation of the - * <code><CreateXMLSignatureRequest></code> - */ - public String createXMLSignatureRequestForeignID(AuthenticationSession session, - X509Certificate cert) throws AuthenticationException, - BuildException, ParseException, ConfigurationException, - ValidateException, ServiceException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID }); - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); - - return getCreateXMLSignatureRequestForeigID(session, authConf, oaParam, - cert); - } - - public String getCreateXMLSignatureRequestForeigID( - AuthenticationSession session, AuthConfigurationProvider authConf, - OAAuthParameter oaParam, X509Certificate cert) - throws ConfigurationException { - - // check for intermediate processing of the infoboxes - if (session.isValidatorInputPending()) - return "Redirect to Input Processor"; - - if (authConf == null) - authConf = AuthConfigurationProvider.getInstance(); - if (oaParam == null) - oaParam = AuthConfigurationProvider.getInstance() - .getOnlineApplicationParameter( - session.getPublicOAURLPrefix()); - - Principal subject = cert.getSubjectDN(); - - String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() - .buildForeignID(subject.toString(), oaParam, session); - return createXMLSignatureRequest; - } - - /** - * Processes an <code><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses response enclosed in - * <code><CreateXMLSignatureResponse></code></li> - * <li>Verifies signature by calling the MOA SP component</li> - * <li>Returns the signer certificate</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param createXMLSignatureResponseParameters - * The parameters from the response returned from the BKU - * including the <code><CreateXMLSignatureResponse></code> - * @throws BKUException - */ - public X509Certificate verifyXMLSignature(String sessionID, - Map<String, String> createXMLSignatureResponseParameters) - throws AuthenticationException, BuildException, ParseException, - ConfigurationException, ValidateException, ServiceException, BKUException { - - if (isEmpty(sessionID)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_GET_FOREIGN_ID, PARAM_SESSIONID }); - - String xmlCreateXMLSignatureResponse = (String) createXMLSignatureResponseParameters - .get(PARAM_XMLRESPONSE); - - if (isEmpty(xmlCreateXMLSignatureResponse)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_GET_FOREIGN_ID, PARAM_XMLRESPONSE }); - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - - // parses the <CreateXMLSignatureResponse> - CreateXMLSignatureResponseParser p = new CreateXMLSignatureResponseParser( - xmlCreateXMLSignatureResponse); - CreateXMLSignatureResponse createXMLSignatureResponse = p - .parseResponseDsig(); - - // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP - Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() - .buildDsig(createXMLSignatureResponse, authConf - .getMoaSpAuthBlockTrustProfileID()); - - // invokes the call - Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() - .verifyXMLSignature(domVerifyXMLSignatureRequest); - - // parses the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( - domVerifyXMLSignatureResponse).parseData(); - - return verifyXMLSignatureResponse.getX509certificate(); - - } - - /** - * Processes an <code><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses response enclosed in - * <code><CreateXMLSignatureResponse></code></li> - * <li>Verifies signature by calling the MOA SP component</li> - * <li>Returns the signer certificate</li> - * </ul> - * - * @param sessionID - * ID of associated authentication session data - * @param readInfoboxResponseParameters - * The parameters from the response returned from the BKU - * including the <code><ReadInfoboxResponse></code> - * @throws BKUException - */ - public X509Certificate getCertificate(String sessionID, - Map<String, String> readInfoboxResponseParameters) throws AuthenticationException, - BuildException, ParseException, ConfigurationException, - ValidateException, ServiceException, BKUException { - - if (isEmpty(sessionID)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID }); - - String xmlReadInfoboxResponse = (String) readInfoboxResponseParameters - .get(PARAM_XMLRESPONSE); - - if (isEmpty(xmlReadInfoboxResponse)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_CERTIFICATE, PARAM_XMLRESPONSE }); - - // parses the <CreateXMLSignatureResponse> - InfoboxReadResponseParser p = new InfoboxReadResponseParser( - xmlReadInfoboxResponse); - X509Certificate cert = p.parseCertificate(); - - return cert; - - } - - /** - * Builds an authentication block <code><saml:Assertion></code> from - * given session data. - * - * @param session - * authentication session - * - * @return <code><saml:Assertion></code> as a String - * - * @throws BuildException - * If an error occurs on serializing an extended SAML attribute - * to be appended to the AUTH-Block. - */ - private String buildAuthenticationBlock(AuthenticationSession session, - OAAuthParameter oaParam) throws BuildException { - - IdentityLink identityLink = session.getIdentityLink(); - String issuer = identityLink.getName(); - String gebDat = identityLink.getDateOfBirth(); - - String identificationValue = null; - String identificationType = null; - - //set empty AuthBlock BPK in case of OW or SSO or bpk is not requested - if (session.isOW() || session.isSsoRequested() || oaParam.isRemovePBKFromAuthBlock()) { - identificationType = ""; - identificationValue = ""; - - } else if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - - if (oaParam.getBusinessService()) { - - String bpkBase64 = new BPKBuilder().buildWBPK(identityLink - .getIdentificationValue(), oaParam.getIdentityLinkDomainIdentifier()); - identificationValue = bpkBase64; - - if (oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_WBPK + "+" )) - identificationType = oaParam.getIdentityLinkDomainIdentifier(); - else - identificationType = Constants.URN_PREFIX_WBPK + "+" + oaParam.getIdentityLinkDomainIdentifier(); - - } else { - String bpkBase64 = new BPKBuilder().buildBPK(identityLink - .getIdentificationValue(), session.getTarget()); - identificationValue = bpkBase64; - identificationType = Constants.URN_PREFIX_CDID + "+" + session.getTarget(); - } - - - } else { - identificationValue = identityLink.getIdentificationValue(); - identificationType = identityLink.getIdentificationType(); - - } - - String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar - .getInstance()); - session.setIssueInstant(issueInstant); - String authURL = session.getAuthURL(); - String target = session.getTarget(); - String targetFriendlyName = session.getTargetFriendlyName(); - - // Bug #485 - // (https://egovlabs.gv.at/tracker/index.php?func=detail&aid=485&group_id=6&atid=105) - // String oaURL = session.getPublicOAURLPrefix(); - - List<ExtendedSAMLAttribute> extendedSAMLAttributes = session.getExtendedSAMLAttributesAUTH(); - - - if (session.isSsoRequested()) { - String oaURL = new String(); - try { - oaURL = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); - - if (MiscUtil.isNotEmpty(oaURL)) - oaURL = oaURL.replaceAll("&", "&"); - - } catch (ConfigurationException e) { - } - String authBlock = new AuthenticationBlockAssertionBuilder() - .buildAuthBlockSSO(issuer, issueInstant, authURL, target, - targetFriendlyName, identificationValue, - identificationType, oaURL, gebDat, - extendedSAMLAttributes, session, oaParam); - return authBlock; - - } else { - String oaURL = session.getPublicOAURLPrefix().replaceAll("&", "&"); - String authBlock = new AuthenticationBlockAssertionBuilder() - .buildAuthBlock(issuer, issueInstant, authURL, target, - targetFriendlyName, identificationValue, - identificationType, oaURL, gebDat, - extendedSAMLAttributes, session, oaParam); - return authBlock; - } - } - - - - /** - * Verifies the infoboxes (except of the identity link infobox) returned by - * the BKU by calling appropriate validator classes. - * - * @param session - * The actual authentication session. - * @param mandate - * The Mandate from the MIS - * - * @throws AuthenticationException - * @throws ConfigurationException - * @throws TransformerException - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - */ - private void validateExtendedSAMLAttributeForMandates( - AuthenticationSession session, MISMandate mandate, - boolean business) - throws ValidateException, ConfigurationException, SAXException, - IOException, ParserConfigurationException, TransformerException { - - ExtendedSAMLAttribute[] extendedSAMLAttributes = addExtendedSamlAttributes( - mandate, business, false); - - int length = extendedSAMLAttributes.length; - for (int i = 0; i < length; i++) { - ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i]; - - verifySAMLAttribute(samlAttribute, i, "MISService", - "MISService"); - - } - } - - /** - * Verifies the infoboxes (except of the identity link infobox) returned by - * the BKU by calling appropriate validator classes. - * - * @param session - * The actual authentication session. - * @param mandate - * The Mandate from the MIS - * - * @throws AuthenticationException - * @throws ConfigurationException - * @throws TransformerException - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - */ - private void setExtendedSAMLAttributeForMandatesOID( - AuthenticationSession session, MISMandate mandate, boolean business) - throws ValidateException, ConfigurationException, SAXException, - IOException, ParserConfigurationException, TransformerException { - - ExtendedSAMLAttribute[] extendedSamlAttributes = addExtendedSamlAttributesOID( - mandate, business); - - AddAdditionalSAMLAttributes(session, extendedSamlAttributes, - "MISService", "MISService"); - - } - - /** - * Adds given SAML Attributes to the current session. They will be appended - * to the final SAML Assertion or the AUTH block. If the attributes are - * already in the list, they will be replaced. - * - * @param session - * The current session - * @param extendedSAMLAttributes - * The SAML attributes to add - * @param identifier - * The infobox identifier for debug purposes - * @param friendlyNam - * The friendly name of the infobox for debug purposes - */ - private static void AddAdditionalSAMLAttributes( - AuthenticationSession session, - ExtendedSAMLAttribute[] extendedSAMLAttributes, String identifier, - String friendlyName) throws ValidateException { - if (extendedSAMLAttributes == null) - return; - List<ExtendedSAMLAttribute> oaAttributes = session.getExtendedSAMLAttributesOA(); - if (oaAttributes == null) - oaAttributes = new Vector<ExtendedSAMLAttribute>(); - List<ExtendedSAMLAttribute> authAttributes = session.getExtendedSAMLAttributesAUTH(); - if (authAttributes == null) - authAttributes = new Vector<ExtendedSAMLAttribute>(); - int length = extendedSAMLAttributes.length; - for (int i = 0; i < length; i++) { - ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i]; - - Object value = verifySAMLAttribute(samlAttribute, i, identifier, - friendlyName); - - if ((value instanceof String) || (value instanceof Element)) { - switch (samlAttribute.getAddToAUTHBlock()) { - case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY: - replaceExtendedSAMLAttribute(authAttributes, samlAttribute); - break; - case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK: - replaceExtendedSAMLAttribute(authAttributes, samlAttribute); - replaceExtendedSAMLAttribute(oaAttributes, samlAttribute); - break; - case ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK: - replaceExtendedSAMLAttribute(oaAttributes, samlAttribute); - break; - default: - Logger - .info("Invalid return value from method \"getAddToAUTHBlock()\" (" - + samlAttribute.getAddToAUTHBlock() - + ") in SAML attribute number " - + (i + 1) - + " for infobox " + identifier); - throw new ValidateException("validator.47", new Object[] { - friendlyName, String.valueOf((i + 1)) }); - } - } else { - Logger - .info("The type of SAML-Attribute number " - + (i + 1) - + " returned from " - + identifier - + "-infobox validator is not valid. Must be either \"java.Lang.String\"" - + " or \"org.w3c.dom.Element\""); - throw new ValidateException("validator.46", new Object[] { - identifier, String.valueOf((i + 1)) }); - } - } - session.setExtendedSAMLAttributesAUTH(authAttributes); - session.setExtendedSAMLAttributesOA(oaAttributes); - } - - /** - * Adds the AUTH block related SAML attributes to the validation result. - * This is needed always before the AUTH block is to be signed, because the - * name of the mandator has to be set - * - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - * @throws TransformerException - */ - - protected static ExtendedSAMLAttribute[] addExtendedSamlAttributes( - MISMandate mandate, boolean business, boolean provideStammzahl) - throws SAXException, IOException, ParserConfigurationException, - TransformerException { - Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>(); - - extendedSamlAttributes.clear(); - - // Name - Element domMandate = mandateToElement(mandate); - Element nameSpaceNode = domMandate.getOwnerDocument().createElement( - "NameSpaceNode"); - nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, - Constants.PD_NS_URI); - nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.MANDATE_POSTFIX, - SZRGWConstants.MANDATE_NS); - - Element mandator = (Element) XPathAPI.selectSingleNode(domMandate, - "//md:Mandate/md:Mandator", nameSpaceNode); - - // Mandate - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_RAW, domMandate, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); - - // (w)bpk - String wbpk = ParepUtils.extractMandatorWbpk(mandator); - if (!ParepUtils.isEmpty(wbpk)) { - if (!ParepUtils.isPhysicalPerson(mandator)) { - String idType = ParepUtils - .extractMandatorIdentificationType(mandator); - if (!ParepUtils.isEmpty(idType) - && idType.startsWith(Constants.URN_PREFIX_BASEID)) { - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_CB_BASE_ID, - ParepUtils.getRegisterString(idType) + ": " + wbpk, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY)); - } - } else if (business) { - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_WBPK, wbpk, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY)); - } - } - - ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes - .size()]; - extendedSamlAttributes.copyInto(ret); - Logger.debug("ExtendedSAML Attributes: " + ret.length); - return ret; - - } - - /** - * Adds the AUTH block related SAML attributes to the validation result. - * This is needed always before the AUTH block is to be signed, because the - * name of the mandator has to be set - * - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - * @throws TransformerException - */ - private static ExtendedSAMLAttribute[] addExtendedSamlAttributesOID( - MISMandate mandate, boolean business) throws SAXException, - IOException, ParserConfigurationException, TransformerException { - - Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>(); - - extendedSamlAttributes.clear(); - - // RepresentationType - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_REPRESENTATIONTYPE, - EXT_SAML_MANDATE_REPRESENTATIONTEXT, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); - - String oid = mandate.getProfRep(); - - if (oid != null) { - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_OID, oid, - SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); - String oidDescription = mandate.getTextualDescriptionOfOID(); - extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( - EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION, - oidDescription, SZRGWConstants.MANDATE_NS, - ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); - - } - - ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes - .size()]; - extendedSamlAttributes.copyInto(ret); - Logger.debug("ExtendedSAML Attributes: " + ret.length); - return ret; - - } - - /** - * - * @param mandate - * @return - * @throws ParserConfigurationException - * @throws IOException - * @throws SAXException - */ - private static Element mandateToElement(MISMandate mandate) - throws SAXException, IOException, ParserConfigurationException { - ByteArrayInputStream bais = new ByteArrayInputStream(mandate - .getMandate()); - Document doc = DOMUtils.parseDocumentSimple(bais); - return doc.getDocumentElement(); - } - - protected static void replaceExtendedSAMLAttribute(List<ExtendedSAMLAttribute> attributes, - ExtendedSAMLAttribute samlAttribute) { - if (null == attributes) { - attributes = new Vector<ExtendedSAMLAttribute>(); - } else { - String id = samlAttribute.getName(); - int length = attributes.size(); - for (int i = 0; i < length; i++) { - ExtendedSAMLAttribute att = (ExtendedSAMLAttribute) attributes - .get(i); - if (id.equals(att.getName())) { - // replace attribute - attributes.set(i, samlAttribute); - return; - } - } - attributes.add(samlAttribute); - } - } - - /** - * Processes a <code><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses <code><CreateXMLSignatureResponse></code> for error - * codes</li> - * <li>Parses authentication block enclosed in - * <code><CreateXMLSignatureResponse></code></li> - * <li>Verifies authentication block by calling the MOA SP component</li> - * <li>Creates authentication data</li> - * <li>Creates a corresponding SAML artifact</li> - * <li>Stores authentication data in the authentication data store indexed - * by the SAML artifact</li> - * <li>Deletes authentication session</li> - * <li>Returns the SAML artifact, encoded BASE64</li> - * </ul> - * - * @param sessionID - * session ID of the running authentication session - * @param xmlCreateXMLSignatureReadResponse - * String representation of the - * <code><CreateXMLSignatureResponse></code> - * @return SAML artifact needed for retrieving authentication data, encoded - * BASE64 - * @throws BKUException - */ - public String verifyAuthenticationBlock(AuthenticationSession session, - String xmlCreateXMLSignatureReadResponse) - throws AuthenticationException, BuildException, ParseException, - ConfigurationException, ServiceException, ValidateException, BKUException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID }); - if (isEmpty(xmlCreateXMLSignatureReadResponse)) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); - - AuthConfigurationProvider authConf = AuthConfigurationProvider - .getInstance(); - // parses <CreateXMLSignatureResponse> - CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser( - xmlCreateXMLSignatureReadResponse).parseResponse(); - - try { - String serializedAssertion = DOMUtils.serializeNode(csresp - .getSamlAssertion()); - session.setAuthBlock(serializedAssertion); - } catch (TransformerException e) { - throw new ParseException("parser.04", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); - } catch (IOException e) { - throw new ParseException("parser.04", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE }); - } - // validates <CreateXMLSignatureResponse> - if (session.isSsoRequested()) - new CreateXMLSignatureResponseValidator().validateSSO(csresp, session); - else - new CreateXMLSignatureResponseValidator().validate(csresp, session); - - // builds a <VerifyXMLSignatureRequest> for a MOA-SPSS call - List<String> vtids = authConf.getMoaSpAuthBlockVerifyTransformsInfoIDs(); - String tpid = authConf.getMoaSpAuthBlockTrustProfileID(); - Element domVsreq = new VerifyXMLSignatureRequestBuilder().build(csresp, - vtids, tpid); - // debug output - - // invokes the call - Element domVsresp = new SignatureVerificationInvoker() - .verifyXMLSignature(domVsreq); - // debug output - - // parses the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponseParser( - domVsresp).parseData(); - - if (Logger.isTraceEnabled()) { - if (domVsresp != null) { - try { - String xmlVerifyXMLSignatureResponse = DOMUtils - .serializeNode(domVsresp, true); - Logger.trace(new LogMsg(xmlCreateXMLSignatureReadResponse)); - Logger.trace(new LogMsg(xmlVerifyXMLSignatureResponse)); - } catch (Throwable t) { - t.printStackTrace(); - Logger.info(new LogMsg(t.getStackTrace())); - } - } - } - - // validates the <VerifyXMLSignatureResponse> - VerifyXMLSignatureResponseValidator.getInstance().validate(vsresp, - null, VerifyXMLSignatureResponseValidator.CHECK_AUTH_BLOCK, - false); - - // Compare AuthBlock Data with information stored in session, especially - // date and time - CreateXMLSignatureResponseValidator.getInstance().validateSigningDateTime(csresp); - - // compares the public keys from the identityLink with the AuthBlock - VerifyXMLSignatureResponseValidator.getInstance().validateCertificate( - vsresp, session.getIdentityLink()); - - // post processing of the infoboxes - Iterator iter = session.getInfoboxValidatorIterator(); - boolean formpending = false; - if (iter != null) { - while (!formpending && iter.hasNext()) { - Vector infoboxValidatorVector = (Vector) iter.next(); - String identifier = (String) infoboxValidatorVector.get(0); - String friendlyName = (String) infoboxValidatorVector.get(1); - InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector - .get(2); - InfoboxValidationResult infoboxValidationResult = null; - try { - infoboxValidationResult = infoboxvalidator.validate(csresp - .getSamlAssertion()); - } catch (ValidateException e) { - Logger.error("Error validating " + identifier + " infobox:" - + e.getMessage()); - throw new ValidateException("validator.44", - new Object[] { friendlyName }); - } - if (!infoboxValidationResult.isValid()) { - Logger.info("Validation of " + identifier - + " infobox failed."); - throw new ValidateException("validator.40", new Object[] { - friendlyName, - infoboxValidationResult.getErrorMessage() }); - } - String form = infoboxvalidator.getForm(); - if (ParepUtils.isEmpty(form)) { - AddAdditionalSAMLAttributes( - session, - infoboxValidationResult.getExtendedSamlAttributes(), - identifier, friendlyName); - } else { - return "Redirect to Input Processor"; - } - } - } - - session.setXMLVerifySignatureResponse(vsresp); - session.setSignerCertificate(vsresp.getX509certificate()); - vsresp.setX509certificate(null); - session.setForeigner(false); - - if (session.getUseMandate()) { - // mandate mode - return null; - - } else { - - session.setAuthenticatedUsed(false); - session.setAuthenticated(true); - - //set QAA Level four in case of card authentifcation - session.setQAALevel(PVPConstants.STORK_QAA_1_4); - - - String oldsessionID = session.getSessionID(); - - //Session is implicte stored in changeSessionID!!! - String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); - - Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); - Logger.info("Daten angelegt zu MOASession " + newMOASessionID); - - return newMOASessionID; - } - } - - /** - * Processes a <code><CreateXMLSignatureResponse></code> sent by the - * security layer implementation.<br> - * <ul> - * <li>Validates given <code><CreateXMLSignatureResponse></code></li> - * <li>Parses <code><CreateXMLSignatureResponse></code> for error - * codes</li> - * <li>Parses authentication block enclosed in - * <code><CreateXMLSignatureResponse></code></li> - * <li>Verifies authentication block by calling the MOA SP component</li> - * <li>Creates authentication data</li> - * <li>Creates a corresponding SAML artifact</li> - * <li>Stores authentication data in the authentication data store indexed - * by the SAML artifact</li> - * <li>Deletes authentication session</li> - * <li>Returns the SAML artifact, encoded BASE64</li> - * </ul> - * - * @param sessionID - * session ID of the running authentication session - * @param xmlCreateXMLSignatureReadResponse - * String representation of the - * <code><CreateXMLSignatureResponse></code> - * @return SAML artifact needed for retrieving authentication data, encoded - * BASE64 - */ - - protected Element createIdentificationBPK(Element mandatePerson, - String baseid, String target) throws BuildException { - Element identificationBpK = mandatePerson.getOwnerDocument() - .createElementNS(Constants.PD_NS_URI, "Identification"); - Element valueBpK = mandatePerson.getOwnerDocument().createElementNS( - Constants.PD_NS_URI, "Value"); - - String bpkBase64 = new BPKBuilder().buildBPK(baseid, target); - valueBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( - bpkBase64)); - Element typeBpK = mandatePerson.getOwnerDocument().createElementNS( - Constants.PD_NS_URI, "Type"); - typeBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( - "urn:publicid:gv.at:cdid+bpk")); - identificationBpK.appendChild(valueBpK); - identificationBpK.appendChild(typeBpK); - - return identificationBpK; - - } - - protected String getBaseId(Element mandatePerson) - throws TransformerException, IOException { - NodeList list = mandatePerson.getElementsByTagNameNS( - Constants.PD_NS_URI, "Identification"); - for (int i = 0; i < list.getLength(); i++) { - Element identification = (Element) list.item(i); - Element type = (Element) identification.getElementsByTagNameNS( - Constants.PD_NS_URI, "Type").item(0); - if (type.getTextContent().compareToIgnoreCase( - "urn:publicid:gv.at:baseid") == 0) { - Element value = (Element) identification - .getElementsByTagNameNS(Constants.PD_NS_URI, "Value") - .item(0); - return value.getTextContent(); - } - } - return null; - - } - - /** - * Gets the foreign authentication data.<br> - * <ul> - * <li>Creates authentication data</li> - * <li>Creates a corresponding SAML artifact</li> - * <li>Stores authentication data in the authentication data store indexed - * by the SAML artifact</li> - * <li>Deletes authentication session</li> - * <li>Returns the SAML artifact, encoded BASE64</li> - * </ul> - * - * @param sessionID - * session ID of the running authentication session - * @return SAML artifact needed for retrieving authentication data, encoded - * BASE64 - */ - public String getForeignAuthenticationData(AuthenticationSession session) - throws AuthenticationException, BuildException, ParseException, - ConfigurationException, ServiceException, ValidateException { - - if (session == null) - throw new AuthenticationException("auth.10", new Object[] { - REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID }); - - // post processing of the infoboxes - Iterator iter = session.getInfoboxValidatorIterator(); - boolean formpending = false; - if (iter != null) { - while (!formpending && iter.hasNext()) { - Vector infoboxValidatorVector = (Vector) iter.next(); - String identifier = (String) infoboxValidatorVector.get(0); - String friendlyName = (String) infoboxValidatorVector.get(1); - InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector - .get(2); - InfoboxValidationResult infoboxValidationResult = null; - try { - infoboxValidationResult = infoboxvalidator.validate(session - .getIdentityLink().getSamlAssertion()); - } catch (ValidateException e) { - Logger.error("Error validating " + identifier + " infobox:" - + e.getMessage()); - throw new ValidateException("validator.44", - new Object[] { friendlyName }); - } - if (!infoboxValidationResult.isValid()) { - Logger.info("Validation of " + identifier - + " infobox failed."); - throw new ValidateException("validator.40", new Object[] { - friendlyName, - infoboxValidationResult.getErrorMessage() }); - } - String form = infoboxvalidator.getForm(); - if (ParepUtils.isEmpty(form)) { - AddAdditionalSAMLAttributes( - session, - infoboxValidationResult.getExtendedSamlAttributes(), - identifier, friendlyName); - } else { - return "Redirect to Input Processor"; - } - } - } - - VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponse(); - X509Certificate cert = session.getSignerCertificate(); - vsresp.setX509certificate(cert); - - session.setAuthenticatedUsed(false); - session.setAuthenticated(true); - - - session.setXMLVerifySignatureResponse(vsresp); - session.setSignerCertificate(vsresp.getX509certificate()); - vsresp.setX509certificate(null); - session.setForeigner(true); - - //TODO: regenerate MOASession ID! - return "new Session"; - } - - /** - * Builds the AuthenticationData object together with the corresponding - * <code><saml:Assertion></code> - * - * @param session - * authentication session - * @param verifyXMLSigResp - * VerifyXMLSignatureResponse from MOA-SP - * @param useUTC uses correct UTC time format - * @param useUTC indicates that authenticated citizen is a foreigner - * @param isForeigner indicates whether Austrian (false) or foreigner (true) authenticates - * @return AuthenticationData object - * @throws ConfigurationException - * while accessing configuration data - * @throws BuildException - * while building the <code><saml:Assertion></code> - */ - public static AuthenticationData buildAuthenticationData( - AuthenticationSession session, OAAuthParameter oaParam, String target) - throws ConfigurationException, BuildException { - - IdentityLink identityLink = session.getIdentityLink(); - AuthenticationData authData = new AuthenticationData(); - - VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); - - boolean businessService = oaParam.getBusinessService(); - - authData.setMajorVersion(1); - authData.setMinorVersion(0); - authData.setAssertionID(Random.nextRandom()); - authData.setIssuer(session.getAuthURL()); - - authData.setIssueInstant(DateTimeUtils.buildDateTimeUTC(Calendar - .getInstance())); - - //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO - authData.setIdentificationValue(identityLink.getIdentificationValue()); - authData.setIdentificationType(identityLink.getIdentificationType()); - - authData.setGivenName(identityLink.getGivenName()); - authData.setFamilyName(identityLink.getFamilyName()); - authData.setDateOfBirth(identityLink.getDateOfBirth()); - authData.setQualifiedCertificate(verifyXMLSigResp - .isQualifiedCertificate()); - authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); - authData.setPublicAuthorityCode(verifyXMLSigResp - .getPublicAuthorityCode()); - authData.setBkuURL(session.getBkuURL()); - - try { - - if (session.getUseMandate() && session.isOW()) { - MISMandate mandate = session.getMISMandate(); - authData.setBPK(mandate.getOWbPK()); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); - authData.setIdentityLink(identityLink); - - Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); - - } else { - - if (businessService) { - //since we have foreigner, wbPK is not calculated in BKU - if(identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - - String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); - - if (registerAndOrdNr.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) { - // If domainIdentifier starts with prefix - // "urn:publicid:gv.at:wbpk+"; remove this prefix - registerAndOrdNr = registerAndOrdNr - .substring(AuthenticationSession.REGISTERANDORDNR_PREFIX_.length()); - Logger.debug("Register and ordernumber prefix stripped off; resulting register string: " - + registerAndOrdNr); - } - - String wbpkBase64 = new BPKBuilder().buildWBPK(identityLink.getIdentificationValue(), registerAndOrdNr); - authData.setBPK(wbpkBase64); - authData.setBPKType( Constants.URN_PREFIX_WBPK + "+" + registerAndOrdNr); - - } else { - authData.setBPK(identityLink.getIdentificationValue()); - authData.setBPKType(identityLink.getIdentificationType()); - - } - - Logger.trace("Authenticate user with wbPK " + authData.getBPK()); - - Element idlassertion = session.getIdentityLink().getSamlAssertion(); - //set bpk/wpbk; - Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); - prIdentification.getFirstChild().setNodeValue(authData.getBPK()); - //set bkp/wpbk type - Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); - prIdentificationType.getFirstChild().setNodeValue(authData.getBPKType()); - - IdentityLinkAssertionParser idlparser = new IdentityLinkAssertionParser(idlassertion); - IdentityLink idl = idlparser.parseIdentityLink(); - authData.setIdentityLink(idl); - - } else { - - if(identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { - // only compute bPK if online application is a public service and we have the Stammzahl - String bpkBase64 = new BPKBuilder().buildBPK(identityLink.getIdentificationValue(), target); - authData.setBPK(bpkBase64); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget()); - } - - Logger.trace("Authenticate user with bPK " + authData.getBPK()); - - authData.setIdentityLink(identityLink); - } - } - - return authData; - - } catch (Throwable ex) { - throw new BuildException("builder.00", new Object[] { - "AuthenticationData", ex.toString() }, ex); - } - } - - /** - * Retrieves a session from the session store. - * - * @param id - * session ID - * @return <code>AuthenticationSession</code> stored with given session ID, - * <code>null</code> if session ID unknown - */ - public static AuthenticationSession getSession(String id) - throws AuthenticationException { - - AuthenticationSession session; - try { - session = AuthenticationSessionStoreage.getSession(id); - - if (session == null) - throw new AuthenticationException("auth.02", new Object[] { id }); - return session; - - } catch (MOADatabaseException e) { - throw new AuthenticationException("parser.04", new Object[] { id }); - } - } - - /** - * Cleans up expired session and authentication data stores. - */ - public void cleanup() { - long now = new Date().getTime(); - - //clean AuthenticationSessionStore - - AuthenticationSessionStoreage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); - - //clean AssertionStore - AssertionStorage assertionstore = AssertionStorage.getInstance(); - assertionstore.clean(now, authDataTimeOut); - - //clean ExeptionStore - DBExceptionStoreImpl exstore = DBExceptionStoreImpl.getStore(); - exstore.clean(now, authDataTimeOut); - - } - - /** - * Sets the sessionTimeOut. - * - * @param seconds - * Time out of the session in seconds - */ - public void setSecondsSessionTimeOutCreated(long seconds) { - sessionTimeOutCreated = seconds * 1000; - } - - public void setSecondsSessionTimeOutUpdated(long seconds) { - sessionTimeOutUpdated = seconds * 1000; - } - - /** - * Sets the authDataTimeOut. - * - * @param seconds - * Time out for signing AuthData in seconds - */ - public void setSecondsAuthDataTimeOut(long seconds) { - authDataTimeOut = seconds * 1000; - } - - /** - * Checks a parameter. - * - * @param param - * parameter - * @return true if the parameter is null or empty - */ - private boolean isEmpty(String param) { - return param == null || param.length() == 0; - } - - /** - * Checks the correctness of SAML attributes and returns its value. - * - * @param param - * samlAttribute - * @param i - * the number of the verified attribute for messages - * @param identifier - * the infobox identifier for messages - * @param friendlyname - * the friendly name of the infobox for messages - * @return the SAML attribute value (Element or String) - */ - protected static Object verifySAMLAttribute( - ExtendedSAMLAttribute samlAttribute, int i, String identifier, - String friendlyName) throws ValidateException { - String name = samlAttribute.getName(); - - if (name == null) { - Logger.info("The name of SAML-Attribute number " + (i + 1) - + " returned from " + identifier - + "-infobox validator is null."); - throw new ValidateException("validator.45", new Object[] { - friendlyName, "Name", String.valueOf((i + 1)), "null" }); - } - if (name == "") { - Logger.info("The name of SAML-Attribute number " + (i + 1) - + " returned from " + identifier - + "-infobox validator is empty."); - throw new ValidateException("validator.45", new Object[] { - friendlyName, "Name", String.valueOf((i + 1)), "leer" }); - } - if (samlAttribute.getNameSpace() == null) { - Logger.info("The namespace of SAML-Attribute number " + (i + 1) - + " returned from " + identifier - + "-infobox validator is null."); - throw new ValidateException("validator.45", - new Object[] { friendlyName, "Namespace", - String.valueOf((i + 1)), "null" }); - } - Object value = samlAttribute.getValue(); - if (value == null) { - Logger.info("The value of SAML-Attribute number " + (i + 1) - + " returned from " + identifier - + "-infobox validator is null."); - throw new ValidateException("validator.45", new Object[] { - friendlyName, "Wert", String.valueOf((i + 1)), "null" }); - } - - return value; - } - - /** - * Does the request to the SZR-GW - * @param oaFriendlyName - * @param signature XMLDSIG signature - * @return Identity link assertion - * @throws SZRGWClientException - */ - - public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String gender, String citizenSignature, String represented, String representative, String mandateContent, String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { - - try { - AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); - ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); - - SZRGWClient client = new SZRGWClient(connectionParameters); - - - CreateIdentityLinkRequest request = new CreateIdentityLinkRequest(); - request.setSignature(citizenSignature.getBytes()); - - PEPSData data = new PEPSData(); - data.setDateOfBirth(PEPSDateOfBirth); - data.setFamilyname(PEPSFamilyname); - data.setFirstname(PEPSFirstname); - data.setIdentifier(PEPSIdentifier); - - data.setRepresentative(representative); - data.setRepresented(represented); - data.setMandateContent(mandateContent); - - data.setLegalPersonCanonicalRegisteredAddress(organizationAddress); - data.setLegalPersonTranslatableType(organizationType); - - if(null != mandateContent) { - MISType mis = new MISType(); - - Target targetObject = new Target(); - targetObject.setType(targetType); - targetObject.setValue(targetValue); - mis.setTarget(targetObject); - - mis.setOAFriendlyName(oaFriendlyName); - - Filters filterObject = new Filters(); - MandateIdentifiers mandateIds = new MandateIdentifiers(); - for(String current : filters.split(",")) - mandateIds.getMandateIdentifier().add(current.trim()); - filterObject.setMandateIdentifiers(mandateIds); - mis.setFilters(filterObject); - - request.setMIS(mis); - } - - Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); - CreateIdentityLinkResponse response = client.sentCreateIDLRequest(request , connectionParameters.getUrl()); - return response; - - } - catch (ConfigurationException e) { - Logger.warn(e); - Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null )); - } - - return null; - - } - - /** - * Does the request to the SZR-GW. - * - * @param signature the signature - * @return the identity link - * @throws SZRGWClientException the sZRGW client exception - * @throws ConfigurationException the configuration exception - */ - public CreateIdentityLinkResponse getIdentityLink(Element signature) throws SZRGWClientException, ConfigurationException { - return getIdentityLink(null, null, null, null, XMLHelper.nodeToString(signature)); - } - - /** - * Does the request to the SZR-GW. - * - * @param PEPSIdentifier the pEPS identifier - * @param PEPSFirstname the pEPS firstname - * @param PEPSFamilyname the pEPS familyname - * @param PEPSDateOfBirth the pEPS date of birth - * @param signature XMLDSIG signature - * @return Identity link assertion - * @throws SZRGWClientException the sZRGW client exception - * @throws ConfigurationException the configuration exception - */ - public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String signature) throws SZRGWClientException { - return getIdentityLink(PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, null, signature, null, null, null, null, null, null, null); - } - - /** - * Gets the identity link. - * - * @param citizenSignature the citizen signature - * @param representative the representative - * @param represented the represented - * @param mandate the mandate - * @param organizationAddress the organization address - * @param organizationType the organization type - * @return the identity link - * @throws SZRGWClientException - */ - public CreateIdentityLinkResponse getIdentityLink(String citizenSignature, - String representative, String represented, String mandateContent, - String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { - return getIdentityLink(null, null, null, null, null, - citizenSignature, represented, representative, mandateContent, organizationAddress, - organizationType, targetType, targetValue, oaFriendlyName, filters); - } - - /** - * SZR-GW Client interface. - * - * @param eIdentifier the e identifier - * @param givenName the given name - * @param lastName the last name - * @param dateOfBirth the date of birth - * @param citizenSignature the citizen signature - * @param representative the representative - * @param represented the represented - * @param mandate the mandate - * @return the identity link - * @throws SZRGWClientException the sZRGW client exception - */ - public CreateIdentityLinkResponse getIdentityLink(String eIdentifier, - String givenName, String lastName, String dateOfBirth, String gender, - String citizenSignature, String representative, String represented, - String mandate, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { - return getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, gender, - citizenSignature, representative, represented, mandate, null, - null, targetType, targetValue, oaFriendlyName, filters); - } - - /** - * Starts a MOA-ID authentication process using STORK - * @param req HttpServletRequest - * @param resp HttpServletResponse - * @param ccc Citizen country code - * @param oaURL URL of the online application - * @param target Target parameter - * @param targetFriendlyName Friendly Name of Target - * @param authURL Authentication URL - * @param sourceID SourceID parameter - * @throws MOAIDException - * @throws AuthenticationException - * @throws WrongParametersException - * @throws ConfigurationException - */ - public static void startSTORKAuthentication( - HttpServletRequest req, - HttpServletResponse resp, - AuthenticationSession moasession) throws MOAIDException, AuthenticationException, WrongParametersException, ConfigurationException { - - if (moasession == null) { - throw new AuthenticationException("auth.18", new Object[] { }); - } - - //read configuration paramters of OA - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); - if (oaParam == null) - throw new AuthenticationException("auth.00", new Object[] { moasession.getPublicOAURLPrefix() }); - - //Start of STORK Processing - STORKConfig storkConfig = AuthConfigurationProvider.getInstance().getStorkConfig(); - - CPEPS cpeps = storkConfig.getCPEPS(moasession.getCcc()); - - Logger.debug("Preparing to assemble STORK AuthnRequest with the following values:"); - String destination = cpeps.getPepsURL().toExternalForm(); - Logger.debug("C-PEPS URL: " + destination); - - String acsURL = HTTPUtils.getBaseURL(req) + PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; - Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL); - - String providerName= oaParam.getFriendlyName(); - String issuerValue = HTTPUtils.getBaseURL(req); - Logger.debug("Issuer value: " + issuerValue); - - // prepare collection of required attributes - // - attributes for online application - List<OAStorkAttribute> attributesFromConfig = oaParam.getRequestedAttributes(); - - // - prepare attribute list - PersonalAttributeList attributeList = new PersonalAttributeList(); - - // - fill container - for(OAStorkAttribute current : attributesFromConfig) { - PersonalAttribute newAttribute = new PersonalAttribute(); - newAttribute.setName(current.getName()); - - boolean globallyMandatory = false; - for(StorkAttribute currentGlobalAttribute : storkConfig.getStorkAttributes()) - if(current.getName().equals(currentGlobalAttribute.getName())) { - globallyMandatory = currentGlobalAttribute.isMandatory(); - break; - } - - newAttribute.setIsRequired(current.isMandatory() || globallyMandatory); - attributeList.add(newAttribute); - } - - // add sign request - PersonalAttribute newAttribute = new PersonalAttribute(); - newAttribute.setName("signedDoc"); - List<String> value = new ArrayList<String>(); - value.add(generateDssSignRequest(CreateXMLSignatureRequestBuilder.buildForeignIDTextToBeSigned("wie im Signaturzertifikat (as in my signature certificate)", oaParam, moasession), - "application/xhtml+xml", - moasession.getCcc())); - newAttribute.setValue(value); - attributeList.add(newAttribute); - - - if (Logger.isDebugEnabled()) { - Logger.debug("The following attributes are requested for this OA:"); - for (OAStorkAttribute logReqAttr : attributesFromConfig) - Logger.debug("OA specific requested attribute: " + logReqAttr.getName() + ", isRequired: " + logReqAttr.isMandatory()); - } - - //TODO: check Target in case of SSO!! - String spSector = StringUtils.isEmpty(moasession.getTarget()) ? "Business" : moasession.getTarget(); - String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName(); - String spApplication = spInstitution; - String spCountry = "AT"; - - //generate AuthnRquest - STORKAuthnRequest authnRequest = new STORKAuthnRequest(); - authnRequest.setDestination(destination); - authnRequest.setAssertionConsumerServiceURL(acsURL); - authnRequest.setProviderName(providerName); - authnRequest.setIssuer(issuerValue); - authnRequest.setQaa(oaParam.getQaaLevel()); - authnRequest.setSpInstitution(spInstitution); - authnRequest.setCountry(spCountry); - authnRequest.setSpApplication(spApplication); - authnRequest.setSpSector(spSector); - authnRequest.setPersonalAttributeList(attributeList); - - authnRequest.setEIDCrossBorderShare(true); - authnRequest.setEIDCrossSectorShare(true); - authnRequest.setEIDSectorShare(true); - - authnRequest.setCitizenCountryCode(moasession.getCcc()); - - - Logger.debug("STORK AuthnRequest succesfully assembled."); - - STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("outgoing"); - try { - authnRequest = samlEngine.generateSTORKAuthnRequest(authnRequest); - } catch (STORKSAMLEngineException e) { - Logger.error("Could not sign STORK SAML AuthnRequest.", e); - throw new MOAIDException("stork.00", null); - } - - Logger.info("STORK AuthnRequest successfully signed!"); - - //validate AuthnRequest - try { - samlEngine.validateSTORKAuthnRequest(authnRequest.getTokenSaml()); - } catch (STORKSAMLEngineException e) { - Logger.error("STORK SAML AuthnRequest not valid.", e); - throw new MOAIDException("stork.01", null); - } - - Logger.debug("STORK AuthnRequest successfully internally validated."); - - //send - moasession.setStorkAuthnRequest(authnRequest); - HttpSession httpSession = req.getSession(); - httpSession.setAttribute("MOA-Session-ID", moasession.getSessionID()); - - - Logger.info("Preparing to send STORK AuthnRequest."); - Logger.info("prepared STORKAuthnRequest: "); - Logger.info(new String(authnRequest.getTokenSaml())); - - try { - Logger.trace("Initialize VelocityEngine..."); - - VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); - Template template = velocityEngine.getTemplate("/resources/templates/saml2-post-binding-moa.vm"); - VelocityContext context = new VelocityContext(); - context.put("SAMLRequest", PEPSUtil.encodeSAMLToken(authnRequest.getTokenSaml())); - context.put("action", destination); - - StringWriter writer = new StringWriter(); - template.merge(context, writer); - - resp.getOutputStream().write(writer.toString().getBytes()); - } catch (Exception e) { - Logger.error("Error sending STORK SAML AuthnRequest.", e); - httpSession.invalidate(); - throw new MOAIDException("stork.02", new Object[] { destination }); - } - - Logger.info("STORK AuthnRequest successfully successfully prepared for client with target location: " + authnRequest.getDestination()); - } - - private static String generateDssSignRequest(String text, String mimeType, String citizenCountry) { - IdentifierGenerator idGenerator; - try { - idGenerator = new SecureRandomIdentifierGenerator(); - - DocumentType doc = new DocumentType(); - doc.setBase64XML(text.getBytes()); - doc.setID(idGenerator.generateIdentifier()); - - SignRequest request = new SignRequest(); - request.setInputDocuments(ApiUtils.createInputDocuments(doc)); - - String id = idGenerator.generateIdentifier(); - request.setRequestID(id); - request.setDocUI(id); - - request.setProfile(Profiles.XADES_BES.toString()); - request.setNumberOfSigners(BigInteger.ONE); - request.setTargetCountry(citizenCountry); - - // no, no todo. PEPS will alter this value anyhow. - request.setReturnURL("http://invalid_return"); - - AnyType required = new AnyType(); - required.getAny().add(ApiUtils.createSignatureType(SignatureTypes.XMLSIG_RFC3275.toString())); - required.getAny().add(ApiUtils.createAdditionalProfile(AdditionalProfiles.XADES.toString())); - required.getAny().add(ApiUtils.createQualityRequirements(QualityLevels.QUALITYLEVEL_QUALIFIEDSIG)); - required.getAny().add(ApiUtils.createIncludeObject(doc)); - request.setOptionalInputs(required); - - return IOUtils.toString(ApiUtils.marshalToInputStream(request)); - } catch (NoSuchAlgorithmException e) { - Logger.error("Cannot generate id", e); - throw new RuntimeException(e); - } catch (ApiUtilsException e) { - Logger.error("Could not create SignRequest", e); - throw new RuntimeException(e); - } catch (DOMException e) { - Logger.error("Could not create SignRequest", e); - throw new RuntimeException(e); - } catch (IOException e) { - Logger.error("Could not create SignRequest", e); - throw new RuntimeException(e); - } - } - - /** - * Extracts an X509 Certificate out of an XML signagture element - * @param signedXML XML signature element - * @return X509Certificate - * @throws CertificateException - */ - public static X509Certificate getCertificateFromXML(Element signedXML) throws CertificateException { - - NodeList nList = signedXML.getElementsByTagNameNS(Constants.DSIG_NS_URI, "X509Certificate"); - - String base64CertString = XMLUtil.getFirstTextValueFromNodeList(nList); - - if (StringUtils.isEmpty(base64CertString)) { - String msg = "XML does not contain a X509Certificate element."; - Logger.error(msg); - throw new CertificateException(msg); - } - - InputStream is = new ByteArrayInputStream(Base64.decode(base64CertString)); - - X509Certificate cert; - try { - cert = new X509Certificate(is); - return cert; - - } catch (Throwable e) { - throw new CertificateException(e); - } - } + //build CertInfo request + String certInfoRequest = new CertInfoVerifyXMLSignatureRequestBuilder() + .build(); + String certInfoDataURL = new DataURLBuilder() + .buildDataURL(session.getAuthURL(), REQ_START_AUTHENTICATION, + session.getSessionID()); + + //get Applet Parameters + String appletwidth = req.getParameter(PARAM_APPLET_WIDTH); + String appletheigth = req.getParameter(PARAM_APPLET_HEIGTH); + appletheigth = StringEscapeUtils.escapeHtml(appletheigth); + appletwidth = StringEscapeUtils.escapeHtml(appletwidth); + + String htmlForm = new GetIdentityLinkFormBuilder().build(template, + session.getBkuURL(), infoboxReadRequest, dataURL, certInfoRequest, + certInfoDataURL, pushInfobox, oaParam, appletheigth, appletwidth); + + return htmlForm; + } + + /** + * Processes an <code><InfoboxReadResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><InfoboxReadResponse></code></li> + * <li>Parses identity link enclosed in + * <code><InfoboxReadResponse></code></li> + * <li>Verifies identity link by calling the MOA SP component</li> + * <li>Checks certificate authority of identity link</li> + * <li>Stores identity link in the session</li> + * <li>Verifies all additional infoboxes returned from the BKU</li> + * <li>Creates an authentication block to be signed by the user</li> + * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> + * containg the authentication block, meant to be returned to the security + * layer implementation</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param infoboxReadResponseParameters The parameters from the response returned from the BKU + * including the <code><InfoboxReadResponse></code> + * @return String representation of the + * <code><CreateXMLSignatureRequest></code> + * @throws BKUException + */ + public String verifyIdentityLink(AuthenticationSession session, + Map<String, String> infoboxReadResponseParameters) throws AuthenticationException, + BuildException, ParseException, ConfigurationException, + ValidateException, ServiceException, BKUException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_IDENTITY_LINK, PARAM_SESSIONID}); + + String xmlInfoboxReadResponse = (String) infoboxReadResponseParameters + .get(PARAM_XMLRESPONSE); + + if (isEmpty(xmlInfoboxReadResponse)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_IDENTITY_LINK, PARAM_XMLRESPONSE}); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + + // check if an identity link was found + // Errorcode 2911 von Trustdesk BKU (nicht spezifikationskonform + // (SL1.2)) + // CharSequence se = "ErrorCode>2911".substring(0); + // boolean b = xmlInfoboxReadResponse.contains(se); + String se = "ErrorCode>2911"; + int b = xmlInfoboxReadResponse.indexOf(se); + if (b != -1) { // no identity link found + Logger + .info("Es konnte keine Personenbindung auf der Karte gefunden werden. Versuche Anmeldung als auslaendische eID."); + return null; + } + // spezifikationsgemaess (SL1.2) Errorcode + se = "ErrorCode>4002"; + // b = xmlInfoboxReadResponse.contains(se); + b = xmlInfoboxReadResponse.indexOf(se); + if (b != -1) { // Unbekannter Infoboxbezeichner + Logger + .info("Unbekannter Infoboxbezeichner. Versuche Anmeldung als auslaendische eID."); + return null; + } + + // parses the <InfoboxReadResponse> + IdentityLink identityLink = new InfoboxReadResponseParser( + xmlInfoboxReadResponse).parseIdentityLink(); + // validates the identity link + IdentityLinkValidator.getInstance().validate(identityLink); + // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP + Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() + .build(identityLink, authConf + .getMoaSpIdentityLinkTrustProfileID()); + + // invokes the call + Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() + .verifyXMLSignature(domVerifyXMLSignatureRequest); + // parses the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( + domVerifyXMLSignatureResponse).parseData(); + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + // if OA is type is business service the manifest validation result has + // to be ignored + boolean ignoreManifestValidationResult = (oaParam.getBusinessService() || oaParam.getStorkService()) ? true + : false; + + // validates the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponseValidator.getInstance().validate( + verifyXMLSignatureResponse, + authConf.getIdentityLinkX509SubjectNames(), + VerifyXMLSignatureResponseValidator.CHECK_IDENTITY_LINK, + ignoreManifestValidationResult); + + session.setIdentityLink(identityLink); + // now validate the extended infoboxes + + //Removed in MOA-ID 2.0 + //verifyInfoboxes(session, infoboxReadResponseParameters, false); + + return "found!"; + } + + /** + * Processes an <code><InfoboxReadResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><InfoboxReadResponse></code></li> + * <li>Parses identity link enclosed in + * <code><InfoboxReadResponse></code></li> + * <li>Verifies identity link by calling the MOA SP component</li> + * <li>Checks certificate authority of identity link</li> + * <li>Stores identity link in the session</li> + * <li>Verifies all additional infoboxes returned from the BKU</li> + * <li>Creates an authentication block to be signed by the user</li> + * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> + * containg the authentication block, meant to be returned to the security + * layer implementation</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param infoboxReadResponseParameters The parameters from the response returned from the BKU + * including the <code><InfoboxReadResponse></code> + * @return String representation of the + * <code><CreateXMLSignatureRequest></code> + */ + public String verifyCertificate(AuthenticationSession session, + X509Certificate certificate) throws AuthenticationException, + BuildException, ParseException, ConfigurationException, + ValidateException, ServiceException, MOAIDException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID}); + + // check if person is a Organwalter + // if true - don't show bPK in AUTH Block + try { + for (ObjectID OWid : MOAIDAuthConstants.OW_LIST) { + if (certificate.getExtension(OWid) != null) { + session.setOW(true); + } + + } + + } catch (X509ExtensionInitException e) { + Logger.warn("Certificate extension is not readable."); + session.setOW(false); + } + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + String returnvalue = getCreateXMLSignatureRequestAuthBlockOrRedirect(session, + authConf, oaParam); + + return returnvalue; + } + + /** + * Processes an <code>Mandate</code> sent by the MIS.<br> + * <ul> + * <li>Validates given <code>Mandate</code></li> + * <li>Verifies Mandate by calling the MOA SP component</li> + * <li>Creates an authentication block to be signed by the user</li> + * <li>Creates and returns a <code><CreateXMLSignatureRequest></code> + * containg the authentication block, meant to be returned to the security + * layer implementation</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param infoboxReadResponseParameters The parameters from the response returned from the BKU + * including the <code><InfoboxReadResponse></code> + * @return String representation of the + * <code><CreateXMLSignatureRequest></code> + */ + public void verifyMandate(AuthenticationSession session, MISMandate mandate) + throws AuthenticationException, BuildException, ParseException, + ConfigurationException, ValidateException, ServiceException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + GET_MIS_SESSIONID, PARAM_SESSIONID}); + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + try { + // sets the extended SAML attributes for OID (Organwalter) + setExtendedSAMLAttributeForMandatesOID(session, mandate, oaParam + .getBusinessService()); + + validateExtendedSAMLAttributeForMandates(session, mandate, oaParam.getBusinessService()); + + + } catch (SAXException e) { + throw new AuthenticationException("auth.16", + new Object[]{GET_MIS_SESSIONID}, e); + } catch (IOException e) { + throw new AuthenticationException("auth.16", + new Object[]{GET_MIS_SESSIONID}, e); + } catch (ParserConfigurationException e) { + throw new AuthenticationException("auth.16", + new Object[]{GET_MIS_SESSIONID}, e); + } catch (TransformerException e) { + throw new AuthenticationException("auth.16", + new Object[]{GET_MIS_SESSIONID}, e); + } + + } + + /** + * @param session + * @param authConf + * @param oaParam + * @return + * @throws ConfigurationException + * @throws BuildException + * @throws ValidateException + */ + public String getCreateXMLSignatureRequestAuthBlockOrRedirect( + AuthenticationSession session, AuthConfigurationProvider authConf, + OAAuthParameter oaParam) throws ConfigurationException, + BuildException, ValidateException { + + // check for intermediate processing of the infoboxes + if (session.isValidatorInputPending()) + return "Redirect to Input Processor"; + + if (authConf == null) + authConf = AuthConfigurationProvider.getInstance(); + if (oaParam == null) + oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + + // builds the AUTH-block + String authBlock = buildAuthenticationBlock(session, oaParam); + + // builds the <CreateXMLSignatureRequest> + List<String> transformsInfos = oaParam.getTransformsInfos(); + if ((transformsInfos == null) || (transformsInfos.size() == 0)) { + // no OA specific transforms specified, use default ones + transformsInfos = authConf.getTransformsInfos(); + } + String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() + .build(authBlock, oaParam.getKeyBoxIdentifier(), + transformsInfos); + return createXMLSignatureRequest; + } + + /** + * Returns an CreateXMLSignatureRequest for signing the ERnP statement.<br> + * <ul> + * <li>Creates an CreateXMLSignatureRequest to be signed by the user</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param cert The certificate from the user + * @return String representation of the + * <code><CreateXMLSignatureRequest></code> + */ + public String createXMLSignatureRequestForeignID(AuthenticationSession session, + X509Certificate cert) throws AuthenticationException, + BuildException, ParseException, ConfigurationException, + ValidateException, ServiceException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID}); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter(session.getPublicOAURLPrefix()); + + return getCreateXMLSignatureRequestForeigID(session, authConf, oaParam, + cert); + } + + public String getCreateXMLSignatureRequestForeigID( + AuthenticationSession session, AuthConfigurationProvider authConf, + OAAuthParameter oaParam, X509Certificate cert) + throws ConfigurationException { + + // check for intermediate processing of the infoboxes + if (session.isValidatorInputPending()) + return "Redirect to Input Processor"; + + if (authConf == null) + authConf = AuthConfigurationProvider.getInstance(); + if (oaParam == null) + oaParam = AuthConfigurationProvider.getInstance() + .getOnlineApplicationParameter( + session.getPublicOAURLPrefix()); + + Principal subject = cert.getSubjectDN(); + + String createXMLSignatureRequest = new CreateXMLSignatureRequestBuilder() + .buildForeignID(subject.toString(), oaParam, session); + return createXMLSignatureRequest; + } + + /** + * Processes an <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses response enclosed in + * <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies signature by calling the MOA SP component</li> + * <li>Returns the signer certificate</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param createXMLSignatureResponseParameters The parameters from the response returned from the BKU + * including the <code><CreateXMLSignatureResponse></code> + * @throws BKUException + */ + public X509Certificate verifyXMLSignature(String sessionID, + Map<String, String> createXMLSignatureResponseParameters) + throws AuthenticationException, BuildException, ParseException, + ConfigurationException, ValidateException, ServiceException, BKUException { + + if (isEmpty(sessionID)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_GET_FOREIGN_ID, PARAM_SESSIONID}); + + String xmlCreateXMLSignatureResponse = (String) createXMLSignatureResponseParameters + .get(PARAM_XMLRESPONSE); + + if (isEmpty(xmlCreateXMLSignatureResponse)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_GET_FOREIGN_ID, PARAM_XMLRESPONSE}); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + + // parses the <CreateXMLSignatureResponse> + CreateXMLSignatureResponseParser p = new CreateXMLSignatureResponseParser( + xmlCreateXMLSignatureResponse); + CreateXMLSignatureResponse createXMLSignatureResponse = p + .parseResponseDsig(); + + // builds a <VerifyXMLSignatureRequest> for a call of MOA-SP + Element domVerifyXMLSignatureRequest = new VerifyXMLSignatureRequestBuilder() + .buildDsig(createXMLSignatureResponse, authConf + .getMoaSpAuthBlockTrustProfileID()); + + // invokes the call + Element domVerifyXMLSignatureResponse = new SignatureVerificationInvoker() + .verifyXMLSignature(domVerifyXMLSignatureRequest); + + // parses the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponse verifyXMLSignatureResponse = new VerifyXMLSignatureResponseParser( + domVerifyXMLSignatureResponse).parseData(); + + return verifyXMLSignatureResponse.getX509certificate(); + + } + + /** + * Processes an <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses response enclosed in + * <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies signature by calling the MOA SP component</li> + * <li>Returns the signer certificate</li> + * </ul> + * + * @param sessionID ID of associated authentication session data + * @param readInfoboxResponseParameters The parameters from the response returned from the BKU + * including the <code><ReadInfoboxResponse></code> + * @throws BKUException + */ + public X509Certificate getCertificate(String sessionID, + Map<String, String> readInfoboxResponseParameters) throws AuthenticationException, + BuildException, ParseException, ConfigurationException, + ValidateException, ServiceException, BKUException { + + if (isEmpty(sessionID)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_CERTIFICATE, PARAM_SESSIONID}); + + String xmlReadInfoboxResponse = (String) readInfoboxResponseParameters + .get(PARAM_XMLRESPONSE); + + if (isEmpty(xmlReadInfoboxResponse)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_CERTIFICATE, PARAM_XMLRESPONSE}); + + // parses the <CreateXMLSignatureResponse> + InfoboxReadResponseParser p = new InfoboxReadResponseParser( + xmlReadInfoboxResponse); + X509Certificate cert = p.parseCertificate(); + + return cert; + + } + + /** + * Builds an authentication block <code><saml:Assertion></code> from + * given session data. + * + * @param session authentication session + * @return <code><saml:Assertion></code> as a String + * @throws BuildException If an error occurs on serializing an extended SAML attribute + * to be appended to the AUTH-Block. + */ + private String buildAuthenticationBlock(AuthenticationSession session, + OAAuthParameter oaParam) throws BuildException { + + IdentityLink identityLink = session.getIdentityLink(); + String issuer = identityLink.getName(); + String gebDat = identityLink.getDateOfBirth(); + + String identificationValue = null; + String identificationType = null; + + //set empty AuthBlock BPK in case of OW or SSO or bpk is not requested + if (session.isOW() || session.isSsoRequested() || oaParam.isRemovePBKFromAuthBlock()) { + identificationType = ""; + identificationValue = ""; + + } else if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + + if (oaParam.getBusinessService()) { + + String bpkBase64 = new BPKBuilder().buildWBPK(identityLink + .getIdentificationValue(), oaParam.getIdentityLinkDomainIdentifier()); + identificationValue = bpkBase64; + + if (oaParam.getIdentityLinkDomainIdentifier().startsWith(Constants.URN_PREFIX_WBPK + "+")) + identificationType = oaParam.getIdentityLinkDomainIdentifier(); + else + identificationType = Constants.URN_PREFIX_WBPK + "+" + oaParam.getIdentityLinkDomainIdentifier(); + + } else { + String bpkBase64 = new BPKBuilder().buildBPK(identityLink + .getIdentificationValue(), session.getTarget()); + identificationValue = bpkBase64; + identificationType = Constants.URN_PREFIX_CDID + "+" + session.getTarget(); + } + + + } else { + identificationValue = identityLink.getIdentificationValue(); + identificationType = identityLink.getIdentificationType(); + + } + + String issueInstant = DateTimeUtils.buildDateTimeUTC(Calendar + .getInstance()); + session.setIssueInstant(issueInstant); + String authURL = session.getAuthURL(); + String target = session.getTarget(); + String targetFriendlyName = session.getTargetFriendlyName(); + + // Bug #485 + // (https://egovlabs.gv.at/tracker/index.php?func=detail&aid=485&group_id=6&atid=105) + // String oaURL = session.getPublicOAURLPrefix(); + + List<ExtendedSAMLAttribute> extendedSAMLAttributes = session.getExtendedSAMLAttributesAUTH(); + + + if (session.isSsoRequested()) { + String oaURL = new String(); + try { + oaURL = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); + + if (MiscUtil.isNotEmpty(oaURL)) + oaURL = oaURL.replaceAll("&", "&"); + + } catch (ConfigurationException e) { + } + String authBlock = new AuthenticationBlockAssertionBuilder() + .buildAuthBlockSSO(issuer, issueInstant, authURL, target, + targetFriendlyName, identificationValue, + identificationType, oaURL, gebDat, + extendedSAMLAttributes, session, oaParam); + return authBlock; + + } else { + String oaURL = session.getPublicOAURLPrefix().replaceAll("&", "&"); + String authBlock = new AuthenticationBlockAssertionBuilder() + .buildAuthBlock(issuer, issueInstant, authURL, target, + targetFriendlyName, identificationValue, + identificationType, oaURL, gebDat, + extendedSAMLAttributes, session, oaParam); + return authBlock; + } + } + + + /** + * Verifies the infoboxes (except of the identity link infobox) returned by + * the BKU by calling appropriate validator classes. + * + * @param session The actual authentication session. + * @param mandate The Mandate from the MIS + * @throws AuthenticationException + * @throws ConfigurationException + * @throws TransformerException + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + */ + private void validateExtendedSAMLAttributeForMandates( + AuthenticationSession session, MISMandate mandate, + boolean business) + throws ValidateException, ConfigurationException, SAXException, + IOException, ParserConfigurationException, TransformerException { + + ExtendedSAMLAttribute[] extendedSAMLAttributes = addExtendedSamlAttributes( + mandate, business, false); + + int length = extendedSAMLAttributes.length; + for (int i = 0; i < length; i++) { + ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i]; + + verifySAMLAttribute(samlAttribute, i, "MISService", + "MISService"); + + } + } + + /** + * Verifies the infoboxes (except of the identity link infobox) returned by + * the BKU by calling appropriate validator classes. + * + * @param session The actual authentication session. + * @param mandate The Mandate from the MIS + * @throws AuthenticationException + * @throws ConfigurationException + * @throws TransformerException + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + */ + private void setExtendedSAMLAttributeForMandatesOID( + AuthenticationSession session, MISMandate mandate, boolean business) + throws ValidateException, ConfigurationException, SAXException, + IOException, ParserConfigurationException, TransformerException { + + ExtendedSAMLAttribute[] extendedSamlAttributes = addExtendedSamlAttributesOID( + mandate, business); + + AddAdditionalSAMLAttributes(session, extendedSamlAttributes, + "MISService", "MISService"); + + } + + /** + * Adds given SAML Attributes to the current session. They will be appended + * to the final SAML Assertion or the AUTH block. If the attributes are + * already in the list, they will be replaced. + * + * @param session The current session + * @param extendedSAMLAttributes The SAML attributes to add + * @param identifier The infobox identifier for debug purposes + * @param friendlyNam The friendly name of the infobox for debug purposes + */ + private static void AddAdditionalSAMLAttributes( + AuthenticationSession session, + ExtendedSAMLAttribute[] extendedSAMLAttributes, String identifier, + String friendlyName) throws ValidateException { + if (extendedSAMLAttributes == null) + return; + List<ExtendedSAMLAttribute> oaAttributes = session.getExtendedSAMLAttributesOA(); + if (oaAttributes == null) + oaAttributes = new Vector<ExtendedSAMLAttribute>(); + List<ExtendedSAMLAttribute> authAttributes = session.getExtendedSAMLAttributesAUTH(); + if (authAttributes == null) + authAttributes = new Vector<ExtendedSAMLAttribute>(); + int length = extendedSAMLAttributes.length; + for (int i = 0; i < length; i++) { + ExtendedSAMLAttribute samlAttribute = extendedSAMLAttributes[i]; + + Object value = verifySAMLAttribute(samlAttribute, i, identifier, + friendlyName); + + if ((value instanceof String) || (value instanceof Element)) { + switch (samlAttribute.getAddToAUTHBlock()) { + case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY: + replaceExtendedSAMLAttribute(authAttributes, samlAttribute); + break; + case ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK: + replaceExtendedSAMLAttribute(authAttributes, samlAttribute); + replaceExtendedSAMLAttribute(oaAttributes, samlAttribute); + break; + case ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK: + replaceExtendedSAMLAttribute(oaAttributes, samlAttribute); + break; + default: + Logger + .info("Invalid return value from method \"getAddToAUTHBlock()\" (" + + samlAttribute.getAddToAUTHBlock() + + ") in SAML attribute number " + + (i + 1) + + " for infobox " + identifier); + throw new ValidateException("validator.47", new Object[]{ + friendlyName, String.valueOf((i + 1))}); + } + } else { + Logger + .info("The type of SAML-Attribute number " + + (i + 1) + + " returned from " + + identifier + + "-infobox validator is not valid. Must be either \"java.Lang.String\"" + + " or \"org.w3c.dom.Element\""); + throw new ValidateException("validator.46", new Object[]{ + identifier, String.valueOf((i + 1))}); + } + } + session.setExtendedSAMLAttributesAUTH(authAttributes); + session.setExtendedSAMLAttributesOA(oaAttributes); + } + + /** + * Adds the AUTH block related SAML attributes to the validation result. + * This is needed always before the AUTH block is to be signed, because the + * name of the mandator has to be set + * + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws TransformerException + */ + + protected static ExtendedSAMLAttribute[] addExtendedSamlAttributes( + MISMandate mandate, boolean business, boolean provideStammzahl) + throws SAXException, IOException, ParserConfigurationException, + TransformerException { + Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>(); + + extendedSamlAttributes.clear(); + + // Name + Element domMandate = mandateToElement(mandate); + Element nameSpaceNode = domMandate.getOwnerDocument().createElement( + "NameSpaceNode"); + nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.PD_POSTFIX, + Constants.PD_NS_URI); + nameSpaceNode.setAttribute("xmlns" + SZRGWConstants.MANDATE_POSTFIX, + SZRGWConstants.MANDATE_NS); + + Element mandator = (Element) XPathAPI.selectSingleNode(domMandate, + "//md:Mandate/md:Mandator", nameSpaceNode); + + // Mandate + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_RAW, domMandate, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); + + // (w)bpk + String wbpk = ParepUtils.extractMandatorWbpk(mandator); + if (!ParepUtils.isEmpty(wbpk)) { + if (!ParepUtils.isPhysicalPerson(mandator)) { + String idType = ParepUtils + .extractMandatorIdentificationType(mandator); + if (!ParepUtils.isEmpty(idType) + && idType.startsWith(Constants.URN_PREFIX_BASEID)) { + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_CB_BASE_ID, + ParepUtils.getRegisterString(idType) + ": " + wbpk, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY)); + } + } else if (business) { + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_WBPK, wbpk, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.ADD_TO_AUTHBLOCK_ONLY)); + } + } + + ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes + .size()]; + extendedSamlAttributes.copyInto(ret); + Logger.debug("ExtendedSAML Attributes: " + ret.length); + return ret; + + } + + /** + * Adds the AUTH block related SAML attributes to the validation result. + * This is needed always before the AUTH block is to be signed, because the + * name of the mandator has to be set + * + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws TransformerException + */ + private static ExtendedSAMLAttribute[] addExtendedSamlAttributesOID( + MISMandate mandate, boolean business) throws SAXException, + IOException, ParserConfigurationException, TransformerException { + + Vector<ExtendedSAMLAttribute> extendedSamlAttributes = new Vector<ExtendedSAMLAttribute>(); + + extendedSamlAttributes.clear(); + + // RepresentationType + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_REPRESENTATIONTYPE, + EXT_SAML_MANDATE_REPRESENTATIONTEXT, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); + + String oid = mandate.getProfRep(); + + if (oid != null) { + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_OID, oid, + SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); + String oidDescription = mandate.getTextualDescriptionOfOID(); + extendedSamlAttributes.add(new ExtendedSAMLAttributeImpl( + EXT_SAML_MANDATE_OIDTEXTUALDESCRIPTION, + oidDescription, SZRGWConstants.MANDATE_NS, + ExtendedSAMLAttribute.NOT_ADD_TO_AUTHBLOCK)); + + } + + ExtendedSAMLAttribute[] ret = new ExtendedSAMLAttribute[extendedSamlAttributes + .size()]; + extendedSamlAttributes.copyInto(ret); + Logger.debug("ExtendedSAML Attributes: " + ret.length); + return ret; + + } + + /** + * @param mandate + * @return + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + */ + private static Element mandateToElement(MISMandate mandate) + throws SAXException, IOException, ParserConfigurationException { + ByteArrayInputStream bais = new ByteArrayInputStream(mandate + .getMandate()); + Document doc = DOMUtils.parseDocumentSimple(bais); + return doc.getDocumentElement(); + } + + protected static void replaceExtendedSAMLAttribute(List<ExtendedSAMLAttribute> attributes, + ExtendedSAMLAttribute samlAttribute) { + if (null == attributes) { + attributes = new Vector<ExtendedSAMLAttribute>(); + } else { + String id = samlAttribute.getName(); + int length = attributes.size(); + for (int i = 0; i < length; i++) { + ExtendedSAMLAttribute att = (ExtendedSAMLAttribute) attributes + .get(i); + if (id.equals(att.getName())) { + // replace attribute + attributes.set(i, samlAttribute); + return; + } + } + attributes.add(samlAttribute); + } + } + + /** + * Processes a <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses <code><CreateXMLSignatureResponse></code> for error + * codes</li> + * <li>Parses authentication block enclosed in + * <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies authentication block by calling the MOA SP component</li> + * <li>Creates authentication data</li> + * <li>Creates a corresponding SAML artifact</li> + * <li>Stores authentication data in the authentication data store indexed + * by the SAML artifact</li> + * <li>Deletes authentication session</li> + * <li>Returns the SAML artifact, encoded BASE64</li> + * </ul> + * + * @param sessionID session ID of the running authentication session + * @param xmlCreateXMLSignatureReadResponse String representation of the + * <code><CreateXMLSignatureResponse></code> + * @return SAML artifact needed for retrieving authentication data, encoded + * BASE64 + * @throws BKUException + */ + public String verifyAuthenticationBlock(AuthenticationSession session, + String xmlCreateXMLSignatureReadResponse) + throws AuthenticationException, BuildException, ParseException, + ConfigurationException, ServiceException, ValidateException, BKUException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID}); + if (isEmpty(xmlCreateXMLSignatureReadResponse)) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); + + AuthConfigurationProvider authConf = AuthConfigurationProvider + .getInstance(); + // parses <CreateXMLSignatureResponse> + CreateXMLSignatureResponse csresp = new CreateXMLSignatureResponseParser( + xmlCreateXMLSignatureReadResponse).parseResponse(); + + try { + String serializedAssertion = DOMUtils.serializeNode(csresp + .getSamlAssertion()); + session.setAuthBlock(serializedAssertion); + } catch (TransformerException e) { + throw new ParseException("parser.04", new Object[]{ + REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); + } catch (IOException e) { + throw new ParseException("parser.04", new Object[]{ + REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE}); + } + // validates <CreateXMLSignatureResponse> + if (session.isSsoRequested()) + new CreateXMLSignatureResponseValidator().validateSSO(csresp, session); + else + new CreateXMLSignatureResponseValidator().validate(csresp, session); + + // builds a <VerifyXMLSignatureRequest> for a MOA-SPSS call + List<String> vtids = authConf.getMoaSpAuthBlockVerifyTransformsInfoIDs(); + String tpid = authConf.getMoaSpAuthBlockTrustProfileID(); + Element domVsreq = new VerifyXMLSignatureRequestBuilder().build(csresp, + vtids, tpid); + // debug output + + // invokes the call + Element domVsresp = new SignatureVerificationInvoker() + .verifyXMLSignature(domVsreq); + // debug output + + // parses the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponseParser( + domVsresp).parseData(); + + if (Logger.isTraceEnabled()) { + if (domVsresp != null) { + try { + String xmlVerifyXMLSignatureResponse = DOMUtils + .serializeNode(domVsresp, true); + Logger.trace(new LogMsg(xmlCreateXMLSignatureReadResponse)); + Logger.trace(new LogMsg(xmlVerifyXMLSignatureResponse)); + } catch (Throwable t) { + t.printStackTrace(); + Logger.info(new LogMsg(t.getStackTrace())); + } + } + } + + // validates the <VerifyXMLSignatureResponse> + VerifyXMLSignatureResponseValidator.getInstance().validate(vsresp, + null, VerifyXMLSignatureResponseValidator.CHECK_AUTH_BLOCK, + false); + + // Compare AuthBlock Data with information stored in session, especially + // date and time + CreateXMLSignatureResponseValidator.getInstance().validateSigningDateTime(csresp); + + // compares the public keys from the identityLink with the AuthBlock + VerifyXMLSignatureResponseValidator.getInstance().validateCertificate( + vsresp, session.getIdentityLink()); + + // post processing of the infoboxes + Iterator iter = session.getInfoboxValidatorIterator(); + boolean formpending = false; + if (iter != null) { + while (!formpending && iter.hasNext()) { + Vector infoboxValidatorVector = (Vector) iter.next(); + String identifier = (String) infoboxValidatorVector.get(0); + String friendlyName = (String) infoboxValidatorVector.get(1); + InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector + .get(2); + InfoboxValidationResult infoboxValidationResult = null; + try { + infoboxValidationResult = infoboxvalidator.validate(csresp + .getSamlAssertion()); + } catch (ValidateException e) { + Logger.error("Error validating " + identifier + " infobox:" + + e.getMessage()); + throw new ValidateException("validator.44", + new Object[]{friendlyName}); + } + if (!infoboxValidationResult.isValid()) { + Logger.info("Validation of " + identifier + + " infobox failed."); + throw new ValidateException("validator.40", new Object[]{ + friendlyName, + infoboxValidationResult.getErrorMessage()}); + } + String form = infoboxvalidator.getForm(); + if (ParepUtils.isEmpty(form)) { + AddAdditionalSAMLAttributes( + session, + infoboxValidationResult.getExtendedSamlAttributes(), + identifier, friendlyName); + } else { + return "Redirect to Input Processor"; + } + } + } + + session.setXMLVerifySignatureResponse(vsresp); + session.setSignerCertificate(vsresp.getX509certificate()); + vsresp.setX509certificate(null); + session.setForeigner(false); + + if (session.getUseMandate()) { + // mandate mode + return null; + + } else { + + session.setAuthenticatedUsed(false); + session.setAuthenticated(true); + + //set QAA Level four in case of card authentifcation + session.setQAALevel(PVPConstants.STORK_QAA_1_4); + + + String oldsessionID = session.getSessionID(); + + //Session is implicte stored in changeSessionID!!! + String newMOASessionID = AuthenticationSessionStoreage.changeSessionID(session); + + Logger.info("Changed MOASession " + oldsessionID + " to Session " + newMOASessionID); + Logger.info("Daten angelegt zu MOASession " + newMOASessionID); + + return newMOASessionID; + } + } + + /** + * Processes a <code><CreateXMLSignatureResponse></code> sent by the + * security layer implementation.<br> + * <ul> + * <li>Validates given <code><CreateXMLSignatureResponse></code></li> + * <li>Parses <code><CreateXMLSignatureResponse></code> for error + * codes</li> + * <li>Parses authentication block enclosed in + * <code><CreateXMLSignatureResponse></code></li> + * <li>Verifies authentication block by calling the MOA SP component</li> + * <li>Creates authentication data</li> + * <li>Creates a corresponding SAML artifact</li> + * <li>Stores authentication data in the authentication data store indexed + * by the SAML artifact</li> + * <li>Deletes authentication session</li> + * <li>Returns the SAML artifact, encoded BASE64</li> + * </ul> + * + * @param sessionID session ID of the running authentication session + * @param xmlCreateXMLSignatureReadResponse String representation of the + * <code><CreateXMLSignatureResponse></code> + * @return SAML artifact needed for retrieving authentication data, encoded + * BASE64 + */ + + protected Element createIdentificationBPK(Element mandatePerson, + String baseid, String target) throws BuildException { + Element identificationBpK = mandatePerson.getOwnerDocument() + .createElementNS(Constants.PD_NS_URI, "Identification"); + Element valueBpK = mandatePerson.getOwnerDocument().createElementNS( + Constants.PD_NS_URI, "Value"); + + String bpkBase64 = new BPKBuilder().buildBPK(baseid, target); + valueBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( + bpkBase64)); + Element typeBpK = mandatePerson.getOwnerDocument().createElementNS( + Constants.PD_NS_URI, "Type"); + typeBpK.appendChild(mandatePerson.getOwnerDocument().createTextNode( + "urn:publicid:gv.at:cdid+bpk")); + identificationBpK.appendChild(valueBpK); + identificationBpK.appendChild(typeBpK); + + return identificationBpK; + + } + + protected String getBaseId(Element mandatePerson) + throws TransformerException, IOException { + NodeList list = mandatePerson.getElementsByTagNameNS( + Constants.PD_NS_URI, "Identification"); + for (int i = 0; i < list.getLength(); i++) { + Element identification = (Element) list.item(i); + Element type = (Element) identification.getElementsByTagNameNS( + Constants.PD_NS_URI, "Type").item(0); + if (type.getTextContent().compareToIgnoreCase( + "urn:publicid:gv.at:baseid") == 0) { + Element value = (Element) identification + .getElementsByTagNameNS(Constants.PD_NS_URI, "Value") + .item(0); + return value.getTextContent(); + } + } + return null; + + } + + /** + * Gets the foreign authentication data.<br> + * <ul> + * <li>Creates authentication data</li> + * <li>Creates a corresponding SAML artifact</li> + * <li>Stores authentication data in the authentication data store indexed + * by the SAML artifact</li> + * <li>Deletes authentication session</li> + * <li>Returns the SAML artifact, encoded BASE64</li> + * </ul> + * + * @param sessionID session ID of the running authentication session + * @return SAML artifact needed for retrieving authentication data, encoded + * BASE64 + */ + public String getForeignAuthenticationData(AuthenticationSession session) + throws AuthenticationException, BuildException, ParseException, + ConfigurationException, ServiceException, ValidateException { + + if (session == null) + throw new AuthenticationException("auth.10", new Object[]{ + REQ_VERIFY_AUTH_BLOCK, PARAM_SESSIONID}); + + // post processing of the infoboxes + Iterator iter = session.getInfoboxValidatorIterator(); + boolean formpending = false; + if (iter != null) { + while (!formpending && iter.hasNext()) { + Vector infoboxValidatorVector = (Vector) iter.next(); + String identifier = (String) infoboxValidatorVector.get(0); + String friendlyName = (String) infoboxValidatorVector.get(1); + InfoboxValidator infoboxvalidator = (InfoboxValidator) infoboxValidatorVector + .get(2); + InfoboxValidationResult infoboxValidationResult = null; + try { + infoboxValidationResult = infoboxvalidator.validate(session + .getIdentityLink().getSamlAssertion()); + } catch (ValidateException e) { + Logger.error("Error validating " + identifier + " infobox:" + + e.getMessage()); + throw new ValidateException("validator.44", + new Object[]{friendlyName}); + } + if (!infoboxValidationResult.isValid()) { + Logger.info("Validation of " + identifier + + " infobox failed."); + throw new ValidateException("validator.40", new Object[]{ + friendlyName, + infoboxValidationResult.getErrorMessage()}); + } + String form = infoboxvalidator.getForm(); + if (ParepUtils.isEmpty(form)) { + AddAdditionalSAMLAttributes( + session, + infoboxValidationResult.getExtendedSamlAttributes(), + identifier, friendlyName); + } else { + return "Redirect to Input Processor"; + } + } + } + + VerifyXMLSignatureResponse vsresp = new VerifyXMLSignatureResponse(); + X509Certificate cert = session.getSignerCertificate(); + vsresp.setX509certificate(cert); + + session.setAuthenticatedUsed(false); + session.setAuthenticated(true); + + + session.setXMLVerifySignatureResponse(vsresp); + session.setSignerCertificate(vsresp.getX509certificate()); + vsresp.setX509certificate(null); + session.setForeigner(true); + + //TODO: regenerate MOASession ID! + return "new Session"; + } + + /** + * Builds the AuthenticationData object together with the corresponding + * <code><saml:Assertion></code> + * + * @param session authentication session + * @param verifyXMLSigResp VerifyXMLSignatureResponse from MOA-SP + * @param useUTC uses correct UTC time format + * @param useUTC indicates that authenticated citizen is a foreigner + * @param isForeigner indicates whether Austrian (false) or foreigner (true) authenticates + * @return AuthenticationData object + * @throws ConfigurationException while accessing configuration data + * @throws BuildException while building the <code><saml:Assertion></code> + */ + public static AuthenticationData buildAuthenticationData( + AuthenticationSession session, OAAuthParameter oaParam, String target) + throws ConfigurationException, BuildException { + + IdentityLink identityLink = session.getIdentityLink(); + AuthenticationData authData = new AuthenticationData(); + + VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); + + boolean businessService = oaParam.getBusinessService(); + + authData.setMajorVersion(1); + authData.setMinorVersion(0); + authData.setAssertionID(Random.nextRandom()); + authData.setIssuer(session.getAuthURL()); + + authData.setIssueInstant(DateTimeUtils.buildDateTimeUTC(Calendar + .getInstance())); + + //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO + authData.setIdentificationValue(identityLink.getIdentificationValue()); + authData.setIdentificationType(identityLink.getIdentificationType()); + + authData.setGivenName(identityLink.getGivenName()); + authData.setFamilyName(identityLink.getFamilyName()); + authData.setDateOfBirth(identityLink.getDateOfBirth()); + authData.setQualifiedCertificate(verifyXMLSigResp + .isQualifiedCertificate()); + authData.setPublicAuthority(verifyXMLSigResp.isPublicAuthority()); + authData.setPublicAuthorityCode(verifyXMLSigResp + .getPublicAuthorityCode()); + authData.setBkuURL(session.getBkuURL()); + + try { + + if (session.getUseMandate() && session.isOW()) { + MISMandate mandate = session.getMISMandate(); + authData.setBPK(mandate.getOWbPK()); + authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); + authData.setIdentityLink(identityLink); + + Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); + + } else { + + if (businessService) { + //since we have foreigner, wbPK is not calculated in BKU + if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + + String registerAndOrdNr = oaParam.getIdentityLinkDomainIdentifier(); + + if (registerAndOrdNr.startsWith(AuthenticationSession.REGISTERANDORDNR_PREFIX_)) { + // If domainIdentifier starts with prefix + // "urn:publicid:gv.at:wbpk+"; remove this prefix + registerAndOrdNr = registerAndOrdNr + .substring(AuthenticationSession.REGISTERANDORDNR_PREFIX_.length()); + Logger.debug("Register and ordernumber prefix stripped off; resulting register string: " + + registerAndOrdNr); + } + + String wbpkBase64 = new BPKBuilder().buildWBPK(identityLink.getIdentificationValue(), registerAndOrdNr); + authData.setBPK(wbpkBase64); + authData.setBPKType(Constants.URN_PREFIX_WBPK + "+" + registerAndOrdNr); + + } else { + authData.setBPK(identityLink.getIdentificationValue()); + authData.setBPKType(identityLink.getIdentificationType()); + + } + + Logger.trace("Authenticate user with wbPK " + authData.getBPK()); + + Element idlassertion = session.getIdentityLink().getSamlAssertion(); + //set bpk/wpbk; + Node prIdentification = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_VALUE_XPATH); + prIdentification.getFirstChild().setNodeValue(authData.getBPK()); + //set bkp/wpbk type + Node prIdentificationType = XPathUtils.selectSingleNode(idlassertion, IdentityLinkAssertionParser.PERSON_IDENT_TYPE_XPATH); + prIdentificationType.getFirstChild().setNodeValue(authData.getBPKType()); + + IdentityLinkAssertionParser idlparser = new IdentityLinkAssertionParser(idlassertion); + IdentityLink idl = idlparser.parseIdentityLink(); + authData.setIdentityLink(idl); + + } else { + + if (identityLink.getIdentificationType().equals(Constants.URN_PREFIX_BASEID)) { + // only compute bPK if online application is a public service and we have the Stammzahl + String bpkBase64 = new BPKBuilder().buildBPK(identityLink.getIdentificationValue(), target); + authData.setBPK(bpkBase64); + authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + oaParam.getTarget()); + } + + Logger.trace("Authenticate user with bPK " + authData.getBPK()); + + authData.setIdentityLink(identityLink); + } + } + + return authData; + + } catch (Throwable ex) { + throw new BuildException("builder.00", new Object[]{ + "AuthenticationData", ex.toString()}, ex); + } + } + + /** + * Retrieves a session from the session store. + * + * @param id session ID + * @return <code>AuthenticationSession</code> stored with given session ID, + * <code>null</code> if session ID unknown + */ + public static AuthenticationSession getSession(String id) + throws AuthenticationException { + + AuthenticationSession session; + try { + session = AuthenticationSessionStoreage.getSession(id); + + if (session == null) + throw new AuthenticationException("auth.02", new Object[]{id}); + return session; + + } catch (MOADatabaseException e) { + throw new AuthenticationException("parser.04", new Object[]{id}); + } + } + + /** + * Cleans up expired session and authentication data stores. + */ + public void cleanup() { + long now = new Date().getTime(); + + //clean AuthenticationSessionStore + + AuthenticationSessionStoreage.clean(now, sessionTimeOutCreated, sessionTimeOutUpdated); + + //clean AssertionStore + AssertionStorage assertionstore = AssertionStorage.getInstance(); + assertionstore.clean(now, authDataTimeOut); + + //clean ExeptionStore + DBExceptionStoreImpl exstore = DBExceptionStoreImpl.getStore(); + exstore.clean(now, authDataTimeOut); + + } + + /** + * Sets the sessionTimeOut. + * + * @param seconds Time out of the session in seconds + */ + public void setSecondsSessionTimeOutCreated(long seconds) { + sessionTimeOutCreated = seconds * 1000; + } + + public void setSecondsSessionTimeOutUpdated(long seconds) { + sessionTimeOutUpdated = seconds * 1000; + } + + /** + * Sets the authDataTimeOut. + * + * @param seconds Time out for signing AuthData in seconds + */ + public void setSecondsAuthDataTimeOut(long seconds) { + authDataTimeOut = seconds * 1000; + } + + /** + * Checks a parameter. + * + * @param param parameter + * @return true if the parameter is null or empty + */ + private boolean isEmpty(String param) { + return param == null || param.length() == 0; + } + + /** + * Checks the correctness of SAML attributes and returns its value. + * + * @param param samlAttribute + * @param i the number of the verified attribute for messages + * @param identifier the infobox identifier for messages + * @param friendlyname the friendly name of the infobox for messages + * @return the SAML attribute value (Element or String) + */ + protected static Object verifySAMLAttribute( + ExtendedSAMLAttribute samlAttribute, int i, String identifier, + String friendlyName) throws ValidateException { + String name = samlAttribute.getName(); + + if (name == null) { + Logger.info("The name of SAML-Attribute number " + (i + 1) + + " returned from " + identifier + + "-infobox validator is null."); + throw new ValidateException("validator.45", new Object[]{ + friendlyName, "Name", String.valueOf((i + 1)), "null"}); + } + if (name == "") { + Logger.info("The name of SAML-Attribute number " + (i + 1) + + " returned from " + identifier + + "-infobox validator is empty."); + throw new ValidateException("validator.45", new Object[]{ + friendlyName, "Name", String.valueOf((i + 1)), "leer"}); + } + if (samlAttribute.getNameSpace() == null) { + Logger.info("The namespace of SAML-Attribute number " + (i + 1) + + " returned from " + identifier + + "-infobox validator is null."); + throw new ValidateException("validator.45", + new Object[]{friendlyName, "Namespace", + String.valueOf((i + 1)), "null"}); + } + Object value = samlAttribute.getValue(); + if (value == null) { + Logger.info("The value of SAML-Attribute number " + (i + 1) + + " returned from " + identifier + + "-infobox validator is null."); + throw new ValidateException("validator.45", new Object[]{ + friendlyName, "Wert", String.valueOf((i + 1)), "null"}); + } + + return value; + } + + /** + * Does the request to the SZR-GW + * + * @param oaFriendlyName + * @param signature XMLDSIG signature + * @return Identity link assertion + * @throws SZRGWClientException + */ + + public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String gender, String citizenSignature, String represented, String representative, String mandateContent, String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { + + try { + AuthConfigurationProvider authConf = AuthConfigurationProvider.getInstance(); + ConnectionParameter connectionParameters = authConf.getForeignIDConnectionParameter(); + + SZRGWClient client = new SZRGWClient(connectionParameters); + + + CreateIdentityLinkRequest request = new CreateIdentityLinkRequest(); + request.setSignature(citizenSignature.getBytes()); + + PEPSData data = new PEPSData(); + data.setDateOfBirth(PEPSDateOfBirth); + data.setFamilyname(PEPSFamilyname); + data.setFirstname(PEPSFirstname); + data.setIdentifier(PEPSIdentifier); + + data.setRepresentative(representative); + data.setRepresented(represented); + data.setMandateContent(mandateContent); + + data.setLegalPersonCanonicalRegisteredAddress(organizationAddress); + data.setLegalPersonTranslatableType(organizationType); + + if (null != mandateContent) { + MISType mis = new MISType(); + + Target targetObject = new Target(); + targetObject.setType(targetType); + targetObject.setValue(targetValue); + mis.setTarget(targetObject); + + mis.setOAFriendlyName(oaFriendlyName); + + Filters filterObject = new Filters(); + MandateIdentifiers mandateIds = new MandateIdentifiers(); + for (String current : filters.split(",")) + mandateIds.getMandateIdentifier().add(current.trim()); + filterObject.setMandateIdentifiers(mandateIds); + mis.setFilters(filterObject); + + request.setMIS(mis); + } + + Logger.info("Starte Kommunikation mit dem Stammzahlenregister Gateway(" + connectionParameters.getUrl() + ")..."); + CreateIdentityLinkResponse response = client.sentCreateIDLRequest(request, connectionParameters.getUrl()); + return response; + + } catch (ConfigurationException e) { + Logger.warn(e); + Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null)); + } + + return null; + + } + + /** + * Does the request to the SZR-GW. + * + * @param signature the signature + * @return the identity link + * @throws SZRGWClientException the sZRGW client exception + * @throws ConfigurationException the configuration exception + */ + public CreateIdentityLinkResponse getIdentityLink(Element signature) throws SZRGWClientException, ConfigurationException { + return getIdentityLink(null, null, null, null, XMLHelper.nodeToString(signature)); + } + + /** + * Does the request to the SZR-GW. + * + * @param PEPSIdentifier the pEPS identifier + * @param PEPSFirstname the pEPS firstname + * @param PEPSFamilyname the pEPS familyname + * @param PEPSDateOfBirth the pEPS date of birth + * @param signature XMLDSIG signature + * @return Identity link assertion + * @throws SZRGWClientException the sZRGW client exception + * @throws ConfigurationException the configuration exception + */ + public CreateIdentityLinkResponse getIdentityLink(String PEPSIdentifier, String PEPSFirstname, String PEPSFamilyname, String PEPSDateOfBirth, String signature) throws SZRGWClientException { + return getIdentityLink(PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, null, signature, null, null, null, null, null, null, null); + } + + /** + * Gets the identity link. + * + * @param citizenSignature the citizen signature + * @param representative the representative + * @param represented the represented + * @param mandate the mandate + * @param organizationAddress the organization address + * @param organizationType the organization type + * @return the identity link + * @throws SZRGWClientException + */ + public CreateIdentityLinkResponse getIdentityLink(String citizenSignature, + String representative, String represented, String mandateContent, + String organizationAddress, String organizationType, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { + return getIdentityLink(null, null, null, null, null, + citizenSignature, represented, representative, mandateContent, organizationAddress, + organizationType, targetType, targetValue, oaFriendlyName, filters); + } + + /** + * SZR-GW Client interface. + * + * @param eIdentifier the e identifier + * @param givenName the given name + * @param lastName the last name + * @param dateOfBirth the date of birth + * @param citizenSignature the citizen signature + * @param representative the representative + * @param represented the represented + * @param mandate the mandate + * @return the identity link + * @throws SZRGWClientException the sZRGW client exception + */ + public CreateIdentityLinkResponse getIdentityLink(String eIdentifier, + String givenName, String lastName, String dateOfBirth, String gender, + String citizenSignature, String representative, String represented, + String mandate, String targetType, String targetValue, String oaFriendlyName, String filters) throws SZRGWClientException { + return getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, gender, + citizenSignature, representative, represented, mandate, null, + null, targetType, targetValue, oaFriendlyName, filters); + } + + /** + * Starts a MOA-ID authentication process using STORK + * + * @param req HttpServletRequest + * @param resp HttpServletResponse + * @param ccc Citizen country code + * @param oaURL URL of the online application + * @param target Target parameter + * @param targetFriendlyName Friendly Name of Target + * @param authURL Authentication URL + * @param sourceID SourceID parameter + * @throws MOAIDException + * @throws AuthenticationException + * @throws WrongParametersException + * @throws ConfigurationException + */ + public static void startSTORKAuthentication( + HttpServletRequest req, + HttpServletResponse resp, + AuthenticationSession moasession) throws MOAIDException, AuthenticationException, WrongParametersException, ConfigurationException { + + if (moasession == null) { + throw new AuthenticationException("auth.18", new Object[]{}); + } + + //read configuration paramters of OA + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); + if (oaParam == null) + throw new AuthenticationException("auth.00", new Object[]{moasession.getPublicOAURLPrefix()}); + + //Start of STORK Processing + STORKConfig storkConfig = AuthConfigurationProvider.getInstance().getStorkConfig(); + + CPEPS cpeps = storkConfig.getCPEPS(moasession.getCcc()); + + Logger.debug("Preparing to assemble STORK AuthnRequest with the following values:"); + String destination = cpeps.getPepsURL().toExternalForm(); + Logger.debug("C-PEPS URL: " + destination); + + String acsURL = HTTPUtils.getBaseURL(req) + PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; + Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL); + + String providerName = oaParam.getFriendlyName(); + String issuerValue = HTTPUtils.getBaseURL(req); + Logger.debug("Issuer value: " + issuerValue); + + // prepare collection of required attributes + // - attributes for online application + List<OAStorkAttribute> attributesFromConfig = oaParam.getRequestedAttributes(); + + // - prepare attribute list + PersonalAttributeList attributeList = new PersonalAttributeList(); + + // - fill container + for (OAStorkAttribute current : attributesFromConfig) { + PersonalAttribute newAttribute = new PersonalAttribute(); + newAttribute.setName(current.getName()); + + boolean globallyMandatory = false; + for (StorkAttribute currentGlobalAttribute : storkConfig.getStorkAttributes()) + if (current.getName().equals(currentGlobalAttribute.getName())) { + globallyMandatory = currentGlobalAttribute.isMandatory(); + break; + } + + newAttribute.setIsRequired(current.isMandatory() || globallyMandatory); + attributeList.add(newAttribute); + } + + // add sign request + PersonalAttribute newAttribute = new PersonalAttribute(); + newAttribute.setName("signedDoc"); + List<String> value = new ArrayList<String>(); + value.add(generateDssSignRequest(CreateXMLSignatureRequestBuilder.buildForeignIDTextToBeSigned("wie im Signaturzertifikat (as in my signature certificate)", oaParam, moasession), + "application/xhtml+xml", + moasession.getCcc())); + newAttribute.setValue(value); + attributeList.add(newAttribute); + + + if (Logger.isDebugEnabled()) { + Logger.debug("The following attributes are requested for this OA:"); + for (OAStorkAttribute logReqAttr : attributesFromConfig) + Logger.debug("OA specific requested attribute: " + logReqAttr.getName() + ", isRequired: " + logReqAttr.isMandatory()); + } + + //TODO: check Target in case of SSO!! + String spSector = StringUtils.isEmpty(moasession.getTarget()) ? "Business" : moasession.getTarget(); + String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName(); + String spApplication = spInstitution; + String spCountry = "AT"; + + //generate AuthnRquest + STORKAuthnRequest authnRequest = new STORKAuthnRequest(); + authnRequest.setDestination(destination); + authnRequest.setAssertionConsumerServiceURL(acsURL); + authnRequest.setProviderName(providerName); + authnRequest.setIssuer(issuerValue); + authnRequest.setQaa(oaParam.getQaaLevel()); + authnRequest.setSpInstitution(spInstitution); + authnRequest.setCountry(spCountry); + authnRequest.setSpApplication(spApplication); + authnRequest.setSpSector(spSector); + authnRequest.setPersonalAttributeList(attributeList); + + authnRequest.setEIDCrossBorderShare(true); + authnRequest.setEIDCrossSectorShare(true); + authnRequest.setEIDSectorShare(true); + + authnRequest.setCitizenCountryCode(moasession.getCcc()); + + + Logger.debug("STORK AuthnRequest succesfully assembled."); + + STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("outgoing"); + try { + authnRequest = samlEngine.generateSTORKAuthnRequest(authnRequest); + } catch (STORKSAMLEngineException e) { + Logger.error("Could not sign STORK SAML AuthnRequest.", e); + throw new MOAIDException("stork.00", null); + } + + Logger.info("STORK AuthnRequest successfully signed!"); + + //validate AuthnRequest + try { + samlEngine.validateSTORKAuthnRequest(authnRequest.getTokenSaml()); + } catch (STORKSAMLEngineException e) { + Logger.error("STORK SAML AuthnRequest not valid.", e); + throw new MOAIDException("stork.01", null); + } + + Logger.debug("STORK AuthnRequest successfully internally validated."); + + //send + moasession.setStorkAuthnRequest(authnRequest); + HttpSession httpSession = req.getSession(); + httpSession.setAttribute("MOA-Session-ID", moasession.getSessionID()); + + + Logger.info("Preparing to send STORK AuthnRequest."); + Logger.info("prepared STORKAuthnRequest: "); + Logger.info(new String(authnRequest.getTokenSaml())); + + try { + Logger.trace("Initialize VelocityEngine..."); + + VelocityEngine velocityEngine = VelocityProvider.getClassPathVelocityEngine(); + Template template = velocityEngine.getTemplate("/resources/templates/saml2-post-binding-moa.vm"); + VelocityContext context = new VelocityContext(); + context.put("SAMLRequest", PEPSUtil.encodeSAMLToken(authnRequest.getTokenSaml())); + context.put("action", destination); + + StringWriter writer = new StringWriter(); + template.merge(context, writer); + + resp.getOutputStream().write(writer.toString().getBytes()); + } catch (Exception e) { + Logger.error("Error sending STORK SAML AuthnRequest.", e); + httpSession.invalidate(); + throw new MOAIDException("stork.02", new Object[]{destination}); + } + + Logger.info("STORK AuthnRequest successfully successfully prepared for client with target location: " + authnRequest.getDestination()); + } + + private static String generateDssSignRequest(String text, String mimeType, String citizenCountry) { + IdentifierGenerator idGenerator; + try { + idGenerator = new SecureRandomIdentifierGenerator(); + + DocumentType doc = new DocumentType(); + doc.setBase64XML(text.getBytes()); + doc.setID(idGenerator.generateIdentifier()); + + SignRequest request = new SignRequest(); + request.setInputDocuments(ApiUtils.createInputDocuments(doc)); + + String id = idGenerator.generateIdentifier(); + request.setRequestID(id); + request.setDocUI(id); + + request.setProfile(Profiles.XADES_BES.toString()); + request.setNumberOfSigners(BigInteger.ONE); + request.setTargetCountry(citizenCountry); + + // no, no todo. PEPS will alter this value anyhow. + request.setReturnURL("http://invalid_return"); + + AnyType required = new AnyType(); + required.getAny().add(ApiUtils.createSignatureType(SignatureTypes.XMLSIG_RFC3275.toString())); + required.getAny().add(ApiUtils.createAdditionalProfile(AdditionalProfiles.XADES.toString())); + required.getAny().add(ApiUtils.createQualityRequirements(QualityLevels.QUALITYLEVEL_QUALIFIEDSIG)); + required.getAny().add(ApiUtils.createIncludeObject(doc)); + request.setOptionalInputs(required); + + return IOUtils.toString(ApiUtils.marshalToInputStream(request)); + } catch (NoSuchAlgorithmException e) { + Logger.error("Cannot generate id", e); + throw new RuntimeException(e); + } catch (ApiUtilsException e) { + Logger.error("Could not create SignRequest", e); + throw new RuntimeException(e); + } catch (DOMException e) { + Logger.error("Could not create SignRequest", e); + throw new RuntimeException(e); + } catch (IOException e) { + Logger.error("Could not create SignRequest", e); + throw new RuntimeException(e); + } + } + + /** + * Extracts an X509 Certificate out of an XML signagture element + * + * @param signedXML XML signature element + * @return X509Certificate + * @throws CertificateException + */ + public static X509Certificate getCertificateFromXML(Element signedXML) throws CertificateException { + + NodeList nList = signedXML.getElementsByTagNameNS(Constants.DSIG_NS_URI, "X509Certificate"); + + String base64CertString = XMLUtil.getFirstTextValueFromNodeList(nList); + + if (StringUtils.isEmpty(base64CertString)) { + String msg = "XML does not contain a X509Certificate element."; + Logger.error(msg); + throw new CertificateException(msg); + } + + InputStream is = new ByteArrayInputStream(Base64.decode(base64CertString)); + + X509Certificate cert; + try { + cert = new X509Certificate(is); + return cert; + + } catch (Throwable e) { + throw new CertificateException(e); + } + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java index bd87737ed..226d05520 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/BPKBuilder.java @@ -2,19 +2,19 @@ * Copyright 2014 Federal Chancellery Austria * MOA-ID has been developed in a cooperation between BRZ, the Federal * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * + * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * http://www.osor.eu/eupl/ - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. - * + * * This product combines work with different licenses. See the "NOTICE" text * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works @@ -46,91 +46,141 @@ package at.gv.egovernment.moa.id.auth.builder; -import java.security.MessageDigest; - import at.gv.egovernment.moa.id.auth.exception.BuildException; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; +import java.security.MessageDigest; + /** * Builder for the bPK, as defined in * <code>"Ableitung f¨r die bereichsspezifische Personenkennzeichnung"</code> * version <code>1.0.1</code> from <code>"reference.e-government.gv.at"</code>. - * + * * @author Paul Schamberger * @version $Id$ */ public class BPKBuilder { - /** - * Builds the bPK from the given parameters. - * @param identificationValue Base64 encoded "Stammzahl" - * @param target "Bereich lt. Verordnung des BKA" - * @return bPK in a BASE64 encoding - * @throws BuildException if an error occurs on building the bPK - */ - public String buildBPK(String identificationValue, String target) - throws BuildException { - - if ((identificationValue == null || - identificationValue.length() == 0 || - target == null || - target.length() == 0)) - { - throw new BuildException("builder.00", - new Object[] {"BPK", "Unvollständige Parameterangaben: identificationValue=" + - identificationValue + ",target=" + target}); + /** + * Builds the bPK from the given parameters. + * + * @param identificationValue Base64 encoded "Stammzahl" + * @param target "Bereich lt. Verordnung des BKA" + * @return bPK in a BASE64 encoding + * @throws BuildException if an error occurs on building the bPK + */ + public String buildBPK(String identificationValue, String target) + throws BuildException { + + if ((identificationValue == null || + identificationValue.length() == 0 || + target == null || + target.length() == 0)) { + throw new BuildException("builder.00", + new Object[]{"BPK", "Unvollständige Parameterangaben: identificationValue=" + + identificationValue + ",target=" + target}); + } + String basisbegriff; + if (target.startsWith(Constants.URN_PREFIX_CDID + "+")) + basisbegriff = identificationValue + "+" + target; + else + basisbegriff = identificationValue + "+" + Constants.URN_PREFIX_CDID + "+" + target; + + try { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + byte[] hash = md.digest(basisbegriff.getBytes("ISO-8859-1")); + String hashBase64 = Base64Utils.encode(hash); + return hashBase64; + } catch (Exception ex) { + throw new BuildException("builder.00", new Object[]{"bPK", ex.toString()}, ex); + } } - String basisbegriff; - if (target.startsWith(Constants.URN_PREFIX_CDID + "+")) - basisbegriff = identificationValue + "+" + target; - else - basisbegriff = identificationValue + "+" + Constants.URN_PREFIX_CDID + "+" + target; - - try { - MessageDigest md = MessageDigest.getInstance("SHA-1"); - byte[] hash = md.digest(basisbegriff.getBytes("ISO-8859-1")); - String hashBase64 = Base64Utils.encode(hash); - return hashBase64; - } catch (Exception ex) { - throw new BuildException("builder.00", new Object[] {"bPK", ex.toString()}, ex); + + /** + * Builds the wbPK from the given parameters. + * + * @param identificationValue Base64 encoded "Stammzahl" + * @param registerAndOrdNr type of register + "+" + number in register. + * @return wbPK in a BASE64 encoding + * @throws BuildException if an error occurs on building the wbPK + */ + public String buildWBPK(String identificationValue, String registerAndOrdNr) + throws BuildException { + + if ((identificationValue == null || + identificationValue.length() == 0 || + registerAndOrdNr == null || + registerAndOrdNr.length() == 0)) { + throw new BuildException("builder.00", + new Object[]{"wbPK", "Unvollständige Parameterangaben: identificationValue=" + + identificationValue + ",Register+Registernummer=" + registerAndOrdNr}); + } + + String basisbegriff; + if (registerAndOrdNr.startsWith(Constants.URN_PREFIX_WBPK + "+")) + basisbegriff = identificationValue + "+" + registerAndOrdNr; + else + basisbegriff = identificationValue + "+" + Constants.URN_PREFIX_WBPK + "+" + registerAndOrdNr; + + try { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + byte[] hash = md.digest(basisbegriff.getBytes("ISO-8859-1")); + String hashBase64 = Base64Utils.encode(hash); + return hashBase64; + } catch (Exception ex) { + throw new BuildException("builder.00", new Object[]{"wbPK", ex.toString()}, ex); + } } - } - - /** - * Builds the wbPK from the given parameters. - * @param identificationValue Base64 encoded "Stammzahl" - * @param registerAndOrdNr type of register + "+" + number in register. - * @return wbPK in a BASE64 encoding - * @throws BuildException if an error occurs on building the wbPK - */ - public String buildWBPK(String identificationValue, String registerAndOrdNr) - throws BuildException { - - if ((identificationValue == null || - identificationValue.length() == 0 || - registerAndOrdNr == null || - registerAndOrdNr.length() == 0)) - { - throw new BuildException("builder.00", - new Object[] {"wbPK", "Unvollständige Parameterangaben: identificationValue=" + - identificationValue + ",Register+Registernummer=" + registerAndOrdNr}); + + /** + * Builds the storkeid from the given parameters. + * + * @param identificationValue Base64 encoded "Stammzahl" + * @param destinationCountry destination country code (2 chars) + * @return storkid in a BASE64 encoding + * @throws BuildException if an error occurs on building the wbPK + */ + public String buildStorkbPK(String identificationValue, String destinationCountry) + throws BuildException { + return buildStorkbPK(identificationValue, "AT", destinationCountry); } - - String basisbegriff; - if (registerAndOrdNr.startsWith(Constants.URN_PREFIX_WBPK + "+" )) - basisbegriff = identificationValue + "+" + registerAndOrdNr; - else - basisbegriff = identificationValue + "+" + Constants.URN_PREFIX_WBPK + "+" + registerAndOrdNr; - - try { - MessageDigest md = MessageDigest.getInstance("SHA-1"); - byte[] hash = md.digest(basisbegriff.getBytes("ISO-8859-1")); - String hashBase64 = Base64Utils.encode(hash); - return hashBase64; - } catch (Exception ex) { - throw new BuildException("builder.00", new Object[] {"wbPK", ex.toString()}, ex); + + + /** + * Builds the storkeid from the given parameters. + * + * @param identificationValue Base64 encoded "Stammzahl" + * @param sourceCountry source country code (2 chars) + * @param destinationCountry destination country code (2 chars) + * @return storkid in a BASE64 encoding + * @throws BuildException if an error occurs on building the wbPK + */ + public String buildStorkbPK(String identificationValue, String sourceCountry, String destinationCountry) + throws BuildException { + + if ((identificationValue == null || + identificationValue.length() == 0 || + destinationCountry == null || + destinationCountry.length() == 0 || + sourceCountry == null || + sourceCountry.length() == 0)) { + throw new BuildException("builder.00", + new Object[]{"storkid", "Unvollständige Parameterangaben: identificationValue=" + + identificationValue + ", Zielland=" + destinationCountry + ", Ursprungsland=" + sourceCountry}); + } + + String basisbegriff = identificationValue + "+" + Constants.URN_PREFIX_STORK + "+" + sourceCountry + "+" + destinationCountry; + + try { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + byte[] hash = md.digest(basisbegriff.getBytes("ISO-8859-1")); + String hashBase64 = Base64Utils.encode(hash); + return hashBase64; + } catch (Exception ex) { + throw new BuildException("builder.00", new Object[]{"storkid", ex.toString()}, ex); + } } - } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java index 828fc78ab..ba347c9e5 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/InfoboxReadRequestBuilder.java @@ -2,19 +2,19 @@ * Copyright 2014 Federal Chancellery Austria * MOA-ID has been developed in a cooperation between BRZ, the Federal * Chancellery Austria - ICT staff unit, and Graz University of Technology. - * + * * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by * the European Commission - subsequent versions of the EUPL (the "Licence"); * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * http://www.osor.eu/eupl/ - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and * limitations under the Licence. - * + * * This product combines work with different licenses. See the "NOTICE" text * file for details on the various modules and licenses. * The "NOTICE" text file is part of the distribution. Any derivative works @@ -51,82 +51,143 @@ import at.gv.egovernment.moa.util.Constants; /** * Builder for the <code><InfoboxReadRequest></code> structure * used for requesting the identity link from the security layer implementation. - * + * * @author Paul Ivancsics * @version $Id$ */ public class InfoboxReadRequestBuilder implements Constants { - /** - * Constructor for InfoboxReadRequestBuilder. - */ - public InfoboxReadRequestBuilder() { - } - - - /** - * Builds an <code><InfoboxReadRequest></code>. - * - * @param slVersion12 specifies whether the Security Layer version is - * version 1.2 or not - * @param businessService specifies whether the online application is a - * business service or not - * @param identityLinkDomainIdentifier the identification number of the business - * company; maybe <code>null</code> if the OA - * is a public service; must not be <code>null</code> - * if the OA is a business service - * - * @return <code><InfoboxReadRequest></code> as String - */ - public String build(boolean businessService, String identityLinkDomainIdentifier) { - - String slPrefix; - String slNsDeclaration; - + /** + * Constructor for InfoboxReadRequestBuilder. + */ + public InfoboxReadRequestBuilder() { + } + + + /** + * Builds an <code><InfoboxReadRequest></code>. + * + * @param slVersion12 specifies whether the Security Layer version is + * version 1.2 or not + * @param businessService specifies whether the online application is a + * business service or not + * @param identityLinkDomainIdentifier the identification number of the business + * company; maybe <code>null</code> if the OA + * is a public service; must not be <code>null</code> + * if the OA is a business service + * @return <code><InfoboxReadRequest></code> as String + */ + public String build(boolean businessService, String identityLinkDomainIdentifier) { + + String slPrefix; + String slNsDeclaration; + // if (slVersion12) { - slPrefix = SL12_PREFIX; - slNsDeclaration = SL12_NS_URI; + slPrefix = SL12_PREFIX; + slNsDeclaration = SL12_NS_URI; // } else { // slPrefix = SL10_PREFIX; // slNsDeclaration = SL10_NS_URI; // } - - StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); - sb.append("<"); - sb.append(slPrefix); - sb.append(":InfoboxReadRequest xmlns:"); - sb.append(slPrefix); - sb.append("=\""); - sb.append(slNsDeclaration); - sb.append("\">"); - sb.append("<"); - sb.append(slPrefix); - sb.append(":InfoboxIdentifier>IdentityLink</"); - sb.append(slPrefix); - sb.append(":InfoboxIdentifier>"); - sb.append("<"); - sb.append(slPrefix); - sb.append(":BinaryFileParameters ContentIsXMLEntity=\"true\"/>"); - if (businessService) { - sb.append("<"); - sb.append(slPrefix); - sb.append(":BoxSpecificParameters>"); - sb.append("<"); - sb.append(slPrefix); - sb.append(":IdentityLinkDomainIdentifier>"); - sb.append(identityLinkDomainIdentifier); - sb.append("</sl:IdentityLinkDomainIdentifier>"); - sb.append("</"); - sb.append(slPrefix); - sb.append(":BoxSpecificParameters>"); + + StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":InfoboxReadRequest xmlns:"); + sb.append(slPrefix); + sb.append("=\""); + sb.append(slNsDeclaration); + sb.append("\">"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":InfoboxIdentifier>IdentityLink</"); + sb.append(slPrefix); + sb.append(":InfoboxIdentifier>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":BinaryFileParameters ContentIsXMLEntity=\"true\"/>"); + if (businessService) { + sb.append("<"); + sb.append(slPrefix); + sb.append(":BoxSpecificParameters>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":IdentityLinkDomainIdentifier>"); + sb.append(identityLinkDomainIdentifier); + sb.append("</sl:IdentityLinkDomainIdentifier>"); + sb.append("</"); + sb.append(slPrefix); + sb.append(":BoxSpecificParameters>"); + } + sb.append("</"); + sb.append(slPrefix); + sb.append(":InfoboxReadRequest>"); + + return sb.toString(); + + } + + + /** + * Builds an <code><InfoboxReadRequest></code>. + * + * @param slVersion12 specifies whether the Security Layer version is + * version 1.2 or not + * @param businessService specifies whether the online application is a + * business service or not + * @param identityLinkDomainIdentifier the identification number of the business + * company; maybe <code>null</code> if the OA + * is a public service; must not be <code>null</code> + * if the OA is a business service + * @return <code><InfoboxReadRequest></code> as String + * + */ + public String buildStorkReadRequest(String identityLinkDomainIdentifier) { + + String slPrefix; + String slNsDeclaration; + + slPrefix = SL12_PREFIX; + slNsDeclaration = SL12_NS_URI; + + StringBuffer sb = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":InfoboxReadRequest xmlns:"); + sb.append(slPrefix); + sb.append("=\""); + sb.append(slNsDeclaration); + sb.append("\">"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":InfoboxIdentifier>IdentityLink</"); + sb.append(slPrefix); + sb.append(":InfoboxIdentifier>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":BinaryFileParameters ContentIsXMLEntity=\"true\"/>"); + + // append box parameters - necessary for stork? + sb.append("<"); + sb.append(slPrefix); + sb.append(":BoxSpecificParameters>"); + sb.append("<"); + sb.append(slPrefix); + sb.append(":IdentityLinkDomainIdentifier>"); + sb.append(identityLinkDomainIdentifier); + sb.append("</sl:IdentityLinkDomainIdentifier>"); + sb.append("</"); + sb.append(slPrefix); + sb.append(":BoxSpecificParameters>"); + // end appending box parameters + + sb.append("</"); + sb.append(slPrefix); + sb.append(":InfoboxReadRequest>"); + + return sb.toString(); + } - sb.append("</"); - sb.append(slPrefix); - sb.append(":InfoboxReadRequest>"); - - return sb.toString(); - - } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java index 7e21c6667..2d0a0e367 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/OAParameter.java @@ -55,7 +55,12 @@ public class OAParameter { this.businessService = true; else this.businessService = false; - + + if (this.oaType.equals("storkService")) + this.storkService = true; + else + this.storkService = false; + this.publicURLPrefix = oa.getPublicURLPrefix(); this.friendlyName = oa.getFriendlyName(); @@ -81,8 +86,15 @@ public class OAParameter { * if value of {@link #oaType} is "businessService" */ private boolean businessService; - - /** + + /** + * specifies whether the online application is a stork application or not (<code>true</code> + * if value of {@link #oaType} is "storkService" + */ + private boolean storkService; + + + /** * public URL prefix of the online application */ private String publicURLPrefix; @@ -139,5 +151,7 @@ public class OAParameter { public OAOAUTH20 getoAuth20Config() { return oAuth20Config; } + + public boolean getStorkService() { return storkService; } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java index 3af8bcfe5..647c8bb39 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/entrypoints/DispatcherServlet.java @@ -491,7 +491,7 @@ public class DispatcherServlet extends AuthServlet{ } } catch (Throwable e) { - Logger.info("An authentication error occous: " + e.getMessage());; + Logger.info("An authentication error occured: " + e.getMessage());; // Try handle module specific, if not possible rethrow if (!info.generateErrorMessage(e, req, resp, protocolRequest)) { throw e; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java index 2056ddf08..0317322ee 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeCollector.java @@ -1,5 +1,9 @@ package at.gv.egovernment.moa.id.protocols.stork2; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.List; + import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; @@ -12,12 +16,11 @@ import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.storage.AssertionStorage; import at.gv.egovernment.moa.logging.Logger; 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.commons.PersonalAttributeList; import eu.stork.peps.auth.engine.STORKSAMLEngine; import eu.stork.peps.exceptions.STORKSAMLEngineException; -import org.apache.commons.io.IOUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; @@ -25,18 +28,13 @@ import org.opensaml.common.impl.SecureRandomIdentifierGenerator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.List; /** * 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. - * <p/> + * * TODO how do we treat mandatory and optional attributes? */ public class AttributeCollector implements IAction { @@ -45,19 +43,24 @@ public class AttributeCollector implements IAction { * The Constant ARTIFACT_ID. */ private static final String ARTIFACT_ID = "artifactId"; - private DataContainer container; - private HttpServletResponse httpResp; - /* (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 String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession moasession) throws MOAIDException { - this.httpResp = httpResp; + // - 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); + } // read configuration parameters of OA - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(container.getRequest().getAssertionConsumerServiceURL()); if (oaParam == null) throw new AuthenticationException("stork.12", new Object[]{moasession.getPublicOAURLPrefix()}); @@ -66,35 +69,22 @@ public class AttributeCollector implements IAction { for (AttributeProvider current : AttributeProviderFactory.getConfiguredPlugins(oaParam.getStorkAPs())) try { newAttributes = current.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. - // TODO check the loop } if (null == newAttributes) { // we do not have a provider which is capable of fetching something // from the received httpreq. - // TODO should we continue with the next attribute? Logger.error("No attribute could be retrieved from the response the attribute provider gave us."); - throw new MOAIDException("stork.11", null); - } - - // - fetch the container - String artifactId = (String) httpReq.getAttribute(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); } - - // - insert the embedded attribute(s) into the container - for (PersonalAttribute current : newAttributes) - container.getResponse().getPersonalAttributeList().add(current); + addOrUpdateAll(container.getResponse().getPersonalAttributeList(), newAttributes); // see if we need some more attributes return processRequest(container, httpReq, httpResp, moasession, oaParam); @@ -110,8 +100,6 @@ public class AttributeCollector implements IAction { */ public String processRequest(DataContainer container, HttpServletRequest request, HttpServletResponse response, AuthenticationSession moasession, OAAuthParameter oaParam) throws MOAIDException { // check if there are attributes we need to fetch - this.httpResp = response; - this.container = container; IPersonalAttributeList requestAttributeList = container.getRequest().getPersonalAttributeList(); IPersonalAttributeList responseAttributeList = container.getResponse().getPersonalAttributeList(); @@ -124,33 +112,42 @@ public class AttributeCollector implements IAction { try { // for each attribute still missing for (PersonalAttribute currentAttribute : missingAttributes) { - // - check if we can find a suitable AttributeProvider Plugin + + /* + * 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("notAvailable"); + addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes); + + // - check if we can find a suitable AttributeProvider Plugin for (AttributeProvider currentProvider : AttributeProviderFactory.getConfiguredPlugins(oaParam.getStorkAPs())) { try { // - hand over control to the suitable plugin - IPersonalAttributeList aquiredAttributes = currentProvider.acquire(currentAttribute, moasession); - - // - add the aquired attribute to the container - for (PersonalAttribute current : aquiredAttributes) - container.getResponse().getPersonalAttributeList().add(current); - //TODO: return after first AP - + aquiredAttributes = currentProvider.acquire(currentAttribute, moasession); + break; } catch (UnsupportedAttributeException e) { // ok, try the next attributeprovider } catch (MOAIDException e) { // the current plugin had an error. Try the next one. - // TODO we might want to add the non-fetchable attribute as "NotAvailable" to prevent an infinite loop } - } + + // 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 + addOrUpdateAll(container.getResponse().getPersonalAttributeList(), aquiredAttributes); } // build response - generateSTORKResponse(); + generateSTORKResponse(container); // set new http response - generateRedirectResponse(); - response = httpResp; + generateRedirectResponse(response, container); return "12345"; // AssertionId @@ -165,34 +162,37 @@ public class AttributeCollector implements IAction { AssertionStorage.getInstance().put(newArtifactId, container); // add container-key to redirect embedded within the return URL - e.getAp().performRedirect(AuthConfigurationProvider.getInstance().getPublicURLPrefix() + "/dispatcher?mod=id_stork2&action=AttributeCollector&" + ARTIFACT_ID + "=" + newArtifactId, container.getRequest().getCitizenCountryCode(), request, response, oaParam); - - - + e.getAp().performRedirect(AuthConfigurationProvider.getInstance().getPublicURLPrefix() + "/stork2/ResumeAuthentication?" + ARTIFACT_ID + "=" + newArtifactId, container.getRequest().getSpCountry(), 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", e); + Logger.error("Error putting incomplete Stork response into temporary storage", e1); throw new MOAIDException("stork.11", null); } return "12345"; // TODO what to do here? } - - } - - private void generateSTORKResponse() throws MOAIDException { - STORKAuthnResponse authnResponse = container.getResponse(); - STORKAuthnRequest authnRequest = container.getRequest(); + /** + * generates binary response from given response class. + * + * @param container the container + * @throws MOAIDException the mOAID exception + */ + private void generateSTORKResponse(DataContainer container) throws MOAIDException { + MOASTORKRequest request = container.getRequest(); + MOASTORKResponse response = container.getResponse(); try { //Get SAMLEngine instance STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); Logger.debug("Starting generation of SAML response"); - authnResponse = engine.generateSTORKAuthnResponse(authnRequest, authnResponse, container.getRemoteAddress(), false); - + 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) { @@ -201,36 +201,32 @@ public class AttributeCollector implements IAction { } Logger.info("STORK SAML Response message succesfully generated "); - String statusCodeValue = authnResponse.getStatusCode(); - - try { - Logger.debug("authn saml plain:" + authnResponse.getTokenSaml()); - Logger.debug("authn saml string:" + new String(authnResponse.getTokenSaml())); // works - Logger.debug("authn saml encodedx: " + new String(org.bouncycastle.util.encoders.Base64.encode(IOUtils.toString(authnResponse.getTokenSaml()).getBytes()))); - - } catch (IOException e) { - e.printStackTrace(); - } - - container.setResponse(authnResponse); - } - - private void generateRedirectResponse() { - STORKAuthnResponse authnResponse = container.getResponse(); - STORKAuthnRequest authnRequest = container.getRequest(); - + /** + * writes the storkresponse to the httpresponse using the velocity engine. + * + * @param httpResp the http resp + * @param container the container + */ + private void generateRedirectResponse(HttpServletResponse httpResp, DataContainer container) { + MOASTORKResponse authnResponse = container.getResponse(); + MOASTORKRequest authnRequest = container.getRequest(); // 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(authnRequest.isAttrRequest()) + blob = authnResponse.getStorkAttrQueryResponse().getTokenSaml(); + else + blob = authnResponse.getStorkAuthnResponse().getTokenSaml(); - context.put("SAMLResponse", new String(org.bouncycastle.util.encoders.Base64.encode(IOUtils.toString(authnResponse.getTokenSaml()).getBytes()))); - Logger.debug("SAMLResponse original: " + new String(org.bouncycastle.util.encoders.Base64.encode(IOUtils.toString(authnResponse.getTokenSaml()).getBytes()))); + context.put("SAMLResponse", PEPSUtil.encodeSAMLToken(blob)); + Logger.debug("SAMLResponse original: " + new String(blob)); Logger.debug("Putting assertion consumer url as action: " + authnRequest.getAssertionConsumerServiceURL()); context.put("action", authnRequest.getAssertionConsumerServiceURL()); @@ -244,25 +240,36 @@ public class AttributeCollector implements IAction { Logger.debug("Sending html content: " + writer.getBuffer().toString()); Logger.debug("Sending html content2 : " + new String(writer.getBuffer())); - httpResp.getOutputStream().write(writer.getBuffer().toString().getBytes()); } catch (Exception e) { Logger.error("Velocity error: " + e.getMessage()); } - - //HttpSession httpSession = this.httpResp.getSession(); - //httpSession.setAttribute("STORKSessionID", "12345"); - //Logger.info("Status code again: " + authnResponse.getStatusCode()); - - //return "12345"; // AssertionId } + + /** + * Adds or updates all {@link PersonalAttribute} objects given in {@code source} to/in {@code target}. + * + * @param target the target + * @param source the source + */ + private void addOrUpdateAll(IPersonalAttributeList target, IPersonalAttributeList source) { + for (PersonalAttribute current : source) { + // check if we need to update the current pa + if (target.containsKey(current.getName())) { + target.get(current.getName()).setStatus(current.getStatus()); + target.get(current.getName()).setValue(current.getValue()); + target.get(current.getName()).setComplexValue(current.getComplexValue()); + } else + target.add(current); + } + } /* (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. + // this action does not need any authentication. The authentication is already done by the preceding AuthenticationRequest-Action. return false; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProvider.java index 59376fef6..d92b0b72f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProvider.java @@ -34,13 +34,13 @@ public interface AttributeProvider { * Perform redirect. * * @param url the return URL ending with ?artifactId=... - * @param citizenCountyCode the citizen county code + * @param spCountyCode the sp county code * @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 + * @throws MOAIDException the mOAID exception */ - public void performRedirect(String url, String citizenCountyCode, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException; + public void performRedirect(String url, String spCountyCode, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException; /** * Parses the response we got from the external attribute provider. @@ -52,4 +52,5 @@ public interface AttributeProvider { */ public IPersonalAttributeList parse(HttpServletRequest httpReq) throws UnsupportedAttributeException, MOAIDException; + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java index 97bb6f480..538e59401 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AttributeProviderFactory.java @@ -1,10 +1,10 @@ package at.gv.egovernment.moa.id.protocols.stork2; +import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; + import java.util.ArrayList; import java.util.List; -import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; - /** * A factory for creating AttributeProvider objects. */ @@ -19,10 +19,12 @@ public class AttributeProviderFactory { List<String> result = new ArrayList<String>(); result.add("StorkAttributeRequestProvider"); result.add("EHvdAttributeProvider"); - result.add("SignedDocAttributeRequestProvider"); + result.add("SignedDocAttributeRequestProvider"); + result.add("MISAttributeProvider"); - return result; - } + + return result; + } /** * Creates an AttributeProvider object for the given shortname. Returns @@ -37,26 +39,28 @@ public class AttributeProviderFactory { return new StorkAttributeRequestProvider(url); } else if(shortname.equals("EHvdAttributeProvider")) { return new EHvdAttributeProviderPlugin(url); - } else if(shortname.equals("SignedDocAttributeRequestProvider")) { - return new SignedDocAttributeRequestProvider(url); - } else { + } else if(shortname.equals("SignedDocAttributeRequestProvider")) { + return new SignedDocAttributeRequestProvider(url); + } else if (shortname.equals("MISAttributeProvider")) { + return new MISAttributeProvider(url); + } else { return null; } } - /** - * Gets fresh instances of the configured plugins. - * - * @param configuredAPs the configured a ps - * @return the configured plugins - */ - public static List<AttributeProvider> getConfiguredPlugins( - List<AttributeProviderPlugin> configuredAPs) { - - List<AttributeProvider> result = new ArrayList<AttributeProvider>(); - for(AttributeProviderPlugin current : configuredAPs) - result.add(create(current.getName(), current.getUrl())); - - return result; - } + /** + * Gets fresh instances of the configured plugins. + * + * @param configuredAPs the configured a ps + * @return the configured plugins + */ + public static List<AttributeProvider> getConfiguredPlugins( + List<AttributeProviderPlugin> configuredAPs) { + + List<AttributeProvider> result = new ArrayList<AttributeProvider>(); + for (AttributeProviderPlugin current : configuredAPs) + result.add(create(current.getName(), current.getUrl())); + + return result; + } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java index d4996c26a..619935abe 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/AuthenticationRequest.java @@ -3,115 +3,96 @@ package at.gv.egovernment.moa.id.protocols.stork2; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.AuthenticationException; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; -import at.gv.egovernment.moa.id.auth.stork.VelocityProvider; -import at.gv.egovernment.moa.id.commons.db.dao.config.StorkAttribute; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; 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.client.mis.simple.MISMandate; import at.gv.egovernment.moa.logging.Logger; -import edu.emory.mathcs.backport.java.util.Collections; import eu.stork.peps.auth.commons.*; -import eu.stork.peps.auth.engine.STORKSAMLEngine; -import eu.stork.peps.exceptions.STORKSAMLEngineException; -import org.apache.commons.io.IOUtils; -import org.apache.velocity.Template; -import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.runtime.RuntimeConstants; -import org.opensaml.xml.util.Base64; -import org.opensaml.xml.util.XMLHelper; -import javax.servlet.ServletOutputStream; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.io.*; -import java.util.HashMap; -import eu.stork.peps.auth.engine.SAMLEngine; /** + * 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 - * Date: 12/3/13, Time: 2:08 PM */ public class AuthenticationRequest implements IAction { - /* - 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 - */ private VelocityEngine velocityEngine; - private AuthenticationSession moaSession; - private MOASTORKAuthnRequest moaStorkAuthnRequest; + private AuthenticationSession moaSession = null; + private MOASTORKRequest moaStorkRequest = null; public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession moasession) throws MOAIDException { this.moaSession = moasession; - this.moaStorkAuthnRequest = (MOASTORKAuthnRequest)req; - - Logger.debug("Starting AuthenticationRequest"); - //AuthenticationServer.getInstance().startSTORKAuthentication(httpReq, httpResp, moasession); - Logger.debug("Http Response: " + httpResp.toString() + ", "); - Logger.debug("Remote user: " + httpReq.getRemoteAddr()); - Logger.debug("Moa session: " + moasession.toString() + " " + moasession.getOAURLRequested() + " " + moasession.getPublicOAURLPrefix() + " " + moasession.getAction() + " " + moasession.getIdentityLink().getName() + " " + moasession.getTarget()); - httpResp.reset(); - - STORKAuthnResponse authnResponse = new STORKAuthnResponse(); - authnResponse.setCountry("AT"); - OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); - if (oaParam == null) - throw new AuthenticationException("stork.12", new Object[] { moasession.getPublicOAURLPrefix() }); + if (req instanceof MOASTORKRequest) { + this.moaStorkRequest = (MOASTORKRequest) req; - // Prepare basic AT attributes - try { - IPersonalAttributeList moaAttrList = moasession.getStorkAttributes(); - Logger.info("Found number of moa personal attributes: " + moasession.getStorkAttributes().size()); - + Logger.debug("Entering MOASTORKRequest"); + httpResp.reset(); + + OAAuthParameter oaParam = AuthConfigurationProvider.getInstance().getOnlineApplicationParameter(moasession.getPublicOAURLPrefix()); + if (oaParam == null) + throw new AuthenticationException("stork.12", new Object[]{moasession.getPublicOAURLPrefix()}); - for (PersonalAttribute personalAttribute : moaAttrList) { - Logger.info("Personal attribute found: " + personalAttribute.getName() + personalAttribute.getStatus()); - if (personalAttribute.getValue().size() > 0) { - for (String value : personalAttribute.getValue()) { - Logger.info(" Value found: " + value); - } - } + MOASTORKResponse moaStorkResponse = new MOASTORKResponse(); + + // 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"); - } catch (Exception e) { - Logger.error("Exception, attributes: " + e.getMessage()); - } + moaStorkResponse.setSTORKAuthnResponse(new STORKAuthnResponse()); + // Get personal attributtes from MOA/IdentityLink + moaStorkResponse.setPersonalAttributeList(populateAttributes()); + } + + moaStorkResponse.setCountry(moaStorkRequest.getSpCountry()); - // Get personal attributtes from MOA/IdentityLink - authnResponse.setPersonalAttributeList(populateAttributes()); + // Prepare extended attributes + Logger.debug("Preparing data container"); - // Prepare extended attributes - Logger.debug("Preparing data container"); + // create fresh container + DataContainer container = new DataContainer(); - // create fresh container - DataContainer container = new DataContainer(); + // - fill in the request we extracted above + container.setRequest(moaStorkRequest); - // - fill in the request we extracted above - container.setRequest(((MOASTORKAuthnRequest) req).getStorkAuthnRequest()); - - // - fill in the partial response created above - container.setResponse(authnResponse); - - // - memorize the target url were we have to return the result - container.setTarget(((MOASTORKAuthnRequest) req).getStorkAuthnRequest().getAssertionConsumerServiceURL()); + // - fill in the partial response created above + container.setResponse(moaStorkResponse); - container.setRemoteAddress(httpReq.getRemoteAddr()); + // - memorize the target url were we have to return the result + container.setTarget(moaStorkRequest.getAssertionConsumerServiceURL()); + container.setRemoteAddress(httpReq.getRemoteAddr()); - Logger.debug("Data container prepared"); - return (new AttributeCollector()).processRequest(container, httpReq, httpResp, moasession, oaParam); + Logger.debug("Data container prepared"); + return (new AttributeCollector()).processRequest(container, httpReq, httpResp, moasession, oaParam); + } else { + Logger.error("Could not recognize request."); + throw new MOAIDException("stork.15", null); + } } public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { @@ -119,21 +100,52 @@ public class AuthenticationRequest implements IAction { } + 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(AuthenticationSession moasession) { + + if (moasession.getUseMandate()) { + try { + MISMandate mandate = moasession.getMISMandate(); + String owbpk = mandate.getOWbPK(); + byte[] mand = mandate.getMandate(); + String profprep = mandate.getProfRep(); + //String textdesc = mandate.getTextualDescriptionOfOID(); + Element mndt = moasession.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() { - IPersonalAttributeList attrLst = moaStorkAuthnRequest.getStorkAuthnRequest().getPersonalAttributeList(); - Logger.info("Found " + attrLst.size() + " personal attributes in the request." ); + 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(moaSession.getIdentityLink()); + MOAAttributeProvider moaAttributeProvider = new MOAAttributeProvider(moaSession.getIdentityLink(), moaStorkRequest); try { for (PersonalAttribute personalAttribute : attrLst) { Logger.debug("Personal attribute found in request: " + personalAttribute.getName() + " isRequired: " + personalAttribute.isRequired()); moaAttributeProvider.populateAttribute(attributeList, personalAttribute); } - } catch (Exception e) { + } catch (Exception e) { Logger.error("Exception, attributes: " + e.getMessage()); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java index 44ad0000a..74239318b 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/DataContainer.java @@ -2,10 +2,6 @@ package at.gv.egovernment.moa.id.protocols.stork2; import java.io.Serializable; -import eu.stork.peps.auth.commons.STORKAuthnRequest; -import eu.stork.peps.auth.commons.STORKAuthnResponse; - -// TODO: Auto-generated Javadoc /** * Holds info about an ongoing but yet incomplete stork authnrequest process. */ @@ -15,31 +11,33 @@ public class DataContainer implements Serializable { private static final long serialVersionUID = -8765997480582363012L; /** The incoming request. */ - private STORKAuthnRequest request; + private MOASTORKRequest request; /** The yet incomplete response. */ - private STORKAuthnResponse response; + private MOASTORKResponse response; /** The target. */ private String target; - private String remoteAddress; - - /** + + /** The remote address. */ + private String remoteAddress; + + /** * Gets the request. * * @return the request */ - public STORKAuthnRequest getRequest() { + public MOASTORKRequest getRequest() { return request; } /** * Sets the request. * - * @param request the new request + * @param moaStorkRequest the new request */ - public void setRequest(STORKAuthnRequest request) { - this.request = request; + public void setRequest(MOASTORKRequest moaStorkRequest) { + this.request = moaStorkRequest; } /** @@ -47,17 +45,17 @@ public class DataContainer implements Serializable { * * @return the response */ - public STORKAuthnResponse getResponse() { + public MOASTORKResponse getResponse() { return response; } /** * Sets the response. * - * @param response the new response + * @param moaStorkResponse the new response */ - public void setResponse(STORKAuthnResponse response) { - this.response = response; + public void setResponse(MOASTORKResponse moaStorkResponse) { + this.response = moaStorkResponse; } /** @@ -77,13 +75,22 @@ public class DataContainer implements Serializable { public void setTarget(String target) { this.target = target; } - - /* - Sets IP address - */ - public void setRemoteAddress(String address) { this.remoteAddress = address; } - public String getRemoteAddress() { - return this.remoteAddress; - } - + + /** + * 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/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/EHvdAttributeProviderPlugin.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/EHvdAttributeProviderPlugin.java index 758b70f2d..d387bfcea 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/EHvdAttributeProviderPlugin.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/EHvdAttributeProviderPlugin.java @@ -8,6 +8,7 @@ import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPBody; @@ -27,6 +28,7 @@ import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; +import at.gv.egovernment.moa.id.auth.builder.BPKBuilder; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; @@ -60,7 +62,7 @@ public class EHvdAttributeProviderPlugin implements AttributeProvider { ExternalAttributeRequestRequiredException, MOAIDException { // break when we cannot handle the requested attribute - if(!attributes.getFriendlyName().equals("isHCP")) + if(!attributes.getName().equals("isHealthCareProfessional")) throw new UnsupportedAttributeException(); try { @@ -94,8 +96,9 @@ public class EHvdAttributeProviderPlugin implements AttributeProvider { // SOAP Body SOAPBody requestBody = envelope.getBody(); SOAPElement requestBodyElem = requestBody.addChildElement("IsHealthcareProfessional"); + requestBodyElem.addAttribute(new QName("xmlns"), "http://gesundheit.gv.at/BAGDAD/DataAccessService"); SOAPElement requestBodyElem1 = requestBodyElem.addChildElement("bPK"); - requestBodyElem1.addTextNode(moasession.getIdentityLink().getIdentificationValue()); + requestBodyElem1.addTextNode(new BPKBuilder().buildBPK(moasession.getIdentityLink().getIdentificationValue(), "GH")); requestMessage.saveChanges(); @@ -153,26 +156,34 @@ public class EHvdAttributeProviderPlugin implements AttributeProvider { if (collection.get("IsHealthcareProfessional").equals("false")) { // the citizen is no HCP - acquiredAttribute = new PersonalAttribute("isHCP", false, new ArrayList<String>(), "NotAvailable"); + acquiredAttribute = new PersonalAttribute("isHealthCareProfessional", false, new ArrayList<String>(), "NotAvailable"); } else { // go on and parse the data Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); + + // create the root element + Element root = doc.createElement("isHealthCareProfessional"); + doc.appendChild(root); Element orgname = doc.createElement("nameOfOrganisation"); - orgname.appendChild(doc.createTextNode(collection.get("NameOfOrganization"))); - doc.appendChild(orgname); + orgname.appendChild(doc.createTextNode(collection.get("NameOfOrganisation"))); + root.appendChild(orgname); Element type = doc.createElement("HCP"); // TODO fix value mapping - if (collection.get("Type").equals("Medical Doctors")) + if (collection.get("Type").equals("Medical doctor")) type.appendChild(doc.createTextNode("D")); - doc.appendChild(type); + root.appendChild(type); Element specialization = doc.createElement("specialisation"); - // TODO fix value mapping - specialization.appendChild(doc.createTextNode(collection.get("Specialization").substring(0, 2))); - doc.appendChild(specialization); + if (collection.get("Specialization").contains("Arzt für Allgemeinmedizin")) + specialization.appendChild(doc.createTextNode("GP")); + root.appendChild(specialization); + + Element aqaa = doc.createElement("AQAA"); + aqaa.appendChild(doc.createTextNode("4")); + root.appendChild(aqaa); // get string from dom tree Source source = new DOMSource(doc); @@ -186,12 +197,18 @@ public class EHvdAttributeProviderPlugin implements AttributeProvider { ArrayList<String> value = new ArrayList<String>(); value.add(out.toString()); - acquiredAttribute = new PersonalAttribute("isHCP", false, value, "Available"); + acquiredAttribute = new PersonalAttribute("isHealthCareProfessional", false, value, "Available"); } // 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().buildStorkbPK(moasession.getIdentityLink().getIdentificationValue(), "IT")); + result.add(new PersonalAttribute("eIdentifier", false, value, "Available")); + return result; } catch (Exception e) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java index 29b09487b..56f31723c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/ExternalAttributeRequestRequiredException.java @@ -1,12 +1,27 @@ package at.gv.egovernment.moa.id.protocols.stork2; public class ExternalAttributeRequestRequiredException extends Exception { + + /** The Constant serialVersionUID. */ + private static final long serialVersionUID = 5207631348933518908L; + + /** The ap. */ private AttributeProvider ap; + /** + * Instantiates a new external attribute request required exception. + * + * @param provider the provider + */ public ExternalAttributeRequestRequiredException(AttributeProvider provider) { ap = provider; } + /** + * Gets the ap. + * + * @return the ap + */ public AttributeProvider getAp() { return ap; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MISAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MISAttributeProvider.java new file mode 100644 index 000000000..ec38db513 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MISAttributeProvider.java @@ -0,0 +1,47 @@ +package at.gv.egovernment.moa.id.protocols.stork2; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; +import at.gv.egovernment.moa.logging.Logger; +import eu.stork.peps.auth.commons.IPersonalAttributeList; +import eu.stork.peps.auth.commons.PersonalAttribute; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Implements Attribute Provider for Mandates + */ +public class MISAttributeProvider implements AttributeProvider { + + String url = null; + + public MISAttributeProvider(String url) { + this.url = url; + } + + public IPersonalAttributeList acquire(PersonalAttribute attributes, AuthenticationSession moasession) throws UnsupportedAttributeException, ExternalAttributeRequestRequiredException, MOAIDException { + Logger.error("Entering MIS for attribute: " + attributes.getName()); + + if (attributes.getName().equals("residencePermit")) { + Logger.error("MIS EXCEPTION: " + attributes.getName()); + //throw new ExternalAttributeRequestRequiredException(this); + } + + return null; // + } + + public void performRedirect(String url, String citizenCountyCode, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException { + Logger.error("Entering MIS redirect for attribute: " ); + + } + + public IPersonalAttributeList parse(HttpServletRequest httpReq) throws UnsupportedAttributeException, MOAIDException { + return null; // + } + + public String getName() { + return "MandateProvider"; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java index 414e383fa..d89fb8cb2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOAAttributeProvider.java @@ -1,6 +1,8 @@ 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.BuildException; import at.gv.egovernment.moa.logging.Logger; import eu.stork.peps.auth.commons.PersonalAttribute; import eu.stork.peps.auth.commons.PersonalAttributeList; @@ -20,6 +22,7 @@ public class MOAAttributeProvider { private final IdentityLink identityLink; private static final Map<String, String> storkAttributeSimpleMapping; private static final Map<String, String> storkAttributeFunctionMapping; + private final MOASTORKRequest moastorkRequest; static { Map<String, String> tempSimpleMap = new HashMap<String, String>(); @@ -32,8 +35,9 @@ public class MOAAttributeProvider { storkAttributeFunctionMapping = Collections.unmodifiableMap(tempFunctionMap); } - public MOAAttributeProvider(IdentityLink identityLink) { + public MOAAttributeProvider(IdentityLink identityLink, MOASTORKRequest moastorkRequest) { this.identityLink = identityLink; + this.moastorkRequest = moastorkRequest; Logger.debug("identity " + identityLink.getIdentificationType() + " " + identityLink.getIdentificationValue()); } @@ -66,9 +70,16 @@ public class MOAAttributeProvider { } private String geteIdentifier() { - return "askdlaskdlaskdsds"; + Logger.debug("Using base urn for identification value: " + identityLink.getIdentificationType() + " and target country: " + moastorkRequest.getStorkAuthnRequest().getSpCountry()); + try { + return new BPKBuilder().buildStorkbPK(identityLink.getIdentificationValue(), moastorkRequest.getStorkAuthnRequest().getSpCountry()); + } catch (BuildException be) { + Logger.error("Stork eid could not be constructed; " + be.getMessage()); + return null; // TODO error + } } + private void populateAttributeWithMethod(Method method, Object object, PersonalAttributeList attributeList, String storkAttribute, Boolean isRequired) { try { String attributeValue = method.invoke(object, new Class[]{}).toString(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKAuthnRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKAuthnRequest.java deleted file mode 100644 index 8c9e288e3..000000000 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKAuthnRequest.java +++ /dev/null @@ -1,76 +0,0 @@ -package at.gv.egovernment.moa.id.protocols.stork2; - -import java.io.Serializable; - -import at.gv.egovernment.moa.id.moduls.IRequest; -import eu.stork.peps.auth.commons.STORKAuthnRequest; -import org.opensaml.common.xml.SAMLConstants; - -/** - * @author bsuzic - * Date: 12/4/13, Time: 6:31 PM - */ - -public class MOASTORKAuthnRequest implements IRequest, Serializable { - private static final long serialVersionUID = 1L; - - - private String requestID; - private String target = null; - String module = null; - String action = null; - private STORKAuthnRequest storkAuthnRequest; - - public void setSTORKAuthnRequest(STORKAuthnRequest request) { - this.storkAuthnRequest = request; - } - - public STORKAuthnRequest getStorkAuthnRequest() { - return this.storkAuthnRequest; - } - - public String getOAURL() { - - return "https://sp:8889/SP"; // - } - - public boolean isPassiv() { - return false; // - } - - public boolean forceAuth() { - return false; // - } - - public boolean isSSOSupported() { - return false; // - } - - public String requestedModule() { - return this.module; // - } - - public String requestedAction() { - return action; // - } - - public void setModule(String module) { - this.module = module; - } - - public void setAction(String action) { - this.action = action; - } - - public String getTarget() { - return this.target; // - } - - public void setRequestID(String id) { - this.requestID = id; - } - - public String getRequestID() { - return this.requestID; // - } -} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java new file mode 100644 index 000000000..e95cfabe2 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKRequest.java @@ -0,0 +1,130 @@ +package at.gv.egovernment.moa.id.protocols.stork2; + +import java.io.Serializable; + +import at.gv.egovernment.moa.id.moduls.IRequest; +import at.gv.egovernment.moa.logging.Logger; +import eu.stork.peps.auth.commons.IPersonalAttributeList; +import eu.stork.peps.auth.commons.STORKAttrQueryRequest; +import eu.stork.peps.auth.commons.STORKAuthnRequest; + +/** + * Implements MOA request and stores StorkAuthn/Attr-Request related data + * + * @author bsuzic + */ + +public class MOASTORKRequest implements IRequest, Serializable { + private static final long serialVersionUID = 4581953368724501376L; + private String requestID; + private String target = null; + String module = null; + String action = null; + private STORKAuthnRequest storkAuthnRequest; + private STORKAttrQueryRequest storkAttrQueryRequest; + private boolean isAttrRequest = false; + private boolean isAuthnRequest = false; + + public void setSTORKAuthnRequest(STORKAuthnRequest request) { + this.storkAuthnRequest = request; + if (request != null) { + isAuthnRequest = true; + } + } + + public void setSTORKAttrRequest(STORKAttrQueryRequest request) { + this.storkAttrQueryRequest = request; + if (request != null) { + isAttrRequest = true; + } + } + + public boolean isAttrRequest() { + return this.isAttrRequest; + } + + public boolean isAuthnRequest() { + return this.isAuthnRequest; + } + + + public STORKAuthnRequest getStorkAuthnRequest() { + return this.storkAuthnRequest; + } + + public STORKAttrQueryRequest getStorkAttrQueryRequest() { + return this.storkAttrQueryRequest; + } + + public String getOAURL() { // TODO CHECK IT + 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; + } + } + + public boolean isPassiv() { + return false; + } + + public boolean forceAuth() { + return false; + } + + public boolean isSSOSupported() { + return false; + } + + public String requestedModule() { + return this.module; + } + + public String requestedAction() { + return action; + } + + public void setModule(String module) { + this.module = module; + } + + public void setAction(String action) { + this.action = action; + } + + public String getTarget() { + return this.target; + } + + public void setRequestID(String id) { + this.requestID = id; + } + + public String getRequestID() { + return this.requestID; + } + + public IPersonalAttributeList getPersonalAttributeList() { + if(isAttrRequest()) + return this.storkAttrQueryRequest.getPersonalAttributeList(); + else + return this.storkAuthnRequest.getPersonalAttributeList(); + } + + public String getSpCountry() { + if(isAttrRequest()) + return this.storkAttrQueryRequest.getSpCountry(); + else + return this.storkAuthnRequest.getSpCountry(); + } + + public String getAssertionConsumerServiceURL() { + if(isAttrRequest()) + return this.storkAttrQueryRequest.getAssertionConsumerServiceURL(); + else + return this.storkAuthnRequest.getAssertionConsumerServiceURL(); + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java new file mode 100644 index 000000000..36f5a80b4 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MOASTORKResponse.java @@ -0,0 +1,75 @@ +package at.gv.egovernment.moa.id.protocols.stork2; + +import java.io.Serializable; + +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; + +/** + * Implements MOA request and stores StorkAuthn/Attr-Request related data + * + * @author bsuzic + */ + +public class MOASTORKResponse implements Serializable { + private static final long serialVersionUID = -5798803155055518747L; + private STORKAuthnResponse storkAuthnRequest; + private STORKAttrQueryResponse storkAttrQueryRequest; + private boolean isAttrRequest = false; + private boolean isAuthnRequest = false; + + public void setSTORKAuthnResponse(STORKAuthnResponse request) { + this.storkAuthnRequest = request; + if (request != null) { + isAuthnRequest = true; + } + } + + public void setSTORKAttrResponse(STORKAttrQueryResponse request) { + this.storkAttrQueryRequest = request; + if (request != null) { + isAttrRequest = true; + } + } + + public boolean isAttrResponse() { + return this.isAttrRequest; + } + + public boolean isAuthnResponse() { + return this.isAuthnRequest; + } + + + public STORKAuthnResponse getStorkAuthnResponse() { + return this.storkAuthnRequest; + } + + public STORKAttrQueryResponse getStorkAttrQueryResponse() { + return this.storkAttrQueryRequest; + } + + public IPersonalAttributeList getPersonalAttributeList() { + if(isAttrResponse()) + return this.storkAttrQueryRequest.getPersonalAttributeList(); + else + return this.storkAuthnRequest.getPersonalAttributeList(); + } + + public void setPersonalAttributeList(PersonalAttributeList populateAttributes) { + if(isAttrResponse()) + this.storkAttrQueryRequest.setPersonalAttributeList(populateAttributes); + else + this.storkAuthnRequest.setPersonalAttributeList(populateAttributes); + } + + public void setCountry(String spCountry) { + if(isAttrResponse()) + this.storkAttrQueryRequest.setCountry(spCountry); + else + this.storkAuthnRequest.setCountry(spCountry); + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java new file mode 100644 index 000000000..bad711dbb --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/MandateRetrievalRequest.java @@ -0,0 +1,28 @@ +package at.gv.egovernment.moa.id.protocols.stork2; + +import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.moduls.IAction; +import at.gv.egovernment.moa.id.moduls.IRequest; +import com.sun.xml.ws.security.trust.WSTrustConstants; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +/** + * Processes mandate data after authentication is done in AT + * @author bsuzic + */ +public class MandateRetrievalRequest implements IAction { + public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession moasession) throws MOAIDException { + return null; // + } + + public boolean needAuthentication(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp) { + return true; + } + + public String getDefaultActionName() { + return STORKProtocol.MANDATERETRIEVALREQUEST; + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java index 34f953514..a361d5f67 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/STORKProtocol.java @@ -5,27 +5,23 @@ import at.gv.egovernment.moa.id.auth.exception.MOAIDException; 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.pvp2x.binding.MOAURICompare; import at.gv.egovernment.moa.logging.Logger; -import eu.stork.peps.auth.commons.PEPSUtil; +import eu.stork.peps.auth.commons.*; import eu.stork.peps.auth.engine.STORKSAMLEngine; import eu.stork.peps.exceptions.STORKSAMLEngineException; import org.opensaml.common.binding.BasicSAMLMessageContext; -import org.opensaml.saml2.binding.decoding.HTTPPostDecoder; import org.opensaml.ws.transport.http.HTTPInTransport; import org.opensaml.ws.transport.http.HTTPOutTransport; import org.opensaml.ws.transport.http.HttpServletRequestAdapter; import org.opensaml.ws.transport.http.HttpServletResponseAdapter; -import eu.stork.peps.auth.commons.STORKAuthnRequest; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import java.util.Collections; import java.util.HashMap; /** * Stork 2 Protocol Support - * Date: 11/29/13, Time: 12:32 PM + * * @author bsuzic */ public class STORKProtocol implements IModulInfo, MOAIDAuthConstants { @@ -34,7 +30,8 @@ public class STORKProtocol implements IModulInfo, MOAIDAuthConstants { public static final String PATH = "id_stork2"; public static final String AUTHENTICATIONREQUEST = "AuthenticationRequest"; - public static final String ATTRIBUTE_COLLECTOR = "AttributeCollector"; + public static final String ATTRIBUTE_COLLECTOR = "AttributeCollector"; + public static final String MANDATERETRIEVALREQUEST = "MandateRetrievalRequest"; private static HashMap<String, IAction> actions = new HashMap<String, IAction>(); @@ -62,7 +59,7 @@ public class STORKProtocol implements IModulInfo, MOAIDAuthConstants { } public STORKProtocol() { - super(); // + super(); } /* @@ -71,90 +68,60 @@ public class STORKProtocol implements IModulInfo, MOAIDAuthConstants { */ public IRequest preProcess(HttpServletRequest request, HttpServletResponse response, String action) throws MOAIDException { Logger.debug("Starting preprocessing"); - Logger.debug("Got request: " + request.toString()); Logger.debug("Request method: " + request.getMethod()); - for (Object o : Collections.list(request.getHeaderNames())) { - Logger.debug("Request header: " + o.toString() + ":::" + request.getHeader(o.toString())); - } - for (Object o : Collections.list(request.getParameterNames())) { - Logger.debug("Request parameter: " + o.toString() + "::::" + request.getParameter(o.toString())); - } - Logger.debug("Request content length: " + request.getContentLength()); - Logger.debug("Request query: " + request.getQueryString()); - Logger.debug("Response: " + response.toString()); - Logger.debug("Action: " + action); + Logger.debug("Initiating action: " + action); - Logger.debug("Processing saml request"); - String SAMLRequest = request.getParameter("SAMLRequest"); + MOASTORKRequest STORK2Request = new MOASTORKRequest(); + + if (AttributeCollector.class.getSimpleName().equals(action)) + return STORK2Request; HTTPInTransport profileReq = new HttpServletRequestAdapter(request); HTTPOutTransport profileResp = new HttpServletResponseAdapter(response, request.isSecure()); - BasicSAMLMessageContext samlMessageContext = new BasicSAMLMessageContext(); samlMessageContext.setInboundMessageTransport(profileReq); - HTTPPostDecoder postDecoder = new HTTPPostDecoder(); - postDecoder.setURIComparator(new MOAURICompare()); // TODO Abstract to use general comparator - - try { - Logger.debug("Attempting to decode request..."); - postDecoder.decode(samlMessageContext); - } catch (Exception e) { - Logger.error("Error decoding STORKAuthnRequest", e); - } - /* - - STORKAuthnRequestImpl ST2Req = (STORKAuthnRequestImpl)samlMessageContext.getInboundSAMLMessage(); - //MOASTORKAuthnRequest STORK2Request = (MOASTORKAuthnRequest)samlMessageContext.getInboundSAMLMessage(); - MOASTORKAuthnRequest STORK2Request = new MOASTORKAuthnRequest(); - STORK2Request.setSTORKAuthnRequest(ST2Req); - - Logger.debug("STORK2 Citizen code: " + ST2Req.getCitizenCountryCode()); - Logger.debug("STORK2 QAA: " + ST2Req.getQAALevel()); - Logger.debug("STORK2 ISSUER: " + ST2Req.getIssuer().toString()); - - */ - //STORKAuthnReq storkAuthnReq = new STORKAuthnReq(); - - - MOASTORKAuthnRequest STORK2Request = new MOASTORKAuthnRequest(); - - //extract STORK Response from HTTP Request - //Decodes SAML Response - - byte[] decSamlToken; try { decSamlToken = PEPSUtil.decodeSAMLToken(request.getParameter("SAMLRequest")); - } catch(NullPointerException e) { - Logger.error("Unable to retrieve STORK Response", e); + } catch (NullPointerException e) { + Logger.error("Unable to retrieve STORK Request", e); throw new MOAIDException("stork.04", null); } //Get SAMLEngine instance - STORKSAMLEngine engine = STORKSAMLEngine.getInstance("VIDP"); + STORKSAMLEngine authnEngine = STORKSAMLEngine.getInstance("incoming"); + STORKSAMLEngine attrEngine = STORKSAMLEngine.getInstance("incoming_attr"); STORKAuthnRequest authnRequest = null; - Logger.error("decsamltoken" +decSamlToken.toString()); + STORKAttrQueryRequest attrRequest = null; + // check if valid authn request is contained try { - authnRequest = engine.validateSTORKAuthnRequest(decSamlToken); + authnRequest = authnEngine.validateSTORKAuthnRequest(decSamlToken); } catch (STORKSAMLEngineException ex) { - Logger.error("Unable to validate storkrkauthnreqeust" + ex.getMessage() ); + 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 = attrEngine.validateSTORKAttrQueryRequest(decSamlToken); + } catch (STORKSAMLEngineException ex) { + Logger.error("Unable to validate Stork AuthenticationRequest: " + ex.getMessage()); + } } - Logger.error("acsu " + authnRequest.getAssertionConsumerServiceURL()); - Logger.error("cc " + authnRequest.getCitizenCountryCode()); - Logger.error("iss " + authnRequest.getIssuer()); - Logger.error("spid " + authnRequest.getSPID()); - Logger.error("spi " + authnRequest.getSpInstitution()); - + // 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); + } STORK2Request.setSTORKAuthnRequest(authnRequest); - + STORK2Request.setSTORKAttrRequest(attrRequest); return STORK2Request; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/StorkAttributeRequestProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/StorkAttributeRequestProvider.java index 4314e666e..797695a00 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/StorkAttributeRequestProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/stork2/StorkAttributeRequestProvider.java @@ -89,12 +89,11 @@ public class StorkAttributeRequestProvider implements AttributeProvider { /* (non-Javadoc) * @see at.gv.egovernment.moa.id.protocols.stork2.AttributeProvider#performRedirect(java.lang.String) */ - public void performRedirect(String url, String citizenCountryCode, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException { + public void performRedirect(String url, String spCountryCode, HttpServletRequest req, HttpServletResponse resp, OAAuthParameter oaParam) throws MOAIDException { String spSector = "Business"; String spInstitution = StringUtils.isEmpty(oaParam.getFriendlyName()) ? "UNKNOWN" : oaParam.getFriendlyName(); String spApplication = spInstitution; - String spCountry = "AT"; //generate AuthnRquest STORKAttrQueryRequest attributeRequest = new STORKAttrQueryRequest(); @@ -103,12 +102,13 @@ public class StorkAttributeRequestProvider implements AttributeProvider { attributeRequest.setIssuer(HTTPUtils.getBaseURL(req)); attributeRequest.setQaa(oaParam.getQaaLevel()); attributeRequest.setSpInstitution(spInstitution); - attributeRequest.setCountry(spCountry); + attributeRequest.setCountry(spCountryCode); + attributeRequest.setSpCountry(spCountryCode); attributeRequest.setSpApplication(spApplication); attributeRequest.setSpSector(spSector); attributeRequest.setPersonalAttributeList(requestedAttributes); - attributeRequest.setCitizenCountryCode(citizenCountryCode); + attributeRequest.setCitizenCountryCode("AT"); Logger.debug("STORK AttrRequest succesfully assembled."); |