diff options
Diffstat (limited to 'id/server/idserverlib/src/main/java/at')
54 files changed, 1215 insertions, 645 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 306b0489d..a8c4daad7 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 @@ -302,12 +302,13 @@ 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()); + //build CertInfo request + //removed in MOA-ID 2.0 +// String certInfoRequest = new CertInfoVerifyXMLSignatureRequestBuilder() +// .build(); +// String certInfoDataURL = new DataURLBuilder() +// .buildDataURL(session.getAuthURL(), REQ_START_AUTHENTICATION, +// session.getSessionID()); //get Applet Parameters String appletwidth = req.getParameter(PARAM_APPLET_WIDTH); @@ -315,9 +316,11 @@ public class AuthenticationServer implements MOAIDAuthConstants { appletheigth = StringEscapeUtils.escapeHtml(appletheigth); appletwidth = StringEscapeUtils.escapeHtml(appletwidth); - String htmlForm = new GetIdentityLinkFormBuilder().build(template, - session.getBkuURL(), infoboxReadRequest, dataURL, certInfoRequest, - certInfoDataURL, pushInfobox, oaParam, appletheigth, appletwidth); + + //TODO: cleanup before MOA-ID 2.1 release + String htmlForm = new GetIdentityLinkFormBuilder().build(template, + session.getBkuURL(), infoboxReadRequest, dataURL, null, + null, pushInfobox, oaParam, appletheigth, appletwidth); return htmlForm; } @@ -1434,44 +1437,45 @@ public class AuthenticationServer implements MOAIDAuthConstants { AuthenticationSession session, OAAuthParameter oaParam, String target) throws ConfigurationException, BuildException { - IdentityLink identityLink = session.getIdentityLink(); - AuthenticationData authData = new AuthenticationData(); - - VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); + IdentityLink identityLink = session.getIdentityLink(); + AuthenticationData authData = new AuthenticationData(); - boolean businessService = oaParam.getBusinessService(); + VerifyXMLSignatureResponse verifyXMLSigResp = session.getXMLVerifySignatureResponse(); - authData.setMajorVersion(1); - authData.setMinorVersion(0); - authData.setAssertionID(Random.nextRandom()); - authData.setIssuer(session.getAuthURL()); + boolean businessService = oaParam.getBusinessService(); - authData.setIssueInstant(DateTimeUtils.buildDateTimeUTC(Calendar - .getInstance())); + authData.setMajorVersion(1); + authData.setMinorVersion(0); + authData.setAssertionID(Random.nextRandom()); + authData.setIssuer(session.getAuthURL()); - //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO - authData.setIdentificationValue(identityLink.getIdentificationValue()); - authData.setIdentificationType(identityLink.getIdentificationType()); + authData.setIssueInstant(DateTimeUtils.buildDateTimeUTC(Calendar + .getInstance())); - 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()); + //baseID or wbpk in case of BusinessService without SSO or BusinessService SSO + authData.setIdentificationValue(identityLink.getIdentificationValue()); + authData.setIdentificationType(identityLink.getIdentificationType()); - try { + 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()); - if (session.getUseMandate() && session.isOW()) { - MISMandate mandate = session.getMISMandate(); - authData.setBPK(mandate.getOWbPK()); - authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); - authData.setIdentityLink(identityLink); + try { - Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); + MISMandate mandate = session.getMISMandate(); + + if (session.getUseMandate() && session.isOW() + && mandate != null && MiscUtil.isNotEmpty(mandate.getOWbPK())) { + authData.setBPK(mandate.getOWbPK()); + authData.setBPKType(Constants.URN_PREFIX_CDID + "+" + "OW"); + authData.setIdentityLink(identityLink); + Logger.trace("Authenticated User is OW: " + mandate.getOWbPK()); } else { @@ -1656,31 +1660,92 @@ public class AuthenticationServer implements MOAIDAuthConstants { 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()); - + + /** + * 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), null); + } + + /** + * 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, String PEPSFiscalNumber) throws SZRGWClientException { + return getIdentityLink(PEPSIdentifier, PEPSFirstname, PEPSFamilyname, PEPSDateOfBirth, null, signature, null, null, null, null, null, null, null, PEPSFiscalNumber); + } + + /** + * 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, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { + return getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, gender, + citizenSignature, representative, represented, mandate, null, + null, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); + } + + /** + * 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, List<String> filters, String PEPSFiscalNumber) throws SZRGWClientException { + return getIdentityLink(null, null, null, null, null, + citizenSignature, represented, representative, mandateContent, organizationAddress, + organizationType, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); + } + + 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, List<String> filters, String PEPSFiscalNumber) 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); @@ -1706,10 +1771,10 @@ public class AuthenticationServer implements MOAIDAuthConstants { Filters filterObject = new Filters(); MandateIdentifiers mandateIds = new MandateIdentifiers(); - for (String current : filters.split(",")) - mandateIds.getMandateIdentifier().add(current.trim()); - filterObject.setMandateIdentifiers(mandateIds); - mis.setFilters(filterObject); + for(String current : filters) + mandateIds.getMandateIdentifier().add(current.trim()); + filterObject.setMandateIdentifiers(mandateIds); + mis.setFilters(filterObject); request.setMIS(mis); } @@ -1717,86 +1782,16 @@ public class AuthenticationServer implements MOAIDAuthConstants { 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); - } + + } + catch (ConfigurationException e) { + Logger.warn(e); + Logger.warn(MOAIDMessageProvider.getInstance().getMessage("config.12", null )); + } + + return null; + + } /** * Starts a MOA-ID authentication process using STORK diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java index 060dc2248..0173c67a1 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/MOAIDAuthConstants.java @@ -4,7 +4,10 @@ package at.gv.egovernment.moa.id.auth; import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import iaik.asn1.ObjectID; @@ -133,4 +136,24 @@ public interface MOAIDAuthConstants { public static final String PARAM_APPLET_HEIGTH = "heigth"; public static final String PARAM_APPLET_WIDTH = "width"; + public static final Map<String, String> COUNTRYCODE_XX_TO_NAME = + Collections.unmodifiableMap(new HashMap<String, String>() { + private static final long serialVersionUID = 1L; + { + put("BE", "België/Belgique"); + put("EE", "Eesti"); + put("ES", "España"); + put("FI", "Suomi"); + put("IS", "Ísland"); + put("IT", "Italia"); + put("LI", "Liechtenstein"); + put("LT", "Lithuania"); + put("LU", "Luxemburg"); + put("PT", "Portugal"); + put("SE", "Sverige"); + put("SI", "Slovenija"); + } + }); + + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java index e7e1e5cbd..f4b5cb4c9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/CreateXMLSignatureRequestBuilderForeign.java @@ -144,7 +144,7 @@ public class CreateXMLSignatureRequestBuilderForeign extends Builder { else if (ch == '<')
out.write("<");
else if (ch == '>')
- out.write(">");
+ out.write(">");
else if (ch == 'ä')
out.write("ä");
else if (ch == 'ö')
@@ -164,7 +164,7 @@ public class CreateXMLSignatureRequestBuilderForeign extends Builder { }
}
catch (IOException ex) {
- throw new BuildException("builder.00", new Object[] {"GetIdentityLinkForm", ex.toString()});
+ throw new BuildException("builder.00", new Object[] {"CreateXMLSignatureRequest", ex.toString()});
}
return out.toString();
}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java index 2e08fad6b..ab93f509c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/GetIdentityLinkFormBuilder.java @@ -72,10 +72,10 @@ public class GetIdentityLinkFormBuilder extends Builder { private static final String XMLREQUEST_TAG = "<XMLRequest>"; /** special tag in the HTML template to be substituted for the data URL */ private static final String DATAURL_TAG = "<DataURL>"; - /** special tag in the HTML template to be substituted for certificate info XML request */ - private static final String CERTINFO_XMLREQUEST_TAG = "<CertInfoXMLRequest>"; - /** special tag in the HTML template to be substituted for the certificate info data URL */ - private static final String CERTINFO_DATAURL_TAG = "<CertInfoDataURL>"; +// /** special tag in the HTML template to be substituted for certificate info XML request */ +// private static final String CERTINFO_XMLREQUEST_TAG = "<CertInfoXMLRequest>"; +// /** special tag in the HTML template to be substituted for the certificate info data URL */ +// private static final String CERTINFO_DATAURL_TAG = "<CertInfoDataURL>"; /** special tag in the HTML template to be substituted for the infoboxes to be pushed from the BKU */ private static final String PUSHINFOBOX_TAG = "<PushInfobox>"; /** special tag in the HTML template to be substituted for the BKU URL */ @@ -109,18 +109,18 @@ public class GetIdentityLinkFormBuilder extends Builder { " value=\"" + PUSHINFOBOX_TAG + "\"/>" + nl + " <input type=\"submit\" value=\"Anmeldung mit Bürgerkarte\"/>" + nl + "</form>" + nl + - "<form name=\"CertificateInfoForm\"" + nl + - " action=\"" + BKU_TAG + "\"" + nl + - " method=\"post\">" + nl + - " <input type=\"hidden\" " + nl + - " name=\"XMLRequest\"" + nl + - " value=\"" + CERTINFO_XMLREQUEST_TAG + "\"/>" + nl + - " <input type=\"hidden\" " + nl + - " name=\"DataURL\"" + nl + - " value=\"" + CERTINFO_DATAURL_TAG + "\"/>" + nl + -// " <input type=\"submit\" value=\"Information zu Wurzelzertifikaten\"/>" + nl + - " <input type=\"hidden\" value=\"Information zu Wurzelzertifikaten\"/>" + nl + - "</form>" + nl + +// "<form name=\"CertificateInfoForm\"" + nl + +// " action=\"" + BKU_TAG + "\"" + nl + +// " method=\"post\">" + nl + +// " <input type=\"hidden\" " + nl + +// " name=\"XMLRequest\"" + nl + +// " value=\"" + CERTINFO_XMLREQUEST_TAG + "\"/>" + nl + +// " <input type=\"hidden\" " + nl + +// " name=\"DataURL\"" + nl + +// " value=\"" + CERTINFO_DATAURL_TAG + "\"/>" + nl + +//// " <input type=\"submit\" value=\"Information zu Wurzelzertifikaten\"/>" + nl + +// " <input type=\"hidden\" value=\"Information zu Wurzelzertifikaten\"/>" + nl + +// "</form>" + nl + "</body>" + nl + "</html>"; @@ -164,8 +164,10 @@ public class GetIdentityLinkFormBuilder extends Builder { htmlForm = replaceTag(htmlForm, DATAURL_TAG, dataURL, true, ALL); htmlForm = replaceTag(htmlForm, PUSHINFOBOX_TAG, pushInfobox, false, ALL); //new:wird oben mitreplaced htmlForm = replaceTag(htmlForm, BKU_TAG, bkuURL); - htmlForm = replaceTag(htmlForm, CERTINFO_XMLREQUEST_TAG, encodeParameter(certInfoXMLRequest), true, ALL); - htmlForm = replaceTag(htmlForm, CERTINFO_DATAURL_TAG, certInfoDataURL, true, ALL); + + //removed in MOA-ID 2.0 +// htmlForm = replaceTag(htmlForm, CERTINFO_XMLREQUEST_TAG, encodeParameter(certInfoXMLRequest), true, ALL); +// htmlForm = replaceTag(htmlForm, CERTINFO_DATAURL_TAG, certInfoDataURL, true, ALL); Map<String, String> map = null; @@ -179,17 +181,17 @@ public class GetIdentityLinkFormBuilder extends Builder { htmlForm = replaceTag(htmlForm, REDIRECTTARGETTAG, FormBuildUtils.getDefaultMap().get(FormBuildUtils.REDIRECTTARGET), false, ALL); } - if (MiscUtil.isNotEmpty(appletheigth)) - htmlForm = replaceTag(htmlForm, APPLETHEIGHT_TAG, appletheigth, false, ALL); - else if (map != null && MiscUtil.isNotEmpty(map.get(FormBuildUtils.APPLET_HEIGHT))) + if (map != null && MiscUtil.isNotEmpty(map.get(FormBuildUtils.APPLET_HEIGHT))) htmlForm = replaceTag(htmlForm, APPLETHEIGHT_TAG, map.get(FormBuildUtils.APPLET_HEIGHT), false, ALL); + else if (MiscUtil.isNotEmpty(appletheigth)) + htmlForm = replaceTag(htmlForm, APPLETHEIGHT_TAG, appletheigth, false, ALL); else htmlForm = replaceTag(htmlForm, APPLETHEIGHT_TAG, "160", false, ALL); - if (MiscUtil.isNotEmpty(appletwidth)) - htmlForm = replaceTag(htmlForm, APPLETWIDTH_TAG, appletwidth, false, ALL); - else if (map != null && MiscUtil.isNotEmpty(map.get(FormBuildUtils.APPLET_WIDTH))) + if (map != null && MiscUtil.isNotEmpty(map.get(FormBuildUtils.APPLET_WIDTH))) htmlForm = replaceTag(htmlForm, APPLETWIDTH_TAG, map.get(FormBuildUtils.APPLET_WIDTH), false, ALL); + else if (MiscUtil.isNotEmpty(appletwidth)) + htmlForm = replaceTag(htmlForm, APPLETWIDTH_TAG, appletwidth, false, ALL); else htmlForm = replaceTag(htmlForm, APPLETWIDTH_TAG, "250", false, ALL); @@ -210,28 +212,29 @@ public class GetIdentityLinkFormBuilder extends Builder { StringWriter out = new StringWriter(); try { for (int ch = in.read(); ch >= 0; ch = in.read()) { - if (ch == '"') + if (ch == '"') { out.write("""); - else if (ch == '<') + } else if (ch == '<') { out.write("<"); - else if (ch == '>') + } else if (ch == '>') { out.write(">"); - else if (ch == 'ä') + } else if (ch == 'ä') { out.write("ä"); - else if (ch == 'ö') + } else if (ch == 'ö') { out.write("ö"); - else if (ch == 'ü') + } else if (ch == 'ü') { out.write("ü"); - else if (ch == 'Ä') + } else if (ch == 'Ä') { out.write("Ä"); - else if (ch == 'Ö') + } else if (ch == 'Ö') { out.write("Ö"); - else if (ch == 'Ãœ') + } else if (ch == 'Ãœ') { out.write("Ü"); - else if (ch == 'ß') + } else if (ch == 'ß') { out.write("ß"); - else + } else { out.write(ch); + } } } catch (IOException ex) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java index ff3b7b170..4d80be1e8 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/LoginFormBuilder.java @@ -31,9 +31,13 @@ import java.io.InputStream; import java.io.StringWriter; import java.net.URI; import java.net.URISyntaxException; +import java.util.List; import org.apache.commons.io.IOUtils; +import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; +import at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS; import at.gv.egovernment.moa.id.config.ConfigurationException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; @@ -56,6 +60,7 @@ public class LoginFormBuilder { private static String BKU_LOCAL = "#LOCAL#"; public static String CONTEXTPATH = "#CONTEXTPATH#"; private static String MOASESSIONID = "#SESSIONID#"; + private static String PEPSLIST = "#PEPSLIST#"; private static String SERVLET = CONTEXTPATH+"/GenerateIframeTemplate"; @@ -147,6 +152,34 @@ public class LoginFormBuilder { value = value.replace(CONTEXTPATH, contextpath); value = value.replace(MOASESSIONID, moaSessionID); + if (oaParam.isShowStorkLogin()) { + String pepslist = ""; + List<CPEPS> cpepsList = null; + try { + cpepsList = ConfigurationDBRead.getMOAIDConfiguration().getAuthComponentGeneral().getForeignIdentities().getSTORK().getCPEPS(); + + for (CPEPS current : oaParam.getPepsList()) + // check if master config has changed... + if(cpepsList != null && cpepsList.contains(current)) { + String countryName = null; + if (MiscUtil.isNotEmpty(MOAIDAuthConstants.COUNTRYCODE_XX_TO_NAME.get(current.getCountryCode().toUpperCase()))) + countryName = MOAIDAuthConstants.COUNTRYCODE_XX_TO_NAME.get(current.getCountryCode().toUpperCase()); + else + countryName = current.getCountryCode().toUpperCase(); + + pepslist += "<option value=" + current.getCountryCode() + ">" + + countryName + + "</option>\n"; + + } + + value = value.replace(PEPSLIST, pepslist); + + } catch (NullPointerException e) { + + } + } + value = FormBuildUtils.customiceLayoutBKUSelection(value, oaParam.isShowMandateCheckBox(), oaParam.isOnlyMandateAllowed(), diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/RedirectFormBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/RedirectFormBuilder.java index e2a736330..2a5c8d418 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/RedirectFormBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/builder/RedirectFormBuilder.java @@ -31,7 +31,8 @@ import at.gv.egovernment.moa.logging.Logger; public class RedirectFormBuilder { - private static String URL = "#URL#"; + private static String URL = "#URL#"; + private static String TARGET = "#TARGET#"; private static String template; private static String getTemplate() { @@ -53,9 +54,10 @@ public class RedirectFormBuilder { return template; } - public static String buildLoginForm(String url) { + public static String buildLoginForm(String url, String redirectTarget) { String value = getTemplate(); value = value.replace(URL, url); + value = value.replace(TARGET, redirectTarget); return value; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java index 896feed9e..13cebdbff 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/data/AuthenticationSession.java @@ -50,7 +50,6 @@ import org.w3c.dom.Element; import eu.stork.peps.auth.commons.IPersonalAttributeList; import eu.stork.peps.auth.commons.STORKAuthnRequest; - import at.gv.egovernment.moa.id.auth.validator.InfoboxValidator; import at.gv.egovernment.moa.id.auth.validator.parep.ParepUtils; import at.gv.egovernment.moa.id.protocols.oauth20.OAuth20SessionObject; @@ -220,6 +219,8 @@ public class AuthenticationSession implements Serializable { */ private STORKAuthnRequest storkAuthnRequest; + private String storkAuthnResponse; + // private AuthenticationData authData; // protocol selection @@ -1022,6 +1023,21 @@ public class AuthenticationSession implements Serializable { QAALevel = qAALevel; } + /** + * @return the storkAuthnResponse + */ + public String getStorkAuthnResponse() { + return storkAuthnResponse; + } + + /** + * @param storkAuthnResponse the storkAuthnResponse to set + */ + public void setStorkAuthnResponse(String storkAuthnResponse) { + this.storkAuthnResponse = storkAuthnResponse; + } + + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java index f4212cc78..e9afb2e68 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java @@ -67,6 +67,7 @@ import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.CreateXMLSignatureResponse;
import at.gv.egovernment.moa.id.auth.data.IdentityLink;
import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.auth.exception.ParseException;
import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
import at.gv.egovernment.moa.id.auth.parser.CreateXMLSignatureResponseParser;
import at.gv.egovernment.moa.id.auth.parser.IdentityLinkAssertionParser;
@@ -169,13 +170,29 @@ public class GetForeignIDServlet extends AuthServlet { session = AuthenticationServer.getSession(sessionID);
-
+ //change MOASessionID
+ sessionID = AuthenticationSessionStoreage.changeSessionID(session);
Logger.debug(xmlCreateXMLSignatureResponse);
CreateXMLSignatureResponse csresp =
new CreateXMLSignatureResponseParser(xmlCreateXMLSignatureResponse).parseResponseDsig();
+ try {
+ String serializedAssertion = DOMUtils.serializeNode(csresp
+ .getDsigSignature());
+ session.setAuthBlock(serializedAssertion);
+
+ } catch (TransformerException e) {
+ throw new ParseException("parser.04", new Object[] {
+ REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE });
+
+ } catch (IOException e) {
+ throw new ParseException("parser.04", new Object[] {
+ REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE });
+
+ }
+
Element signature = csresp.getDsigSignature();
try {
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java index 8bf437cca..5733cee85 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetMISSessionIDServlet.java @@ -174,6 +174,9 @@ public class GetMISSessionIDServlet extends AuthServlet { session = AuthenticationServer.getSession(sessionID); + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + String misSessionID = session.getMISSessionID(); AuthConfigurationProvider authConf = AuthConfigurationProvider diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java index f3495966a..84732d4ce 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/LogOutServlet.java @@ -54,12 +54,14 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import at.gv.egovernment.moa.id.auth.MOAIDAuthInitializer; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.moduls.AuthenticationManager; import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.moduls.SSOManager; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; public class LogOutServlet extends AuthServlet { @@ -80,6 +82,12 @@ public class LogOutServlet extends AuthServlet { //get SSO token from request String ssoid = ssomanager.getSSOSessionID(req); + if (MiscUtil.isEmpty(redirectUrl)) { + //set default redirect Target + Logger.debug("Set default RedirectURL back to MOA-ID-Auth"); + redirectUrl = AuthConfigurationProvider.getInstance().getPublicURLPrefix(); + } + if (ssomanager.isValidSSOSession(ssoid, req)) { //TODO: Single LogOut Implementation @@ -88,8 +96,7 @@ public class LogOutServlet extends AuthServlet { AuthenticationManager authmanager = AuthenticationManager.getInstance(); String moasessionid = AuthenticationSessionStoreage.getMOASessionID(ssoid); - RequestStorage.removePendingRequest(RequestStorage.getPendingRequest(req.getSession()), - AuthenticationSessionStoreage.getPendingRequestID(moasessionid)); + RequestStorage.removePendingRequest(AuthenticationSessionStoreage.getPendingRequestID(moasessionid)); authmanager.logout(req, resp, moasessionid); Logger.info("User with SSO Id " + ssoid + " is logged out and get redirect to "+ redirectUrl); @@ -105,7 +112,7 @@ public class LogOutServlet extends AuthServlet { } //Redirect to Application - resp.setStatus(301); + resp.setStatus(302); resp.addHeader("Location", redirectUrl); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java index fb0d4cd1b..328a441cd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/PEPSConnectorServlet.java @@ -38,6 +38,7 @@ import javax.xml.bind.JAXBElement; import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.IOUtils;
+import org.apache.commons.lang.StringEscapeUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
@@ -49,8 +50,10 @@ import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; import at.gv.egovernment.moa.id.auth.data.IdentityLink;
import at.gv.egovernment.moa.id.auth.exception.AuthenticationException;
import at.gv.egovernment.moa.id.auth.exception.MOAIDException;
+import at.gv.egovernment.moa.id.auth.exception.WrongParametersException;
import at.gv.egovernment.moa.id.auth.stork.STORKException;
import at.gv.egovernment.moa.id.auth.stork.STORKResponseProcessor;
+import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils;
import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException;
import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider;
import at.gv.egovernment.moa.id.config.auth.OAAuthParameter;
@@ -58,6 +61,7 @@ import at.gv.egovernment.moa.id.moduls.ModulUtils; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants;
import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage;
import at.gv.egovernment.moa.id.util.HTTPUtils;
+import at.gv.egovernment.moa.id.util.ParamValidatorUtils;
import at.gv.egovernment.moa.id.util.VelocityProvider;
import at.gv.egovernment.moa.logging.Logger;
import at.gv.egovernment.moa.util.StringUtils;
@@ -67,6 +71,7 @@ import eu.stork.oasisdss.api.ApiUtils; import eu.stork.oasisdss.api.LightweightSourceResolver;
import eu.stork.oasisdss.api.exceptions.ApiUtilsException;
import eu.stork.oasisdss.profile.SignResponse;
+import eu.stork.peps.auth.commons.IPersonalAttributeList;
import eu.stork.peps.auth.commons.PEPSUtil;
import eu.stork.peps.auth.commons.PersonalAttribute;
import eu.stork.peps.auth.commons.STORKAuthnRequest;
@@ -110,17 +115,28 @@ public class PEPSConnectorServlet extends AuthServlet { super.checkIfHTTPisAllowed(request.getRequestURL().toString());
Logger.debug("Trying to find MOA Session-ID");
- HttpSession httpSession = request.getSession();
- String moaSessionID = (String) httpSession.getAttribute("MOA-Session-ID");
+ String moaSessionID = request.getParameter(PARAM_SESSIONID);
+
+ // escape parameter strings
+ moaSessionID= StringEscapeUtils.escapeHtml(moaSessionID);
if (StringUtils.isEmpty(moaSessionID)) {
//No authentication session has been started before
Logger.error("MOA-SessionID was not found, no previous AuthnRequest had been started");
throw new AuthenticationException("auth.02", new Object[] { moaSessionID });
}
-
+
+ if (!ParamValidatorUtils.isValidSessionID(moaSessionID))
+ throw new WrongParametersException("VerifyAuthenticationBlock", PARAM_SESSIONID, "auth.12");
+
pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(moaSessionID);
+ //load MOASession from database
+ AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID);
+
+ //change MOASessionID
+ moaSessionID = AuthenticationSessionStoreage.changeSessionID(moaSession);
+
Logger.info("Found MOA sessionID: " + moaSessionID);
Logger.debug("Beginning to extract SAMLResponse out of HTTP Request");
@@ -161,10 +177,7 @@ public class PEPSConnectorServlet extends AuthServlet { }
Logger.info("Got SAML response with authentication success message.");
-
- //check if authentication request was created before
- AuthenticationSession moaSession = AuthenticationServer.getSession(moaSessionID);
-
+
Logger.debug("MOA session is still valid");
STORKAuthnRequest storkAuthnRequest = moaSession.getStorkAuthnRequest();
@@ -178,7 +191,15 @@ public class PEPSConnectorServlet extends AuthServlet { ////////////// incorporate gender from parameters if not in stork response
- PersonalAttribute gender = authnResponse.getPersonalAttributeList().get("gender");
+ IPersonalAttributeList attributeList = authnResponse.getPersonalAttributeList();
+
+ // but first, check if we have a representation case
+ if(STORKResponseProcessor.hasAttribute("mandateContent", attributeList) || STORKResponseProcessor.hasAttribute("representative", attributeList) || STORKResponseProcessor.hasAttribute("represented", attributeList)) {
+ // in a representation case...
+ moaSession.setUseMandate("true");
+
+ // and check if we have the gender value
+ PersonalAttribute gender = attributeList.get("gender");
if(null == gender) {
String gendervalue = (String) request.getParameter("gender");
if(null != gendervalue) {
@@ -191,6 +212,7 @@ public class PEPSConnectorServlet extends AuthServlet { authnResponse.getPersonalAttributeList().add(gender);
}
}
+ }
//////////////////////////////////////////////////////////////////////////
@@ -295,7 +317,7 @@ public class PEPSConnectorServlet extends AuthServlet { response.getOutputStream().write(writer.toString().getBytes());
} catch (Exception e1) {
Logger.error("Error sending gender retrival form.", e1);
- httpSession.invalidate();
+// httpSession.invalidate();
throw new MOAIDException("stork.10", null);
}
@@ -317,6 +339,9 @@ public class PEPSConnectorServlet extends AuthServlet { Logger.debug("Adding addtional STORK attributes to MOA session");
moaSession.setStorkAttributes(authnResponse.getPersonalAttributeList());
+ Logger.debug("Add full STORK AuthnResponse to MOA session");
+ moaSession.setStorkAuthnResponse(request.getParameter("SAMLResponse"));
+
//We don't have BKUURL, setting from null to "Not applicable"
moaSession.setBkuURL("Not applicable (STORK Authentication)");
@@ -363,6 +388,10 @@ public class PEPSConnectorServlet extends AuthServlet { handleError(null, e, request, response, pendingRequestID);
}
+ finally {
+ ConfigurationDBUtils.closeSession();
+ }
+
}
}
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java index 7c51e7d6b..671151bbe 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/RedirectServlet.java @@ -30,6 +30,9 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import at.gv.egovernment.moa.id.auth.builder.RedirectFormBuilder; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBRead; +import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.dao.config.OnlineApplication; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLEncoder; @@ -45,12 +48,45 @@ public class RedirectServlet extends AuthServlet{ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { - Logger.info("Receive " + RedirectServlet.class + " Request"); + Logger.debug("Receive " + RedirectServlet.class + " Request"); String url = req.getParameter(REDIRCT_PARAM_URL); String target = req.getParameter(PARAM_TARGET); String artifact = req.getParameter(PARAM_SAMLARTIFACT); + if (MiscUtil.isEmpty(artifact)) { + resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Parameters not valid"); + return; + } + + Logger.debug("Check URL against online-applications"); + OnlineApplication oa = null; + String redirectTarget = "_parent"; + try { + oa = ConfigurationDBRead.getActiveOnlineApplication(url); + if (oa == null) { + resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Parameters not valid"); + return; + + } else { + try { + redirectTarget = oa.getAuthComponentOA().getTemplates().getBKUSelectionCustomization().getAppletRedirectTarget(); + + } catch (Exception e) { + Logger.debug("Use default redirectTarget."); + } + + } + + } catch (Throwable e) { + resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Request not allowed."); + return; + + } finally { + ConfigurationDBUtils.closeSession(); + + } + Logger.info("Redirect to " + url); if (MiscUtil.isNotEmpty(target)) { @@ -65,12 +101,15 @@ public class RedirectServlet extends AuthServlet{ URLEncoder.encode(artifact, "UTF-8")); url = resp.encodeRedirectURL(url); - String redirect_form = RedirectFormBuilder.buildLoginForm(url); + String redirect_form = RedirectFormBuilder.buildLoginForm(url, redirectTarget); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = new PrintWriter(resp.getOutputStream()); out.write(redirect_form); out.flush(); + + } + } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java index 4f722c8b3..2b46c8ff2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyAuthenticationBlockServlet.java @@ -50,6 +50,7 @@ import iaik.pki.PKIException; import java.io.IOException; import java.security.GeneralSecurityException; +import java.util.List; import java.util.Map; import javax.net.ssl.SSLSocketFactory; @@ -174,9 +175,8 @@ public class VerifyAuthenticationBlockServlet extends AuthServlet { // escape parameter strings sessionID = StringEscapeUtils.escapeHtml(sessionID); - pendingRequestID = AuthenticationSessionStoreage.getPendingRequestID(sessionID); - + String redirectURL = null; try { // check parameter @@ -187,6 +187,9 @@ public class VerifyAuthenticationBlockServlet extends AuthServlet { AuthenticationSession session = AuthenticationServer.getSession(sessionID); + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); + String samlArtifactBase64 = AuthenticationServer.getInstance().verifyAuthenticationBlock(session, createXMLSignatureResponse); @@ -220,17 +223,17 @@ public class VerifyAuthenticationBlockServlet extends AuthServlet { String oaURL = session.getOAURLRequested(); OAAuthParameter oaParam = authConf.getOnlineApplicationParameter(oaURL); - String profiles = oaParam.getMandateProfiles(); + List<String> profiles = oaParam.getMandateProfiles(); if (profiles == null) { Logger.error("No Mandate/Profile for OA configured."); throw new AuthenticationException("auth.16", new Object[] { GET_MIS_SESSIONID}); } - String profilesArray[] = profiles.split(","); - for(int i = 0; i < profilesArray.length; i++) { - profilesArray[i] = profilesArray[i].trim(); - } +// String profilesArray[] = profiles.split(","); +// for(int i = 0; i < profilesArray.length; i++) { +// profilesArray[i] = profilesArray[i].trim(); +// } String oaFriendlyName = oaParam.getFriendlyName(); String mandateReferenceValue = session.getMandateReferenceValue(); @@ -249,7 +252,7 @@ public class VerifyAuthenticationBlockServlet extends AuthServlet { targetType = AuthenticationSession.TARGET_PREFIX_ + oaParam.getTarget(); } - MISSessionId misSessionID = MISSimpleClient.sendSessionIdRequest(connectionParameters.getUrl(), idl, cert, oaFriendlyName, redirectURL, mandateReferenceValue, profilesArray, targetType, sslFactory); + MISSessionId misSessionID = MISSimpleClient.sendSessionIdRequest(connectionParameters.getUrl(), idl, cert, oaFriendlyName, redirectURL, mandateReferenceValue, profiles, targetType, sslFactory); if (misSessionID == null) { Logger.error("Fehler bei Anfrage an Vollmachten Service. MIS Session ID ist null."); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java index 80b1547c9..fddd0d6b9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyCertificateServlet.java @@ -157,6 +157,8 @@ public class VerifyCertificateServlet extends AuthServlet { session = AuthenticationServer.getSession(sessionID);
+ //change MOASessionID
+ sessionID = AuthenticationSessionStoreage.changeSessionID(session);
X509Certificate cert = AuthenticationServer.getInstance().getCertificate(sessionID, parameters);
if (cert == null) {
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java index 7c2a032a1..10a41c487 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/VerifyIdentityLinkServlet.java @@ -66,6 +66,7 @@ import at.gv.egovernment.moa.id.auth.exception.MOAIDException; import at.gv.egovernment.moa.id.auth.exception.ParseException; import at.gv.egovernment.moa.id.auth.exception.WrongParametersException; import at.gv.egovernment.moa.id.commons.db.ConfigurationDBUtils; +import at.gv.egovernment.moa.id.commons.db.MOASessionDBUtils; import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; @@ -147,8 +148,7 @@ public class VerifyIdentityLinkServlet extends AuthServlet { throw new IOException(e.getMessage()); } String sessionID = req.getParameter(PARAM_SESSIONID); - - + // escape parameter strings sessionID = StringEscapeUtils.escapeHtml(sessionID); @@ -167,6 +167,9 @@ public class VerifyIdentityLinkServlet extends AuthServlet { AuthenticationSession session = AuthenticationServer.getSession(sessionID); + + //change MOASessionID + sessionID = AuthenticationSessionStoreage.changeSessionID(session); String createXMLSignatureRequestOrRedirect = AuthenticationServer.getInstance().verifyIdentityLink(session, parameters); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java index ab9decde0..c3b45f165 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/stork/STORKResponseProcessor.java @@ -86,7 +86,7 @@ public class STORKResponseProcessor { * @param attributeList the attribute list
* @return true, if successful
*/
- private static boolean hasAttribute(String attributeName, IPersonalAttributeList attributeList) {
+ public static boolean hasAttribute(String attributeName, IPersonalAttributeList attributeList) {
try {
getAttributeValue(attributeName, attributeList);
return true;
@@ -125,7 +125,7 @@ public class STORKResponseProcessor { * @return Identity Link
* @throws STORKException the sTORK exception
*/
- public static IdentityLink connectToSZRGateway(IPersonalAttributeList attributeList, String oaFriendlyName, String targetType, String targetValue, String filters) throws STORKException {
+ public static IdentityLink connectToSZRGateway(IPersonalAttributeList attributeList, String oaFriendlyName, String targetType, String targetValue, List<String> filters) throws STORKException {
Logger.trace("Calling SZR Gateway with the following attributes:");
CreateIdentityLinkResponse identityLinkResponse = null;
@@ -133,9 +133,9 @@ public class STORKResponseProcessor { try {
Logger.trace("Starting call...");
-
// if there is no signedDoc attribute, we cannot go on
String citizenSignature = getAttributeValue("signedDoc", attributeList);
+ String fiscalNumber = getAttributeValue("fiscalNumber", attributeList);
// if we have a signedDoc we test for a representation case
// - according to stork samlengine and commons
@@ -148,7 +148,7 @@ public class STORKResponseProcessor { String organizationAddress = getAttributeValue("canonicalRegisteredAddress", attributeList);
String organizationType = getAttributeValue("translateableType", attributeList);
- identityLinkResponse = AuthenticationServer.getInstance().getIdentityLink(citizenSignature, null, null, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters);
+ identityLinkResponse = AuthenticationServer.getInstance().getIdentityLink(citizenSignature, null, null, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
} else {
// if we get here, we have a natural person representing another natural person
String eIdentifier = getAttributeValue("eIdentifier", attributeList);
@@ -164,7 +164,7 @@ public class STORKResponseProcessor { identityLinkResponse = AuthenticationServer.getInstance().getIdentityLink(eIdentifier,
givenName, lastName, dateOfBirth, gender, citizenSignature, null,
- null, mandate, targetType, targetValue, oaFriendlyName, filters);
+ null, mandate, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
}
}
// - according to stork spec
@@ -178,15 +178,15 @@ public class STORKResponseProcessor { // if we get here, we have a natural person representing a legal person
String organizationAddress = getAttributeValue("canonicalRegisteredAddress", attributeList);
String organizationType = getAttributeValue("translateableType", attributeList);
-
- identityLinkResponse = AuthenticationServer.getInstance().getIdentityLink(citizenSignature, representative, represented, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters);
+
+ identityLinkResponse = AuthenticationServer.getInstance().getIdentityLink(citizenSignature, representative, represented, mandate, organizationAddress, organizationType, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
} else {
// if we get here, we have a natural person representing another natural person
String eIdentifier = getAttributeValue("eIdentifier", attributeList);
String givenName = getAttributeValue("givenName", attributeList);
String lastName = getAttributeValue("surname", attributeList);
String dateOfBirth = getAttributeValue("dateOfBirth", attributeList);
-
+
// gender attribute is mandatory here because of some legal stuff
String gender = getAttributeValue("gender", attributeList);
@@ -195,7 +195,7 @@ public class STORKResponseProcessor { identityLinkResponse = AuthenticationServer.getInstance().getIdentityLink(eIdentifier,
givenName, lastName, dateOfBirth, gender, citizenSignature, representative,
- represented, mandate, targetType, targetValue, oaFriendlyName, filters);
+ represented, mandate, targetType, targetValue, oaFriendlyName, filters, fiscalNumber);
}
} else {
// we do not have a representation case
@@ -205,7 +205,7 @@ public class STORKResponseProcessor { String dateOfBirth = getAttributeValue("dateOfBirth", attributeList);
if (!StringUtils.isEmpty(dateOfBirth))
dateOfBirth = DateTimeUtils.formatPEPSDateToMOADate(dateOfBirth);
- identityLinkResponse = AuthenticationServer.getInstance().getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, citizenSignature);
+ identityLinkResponse = AuthenticationServer.getInstance().getIdentityLink(eIdentifier, givenName, lastName, dateOfBirth, citizenSignature, fiscalNumber);
}
if (null != identityLinkResponse.getErrorResponse()){
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java index 7e248243b..038e92f1c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/validator/VerifyXMLSignatureResponseValidator.java @@ -60,6 +60,8 @@ import at.gv.egovernment.moa.id.auth.MOAIDAuthConstants; import at.gv.egovernment.moa.id.auth.data.IdentityLink; import at.gv.egovernment.moa.id.auth.data.VerifyXMLSignatureResponse; import at.gv.egovernment.moa.id.auth.exception.ValidateException; +import at.gv.egovernment.moa.id.config.ConfigurationException; +import at.gv.egovernment.moa.id.config.auth.AuthConfigurationProvider; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; import at.gv.egovernment.moa.logging.Logger; @@ -101,12 +103,13 @@ public class VerifyXMLSignatureResponseValidator { * manifest has to be ignored (identityLink validation if * the OA is a business service) or not * @throws ValidateException on any validation error + * @throws ConfigurationException */ public void validate(VerifyXMLSignatureResponse verifyXMLSignatureResponse, List<String> identityLinkSignersSubjectDNNames, String whatToCheck, boolean ignoreManifestValidationResult) - throws ValidateException { + throws ValidateException, ConfigurationException { if (verifyXMLSignatureResponse.getSignatureCheckCode() != 0) throw new ValidateException("validator.06", null); @@ -131,6 +134,12 @@ public class VerifyXMLSignatureResponseValidator { // throw new ValidateException("validator.19", new Object[] { checkFailedReason } ); } + //check QC + if (AuthConfigurationProvider.getInstance().isCertifiacteQCActive() && + !whatToCheck.equals(CHECK_IDENTITY_LINK) && + !verifyXMLSignatureResponse.isQualifiedCertificate()) + throw new ValidateException("validator.71", null); + if (ignoreManifestValidationResult) { Logger.debug("OA type is business service, thus ignoring DSIG manifest validation result"); } else { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationUtils.java index a5ee41a9d..1a2136ebd 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/ConfigurationUtils.java @@ -44,12 +44,10 @@ public class ConfigurationUtils { list.add(encoded); } catch (UnsupportedEncodingException e) { - Logger.warn("Transformation can not be loaded. An encoding error ocurs"); - return null; + Logger.warn("Transformation can not be loaded. An encoding error ocurs", e); } catch (IOException e) { - Logger.warn("Transformation can not be loaded from database."); - return null; + Logger.warn("Transformation can not be loaded from database.", e); } } return list; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java index 1674715d1..b02c0946c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigLoader.java @@ -42,21 +42,29 @@ public class AuthConfigLoader implements Runnable { Logger.info("check for new config."); MOAIDConfiguration moaidconfig = ConfigurationDBRead.getMOAIDConfiguration(); - Date dbdate = moaidconfig.getTimestampItem(); - Date pvprefresh = moaidconfig.getPvp2RefreshItem(); - - Date date = AuthConfigurationProvider.getTimeStamp(); - - if (dbdate != null && dbdate.after(date)) { - AuthConfigurationProvider instance = AuthConfigurationProvider.getInstance(); - instance.reloadDataBaseConfig(); - } - Date pvpdate = MOAMetadataProvider.getTimeStamp(); - if (pvprefresh != null && pvpdate != null && pvprefresh.after(pvpdate)) { - MOAMetadataProvider.reInitialize(); + if (moaidconfig != null) { + Date dbdate = moaidconfig.getTimestampItem(); + Date pvprefresh = moaidconfig.getPvp2RefreshItem(); + + Date date = AuthConfigurationProvider.getTimeStamp(); + + if (dbdate != null && dbdate.after(date)) { + AuthConfigurationProvider instance = AuthConfigurationProvider.getInstance(); + instance.reloadDataBaseConfig(); + } + + Date pvpdate = MOAMetadataProvider.getTimeStamp(); + if (pvprefresh != null && pvpdate != null && pvprefresh.after(pvpdate)) { + MOAMetadataProvider.reInitialize(); + } + + } else { + Logger.warn("MOA-ID Configuration is actually not found. Reuse old configuration."); + } + } catch (Throwable e) { Logger.warn("MOA-ID Configuration is actually not loadable. Reuse old configuration.", e); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java index 1a3c1b0a1..8b5c8d796 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/AuthConfigurationProvider.java @@ -663,7 +663,13 @@ public class AuthConfigurationProvider extends ConfigurationProvider { Logger.warn("Error in MOA-ID Configuration. No generalAuthConfiguration->SecurityLayer found"); throw new ConfigurationException("config.02", null); } else { - TransformsInfos = ConfigurationUtils.getTransformInfos(seclayer.getTransformsInfo()); + TransformsInfos = ConfigurationUtils.getTransformInfos(seclayer.getTransformsInfo()); + + if (TransformsInfos == null || TransformsInfos.size() == 0) { + Logger.error("No Security-Layer Transformation found."); + throw new ConfigurationException("config.05", new Object[]{"Security-Layer Transformation"}); + } + } //set IdentityLinkSignerSubjectNames @@ -992,6 +998,16 @@ public class AuthConfigurationProvider extends ConfigurationProvider { return publicURLPreFix; } + public boolean isPVP2AssertionEncryptionActive() { + String prop = props.getProperty("protocols.pvp2.assertion.encryption.active", "true"); + return Boolean.valueOf(prop); + } + + public boolean isCertifiacteQCActive() { + String prop = props.getProperty("configuration.validation.certificate.QC.ignore", "false"); + return !Boolean.valueOf(prop); + } + /** * Retruns the STORK Configuration * @return STORK Configuration diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java index 31ba64be0..492770aad 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/auth/OAAuthParameter.java @@ -55,8 +55,10 @@ import at.gv.egovernment.moa.id.commons.db.dao.config.AttributeProviderPlugin; import at.gv.egovernment.moa.id.commons.db.dao.config.AuthComponentOA; import at.gv.egovernment.moa.id.commons.db.dao.config.BKUSelectionCustomizationType; import at.gv.egovernment.moa.id.commons.db.dao.config.BKUURLS; +import at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS; import at.gv.egovernment.moa.id.commons.db.dao.config.IdentificationNumber; import at.gv.egovernment.moa.id.commons.db.dao.config.Mandates; +import at.gv.egovernment.moa.id.commons.db.dao.config.MandatesProfileNameItem; import at.gv.egovernment.moa.id.commons.db.dao.config.OAPVP2; import at.gv.egovernment.moa.id.commons.db.dao.config.OASAML1; import at.gv.egovernment.moa.id.commons.db.dao.config.OASSO; @@ -222,13 +224,32 @@ public List<String> getTransformsInfos() { /** * @return the mandateProfiles */ -public String getMandateProfiles() { +public List<String> getMandateProfiles() { Mandates mandates = oa_auth.getMandates(); - if (mandates != null) - return mandates.getProfiles(); - else + List<String> list = new ArrayList<String>(); + + if (mandates != null) { + String oldProfilList = mandates.getProfiles(); + + List<MandatesProfileNameItem> profileList = mandates.getProfileNameItems(); + for (MandatesProfileNameItem el : profileList) { + list.add(el.getItem()); + + } + + //only for RC1 + if (MiscUtil.isNotEmpty(oldProfilList)) { + String profilesArray[] = oldProfilList.split(","); + for(int i = 0; i < profilesArray.length; i++) { + list.add(profilesArray[i].trim()); + } + } + + return list; + + } else return null; } @@ -378,9 +399,9 @@ public byte[] getSendAssertionTemplate() { return null; } - - - +public List<CPEPS> getPepsList() { + return new ArrayList<CPEPS>(oa_auth.getOASTORK().getCPEPS()); +} } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java index 7ecd7dde8..e6e77911a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/legacy/BuildFromLegacyConfig.java @@ -28,6 +28,9 @@ import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; +import java.net.URI; +import java.net.URL; +import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -55,6 +58,7 @@ import at.gv.egovernment.moa.id.commons.db.dao.config.MOAIDConfiguration; import at.gv.egovernment.moa.id.commons.db.dao.config.MOAKeyBoxSelector; import at.gv.egovernment.moa.id.commons.db.dao.config.MOASP; import at.gv.egovernment.moa.id.commons.db.dao.config.Mandates; +import at.gv.egovernment.moa.id.commons.db.dao.config.MandatesProfileNameItem; import at.gv.egovernment.moa.id.commons.db.dao.config.OAPVP2; import at.gv.egovernment.moa.id.commons.db.dao.config.OASAML1; import at.gv.egovernment.moa.id.commons.db.dao.config.OASSO; @@ -83,6 +87,7 @@ import at.gv.egovernment.moa.id.data.IssuerAndSerial; import at.gv.egovernment.moa.logging.Logger; import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.DOMUtils; +import at.gv.egovernment.moa.util.FileUtils; import at.gv.egovernment.moa.util.MiscUtil; public class BuildFromLegacyConfig { @@ -237,7 +242,10 @@ public class BuildFromLegacyConfig { for (int i=0; i<transformsInfos.length; i++) { TransformsInfoType transforminfotype = new TransformsInfoType(); - transforminfotype.setFilename(transformsInfoFileNames[i]); + + String fileURL = FileUtils.makeAbsoluteURL(transformsInfoFileNames[i], rootConfigFileDir); + Path fileName_ = new File(new URI(fileURL)).toPath().getFileName(); + transforminfotype.setFilename(fileName_.toString()); transforminfotype.setTransformation(Base64Utils.encode(transformsInfos[i].getBytes("UTF-8")).getBytes("UTF-8")); auth_transformInfos.add(transforminfotype); @@ -392,22 +400,32 @@ public class BuildFromLegacyConfig { templates.setTemplate(template_list); - //set TransformsInfo + //TransformsInfo not supported by MOAID 2.0 String[] transforminfos = oa.getTransformsInfos(); - ArrayList<TransformsInfoType> oa_transforminfos = new ArrayList<TransformsInfoType>(); - for (String e1 : transforminfos) { - TransformsInfoType transforminfo = new TransformsInfoType(); - transforminfo.setFilename(e1); - oa_transforminfos.add(transforminfo); + for (String e1 : transforminfos) { + if (MiscUtil.isNotEmpty(e1)) { + Logger.warn("OA specific transformation for OA " + oa.getPublicURLPrefix() + + " are not supported. USE AdditionalAuthBlock text!"); + } } - oa_auth.setTransformsInfo(oa_transforminfos); //VerifyInfoBoxes not supported by MOAID 2.0 //set Mandates Mandates oa_mandates = new Mandates(); oa_auth.setMandates(oa_mandates); - oa_mandates.setProfiles(oa.getMandateProfiles()); + List<MandatesProfileNameItem> profileList = new ArrayList<MandatesProfileNameItem>(); + + String oldProfiles = oa.getMandateProfiles(); + if (MiscUtil.isNotEmpty(oldProfiles)) { + String[] oldprofileList = oldProfiles.split(","); + for (int i=0; i<oldprofileList.length; i++) { + MandatesProfileNameItem item = new MandatesProfileNameItem(); + item.setItem(oldprofileList[i].trim()); + profileList.add(item); + } + oa_mandates.setProfileNameItems(profileList ); + } //STORK //TODO: OA specific STORK config is deactivated in MOA 1.5.2 @@ -447,7 +465,16 @@ public class BuildFromLegacyConfig { ChainingModes moa_chainingModes = new ChainingModes(); moaIDConfig.setChainingModes(moa_chainingModes); - ChainingModeType type = ChainingModeType.fromValue(builder.getDefaultChainingMode()); + + + String defaultmode = builder.getDefaultChainingMode(); + ChainingModeType type; + if (defaultmode.equals(iaik.pki.pathvalidation.ChainingModes.CHAIN_MODE)) + type = ChainingModeType.CHAINING; + else + type = ChainingModeType.PKIX; + + moa_chainingModes.setSystemDefaultMode(type); Map<IssuerAndSerial, String> chainingModes = builder.buildChainingModes(); 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 647c8bb39..480deb867 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 @@ -54,6 +54,7 @@ import at.gv.egovernment.moa.id.moduls.ModulStorage; import at.gv.egovernment.moa.id.moduls.NoPassivAuthenticationException; import at.gv.egovernment.moa.id.moduls.RequestStorage; import at.gv.egovernment.moa.id.moduls.SSOManager; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; import at.gv.egovernment.moa.id.storage.AuthenticationSessionStoreage; import at.gv.egovernment.moa.id.storage.DBExceptionStoreImpl; import at.gv.egovernment.moa.id.util.MOAIDMessageProvider; @@ -108,41 +109,24 @@ public class DispatcherServlet extends AuthServlet{ Object idObject = req.getParameter(PARAM_TARGET_PENDINGREQUESTID); - Map<String, IRequest> errorRequests = RequestStorage.getPendingRequest(req.getSession()); + //Map<String, IRequest> errorRequests = RequestStorage.getPendingRequest(req.getSession()); String pendingRequestID = null; if (idObject != null && (idObject instanceof String)) { - if (errorRequests.containsKey((String)idObject)) - pendingRequestID = (String) idObject; + pendingRequestID = (String) idObject; } if (throwable != null) { - if (errorRequests != null) { - - synchronized (errorRequests) { IRequest errorRequest = null; if (pendingRequestID != null) { - errorRequest = errorRequests.get(pendingRequestID); + errorRequest = RequestStorage.getPendingRequest(pendingRequestID); - //remove the - RequestStorage.removePendingRequest(errorRequests, pendingRequestID); - } - else { - if (errorRequests.size() > 1) { - handleErrorNoRedirect(throwable.getMessage(), throwable, - req, resp); - - } else { - Set<String> keys = errorRequests.keySet(); - errorRequest = errorRequests.get(keys.toArray()[0]); - RequestStorage.removeAllPendingRequests(req.getSession()); - } - } if (errorRequest != null) { - + RequestStorage.removePendingRequest(pendingRequestID); + try { IModulInfo handlingModule = ModulStorage .getModuleByPath(errorRequest @@ -156,6 +140,10 @@ public class DispatcherServlet extends AuthServlet{ StatisticLogger logger = StatisticLogger.getInstance(); logger.logErrorOperation(throwable, errorRequest); + //remove MOASession + AuthenticationSession moaSession = AuthenticationSessionStoreage.getSessionWithPendingRequestID(pendingRequestID); + AuthenticationManager.getInstance().logout(req, resp, moaSession.getSessionID()); + return; } } @@ -172,16 +160,9 @@ public class DispatcherServlet extends AuthServlet{ } handleErrorNoRedirect(throwable.getMessage(), throwable, req, resp); - - } else { - // TODO: use better string - handleErrorNoRedirect("UNKOWN ERROR DETECTED!", null, req, - resp); - } return; } - } Object moduleObject = req.getParameter(PARAM_TARGET_MODULE); String module = null; @@ -242,32 +223,24 @@ public class DispatcherServlet extends AuthServlet{ } } - HttpSession httpSession = req.getSession(); - Map<String, IRequest> protocolRequests = null; + //HttpSession httpSession = req.getSession(); + //Map<String, IRequest> protocolRequests = null; IRequest protocolRequest = null; try { - protocolRequests = RequestStorage.getPendingRequest(httpSession); - Object idObject = req.getParameter(PARAM_TARGET_PENDINGREQUESTID); - if (protocolRequests != null && - idObject != null && (idObject instanceof String)) { + if (idObject != null && (idObject instanceof String)) { protocolRequestID = (String) idObject; - + protocolRequest = RequestStorage.getPendingRequest(protocolRequestID); + //get IRequest if it exits - if (protocolRequests.containsKey(protocolRequestID)) { - protocolRequest = protocolRequests.get(protocolRequestID); + if (protocolRequest != null) { Logger.debug(DispatcherServlet.class.getName()+": Found PendingRequest with ID " + protocolRequestID); } else { - Logger.error("No PendingRequest with ID " + protocolRequestID + " found.!"); - - Set<String> mapkeys = protocolRequests.keySet(); - for (String el : mapkeys) - Logger.debug("PendingRequest| ID=" + el + " OAIdentifier=" + protocolRequests.get(el)); - + Logger.error("No PendingRequest with ID " + protocolRequestID + " found.!"); handleErrorNoRedirect("Während des Anmeldevorgangs ist ein Fehler aufgetreten. Bitte versuchen Sie es noch einmal.", null, req, resp); return; @@ -277,59 +250,38 @@ public class DispatcherServlet extends AuthServlet{ protocolRequest = info.preProcess(req, resp, action); if (protocolRequest != null) { + + //Start new Authentication + protocolRequest.setAction(action); + protocolRequest.setModule(module); + protocolRequestID = Random.nextRandom(); + protocolRequest.setRequestID(protocolRequestID); - if(protocolRequests != null) { + RequestStorage.setPendingRequest(protocolRequest); - Set<String> mapkeys = protocolRequests.keySet(); - for (String el : mapkeys) { - IRequest value = protocolRequests.get(el); - - if (value.getOAURL().equals(protocolRequest.getOAURL())) { - - if(!AuthenticationSessionStoreage.deleteSessionWithPendingRequestID(el)) { - Logger.warn(DispatcherServlet.class.getName()+": NO MOASession with PendingRequestID " + el + " found. Delete all user sessions!"); - RequestStorage.removeAllPendingRequests(req.getSession()); - - } else { - RequestStorage.removePendingRequest(protocolRequests, el); - } - } - } - - } else { - protocolRequests = new ConcurrentHashMap<String, IRequest>(); - } + Logger.debug(DispatcherServlet.class.getName()+": Create PendingRequest with ID " + protocolRequestID + "."); + + } else { + Logger.error("Failed to generate a valid protocol request!"); + resp.setContentType("text/html;charset=UTF-8"); + resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!"); + return; - synchronized (protocolRequest) { - synchronized (protocolRequests) { - - //Start new Authentication - protocolRequest.setAction(action); - protocolRequest.setModule(module); - protocolRequestID = Random.nextRandom(); - protocolRequest.setRequestID(protocolRequestID); - protocolRequests.put(protocolRequestID, protocolRequest); - Logger.debug(DispatcherServlet.class.getName()+": Create PendingRequest with ID " + protocolRequestID + "."); - } - } } - + } catch (ProtocolNotActiveException e) { resp.getWriter().write(e.getMessage()); resp.setContentType("text/html;charset=UTF-8"); resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage()); return; - - } catch (MOAIDException e) { - Logger.error("Failed to generate a valid protocol request!"); - resp.setContentType("text/html;charset=UTF-8"); - resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!"); + } catch (AuthnRequestValidatorException e) { + //log Error Message + StatisticLogger logger = StatisticLogger.getInstance(); + logger.logErrorOperation(e, e.getErrorRequest()); return; - - } - - if (protocolRequest == null) { + + } catch (MOAIDException e) { Logger.error("Failed to generate a valid protocol request!"); resp.setContentType("text/html;charset=UTF-8"); resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "NO valid protocol request received!"); @@ -337,9 +289,7 @@ public class DispatcherServlet extends AuthServlet{ } } - - RequestStorage.setPendingRequest(httpSession, protocolRequests); - + AuthenticationManager authmanager = AuthenticationManager.getInstance(); SSOManager ssomanager = SSOManager.getInstance(); @@ -460,7 +410,7 @@ public class DispatcherServlet extends AuthServlet{ String assertionID = moduleAction.processRequest(protocolRequest, req, resp, moasession); - RequestStorage.removePendingRequest(protocolRequests, protocolRequestID); + RequestStorage.removePendingRequest(protocolRequestID); if (needAuthentication) { boolean isSSOSession = MiscUtil.isNotEmpty(newSSOSessionId); @@ -491,7 +441,7 @@ public class DispatcherServlet extends AuthServlet{ } } catch (Throwable e) { - Logger.info("An authentication error occured: " + e.getMessage());; + Logger.warn("An authentication error occured: ", e);; // 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/moduls/AuthenticationManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java index 666224b3a..03a61d08f 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/AuthenticationManager.java @@ -252,7 +252,7 @@ public class AuthenticationManager extends AuthServlet { } //set MOAIDSession - request.getSession().setAttribute(MOA_SESSION, moasession.getSessionID()); + //request.getSession().setAttribute(MOA_SESSION, moasession.getSessionID()); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = new PrintWriter(response.getOutputStream()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java index bfe1151c4..21b4e2b65 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/RequestStorage.java @@ -22,64 +22,53 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.moduls; -import java.util.Map; - -import javax.servlet.http.HttpSession; - +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.commons.db.ex.MOADatabaseException; +import at.gv.egovernment.moa.id.storage.AssertionStorage; import at.gv.egovernment.moa.logging.Logger; public class RequestStorage { - private static final String PENDING_REQUEST = "PENDING_REQUEST"; - - public static Map<String,IRequest> getPendingRequest(HttpSession session) { + public static IRequest getPendingRequest(String pendingReqID) { - - Object obj = session.getAttribute(PENDING_REQUEST); - if (obj != null) { - synchronized (obj) { - if (obj instanceof Map<?,?>) { - if (((Map<?,?>) obj).size() > 0) { - if ( ((Map<?,?>) obj).keySet().toArray()[0] instanceof String) { - if (((Map<?,?>) obj).get(((Map<?,?>) obj).keySet().toArray()[0]) - instanceof IRequest) { - return (Map<String, IRequest>) obj; - - - - } - } - } - } - } - session.setAttribute(PENDING_REQUEST, null); - } + try { + AssertionStorage storage = AssertionStorage.getInstance(); + IRequest pendingRequest = storage.get(pendingReqID, IRequest.class); + return pendingRequest; + + } catch (MOADatabaseException e) { + Logger.info("No PendingRequst found with pendingRequestID " + pendingReqID); return null; + + } } - public static void setPendingRequest(HttpSession session, Map<String, IRequest> request) { - session.setAttribute(PENDING_REQUEST, request); - } - - public static void removeAllPendingRequests(HttpSession session) { - - Logger.debug(RequestStorage.class.getName()+": Remove all PendingRequests"); + public static void setPendingRequest(Object pendingRequest) throws MOAIDException { + try { + AssertionStorage storage = AssertionStorage.getInstance(); + + if (pendingRequest instanceof IRequest) { + storage.put(((IRequest)pendingRequest).getRequestID(), pendingRequest); + + } else { + throw new MOAIDException("auth.20", null); + + } + + } catch (MOADatabaseException e) { + Logger.warn("Pending Request with ID=" + ((IRequest)pendingRequest).getRequestID() + + " can not stored.", e); + throw new MOAIDException("auth.20", null); + } - session.setAttribute(PENDING_REQUEST, null); } - public static void removePendingRequest(Map<String, IRequest> requestmap, String requestID) { - - if (requestmap != null && requestID != null) { + public static void removePendingRequest(String requestID) { - synchronized (requestmap) { - - if (requestmap.containsKey(requestID)) { - requestmap.remove(requestID); - Logger.debug(RequestStorage.class.getName()+": Remove PendingRequest with ID " + requestID); - - } - } + if (requestID != null) { + AssertionStorage storage = AssertionStorage.getInstance(); + storage.remove(requestID); + } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java index 82de940db..684c6630a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/moduls/SSOManager.java @@ -147,9 +147,7 @@ public class SSOManager { public String createSSOSessionInformations(String moaSessionID, String OAUrl) { String newSSOId = Random.nextRandom(); - - System.out.println("generate new SSO Tokken (" + newSSOId + ")"); - + if (MiscUtil.isEmpty(moaSessionID) || MiscUtil.isEmpty(OAUrl)) { Logger.warn("MoaSessionID or OAUrl are empty -> SSO is not enabled!"); return null; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAKeyStoreX509CredentialAdapter.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAKeyStoreX509CredentialAdapter.java new file mode 100644 index 000000000..81afcfbc1 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/opemsaml/MOAKeyStoreX509CredentialAdapter.java @@ -0,0 +1,52 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.opemsaml; + +import java.security.KeyStore; + +import org.opensaml.xml.security.x509.X509Credential; + + +/** + * @author tlenz + * + */ +public class MOAKeyStoreX509CredentialAdapter extends + org.opensaml.xml.security.x509.KeyStoreX509CredentialAdapter { + + /** + * @param store + * @param alias + * @param password + */ + public MOAKeyStoreX509CredentialAdapter(KeyStore store, String alias, + char[] password) { + super(store, alias, password); + } + + public Class<? extends X509Credential> getCredentialType() { + return X509Credential.class; + } + + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java index 7bb97b9d8..394fd1430 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/oauth20/attributes/OAuth20AttributeBuilder.java @@ -156,7 +156,6 @@ public final class OAuth20AttributeBuilder { // STORK buildersSTORK.add(new EIDSTORKTOKEN()); - buildersSTORK.add(new EIDSTORKTOKEN()); buildersSTORK.add(new STORKAdoptedFamilyNameAttributBuilder()); buildersSTORK.add(new STORKAgeAttributBuilder()); buildersSTORK.add(new STORKCanonicalResidenceAddressAttributBuilder()); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java index f0d503d88..10618071a 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/AuthenticationAction.java @@ -36,7 +36,6 @@ public class AuthenticationAction implements IAction { public String processRequest(IRequest req, HttpServletRequest httpReq, HttpServletResponse httpResp, AuthenticationSession moasession) throws MOAIDException { - System.out.println("Process PVP2 auth request!"); PVPTargetConfiguration pvpRequest = (PVPTargetConfiguration) req; return RequestManager.getInstance().handle(pvpRequest.request, httpReq, httpResp, moasession); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java index 1668c31ce..99cba3277 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/MetadataAction.java @@ -46,6 +46,7 @@ import org.opensaml.saml2.metadata.KeyDescriptor; import org.opensaml.saml2.metadata.NameIDFormat; import org.opensaml.saml2.metadata.SingleSignOnService; import org.opensaml.xml.io.Marshaller; +import org.opensaml.xml.security.SecurityHelper; import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.credential.UsageType; import org.opensaml.xml.security.keyinfo.KeyInfoGenerator; @@ -106,7 +107,7 @@ public class MetadataAction implements IAction { .getIDPOrganisation()); X509KeyInfoGeneratorFactory keyInfoFactory = new X509KeyInfoGeneratorFactory(); - keyInfoFactory.setEmitPublicKeyValue(true); + //keyInfoFactory.setEmitPublicKeyValue(true); keyInfoFactory.setEmitEntityIDAsKeyName(true); keyInfoFactory.setEmitEntityCertificate(true); KeyInfoGenerator keyInfoGenerator = keyInfoFactory.newInstance(); @@ -114,7 +115,10 @@ public class MetadataAction implements IAction { Credential metadataSigningCredential = CredentialProvider.getIDPMetaDataSigningCredential(); Signature signature = CredentialProvider .getIDPSignature(metadataSigningCredential); - + + //set KeyInfo Element + SecurityHelper.prepareSignatureParams(signature, metadataSigningCredential, null, null); + idpEntitiesDescriptor.setSignature(signature); // //set SignatureMethode diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java index 84c0138a5..e81b23d41 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVP2XProtocol.java @@ -40,6 +40,7 @@ import org.opensaml.saml2.core.Response; import org.opensaml.saml2.core.Status; import org.opensaml.saml2.core.StatusCode; import org.opensaml.saml2.core.StatusMessage; +import org.opensaml.saml2.core.impl.AuthnRequestImpl; import org.opensaml.saml2.metadata.AssertionConsumerService; import org.opensaml.saml2.metadata.AttributeConsumingService; import org.opensaml.saml2.metadata.EntityDescriptor; @@ -58,11 +59,14 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.MOARequest; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.PostBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.RedirectBinding; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.MandateAttributesNotHandleAbleException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NameIDFormatNotSupportedException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMetadataInformationException; import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.PVP2Exception; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.CheckMandateAttributes; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; +import at.gv.egovernment.moa.id.protocols.pvp2x.validation.AuthnRequestValidator; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.SAMLVerificationEngine; import at.gv.egovernment.moa.id.protocols.pvp2x.verification.TrustEngineFactory; import at.gv.egovernment.moa.id.util.VelocityLogAdapter; @@ -90,6 +94,8 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { actions.put(POST, new AuthenticationAction()); actions.put(METADATA, new MetadataAction()); + //TODO: insert getArtifact action + instance = new PVP2XProtocol(); new VelocityLogAdapter(); @@ -167,7 +173,7 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { if(!(samlReq instanceof AuthnRequest)) { throw new MOAIDException("Unsupported request", new Object[] {}); } - + EntityDescriptor metadata = moaRequest.getEntityMetadata(); if(metadata == null) { throw new NoMetadataInformationException(); @@ -201,7 +207,7 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { spSSODescriptor.getAttributeConsumingServices().size() > 0) { attributeConsumer = spSSODescriptor.getAttributeConsumingServices().get(attributeIdx); } - + String oaURL = moaRequest.getEntityMetadata().getEntityID(); String binding = consumerService.getBinding(); // String entityID = moaRequest.getEntityMetadata().getEntityID(); @@ -223,12 +229,33 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { } } } - - request.getSession().setAttribute(PARAM_OA, oaURL); + //validate AuthnRequest + try { + AuthnRequestValidator.validate((AuthnRequestImpl) samlReq); + + } catch (AuthnRequestValidatorException e) { + if (generateErrorMessage(e, request, response, config)) { + throw new AuthnRequestValidatorException(e.getMessage(), + new Object[] {}, config); + + } else { + throw new MOAIDException(e.getMessage(), new Object[] {}); + + } + } + + //request.getSession().setAttribute(PARAM_OA, oaURL); + return config; - } catch (Exception e) { - e.printStackTrace(); + + } catch (PVP2Exception e) { + throw e; + + } catch (Throwable e) { + String samlRequest = request.getParameter("SAMLRequest"); + Logger.warn("Receive INVALID protocol request: " + samlRequest, e); + throw new MOAIDException(e.getMessage(), new Object[] {}); } } @@ -253,17 +280,23 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { StatusMessage statusMessage = SAML2Utils.createSAMLObject(StatusMessage.class); if(e instanceof NoPassivAuthenticationException) { statusCode.setValue(StatusCode.NO_PASSIVE_URI); - statusMessage.setMessage(e.getLocalizedMessage()); + statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); + + } else if (e instanceof NameIDFormatNotSupportedException) { + statusCode.setValue(StatusCode.INVALID_NAMEID_POLICY_URI); + statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); + } else if(e instanceof PVP2Exception) { PVP2Exception ex = (PVP2Exception) e; statusCode.setValue(ex.getStatusCodeValue()); String statusMessageValue = ex.getStatusMessageValue(); if(statusMessageValue != null) { - statusMessage.setMessage(statusMessageValue); + statusMessage.setMessage(StringEscapeUtils.escapeXml(statusMessageValue)); } + } else { statusCode.setValue(StatusCode.RESPONDER_URI); - statusMessage.setMessage(e.getLocalizedMessage()); + statusMessage.setMessage(StringEscapeUtils.escapeXml(e.getLocalizedMessage())); } status.setStatusCode(statusCode); @@ -271,7 +304,9 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { status.setStatusMessage(statusMessage); } samlResponse.setStatus(status); - + String remoteSessionID = SAML2Utils.getSecureIdentifier(); + samlResponse.setID(remoteSessionID); + IEncoder encoder = null; if(pvpRequest.getBinding().equals(SAMLConstants.SAML2_REDIRECT_BINDING_URI)) { @@ -288,7 +323,12 @@ public class PVP2XProtocol implements IModulInfo, MOAIDAuthConstants { encoder = new RedirectBinding(); } - encoder.encodeRespone(request, response, samlResponse, pvpRequest.getConsumerURL()); + String relayState = null; + if (pvpRequest.getRequest() != null) + relayState = pvpRequest.getRequest().getRelayState(); + + encoder.encodeRespone(request, response, samlResponse, pvpRequest.getConsumerURL(), + relayState); return true; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java index 18d757208..b3887a444 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/PVPTargetConfiguration.java @@ -57,5 +57,4 @@ public class PVPTargetConfiguration extends RequestImpl { this.consumerURL = consumerURL; } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java index a0fba918c..43a17af23 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/ArtifactBinding.java @@ -55,7 +55,7 @@ public class ArtifactBinding implements IDecoder, IEncoder { } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation) + StatusResponseType response, String targetLocation, String relayState) throws MessageEncodingException, SecurityException { try { Credential credentials = CredentialProvider diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java index 8b888e806..f7dfd055c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/IEncoder.java @@ -47,6 +47,6 @@ public interface IEncoder { * @throws SecurityException */ public void encodeRespone(HttpServletRequest req, - HttpServletResponse resp, StatusResponseType response, String targetLocation) + HttpServletResponse resp, StatusResponseType response, String targetLocation, String relayState) throws MessageEncodingException, SecurityException, PVP2Exception; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOARequest.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOARequest.java index d28c5eeec..11054fd57 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOARequest.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/MOARequest.java @@ -24,27 +24,68 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.binding; import java.io.Serializable; +import org.opensaml.Configuration; import org.opensaml.saml2.core.RequestAbstractType; +import org.opensaml.saml2.core.impl.RequestAbstractTypeMarshaller; +import org.opensaml.saml2.core.impl.RequestAbstractTypeUnmarshaller; import org.opensaml.saml2.metadata.EntityDescriptor; +import org.opensaml.saml2.metadata.provider.MetadataProviderException; +import org.opensaml.xml.XMLObject; +import org.opensaml.xml.io.Unmarshaller; +import org.opensaml.xml.io.UnmarshallerFactory; +import org.opensaml.xml.io.UnmarshallingException; +import org.w3c.dom.Element; + +import at.gv.egovernment.moa.id.auth.exception.MOAIDException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NoMetadataInformationException; +import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; +import at.gv.egovernment.moa.logging.Logger; public class MOARequest implements Serializable{ private static final long serialVersionUID = 2395131650841669663L; - private RequestAbstractType samlRequest; - private EntityDescriptor entityMetadata; + private Element samlRequest; private boolean verified = false; - + private String entityID = null; + private String relayState = null; + public MOARequest(RequestAbstractType request) { - samlRequest = request; + samlRequest = request.getDOM(); } public RequestAbstractType getSamlRequest() { - return samlRequest; + UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory(); + Unmarshaller unmashaller = unmarshallerFactory.getUnmarshaller(samlRequest); + + try { + return (RequestAbstractType) unmashaller.unmarshall(samlRequest); + + } catch (UnmarshallingException e) { + Logger.warn("AuthnRequest Unmarshaller error", e); + return null; + } + + } + + + + /** + * @return the relayState + */ + public String getRelayState() { + return relayState; + } + + /** + * @param relayState the relayState to set + */ + public void setRelayState(String relayState) { + this.relayState = relayState; } public void setSamlRequest(RequestAbstractType request) { - this.samlRequest = request; + this.samlRequest = request.getDOM(); } public boolean isVerified() { @@ -55,13 +96,29 @@ public class MOARequest implements Serializable{ this.verified = verified; } - public EntityDescriptor getEntityMetadata() { - return entityMetadata; + public EntityDescriptor getEntityMetadata() throws NoMetadataInformationException { + + try { + return MOAMetadataProvider.getInstance().getEntityDescriptor(this.entityID); + + } catch (MetadataProviderException e) { + Logger.warn("No Metadata for EntitiyID " + entityID); + throw new NoMetadataInformationException(); + } } - public void setEntityMetadata(EntityDescriptor entityMetadata) { - this.entityMetadata = entityMetadata; + /** + * @return the entitiyID + */ + public String getEntityID() { + return entityID; + } + + /** + * @param entitiyID the entitiyID to set + */ + public void setEntityID(String entitiyID) { + this.entityID = entitiyID; } - } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java index 6bbbee302..6517325b9 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/PostBinding.java @@ -44,6 +44,8 @@ import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.x509.KeyStoreX509CredentialAdapter; +import org.opensaml.xml.security.x509.X509Credential; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.signer.CredentialProvider; @@ -61,11 +63,11 @@ public class PostBinding implements IDecoder, IEncoder { } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation) + StatusResponseType response, String targetLocation, String relayState) throws MessageEncodingException, SecurityException { try { - Credential credentials = CredentialProvider + X509Credential credentials = CredentialProvider .getIDPAssertionSigningCredential(); Logger.debug("create SAML POSTBinding response"); @@ -86,6 +88,7 @@ public class PostBinding implements IDecoder, IEncoder { // context.setOutboundMessage(authReq); context.setOutboundSAMLMessage(response); context.setOutboundMessageTransport(responseAdapter); + context.setRelayState(relayState); encoder.encode(context); } catch (CredentialsNotAvailableException e) { @@ -115,9 +118,12 @@ public class PostBinding implements IDecoder, IEncoder { RequestAbstractType inboundMessage = (RequestAbstractType) messageContext .getInboundMessage(); + + MOARequest request = new MOARequest(inboundMessage); request.setVerified(false); - request.setEntityMetadata(messageContext.getPeerEntityMetadata()); + request.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); + request.setRelayState(messageContext.getRelayState()); return request; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 7c9cc6259..dc6a1f637 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java @@ -48,6 +48,7 @@ import org.opensaml.ws.transport.http.HttpServletResponseAdapter; import org.opensaml.xml.parse.BasicParserPool; import org.opensaml.xml.security.SecurityException; import org.opensaml.xml.security.credential.Credential; +import org.opensaml.xml.security.x509.X509Credential; import at.gv.egovernment.moa.id.protocols.pvp2x.PVP2XProtocol; import at.gv.egovernment.moa.id.protocols.pvp2x.metadata.MOAMetadataProvider; @@ -66,10 +67,10 @@ public class RedirectBinding implements IDecoder, IEncoder { } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation) + StatusResponseType response, String targetLocation, String relayState) throws MessageEncodingException, SecurityException { try { - Credential credentials = CredentialProvider + X509Credential credentials = CredentialProvider .getIDPAssertionSigningCredential(); Logger.debug("create SAML RedirectBinding response"); @@ -131,7 +132,7 @@ public class RedirectBinding implements IDecoder, IEncoder { .getInboundMessage(); MOARequest request = new MOARequest(inboundMessage); request.setVerified(true); - request.setEntityMetadata(messageContext.getPeerEntityMetadata()); + request.setEntityID(messageContext.getPeerEntityMetadata().getEntityID()); return request; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java index 9fe75618d..1d41654eb 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/SoapBinding.java @@ -83,7 +83,7 @@ public class SoapBinding implements IDecoder, IEncoder { } public void encodeRespone(HttpServletRequest req, HttpServletResponse resp, - StatusResponseType response, String targetLocation) + StatusResponseType response, String targetLocation, String relayState) throws MessageEncodingException, SecurityException, PVP2Exception { try { Credential credentials = CredentialProvider diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java index bc90da8df..9def5d22c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/assertion/PVP2AssertionBuilder.java @@ -22,6 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.assertion; +import java.security.MessageDigest; import java.util.Iterator; import java.util.List; @@ -43,6 +44,7 @@ import org.opensaml.saml2.core.RequestedAuthnContext; import org.opensaml.saml2.core.Subject; import org.opensaml.saml2.core.SubjectConfirmation; import org.opensaml.saml2.core.SubjectConfirmationData; +import org.opensaml.saml2.core.impl.AuthnRequestImpl; import org.opensaml.saml2.metadata.AssertionConsumerService; import org.opensaml.saml2.metadata.AttributeConsumingService; import org.opensaml.saml2.metadata.EntityDescriptor; @@ -51,6 +53,8 @@ import org.opensaml.saml2.metadata.RequestedAttribute; import org.opensaml.saml2.metadata.SPSSODescriptor; import org.w3c.dom.Element; +import edu.emory.mathcs.backport.java.util.Arrays; + import at.gv.e_government.reference.namespace.mandates._20040701_.Mandate; import at.gv.e_government.reference.namespace.persondata._20020228_.CorporateBodyType; import at.gv.e_government.reference.namespace.persondata._20020228_.IdentificationType; @@ -75,12 +79,14 @@ import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.UnprovideableAttribut import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.id.util.MandateBuilder; import at.gv.egovernment.moa.id.util.QAALevelVerifier; +import at.gv.egovernment.moa.id.util.Random; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.Base64Utils; import at.gv.egovernment.moa.util.Constants; public class PVP2AssertionBuilder implements PVPConstants { public static Assertion buildAssertion(AuthnRequest authnRequest, - AuthenticationSession authSession, EntityDescriptor peerEntity, DateTime date) + AuthenticationSession authSession, EntityDescriptor peerEntity, DateTime date, AssertionConsumerService assertionConsumerService) throws MOAIDException { Assertion assertion = SAML2Utils.createSAMLObject(Assertion.class); @@ -95,77 +101,56 @@ public class PVP2AssertionBuilder implements PVPConstants { peerEntity.getEntityID()); if (reqAuthnContext == null) { - authnContextClassRef.setAuthnContextClassRef(STORK_QAA_1_4); + authnContextClassRef.setAuthnContextClassRef(authSession.getQAALevel()); - } + } else { - boolean stork_qaa_1_4_found = false; + boolean stork_qaa_1_4_found = false; - List<AuthnContextClassRef> reqAuthnContextClassRefIt = reqAuthnContext - .getAuthnContextClassRefs(); + List<AuthnContextClassRef> reqAuthnContextClassRefIt = reqAuthnContext + .getAuthnContextClassRefs(); - if (reqAuthnContextClassRefIt.size() == 0) { + if (reqAuthnContextClassRefIt.size() == 0) { - QAALevelVerifier.verifyQAALevel(authSession.getQAALevel(), - STORK_QAA_1_4); + QAALevelVerifier.verifyQAALevel(authSession.getQAALevel(), + STORK_QAA_1_4); - stork_qaa_1_4_found = true; - authnContextClassRef.setAuthnContextClassRef(STORK_QAA_1_4); + stork_qaa_1_4_found = true; + authnContextClassRef.setAuthnContextClassRef(STORK_QAA_1_4); - } else { - for (AuthnContextClassRef authnClassRef : reqAuthnContextClassRefIt) { - String qaa_uri = authnClassRef.getAuthnContextClassRef(); - if (qaa_uri.trim().equals(STORK_QAA_1_4) - || qaa_uri.trim().equals(STORK_QAA_1_3) - || qaa_uri.trim().equals(STORK_QAA_1_2) - || qaa_uri.trim().equals(STORK_QAA_1_1)) { + } else { + for (AuthnContextClassRef authnClassRef : reqAuthnContextClassRefIt) { + String qaa_uri = authnClassRef.getAuthnContextClassRef(); + if (qaa_uri.trim().equals(STORK_QAA_1_4) + || qaa_uri.trim().equals(STORK_QAA_1_3) + || qaa_uri.trim().equals(STORK_QAA_1_2) + || qaa_uri.trim().equals(STORK_QAA_1_1)) { - if (authSession.isForeigner()) { - QAALevelVerifier.verifyQAALevel(authSession.getQAALevel(), - STORK_QAA_PREFIX + oaParam.getQaaLevel()); - - stork_qaa_1_4_found = true; - authnContextClassRef.setAuthnContextClassRef(authSession.getQAALevel()); - - } else { - - QAALevelVerifier.verifyQAALevel(authSession.getQAALevel(), - qaa_uri.trim()); - - stork_qaa_1_4_found = true; - authnContextClassRef.setAuthnContextClassRef(authSession.getQAALevel()); - + if (authSession.isForeigner()) { + QAALevelVerifier.verifyQAALevel(authSession.getQAALevel(), + STORK_QAA_PREFIX + oaParam.getQaaLevel()); + + stork_qaa_1_4_found = true; + authnContextClassRef.setAuthnContextClassRef(authSession.getQAALevel()); + + } else { + + QAALevelVerifier.verifyQAALevel(authSession.getQAALevel(), + qaa_uri.trim()); + + stork_qaa_1_4_found = true; + authnContextClassRef.setAuthnContextClassRef(authSession.getQAALevel()); + + } + break; } - break; } } - } - - if (!stork_qaa_1_4_found) { - throw new QAANotSupportedException(STORK_QAA_1_4); + + if (!stork_qaa_1_4_found) { + throw new QAANotSupportedException(STORK_QAA_1_4); + } } - -// reqAuthnContextClassRefIt = reqAuthnContext.getAuthnContextClassRefs() -// .iterator(); -// -// StringBuilder authContextsb = new StringBuilder(); -// -// while (reqAuthnContextClassRefIt.hasNext()) { -// AuthnContextClassRef authnClassRef = reqAuthnContextClassRefIt -// .next(); -// String[] qaa_uris = authnClassRef.getAuthnContextClassRef().split( -// "\\s+"); -// for (int i = 0; i < qaa_uris.length; i++) { -// if (qaa_uris[i].trim().equals(STORK_QAA_1_4) -// || qaa_uris[i].trim().equals(STORK_QAA_1_3) -// || qaa_uris[i].trim().equals(STORK_QAA_1_2) -// || qaa_uris[i].trim().equals(STORK_QAA_1_1)) { -// authContextsb.append(qaa_uris[i].trim()); -// authContextsb.append(" "); -// } -// } -// -// } AuthnContext authnContext = SAML2Utils .createSAMLObject(AuthnContext.class); @@ -184,78 +169,61 @@ public class PVP2AssertionBuilder implements PVPConstants { SPSSODescriptor spSSODescriptor = peerEntity .getSPSSODescriptor(SAMLConstants.SAML20P_NS); - Integer aIdx = authnRequest.getAttributeConsumingServiceIndex(); - int idx = 0; - - if (aIdx != null) { - idx = aIdx.intValue(); - - } - AttributeStatement attributeStatement = SAML2Utils .createSAMLObject(AttributeStatement.class); Subject subject = SAML2Utils.createSAMLObject(Subject.class); - NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); - boolean foundFormat = false; - - // TL: AuthData generation is moved to Assertion generation. - - Iterator<NameIDFormat> formatIt = spSSODescriptor.getNameIDFormats() - .iterator(); - while (formatIt.hasNext()) { - if (formatIt.next().getFormat().equals(NameID.PERSISTENT)) { - foundFormat = true; - break; - } - } - if (!foundFormat) { - // TODO use correct exception - throw new NameIDFormatNotSupportedException(""); - } - - // TODO: Check if we need to hide source pin - /* - * if(authSession.getUseMandate()) { Element mandate = - * authSession.getMandate(); if(authSession.getBusinessService()) { // - * Hide Source PIN! ParepUtils.HideStammZahlen(mandate, true, null, - * authSession.getDomainIdentifier(), true); } else { - * ParepUtils.HideStammZahlen(mandate, false, authSession.getTarget(), - * null, true); } } - */ AuthenticationData authData = AuthenticationServer .buildAuthenticationData(authSession, oaParam, oaParam.getTarget()); + //add Attributes to Assertion if (spSSODescriptor.getAttributeConsumingServices() != null && spSSODescriptor.getAttributeConsumingServices().size() > 0) { - AttributeConsumingService attributeConsumingService = spSSODescriptor - .getAttributeConsumingServices().get(idx); + Integer aIdx = authnRequest.getAttributeConsumingServiceIndex(); + int idx = 0; + + AttributeConsumingService attributeConsumingService = null; - Iterator<RequestedAttribute> it = attributeConsumingService - .getRequestAttributes().iterator(); - while (it.hasNext()) { - RequestedAttribute reqAttribut = it.next(); - try { - Attribute attr = PVPAttributeBuilder.buildAttribute( - reqAttribut.getName(), authSession, oaParam, authData); - if (attr == null) { + if (aIdx != null) { + idx = aIdx.intValue(); + attributeConsumingService = spSSODescriptor + .getAttributeConsumingServices().get(idx); + + } else { + List<AttributeConsumingService> attrConsumingServiceList = spSSODescriptor.getAttributeConsumingServices(); + for (AttributeConsumingService el : attrConsumingServiceList) { + if (el.isDefault()) + attributeConsumingService = el; + } + } + + if (attributeConsumingService != null) { + Iterator<RequestedAttribute> it = attributeConsumingService + .getRequestAttributes().iterator(); + while (it.hasNext()) { + RequestedAttribute reqAttribut = it.next(); + try { + Attribute attr = PVPAttributeBuilder.buildAttribute( + reqAttribut.getName(), authSession, oaParam, authData); + if (attr == null) { + if (reqAttribut.isRequired()) { + throw new UnprovideableAttributeException( + reqAttribut.getName()); + } + } else { + attributeStatement.getAttributes().add(attr); + } + } catch (PVP2Exception e) { + Logger.error( + "Attribute generation failed! for " + + reqAttribut.getFriendlyName(), e); if (reqAttribut.isRequired()) { throw new UnprovideableAttributeException( reqAttribut.getName()); } - } else { - attributeStatement.getAttributes().add(attr); - } - } catch (PVP2Exception e) { - Logger.error( - "Attribute generation failed! for " - + reqAttribut.getFriendlyName(), e); - if (reqAttribut.isRequired()) { - throw new UnprovideableAttributeException( - reqAttribut.getName()); } } } @@ -263,9 +231,9 @@ public class PVP2AssertionBuilder implements PVPConstants { if (attributeStatement.getAttributes().size() > 0) { assertion.getAttributeStatements().add(attributeStatement); } - - subjectNameID.setFormat(NameID.PERSISTENT); + NameID subjectNameID = SAML2Utils.createSAMLObject(NameID.class); + //TLenz: set correct bPK Type and Value from AuthData if (authSession.getUseMandate()) { Element mandate = authSession.getMandate(); @@ -295,6 +263,7 @@ public class PVP2AssertionBuilder implements PVPConstants { String bpktype = id.getType(); String bpk = id.getValue().getValue(); + if (bpktype.equals(Constants.URN_PREFIX_BASEID)) { if (authSession.getBusinessService()) { subjectNameID.setValue(new BPKBuilder().buildWBPK(bpk, oaParam.getIdentityLinkDomainIdentifier())); @@ -322,7 +291,52 @@ public class PVP2AssertionBuilder implements PVPConstants { subjectNameID.setValue(authData.getBPK()); } - + String nameIDFormat = NameID.TRANSIENT; + + //get NameIDFormat from request + AuthnRequest authnReq = (AuthnRequestImpl) authnRequest; + if (authnReq.getNameIDPolicy() != null) { + nameIDFormat = authnReq.getNameIDPolicy().getFormat(); + + } else { + //get NameIDFormat from metadata + List<NameIDFormat> metadataNameIDFormats = spSSODescriptor.getNameIDFormats(); + + if (metadataNameIDFormats != null) { + + for (NameIDFormat el : metadataNameIDFormats) { + if (NameID.PERSISTENT.equals(el.getFormat())) { + nameIDFormat = NameID.PERSISTENT; + break; + + } else if (NameID.TRANSIENT.equals(el.getFormat()) || + NameID.UNSPECIFIED.equals(el.getFormat())) + break; + + } + } + } + + if (NameID.TRANSIENT.equals(nameIDFormat) || NameID.UNSPECIFIED.equals(nameIDFormat)) { + String random = Random.nextRandom(); + String nameID = subjectNameID.getValue(); + + try { + MessageDigest md = MessageDigest.getInstance("SHA-1"); + byte[] hash = md.digest((nameID + random).getBytes("ISO-8859-1")); + subjectNameID.setValue(Base64Utils.encode(hash)); + subjectNameID.setNameQualifier(null); + subjectNameID.setFormat(NameID.TRANSIENT); + + } catch (Exception e) { + Logger.warn("PVP2 subjectNameID error", e); + throw new MOAIDException("pvp2.13", null, e); + } + + } else + subjectNameID.setFormat(nameIDFormat); + + subject.setNameID(subjectNameID); SubjectConfirmation subjectConfirmation = SAML2Utils @@ -332,16 +346,8 @@ public class PVP2AssertionBuilder implements PVPConstants { .createSAMLObject(SubjectConfirmationData.class); subjectConfirmationData.setInResponseTo(authnRequest.getID()); subjectConfirmationData.setNotOnOrAfter(date.plusMinutes(5)); - - //TL: change from entityID to destination URL - AssertionConsumerService consumerService = spSSODescriptor - .getAssertionConsumerServices().get(idx); - - if (consumerService == null) { - throw new InvalidAssertionConsumerServiceException(idx); - } - - subjectConfirmationData.setRecipient(consumerService.getLocation()); + + subjectConfirmationData.setRecipient(assertionConsumerService.getLocation()); subjectConfirmation.setSubjectConfirmationData(subjectConfirmationData); @@ -357,7 +363,6 @@ public class PVP2AssertionBuilder implements PVPConstants { conditions.setNotBefore(date); conditions.setNotOnOrAfter(date.plusMinutes(5)); -// conditions.setNotOnOrAfter(new DateTime()); conditions.getAudienceRestrictions().add(audienceRestriction); @@ -365,8 +370,6 @@ public class PVP2AssertionBuilder implements PVPConstants { Issuer issuer = SAML2Utils.createSAMLObject(Issuer.class); - //TODO: check! - //change to entity value from entity name to IDP EntityID (URL) issuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath()); issuer.setFormat(NameID.ENTITY); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSTORKTOKEN.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSTORKTOKEN.java index e3e33d6db..e8fba6af2 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSTORKTOKEN.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/builder/attributes/EIDSTORKTOKEN.java @@ -22,15 +22,12 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes; -import eu.stork.peps.auth.commons.IPersonalAttributeList; -import eu.stork.peps.auth.commons.PersonalAttribute; import at.gv.egovernment.moa.id.auth.data.AuthenticationSession; -import at.gv.egovernment.moa.id.auth.stork.STORKConstants; import at.gv.egovernment.moa.id.config.auth.OAAuthParameter; import at.gv.egovernment.moa.id.data.AuthenticationData; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.AttributeException; import at.gv.egovernment.moa.id.protocols.pvp2x.builder.attributes.exceptions.UnavailableAttributeException; -import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; public class EIDSTORKTOKEN implements IPVPAttributeBuilder { @@ -46,27 +43,14 @@ public class EIDSTORKTOKEN implements IPVPAttributeBuilder { throw new UnavailableAttributeException(EID_STORK_TOKEN_NAME); } else { - IPersonalAttributeList storkAttributes = authSession.getStorkAttributes(); - - if ( storkAttributes == null ) { + String storkResponse = authSession.getStorkAuthnResponse(); + + if ( MiscUtil.isEmpty(storkResponse) ) { throw new UnavailableAttributeException(EID_STORK_TOKEN_NAME); - } - - try { - PersonalAttribute attribut = storkAttributes.get(STORKConstants.EIDENTIFIER_NAME); - ATT attr; - if (attribut != null) { - - attr = g.buildStringAttribute(EID_STORK_TOKEN_FRIENDLY_NAME, EID_STORK_TOKEN_NAME, attribut.getValue().get(0)); - return attr; - - } else - throw new UnavailableAttributeException(EID_STORK_TOKEN_NAME); + } else { + return g.buildStringAttribute(EID_STORK_TOKEN_FRIENDLY_NAME, EID_STORK_TOKEN_NAME, storkResponse); - } catch (Exception e) { - Logger.warn("Attribut " + EID_STORK_TOKEN_FRIENDLY_NAME + " generation error", e); - throw new UnavailableAttributeException(EID_STORK_TOKEN_NAME); } } } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultSecurityConfigurationBootstrap.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultSecurityConfigurationBootstrap.java index 1563ba9be..f878b95d3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultSecurityConfigurationBootstrap.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/config/MOADefaultSecurityConfigurationBootstrap.java @@ -25,6 +25,10 @@ package at.gv.egovernment.moa.id.protocols.pvp2x.config; import org.opensaml.xml.encryption.EncryptionConstants; import org.opensaml.xml.security.BasicSecurityConfiguration; import org.opensaml.xml.security.DefaultSecurityConfigurationBootstrap; +import org.opensaml.xml.security.credential.BasicKeyInfoGeneratorFactory; +import org.opensaml.xml.security.keyinfo.KeyInfoGeneratorManager; +import org.opensaml.xml.security.keyinfo.NamedKeyInfoGeneratorManager; +import org.opensaml.xml.security.x509.X509KeyInfoGeneratorFactory; import org.opensaml.xml.signature.SignatureConstants; /** @@ -46,6 +50,25 @@ public class MOADefaultSecurityConfigurationBootstrap extends return config; } + protected static void populateKeyInfoGeneratorManager( + BasicSecurityConfiguration config) { + NamedKeyInfoGeneratorManager namedManager = new NamedKeyInfoGeneratorManager(); + config.setKeyInfoGeneratorManager(namedManager); + + namedManager.setUseDefaultManager(true); + KeyInfoGeneratorManager defaultManager = namedManager + .getDefaultManager(); + + BasicKeyInfoGeneratorFactory basicFactory = new BasicKeyInfoGeneratorFactory(); + basicFactory.setEmitPublicKeyValue(true); + + X509KeyInfoGeneratorFactory x509Factory = new X509KeyInfoGeneratorFactory(); + x509Factory.setEmitEntityCertificate(true); + + defaultManager.registerFactory(basicFactory); + defaultManager.registerFactory(x509Factory); + } + protected static void populateSignatureParams( BasicSecurityConfiguration config) { diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestValidatorException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestValidatorException.java new file mode 100644 index 000000000..7ed438471 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/AuthnRequestValidatorException.java @@ -0,0 +1,62 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; + +import at.gv.egovernment.moa.id.moduls.IRequest; + +/** + * @author tlenz + * + */ +public class AuthnRequestValidatorException extends PVP2Exception { + + private IRequest errorRequest = null; + + /** + * + */ + private static final long serialVersionUID = 4939651000658508576L; + + /** + * @param messageId + * @param parameters + */ + public AuthnRequestValidatorException(String messageId, Object[] parameters) { + super(messageId, parameters); + + } + + public AuthnRequestValidatorException(String messageId, Object[] parameters, IRequest errorRequest) { + super(messageId, parameters); + this.errorRequest = errorRequest; + + } + + /** + * @return the errorRequest + */ + public IRequest getErrorRequest() { + return errorRequest; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NameIDFormatNotSupportedException.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NameIDFormatNotSupportedException.java index 5a393062f..b5facde34 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NameIDFormatNotSupportedException.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/exceptions/NameIDFormatNotSupportedException.java @@ -22,7 +22,7 @@ *******************************************************************************/ package at.gv.egovernment.moa.id.protocols.pvp2x.exceptions; -public class NameIDFormatNotSupportedException extends PVP2Exception { +public class NameIDFormatNotSupportedException extends AuthnRequestValidatorException { public NameIDFormatNotSupportedException(String nameIDFormat) { super("pvp2.12", new Object[] {nameIDFormat}); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java index f84e6e588..04ef4cdbf 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/ArtifactResolution.java @@ -67,7 +67,7 @@ public class ArtifactResolution implements IRequestHandler { response.setMessage(assertion.getSamlMessage()); response.setIssueInstant(new DateTime()); SoapBinding encoder = new SoapBinding(); - encoder.encodeRespone(req, resp, response, null); + encoder.encodeRespone(req, resp, response, null, null); } catch (Exception e) { Logger.error("Failed to resolve artifact", e); } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index 229158778..fd7ff9885 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java @@ -58,6 +58,7 @@ import org.opensaml.xml.security.x509.X509Credential; 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.AuthConfigurationProvider; import at.gv.egovernment.moa.id.protocols.pvp2x.PVPConstants; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.ArtifactBinding; import at.gv.egovernment.moa.id.protocols.pvp2x.binding.IEncoder; @@ -85,32 +86,13 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { throw new MOAIDException("pvp2.13", null); } + //get basic information AuthnRequest authnRequest = (AuthnRequest) obj.getSamlRequest(); - EntityDescriptor peerEntity = obj.getEntityMetadata(); - - DateTime date = new DateTime(); - - Assertion assertion = PVP2AssertionBuilder.buildAssertion(authnRequest, authSession, peerEntity, date); - - Response authResponse = SAML2Utils.createSAMLObject(Response.class); - - Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); - - //change to entity value from entity name to IDP EntityID (URL) - nissuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath()); - nissuer.setFormat(NameID.ENTITY); - authResponse.setIssuer(nissuer); - authResponse.setInResponseTo(authnRequest.getID()); - - - //SAML2 response required IssueInstant - authResponse.setIssueInstant(date); - - authResponse.setStatus(SAML2Utils.getSuccessStatus()); - + EntityDescriptor peerEntity = obj.getEntityMetadata(); SPSSODescriptor spSSODescriptor = peerEntity .getSPSSODescriptor(SAMLConstants.SAML20P_NS); + //get AssertionConsumingService Integer aIdx = authnRequest.getAssertionConsumerServiceIndex(); int idx = 0; @@ -129,6 +111,31 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { } + DateTime date = new DateTime(); + + //build Assertion + Assertion assertion = PVP2AssertionBuilder.buildAssertion(authnRequest, authSession, peerEntity, date, consumerService); + + Response authResponse = SAML2Utils.createSAMLObject(Response.class); + + Issuer nissuer = SAML2Utils.createSAMLObject(Issuer.class); + + //change to entity value from entity name to IDP EntityID (URL) + nissuer.setValue(PVPConfiguration.getInstance().getIDPPublicPath()); + nissuer.setFormat(NameID.ENTITY); + authResponse.setIssuer(nissuer); + authResponse.setInResponseTo(authnRequest.getID()); + + //set responseID + String remoteSessionID = SAML2Utils.getSecureIdentifier(); + authResponse.setID(remoteSessionID); + + + //SAML2 response required IssueInstant + authResponse.setIssueInstant(date); + + authResponse.setStatus(SAML2Utils.getSuccessStatus()); + String oaURL = consumerService.getLocation(); //check, if metadata includes an encryption key @@ -150,7 +157,8 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { } - if (encryptionCredentials != null) { + boolean isEncryptionActive = AuthConfigurationProvider.getInstance().isPVP2AssertionEncryptionActive(); + if (encryptionCredentials != null && isEncryptionActive) { //encrypt SAML2 assertion try { @@ -212,7 +220,7 @@ public class AuthnRequestHandler implements IRequestHandler, PVPConstants { } try { - binding.encodeRespone(req, resp, authResponse, oaURL); + binding.encodeRespone(req, resp, authResponse, oaURL, obj.getRelayState()); // TODO add remoteSessionID to AuthSession ExternalPVPSessionStore // Logger logger = new Logger(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java index e3e25b1a9..d95e21a0e 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/signer/CredentialProvider.java @@ -30,9 +30,11 @@ import org.opensaml.xml.security.credential.Credential; import org.opensaml.xml.security.credential.UsageType; import org.opensaml.xml.security.x509.BasicX509Credential; import org.opensaml.xml.security.x509.KeyStoreX509CredentialAdapter; +import org.opensaml.xml.security.x509.X509Credential; import org.opensaml.xml.signature.Signature; import org.opensaml.xml.signature.SignatureConstants; +import at.gv.egovernment.moa.id.opemsaml.MOAKeyStoreX509CredentialAdapter; import at.gv.egovernment.moa.id.protocols.pvp2x.config.PVPConfiguration; import at.gv.egovernment.moa.id.protocols.pvp2x.utils.SAML2Utils; import at.gv.egovernment.moa.logging.Logger; @@ -42,7 +44,7 @@ public class CredentialProvider { private static KeyStore keyStore = null; - public static Credential getIDPMetaDataSigningCredential() + public static X509Credential getIDPMetaDataSigningCredential() throws CredentialsNotAvailableException { PVPConfiguration config = PVPConfiguration.getInstance(); try { @@ -51,7 +53,7 @@ public class CredentialProvider { keyStore = KeyStoreUtils.loadKeyStore(config.getIDPKeyStoreFilename(), config.getIDPKeyStorePassword()); - KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter( + MOAKeyStoreX509CredentialAdapter credentials = new MOAKeyStoreX509CredentialAdapter( keyStore, config.getIDPKeyAliasMetadata(), config .getIDPKeyPasswordMetadata().toCharArray()); @@ -64,7 +66,7 @@ public class CredentialProvider { } } - public static Credential getIDPAssertionSigningCredential() + public static X509Credential getIDPAssertionSigningCredential() throws CredentialsNotAvailableException { PVPConfiguration config = PVPConfiguration.getInstance(); try { @@ -72,12 +74,12 @@ public class CredentialProvider { keyStore = KeyStoreUtils.loadKeyStore(config.getIDPKeyStoreFilename(), config.getIDPKeyStorePassword()); - KeyStoreX509CredentialAdapter credentials = new KeyStoreX509CredentialAdapter( + MOAKeyStoreX509CredentialAdapter credentials = new MOAKeyStoreX509CredentialAdapter( keyStore, config.getIDPKeyAliasAssertionSign(), config .getIDPKeyPasswordAssertionSign().toCharArray()); - + credentials.setUsageType(UsageType.SIGNING); - return credentials; + return (X509Credential) credentials; } catch (Exception e) { Logger.error("Failed to generate IDP Assertion Signing credentials"); e.printStackTrace(); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AuthnRequestValidator.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AuthnRequestValidator.java new file mode 100644 index 000000000..ab8fab5d1 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/validation/AuthnRequestValidator.java @@ -0,0 +1,58 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.pvp2x.validation; + +import org.opensaml.saml2.core.AuthnRequest; +import org.opensaml.saml2.core.NameID; +import org.opensaml.saml2.core.NameIDPolicy; + +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.AuthnRequestValidatorException; +import at.gv.egovernment.moa.id.protocols.pvp2x.exceptions.NameIDFormatNotSupportedException; + +/** + * @author tlenz + * + */ +public class AuthnRequestValidator { + + public static void validate(AuthnRequest req) throws AuthnRequestValidatorException{ + + //validate NameIDPolicy + NameIDPolicy nameIDPolicy = req.getNameIDPolicy(); + if (nameIDPolicy != null) { + String nameIDFormat = nameIDPolicy.getFormat(); + + if ( !(nameIDFormat != null && + (NameID.TRANSIENT.equals(nameIDFormat) || + NameID.PERSISTENT.equals(nameIDFormat) || + NameID.UNSPECIFIED.equals(nameIDFormat))) ) { + + throw new NameIDFormatNotSupportedException(nameIDFormat); + + } + } + + + + } +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java index 3f6495a1a..c337433b6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/GetArtifactAction.java @@ -52,6 +52,13 @@ public class GetArtifactAction implements IAction { String oaURL = (String) req.getOAURL(); String target = (String) req.getTarget(); + String sourceID = null; + if (req instanceof SAML1RequestImpl) { + SAML1RequestImpl saml1req = (SAML1RequestImpl) req; + sourceID = saml1req.getSourceID(); + + } + try { @@ -78,13 +85,13 @@ public class GetArtifactAction implements IAction { // add other stork attributes to MOA assertion if available if(null != session.getStorkAttributes()) { List<ExtendedSAMLAttribute> moaExtendedSAMLAttibutes = STORKResponseProcessor.addAdditionalSTORKAttributes(session.getStorkAttributes()); - session.setExtendedSAMLAttributesOA(moaExtendedSAMLAttibutes); + session.getExtendedSAMLAttributesOA().addAll(moaExtendedSAMLAttibutes); //produce MOA-Assertion and artifact AuthenticationServer.getInstance().getForeignAuthenticationData(session); Logger.info("MOA assertion assembled and SAML Artifact generated."); } - String samlArtifactBase64 = saml1server.BuildSAMLArtifact(session, oaParam, authData); + String samlArtifactBase64 = saml1server.BuildSAMLArtifact(session, oaParam, authData, sourceID); if (AuthenticationSessionStoreage.isSSOSession(session.getSessionID())) { String url = "RedirectServlet"; diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java index 7c91026bf..6391860ff 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1AuthenticationServer.java @@ -165,7 +165,7 @@ public class SAML1AuthenticationServer extends AuthenticationServer { public String BuildSAMLArtifact(AuthenticationSession session, OAAuthParameter oaParam, - AuthenticationData authData) + AuthenticationData authData, String sourceID) throws ConfigurationException, BuildException, AuthenticationException { //Load SAML1 Parameter from OA config @@ -326,7 +326,7 @@ public class SAML1AuthenticationServer extends AuthenticationServer { String samlArtifact = new SAMLArtifactBuilder().build( session.getAuthURL(), Random.nextRandom(), - saml1parameter.getSourceID()); + sourceID); storeAuthenticationData(samlArtifact, authData); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java index e587ef0e1..b6a2ac0b6 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java @@ -44,6 +44,7 @@ import at.gv.egovernment.moa.id.moduls.IRequest; import at.gv.egovernment.moa.id.moduls.RequestImpl; import at.gv.egovernment.moa.id.util.ParamValidatorUtils; import at.gv.egovernment.moa.logging.Logger; +import at.gv.egovernment.moa.util.MiscUtil; import at.gv.egovernment.moa.util.URLEncoder; public class SAML1Protocol implements IModulInfo, MOAIDAuthConstants { @@ -81,7 +82,7 @@ public class SAML1Protocol implements IModulInfo, MOAIDAuthConstants { public IRequest preProcess(HttpServletRequest request, HttpServletResponse response, String action) throws MOAIDException { - RequestImpl config = new RequestImpl(); + SAML1RequestImpl config = new SAML1RequestImpl(); if (!AuthConfigurationProvider.getInstance().getAllowedProtocols().isSAML1Active()) { Logger.info("SAML1 is deaktivated!"); @@ -95,19 +96,34 @@ public class SAML1Protocol implements IModulInfo, MOAIDAuthConstants { String target = (String) request.getParameter(PARAM_TARGET); target = StringEscapeUtils.escapeHtml(target); + String sourceID = request.getParameter(PARAM_SOURCEID); + sourceID = StringEscapeUtils.escapeHtml(sourceID); + //the target parameter is used to define the OA in SAML1 standard if (target != null && target.startsWith("http")) { oaURL = target; target = null; } + if (MiscUtil.isEmpty(oaURL)) { + Logger.info("Receive SAML1 request with no OA parameter. Authentication STOPPED!"); + throw new WrongParametersException("StartAuthentication", PARAM_OA, + "auth.12"); + + } + if (!ParamValidatorUtils.isValidOA(oaURL)) throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12"); + config.setOAURL(oaURL); Logger.info("Dispatch SAML1 Request: OAURL=" + oaURL); + if (!ParamValidatorUtils.isValidSourceID(sourceID)) + throw new WrongParametersException("StartAuthentication", PARAM_SOURCEID, "auth.12"); + + //load Target only from OA config OAAuthParameter oaParam = AuthConfigurationProvider.getInstance() .getOnlineApplicationParameter(oaURL); @@ -123,10 +139,12 @@ public class SAML1Protocol implements IModulInfo, MOAIDAuthConstants { new Object[] { oaURL }); } + config.setSourceID(sourceID); + config.setTarget(oaParam.getTarget()); - request.getSession().setAttribute(PARAM_OA, oaURL); - request.getSession().setAttribute(PARAM_TARGET, oaParam.getTarget()); +// request.getSession().setAttribute(PARAM_OA, oaURL); +// request.getSession().setAttribute(PARAM_TARGET, oaParam.getTarget()); return config; } diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java new file mode 100644 index 000000000..72adfe0e7 --- /dev/null +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1RequestImpl.java @@ -0,0 +1,51 @@ +/* + * Copyright 2014 Federal Chancellery Austria + * MOA-ID has been developed in a cooperation between BRZ, the Federal + * Chancellery Austria - ICT staff unit, and Graz University of Technology. + * + * Licensed under the EUPL, Version 1.1 or - as soon they will be approved by + * the European Commission - subsequent versions of the EUPL (the "Licence"); + * You may not use this work except in compliance with the Licence. + * You may obtain a copy of the Licence at: + * http://www.osor.eu/eupl/ + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the Licence is distributed on an "AS IS" basis, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the Licence for the specific language governing permissions and + * limitations under the Licence. + * + * This product combines work with different licenses. See the "NOTICE" text + * file for details on the various modules and licenses. + * The "NOTICE" text file is part of the distribution. Any derivative works + * that you distribute must include a readable copy of the "NOTICE" text file. + */ +package at.gv.egovernment.moa.id.protocols.saml1; + +import at.gv.egovernment.moa.id.moduls.RequestImpl; + +/** + * @author tlenz + * + */ +public class SAML1RequestImpl extends RequestImpl { + + private static final long serialVersionUID = -4961979968425683115L; + + private String sourceID = null; + + /** + * @return the sourceID + */ + public String getSourceID() { + return sourceID; + } + + /** + * @param sourceID the sourceID to set + */ + public void setSourceID(String sourceID) { + this.sourceID = sourceID; + } + +} diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java index e1e03bce7..6d8979da3 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/storage/AssertionStorage.java @@ -73,10 +73,10 @@ public class AssertionStorage { //store AssertionStore element to Database try { MOASessionDBUtils.saveOrUpdate(element); - Logger.info("Assertion with Artifact=" + artifact + " is stored in Database"); + Logger.info("Sessioninformation with ID=" + artifact + " is stored in Database"); } catch (MOADatabaseException e) { - Logger.warn("Assertion could not be stored."); + Logger.warn("Sessioninformation could not be stored."); throw new MOADatabaseException(e); } @@ -96,8 +96,8 @@ public class AssertionStorage { return test; } catch (Exception e) { - Logger.warn("Assertion Cast-Exception by using Artifact=" + artifact); - throw new MOADatabaseException("Assertion Cast-Exception"); + Logger.warn("Sessioninformation Cast-Exception by using Artifact=" + artifact); + throw new MOADatabaseException("Sessioninformation Cast-Exception"); } } @@ -119,11 +119,11 @@ public class AssertionStorage { for(AssertionStore result : results) { try { MOASessionDBUtils.delete(result); - Logger.info("Remove Assertion with Artifact=" + result.getArtifact() - + " after assertion timeout."); + Logger.info("Remove sessioninformation with ID=" + result.getArtifact() + + " after timeout."); } catch (HibernateException e){ - Logger.warn("Assertion with Artifact=" + result.getArtifact() + Logger.warn("Sessioninformation with ID=" + result.getArtifact() + " not removed after timeout! (Error during Database communication)", e); } @@ -136,22 +136,22 @@ public class AssertionStorage { try { AssertionStore element = searchInDatabase(artifact); MOASessionDBUtils.delete(element); - Logger.info("Remove Assertion with Artifact" + artifact); + Logger.info("Remove sessioninformation with ID" + artifact); } catch (MOADatabaseException e) { - Logger.info("Assertion not removed! (Assertion with Artifact=" + artifact + Logger.info("Sessioninformation not removed! (Sessioninformation with ID=" + artifact + "not found)"); } catch (HibernateException e) { - Logger.warn("Assertion not removed! (Error during Database communication)", e); + Logger.warn("Sessioninformation not removed! (Error during Database communication)", e); } } @SuppressWarnings("rawtypes") private AssertionStore searchInDatabase(String artifact) throws MOADatabaseException { MiscUtil.assertNotNull(artifact, "artifact"); - Logger.trace("Getting Assertion with Artifact " + artifact + " from database."); + Logger.trace("Getting sessioninformation with ID " + artifact + " from database."); Session session = MOASessionDBUtils.getCurrentSession(); List result; @@ -170,7 +170,7 @@ public class AssertionStorage { //Assertion requires an unique artifact if (result.size() != 1) { Logger.trace("No entries found."); - throw new MOADatabaseException("No Assertion found with this Artifact"); + throw new MOADatabaseException("No sessioninformation found with this ID"); } return (AssertionStore) result.get(0); diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ParamValidatorUtils.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ParamValidatorUtils.java index 9df283965..6efe9b39c 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ParamValidatorUtils.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/ParamValidatorUtils.java @@ -508,7 +508,6 @@ public class ParamValidatorUtils implements MOAIDAuthConstants{ String oaURL = req.getParameter(PARAM_OA);
String bkuURL = req.getParameter(PARAM_BKU);
- String templateURL = req.getParameter(PARAM_TEMPLATE);
String useMandate = req.getParameter(PARAM_USEMANDATE);
String ccc = req.getParameter(PARAM_CCC);
@@ -519,8 +518,6 @@ public class ParamValidatorUtils implements MOAIDAuthConstants{ throw new WrongParametersException("StartAuthentication", PARAM_OA, "auth.12");
if (MiscUtil.isEmpty(bkuURL))
throw new WrongParametersException("StartAuthentication", PARAM_BKU, "auth.12");
-// if (MiscUtil.isEmpty(templateURL))
-// throw new WrongParametersException("StartAuthentication", PARAM_TEMPLATE, "auth.12");
if (!ParamValidatorUtils.isValidUseMandate(useMandate))
throw new WrongParametersException("StartAuthentication", PARAM_USEMANDATE, "auth.12");
if (!ParamValidatorUtils.isValidCCC(ccc))
diff --git a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java index c0fde8146..b9c4e88b7 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/util/client/mis/simple/MISSimpleClient.java @@ -157,7 +157,7 @@ public class MISSimpleClient { }
}
- public static MISSessionId sendSessionIdRequest(String webServiceURL, byte[] idl, byte[] cert, String oaFriendlyName, String redirectURL, String referenceValue, String mandateIdentifier[], String targetType, SSLSocketFactory sSLSocketFactory) throws MISSimpleClientException {
+ public static MISSessionId sendSessionIdRequest(String webServiceURL, byte[] idl, byte[] cert, String oaFriendlyName, String redirectURL, String referenceValue, List<String> mandateIdentifier, String targetType, SSLSocketFactory sSLSocketFactory) throws MISSimpleClientException {
if (webServiceURL == null) {
throw new NullPointerException("Argument webServiceURL must not be null.");
}
@@ -205,12 +205,12 @@ public class MISSimpleClient { referenceValueElement.appendChild(doc.createTextNode(referenceValue));
mirElement.appendChild(referenceValueElement);
- if (mandateIdentifier != null && mandateIdentifier.length > 0) {
+ if (mandateIdentifier != null && mandateIdentifier.size() > 0) {
Element filtersElement = doc.createElementNS(MIS_NS, "Filters");
Element mandateIdentifiersElement = doc.createElementNS(MIS_NS, "MandateIdentifiers");
- for (int i=0; i<mandateIdentifier.length; i++) {
+ for (int i=0; i<mandateIdentifier.size(); i++) {
Element mandateIdentifierElement = doc.createElementNS(MIS_NS, "MandateIdentifier");
- mandateIdentifierElement.appendChild(doc.createTextNode(mandateIdentifier[i]));
+ mandateIdentifierElement.appendChild(doc.createTextNode(mandateIdentifier.get(i)));
mandateIdentifiersElement.appendChild(mandateIdentifierElement);
}
filtersElement.appendChild(mandateIdentifiersElement);
@@ -306,15 +306,24 @@ public class MISSimpleClient { //Element elem = parse(post.getResponseBodyAsStream());
Document doc = DOMUtils.parseDocumentSimple(post.getResponseBodyAsStream());
return unpackFromSOAP(doc.getDocumentElement());
+
} catch(IOException e) {
- throw new MISSimpleClientException(e);
+ throw new MISSimpleClientException(e.getLocalizedMessage(), e);
+
} catch (TransformerException e) {
throw new MISSimpleClientException(e);
+
} catch (SAXException e) {
throw new MISSimpleClientException(e);
+
} catch (ParserConfigurationException e) {
throw new MISSimpleClientException(e);
+
+ } catch (Exception e) {
+ throw new MISSimpleClientException(e.getLocalizedMessage(), e);
+
}
+
}
private static Element packIntoSOAP(Element element) throws MISSimpleClientException {
|