diff options
Diffstat (limited to 'id/server/idserverlib/src')
37 files changed, 848 insertions, 441 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 9ac9986c8..1e4faed66 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 @@ -1503,14 +1503,15 @@ public class AuthenticationServer implements MOAIDAuthConstants { try { - if (session.getUseMandate() && session.isOW()) { - MISMandate mandate = session.getMISMandate(); + 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 { if (businessService) { @@ -1714,7 +1715,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { * @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 { + 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(); @@ -1731,6 +1732,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { data.setFamilyname(PEPSFamilyname); data.setFirstname(PEPSFirstname); data.setIdentifier(PEPSIdentifier); + data.setFiscalNumber(PEPSFiscalNumber); data.setRepresentative(representative); data.setRepresented(represented); @@ -1751,7 +1753,9 @@ public class AuthenticationServer implements MOAIDAuthConstants { Filters filterObject = new Filters(); MandateIdentifiers mandateIds = new MandateIdentifiers(); - for(String current : filters.split(",")) + + //TODO! + for(String current : filters) mandateIds.getMandateIdentifier().add(current.trim()); filterObject.setMandateIdentifiers(mandateIds); mis.setFilters(filterObject); @@ -1782,7 +1786,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { * @throws ConfigurationException the configuration exception */ public CreateIdentityLinkResponse getIdentityLink(Element signature) throws SZRGWClientException, ConfigurationException { - return getIdentityLink(null, null, null, null, XMLHelper.nodeToString(signature)); + return getIdentityLink(null, null, null, null, XMLHelper.nodeToString(signature), null); } /** @@ -1797,8 +1801,8 @@ public class AuthenticationServer implements MOAIDAuthConstants { * @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); + 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); } /** @@ -1815,10 +1819,10 @@ public class AuthenticationServer implements MOAIDAuthConstants { */ 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 { + 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); + organizationType, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); } /** @@ -1838,10 +1842,10 @@ public class AuthenticationServer implements MOAIDAuthConstants { 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 { + 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); + null, targetType, targetValue, oaFriendlyName, filters, PEPSFiscalNumber); } /** @@ -1886,7 +1890,9 @@ public class AuthenticationServer implements MOAIDAuthConstants { String providerName= oaParam.getFriendlyName(); Logger.debug("Issuer value: " + issuerValue); - String acsURL = issuerValue + PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN; +// String acsURL = issuerValue + PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN + String acsURL = new DataURLBuilder().buildDataURL(issuerValue, + PEPSConnectorServlet.PEPSCONNECTOR_SERVLET_URL_PATTERN, moasession.getSessionID()); Logger.debug("MOA Assertion Consumer URL (PEPSConnctor): " + acsURL); // prepare collection of required attributes @@ -1957,12 +1963,27 @@ public class AuthenticationServer implements MOAIDAuthConstants { Logger.debug("STORK AuthnRequest succesfully assembled."); - STORKSAMLEngine samlEngine = STORKSAMLEngine.getInstance("outgoing"); + STORKSAMLEngine samlEngine = null; + + try { + samlEngine = STORKSAMLEngine.getInstance("outgoing"); + + } catch (Exception e) { + Logger.error("STORK engine initialization FAILED with error " + + e.getLocalizedMessage(), e); + throw new MOAIDException("stork.11", null, e); + + } + if (samlEngine == null) + throw new MOAIDException("stork.11", null); + + try { authnRequest = samlEngine.generateSTORKAuthnRequest(authnRequest); - } catch (STORKSAMLEngineException e) { + + } catch (Exception e ) { Logger.error("Could not sign STORK SAML AuthnRequest.", e); - throw new MOAIDException("stork.00", null); + throw new MOAIDException("stork.00", null, e); } Logger.info("STORK AuthnRequest successfully signed!"); @@ -1970,17 +1991,19 @@ public class AuthenticationServer implements MOAIDAuthConstants { //validate AuthnRequest try { samlEngine.validateSTORKAuthnRequest(authnRequest.getTokenSaml()); - } catch (STORKSAMLEngineException e) { + + } catch (Exception e) { Logger.error("STORK SAML AuthnRequest not valid.", e); throw new MOAIDException("stork.01", null); - } + + } Logger.debug("STORK AuthnRequest successfully internally validated."); //send moasession.setStorkAuthnRequest(authnRequest); - HttpSession httpSession = req.getSession(); - httpSession.setAttribute("MOA-Session-ID", moasession.getSessionID()); +// HttpSession httpSession = req.getSession(); +// httpSession.setAttribute("MOA-Session-ID", moasession.getSessionID()); Logger.info("Preparing to send STORK AuthnRequest."); @@ -2002,7 +2025,7 @@ public class AuthenticationServer implements MOAIDAuthConstants { resp.getOutputStream().write(writer.toString().getBytes()); } catch (Exception e) { Logger.error("Error sending STORK SAML AuthnRequest.", e); - httpSession.invalidate(); + //httpSession.invalidate(); throw new MOAIDException("stork.02", new Object[] { destination }); } 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/servlet/GetForeignIDServlet.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/auth/servlet/GetForeignIDServlet.java index f4212cc78..5ad937b2a 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
+ .getSamlAssertion());
+ session.setAuthBlock(serializedAssertion);
+
+ } catch (TransformerException e) {
+ throw new ParseException("parser.04", new Object[] {
+ REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE });
+
+ } catch (IOException e) {
+ throw new ParseException("parser.04", new Object[] {
+ REQ_VERIFY_AUTH_BLOCK, PARAM_XMLRESPONSE });
+
+ }
+
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..12cf54e16 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 @@ -88,8 +88,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); 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 c6cd5cd86..83d0ced20 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 @@ -40,6 +40,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;
@@ -51,6 +52,7 @@ 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.auth.stork.VelocityProvider;
@@ -61,6 +63,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.logging.Logger;
import at.gv.egovernment.moa.util.StringUtils;
import at.gv.util.xsd.xmldsig.SignatureType;
@@ -112,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");
@@ -163,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();
@@ -308,7 +319,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);
}
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 c5f0dbd49..dbb184e43 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 @@ -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
if(hasAttribute("mandateContent", attributeList) || hasAttribute("representative", attributeList) || hasAttribute("represented", attributeList)) {
@@ -148,15 +148,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);
@@ -165,7 +165,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
@@ -175,7 +175,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/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 f9a038d9f..8d1fc7979 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 @@ -998,6 +998,11 @@ public class AuthConfigurationProvider extends ConfigurationProvider { return publicURLPreFix; } + public boolean isPVP2AssertionEncryptionActive() { + String prop = props.getProperty("protocols.pvp2.assertion.encryption.active", "true"); + 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 8e7ca0779..50b870c98 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 @@ -56,6 +56,7 @@ import at.gv.egovernment.moa.id.commons.db.dao.config.BKUSelectionCustomizationT import at.gv.egovernment.moa.id.commons.db.dao.config.BKUURLS; 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; @@ -221,13 +222,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; } 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/config/stork/STORKConfig.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/STORKConfig.java index ff481b825..b3a4cca78 100644 --- a/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/STORKConfig.java +++ b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/config/stork/STORKConfig.java @@ -58,30 +58,32 @@ public class STORKConfig { this.basedirectory = basedirectory;
this.props = props;
- //create CPEPS map
- List<at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS> cpeps = stork.getCPEPS();
-
cpepsMap = new HashMap<String, CPEPS>();
+ attr = new ArrayList<StorkAttribute>();
+
+ if (stork != null) {
+ //create CPEPS map
+ List<at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS> cpeps = stork.getCPEPS();
+
+ if (cpeps != null) {
+ for(at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS cpep : cpeps) {
- if (cpeps != null) {
- for(at.gv.egovernment.moa.id.commons.db.dao.config.CPEPS cpep : cpeps) {
-
- try {
- CPEPS moacpep = new CPEPS(cpep.getCountryCode(), new URL(cpep.getURL()));
+ try {
+ CPEPS moacpep = new CPEPS(cpep.getCountryCode(), new URL(cpep.getURL()));
- cpepsMap.put(cpep.getCountryCode(), moacpep);
+ cpepsMap.put(cpep.getCountryCode(), moacpep);
- } catch (MalformedURLException e) {
- Logger.warn("Error in MOA-ID Configuration. CPEP entry for country "
- + cpep.getCountryCode() + " has an invalid URL and is ignored.");
+ } catch (MalformedURLException e) {
+ Logger.warn("Error in MOA-ID Configuration. CPEP entry for country "
+ + cpep.getCountryCode() + " has an invalid URL and is ignored.");
+ }
}
}
- }
- attr = new ArrayList<StorkAttribute>();
- if (stork.getAttributes() != null) {
- for(StorkAttribute current : stork.getAttributes()) {
- attr.add(current);
+ if (stork.getAttributes() != null) {
+ for(StorkAttribute current : stork.getAttributes()) {
+ attr.add(current);
+ }
}
}
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 34366b790..487e86b34 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); 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/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/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 e5158f4bf..db83233fe 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; @@ -169,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(); @@ -203,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(); @@ -225,11 +229,30 @@ 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) { + + } catch (PVP2Exception e) { + throw e; + + } catch (Throwable e) { e.printStackTrace(); throw new MOAIDException(e.getMessage(), new Object[] {}); } @@ -255,17 +278,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); @@ -273,7 +302,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)) { 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..c1104f9f5 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,51 @@ 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; + 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; + } + } public void setSamlRequest(RequestAbstractType request) { - this.samlRequest = request; + this.samlRequest = request.getDOM(); } public boolean isVerified() { @@ -55,13 +79,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 af29054e1..aebd94a29 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 @@ -45,6 +45,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; @@ -65,7 +67,7 @@ public class PostBinding implements IDecoder, IEncoder { throws MessageEncodingException, SecurityException { try { - Credential credentials = CredentialProvider + X509Credential credentials = CredentialProvider .getIDPAssertionSigningCredential(); Logger.debug("create SAML POSTBinding response"); @@ -128,7 +130,7 @@ public class PostBinding implements IDecoder, IEncoder { MOARequest request = new MOARequest(inboundMessage); request.setVerified(false); - 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/RedirectBinding.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/binding/RedirectBinding.java index 7c9cc6259..5155d6958 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; @@ -69,7 +70,7 @@ public class RedirectBinding implements IDecoder, IEncoder { StatusResponseType response, String targetLocation) 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/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/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/AuthnRequestHandler.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/pvp2x/requestHandler/AuthnRequestHandler.java index 229158778..c5afbabe5 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 { 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/SAML1Protocol.java b/id/server/idserverlib/src/main/java/at/gv/egovernment/moa/id/protocols/saml1/SAML1Protocol.java index e587ef0e1..ada0bfa8f 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 { @@ -101,6 +102,13 @@ public class SAML1Protocol implements IModulInfo, MOAIDAuthConstants { 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"); @@ -125,8 +133,8 @@ public class SAML1Protocol implements IModulInfo, MOAIDAuthConstants { 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/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/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 {
diff --git a/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties b/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties index 2559d3d18..ec787d745 100644 --- a/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties +++ b/id/server/idserverlib/src/main/resources/resources/properties/id_messages_de.properties @@ -205,6 +205,7 @@ stork.07=Es existiert kein STORK AuthnRequest f\u00FCr diese STORK Response stork.08=STORK SAML Assertion Validierung fehlgeschlagen
stork.09=Fehler beim \u00FCberpr\u00FCfen der STORK B\u00FCrgerInnen Signatur
stork.10=Fehler in der Verbindung zum SZR-Gateway
+stork.11=STORK-SAML Engine konnte nicht initialisiert werden.
pvp2.00={0} ist kein gueltiger consumer service index
pvp2.01=Fehler beim kodieren der PVP2 Antwort
diff --git a/id/server/idserverlib/src/main/resources/resources/templates/redirectForm.html b/id/server/idserverlib/src/main/resources/resources/templates/redirectForm.html index 517f207ff..9bddee931 100644 --- a/id/server/idserverlib/src/main/resources/resources/templates/redirectForm.html +++ b/id/server/idserverlib/src/main/resources/resources/templates/redirectForm.html @@ -7,7 +7,7 @@ <body onload="document.getElementById('link').click();"> - <a href="#URL#" target="_parent" id="link">CLICK to perform a + <a href="#URL#" target="#TARGET#" id="link">CLICK to perform a redirect back to Online Application</a> </body> </html> |